
    kKjf                    n    d Z ddlmZ ddlZddlmZ ddlmZm	Z	m
Z
 ddlmZ  ee      Z G d de      Zy)	u  Enhanced authentication middleware with better error messages.

This module provides enhanced versions of MCP SDK authentication middleware
that return more helpful error messages for developers troubleshooting
authentication issues.

Implements RFC 6750 §3.1 compliance by distinguishing between missing
authentication (no error attribute) and invalid authentication (with error).
    )annotationsN)RequireAuthMiddleware)ReceiveScopeSend)
get_loggerc                  X     e Zd ZdZ	 	 	 	 	 	 	 	 d fdZddZ	 	 	 	 	 	 	 	 	 	 ddZ xZS )r   u  Enhanced authentication middleware with detailed error messages.

    Extends the SDK's RequireAuthMiddleware to provide more actionable
    error messages when authentication fails. This helps developers
    understand what went wrong and how to fix it.

    Also implements RFC 6750 §3.1 compliance by distinguishing between
    missing authentication (initial discovery) and invalid authentication
    (token validation failure).
    c                  K   |d   dk7  r| j                  |||       d{    y|j                  dg       }t        d |D              }|s| j                  |       d{    yt        |   |||       d{    y7 _7 !7 	w)u  Process ASGI scope, distinguishing missing vs invalid auth.

        Per RFC 6750 §3.1:
        - Missing auth (no Authorization header) → 401 without error attribute
        - Invalid auth (Authorization header present) → 401 with error attribute

        This ensures OAuth flow initialization works correctly in MCP clients
        during initial discovery phase.

        Args:
            scope: ASGI scope
            receive: ASGI receive callable
            send: ASGI send callable
        typehttpNheadersc              3  H   K   | ]  }|d    j                         dk(    yw)r   s   authorizationN)lower).0headers     o/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/server/auth/middleware.py	<genexpr>z1RequireAuthMiddleware.__call__.<locals>.<genexpr>?   s%      
@GfF1IOO!11s    ")appgetany_send_missing_authsuper__call__)selfscopereceivesendr   has_auth_header	__class__s         r   r   zRequireAuthMiddleware.__call__%   s     ( =F"((5'4000 ))Ir* 
@G
 
 ))$/// gugt444! 1 0
 	5s3   BB?B"B#B<B=BBBc                :  K   g }| j                   r|j                  d| j                    d       |rddj                  |      z   nd} |dddd	|j                         fgd
       d{     |ddd       d{    t        j                  d       y7 -7 w)u  Send 401 response for missing authentication (RFC 6750 §3.1 compliant).

        When a request lacks any authentication information, per RFC 6750 §3.1:
        "If the request lacks any authentication information, the error
        attribute SHOULD NOT be included."

        This allows MCP clients to properly initiate OAuth flow during
        initial discovery phase.

        Args:
            send: ASGI send callable
        resource_metadata=""Bearer , Bearerhttp.response.start  )   content-length   0   www-authenticater   statusr   Nhttp.response.body    r   bodyuI   Missing auth: sent 401 without error attribute (RFC 6750 §3.1 compliant))resource_metadata_urlappendjoinencodeloggerdebug)r   r   www_auth_partswww_authenticates       r   r   z(RequireAuthMiddleware._send_missing_authL   s      %%!!$78R8R7SST"UV 8FY>228 	 --(*:*A*A*CD	
 		
 		
 0#>???W	
		
 	@s$   A'B)B*B<B=BBc                
  K   |}|dk(  r|dk(  rd}n|dk(  r	 d| dd| dg}| j                   r|j                  d| j                    d       d	d
j                  |       }||d}t        j                  |      j                         }	 |d|ddt        t        |	            j                         fd|j                         fgd       d{     |d|	d       d{    t        j                  d||       y7 /7 w)a  Send an authentication error response with enhanced error messages.

        Overrides the SDK's _send_auth_error to provide more detailed
        error descriptions that help developers troubleshoot authentication
        issues.

        Args:
            send: ASGI send callable
            status_code: HTTP status code (401 or 403)
            error: OAuth error code
            description: Base error description
        invalid_tokenr'   zAuthentication failed. The provided bearer token is invalid, expired, or no longer recognized by the server. To resolve: clear authentication tokens in your MCP client and reconnect. Your client should automatically re-register and obtain new tokens.insufficient_scopezerror="r"   zerror_description="r!   r#   r$   )errorerror_descriptionr&   )s   content-types   application/jsonr(   r*   r+   Nr-   r/   z#Auth error returned: %s (status=%d))
r1   r2   r3   jsondumpsr4   strlenr5   info)
r   r   status_coder<   descriptionenhanced_descriptionr7   r8   r0   
body_bytess
             r   _send_auth_errorz&RequireAuthMiddleware._send_auth_errorq   sQ       +O#s(:V !
 ** eWA!"6!7q9
 %%!!$78R8R7SST"UV$TYY~%>$?@ 5IJZZ%,,.
-%:&C
O(<(C(C(EF(*:*A*A*CD

 
	
 
	
 ,"
 	
 	
 	1	
'
	
	
s$   CDC?D"D#DD)r   r   r   r   r   r   returnNone)r   r   rH   rI   )
r   r   rC   intr<   r@   rD   r@   rH   rI   )__name__
__module____qualname____doc__r   r   rG   __classcell__)r   s   @r   r   r      sm    	%5%5 %5 	%5
 
%5N#
JB
B
'*B
36B
EHB
	B
r.   r   )rN   
__future__r   r>   &mcp.server.auth.middleware.bearer_authr   SDKRequireAuthMiddlewarestarlette.typesr   r   r   fastmcp.utilities.loggingr   rK   r5    r.   r   <module>rV      s;    #  1 0 0	H	Z
4 Z
r.   