
    )`iG                         d dl Z d dlZd dlmZ d dlmZ d dlmZmZm	Z	 d dl
mZ d dlmZmZmZ d dlmZmZ  G d d	e	          Z G d
 de          Z G d d          ZdS )    N)Any)
AnyHttpUrl)AuthCredentialsAuthenticationBackend
SimpleUser)HTTPConnection)ReceiveScopeSend)AccessTokenTokenVerifierc                   (     e Zd ZdZdef fdZ xZS )AuthenticatedUserzUser with authentication info.	auth_infoc                 z    t                                          |j                   || _        |j        | _        d S N)super__init__	client_idaccess_tokenscopes)selfr   	__class__s     z/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/mcp/server/auth/middleware/bearer_auth.pyr   zAuthenticatedUser.__init__   s4    ,---%&    )__name__
__module____qualname____doc__r   r   __classcell__)r   s   @r   r   r      sJ        (('+ ' ' ' ' ' ' ' ' ' 'r   r   c                   *    e Zd ZdZdefdZdefdZdS )BearerAuthBackendzT
    Authentication backend that validates Bearer tokens using a TokenVerifier.
    token_verifierc                     || _         d S r   )r#   )r   r#   s     r   r   zBearerAuthBackend.__init__   s    ,r   connc                   K   t          fdj        D             d           }|r'|                                                    d          sd S |dd          }| j                            |           d {V }|sd S |j        r+|j        t          t          j                              k     rd S t          |j
                  t          |          fS )Nc              3   |   K   | ]6}|                                 d k    j                            |          V  7dS )authorizationN)lowerheadersget).0keyr%   s     r   	<genexpr>z1BearerAuthBackend.authenticate.<locals>.<genexpr>    sE      ]]sciikk_>\>\T\c"">\>\>\>\]]r   zbearer    )nextr*   r)   
startswithr#   verify_token
expires_atinttimer   r   r   )r   r%   auth_headertokenr   s    `   r   authenticatezBearerAuthBackend.authenticate   s      ]]]]dl]]]
 
  	+"3"3"5"5"@"@"K"K 	4ABB -::5AAAAAAAA	 	4 	I$83ty{{;K;K$K$K4y/002CI2N2NNNr   N)r   r   r   r   r   r   r   r8    r   r   r"   r"      s[         -} - - - -O~ O O O O O Or   r"   c            
       p    e Zd ZdZ	 ddedee         dedz  fdZde	de
d	ed
dfdZd	edededed
df
dZdS )RequireAuthMiddlewarez
    Middleware that requires a valid Bearer token in the Authorization header.

    This will validate the token with the auth provider and store the resulting
    auth info in the request state.
    Napprequired_scopesresource_metadata_urlc                 0    || _         || _        || _        dS )a
  
        Initialize the middleware.

        Args:
            app: ASGI application
            required_scopes: List of scopes that the token must have
            resource_metadata_url: Optional protected resource metadata URL for WWW-Authenticate header
        N)r<   r=   r>   )r   r<   r=   r>   s       r   r   zRequireAuthMiddleware.__init__<   s!     .%:"""r   scopereceivesendreturnc                 x  K   |                     d          }t          |t                    s!|                     |ddd           d {V  d S |                     d          }| j        D ]2}|	||j        vr%|                     |ddd	|            d {V   d S 3|                     |||           d {V  d S )
Nuseri  invalid_tokenzAuthentication required)status_codeerrordescriptionauthi  insufficient_scopezRequired scope: )r+   
isinstancer   _send_auth_errorr=   r   r<   )r   r@   rA   rB   	auth_userauth_credentialsrequired_scopes          r   __call__zRequireAuthMiddleware.__call__N   s<     IIf%%	)%677 	''#_Jc (          F 99V,,"2 	 	N'>AQAX+X+X++c1ESvftSvSv ,          	 ,Y hhugt,,,,,,,,,,,r   rG   rH   rI   c                   K   d| dd| dg}| j         r|                    d| j          d           dd                    |           }||d}t          j        |                                          } |d|d	d
t          t          |                                                    fd|                                fgd           d{V   |d|d           d{V  dS )zCSend an authentication error response with WWW-Authenticate header.zerror=""zerror_description="zresource_metadata="zBearer z, )rH   error_descriptionzhttp.response.start)s   content-types   application/jsons   content-lengths   www-authenticate)typestatusr*   Nzhttp.response.body)rU   body)r>   appendjoinjsondumpsencodestrlen)	r   rB   rG   rH   rI   www_auth_partswww_authenticaterW   
body_bytess	            r   rM   z&RequireAuthMiddleware._send_auth_errorb   sk      -E,,,.RK.R.R.RS% 	W!!"U8R"U"U"UVVV@TYY~%>%>@@ [AAZ%%,,..
d-%:&C
OO(<(<(C(C(E(EF(*:*A*A*C*CD 

 

 
	
 
	
 
	
 
	
 
	
 
	
 
	
 d," 
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
r   r   )r   r   r   r   r   listr]   r   r   r
   r	   r   rQ   r4   rM   r9   r   r   r;   r;   4   s          48	; ;; c;  *D0	; ; ; ;$-E -G -4 -D - - - -(
4 
c 
# 
\_ 
dh 
 
 
 
 
 
r   r;   )rZ   r5   typingr   pydanticr   starlette.authenticationr   r   r   starlette.requestsr   starlette.typesr	   r
   r   mcp.server.auth.providerr   r   r   r"   r;   r9   r   r   <module>ri      s:                 W W W W W W W W W W - - - - - - 0 0 0 0 0 0 0 0 0 0 ? ? ? ? ? ? ? ?' ' ' ' '
 ' ' 'O O O O O- O O O<L
 L
 L
 L
 L
 L
 L
 L
 L
 L
r   