o
    i3                     @   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__	client_idaccess_tokenscopes)selfr   	__class__ l/var/www/html/karishye-ai-python/venv/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    verify_token
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   r3   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)r5   r6   r7   )r   r5   r6   r7   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  invalid_tokenzAuthentication required)status_codeerrordescriptionauthi  insufficient_scopezRequired scope: )r%   
isinstancer   _send_auth_errorr6   r   r5   )r   r8   r9   r:   	auth_userauth_credentialsrequired_scoper   r   r   __call__N   s    



zRequireAuthMiddleware.__call__r>   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?   error_descriptionzhttp.response.start)s   content-types   application/jsons   content-lengths   www-authenticate)typestatusr$   Nzhttp.response.body)rK   body)r7   appendjoinjsondumpsencodestrlen)	r   r:   r>   r?   r@   www_auth_partswww_authenticaterM   
body_bytesr   r   r   rD   b   s*   


z&RequireAuthMiddleware._send_auth_errorr   )r   r   r   r   r   listrS   r   r   r	   r   r
   rH   r/   rD   r   r   r   r   r4   4   s    
"r4   )rP   r0   typingr   pydanticr   starlette.authenticationr   r   r   starlette.requestsr   starlette.typesr   r	   r
   mcp.server.auth.providerr   r   r   r   r4   r   r   r   r   <module>   s    	