o
    iG                     @   s   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	 d	e	ZG d
d deZG dd dZdS )    N)Any)
AnyHttpUrl)AuthCredentialsAuthenticationBackend
SimpleUser)HTTPConnection)ReceiveScopeSend)AccessTokenTokenVerifierc                       s&   e Zd ZdZdef fddZ  ZS )AuthenticatedUserzUser with authentication info.	auth_infoc                    s    t  |j || _|j| _d S N)super__init__Z	client_idZaccess_tokenscopes)selfr   	__class__ ]/home/app/Keep/.python/lib/python3.10/site-packages/mcp/server/auth/middleware/bearer_auth.pyr      s   zAuthenticatedUser.__init__)__name__
__module____qualname____doc__r   r   __classcell__r   r   r   r   r      s    r   c                   @   s,   e Zd ZdZdefddZdefddZdS )	BearerAuthBackendzT
    Authentication backend that validates Bearer tokens using a TokenVerifier.
    token_verifierc                 C   s
   || _ d S r   )r   )r   r   r   r   r   r      s   
zBearerAuthBackend.__init__connc                    s   t  fdd jD d }|r| dsd S |dd  }| j|I d H }|s,d S |jr:|jtt k r:d S t	|j
t|fS )Nc                 3   s(    | ]}|  d kr j|V  qdS )authorizationN)lowerheadersget).0keyr   r   r   	<genexpr>    s   & z1BearerAuthBackend.authenticate.<locals>.<genexpr>zbearer    )nextr"   r!   
startswithr   Zverify_tokenZ
expires_atinttimer   r   r   )r   r   auth_headertokenr   r   r&   r   authenticate   s   zBearerAuthBackend.authenticateN)r   r   r   r   r   r   r   r/   r   r   r   r   r      s    r   c                
   @   sj   e Zd ZdZ	ddedee dedB fddZde	d	e
d
eddfddZd
ededededdf
d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                 C   s   || _ || _|| _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)r1   r2   r3   )r   r1   r2   r3   r   r   r   r   <   s   
zRequireAuthMiddleware.__init__scopereceivesendreturnc                    s   | d}t|ts| j|ddddI d H  d S | d}| jD ]}|d u s,||jvr>| j|ddd	| dI d H   d S q!| |||I d H  d S )
Nuseri  Zinvalid_tokenzAuthentication required)status_codeerrordescriptionauthi  Zinsufficient_scopezRequired scope: )r#   
isinstancer   _send_auth_errorr2   r   r1   )r   r4   r5   r6   Z	auth_userZauth_credentialsZrequired_scoper   r   r   __call__N   s    



zRequireAuthMiddleware.__call__r9   r:   r;   c           	         s   d| dd| dg}| j r|d| j  d dd| }||d}t| }|d|d	d
tt| fd| fgdI dH  |d|dI dH  dS )zCSend an authentication error response with WWW-Authenticate header.zerror=""zerror_description="zresource_metadata="zBearer z, )r:   Zerror_descriptionzhttp.response.start)s   content-types   application/jsons   content-lengths   www-authenticate)typestatusr"   Nzhttp.response.body)rA   body)r3   appendjoinjsondumpsencodestrlen)	r   r6   r9   r:   r;   Zwww_auth_partsZwww_authenticaterC   Z
body_bytesr   r   r   r>   b   s*   


z&RequireAuthMiddleware._send_auth_errorr   )r   r   r   r   r   listrI   r   r   r	   r   r
   r?   r+   r>   r   r   r   r   r0   4   s    
"r0   )rF   r,   typingr   Zpydanticr   Zstarlette.authenticationr   r   r   Zstarlette.requestsr   Zstarlette.typesr   r	   r
   Zmcp.server.auth.providerr   r   r   r   r0   r   r   r   r   <module>   s    	