
    {h3                         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y)    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                 h    t         |   |j                         || _        |j                  | _        y N)super__init__	client_idaccess_tokenscopes)selfr   	__class__s     g/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/mcp/server/auth/middleware/bearer_auth.pyr   zAuthenticatedUser.__init__   s+    ,,-%&&    )__name__
__module____qualname____doc__r   r   __classcell__)r   s   @r   r   r      s    ('+ ' 'r   r   c                   (    e Zd ZdZdefdZdefdZy)BearerAuthBackendzT
    Authentication backend that validates Bearer tokens using a TokenVerifier.
    token_verifierc                     || _         y r   )r#   )r   r#   s     r   r   zBearerAuthBackend.__init__   s
    ,r   connc                   K   t        fdj                  D        d       }|r|j                         j                  d      sy |dd  }| j                  j                  |       d {   }|sy |j                  r+|j                  t        t        j                               k  ry t        |j                        t        |      fS 7 ^w)Nc              3   |   K   | ]3  }|j                         d k(  sj                  j                  |       5 yw)authorizationN)lowerheadersget).0keyr%   s     r   	<genexpr>z1BearerAuthBackend.authenticate.<locals>.<genexpr>    s-     ]sciik_>\T\\c"]s   < <zbearer    )nextr*   r)   
startswithr#   verify_token
expires_atinttimer   r   r   )r   r%   auth_headertokenr   s    `   r   authenticatezBearerAuthBackend.authenticate   s     ]dll]
 +"3"3"5"@"@"KAB --::5AA	I$8$83tyy{;K$Ky//02CI2NNN Bs   A%C	(C)AC	N)r   r   r   r   r   r   r   r8    r   r   r"   r"      s!    -} -O~ Or   r"   c            
       h    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y)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                 .    || _         || _        || _        y)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                 t  K   |j                  d      }t        |t              s| j                  |ddd       d {    y |j                  d      }| j                  D ]4  }|||j
                  vs| j                  |ddd	|        d {     y  | j                  |||       d {    y 7 u7 %7 	w)
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''#_Jc (     99V,"22 	N'>AQAXAX+X++c1EUefteuSv ,    	 hhugt,,,
 	-s9   :B8B25B83B8B4B8,B6-B84B86B8rG   rH   rI   c                   K   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{    y7 7 w)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   s     $E7!,0CK=PQ.RS%%!!$78R8R7SST"UV$TYY~%>$?@ [AZZ%,,.
-%:&C
O(<(C(C(EF(*:*A*A*CD

 
	
 
	
 ,"
 	
 	

	
	
s$   B8C:C;CCCC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      sJ        W W - 0 0 ?'
 'O- O<L
 L
r   