o
    i8                     @  s(  d dl mZ d dlmZmZ d dlm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 d d	lmZmZ d d
lmZmZ d dlmZ d dlmZ d dlmZ d dl m!Z! e!e"Z#G dd deZ
G dd deZ$G dd de$ZG dd de$Z%G dd de$eeee
f Z&dS )    )annotations)Anycast)AuthContextMiddleware)BearerAuthBackend)AccessToken)AuthorizationCode OAuthAuthorizationServerProviderRefreshToken)TokenVerifier)create_auth_routes create_protected_resource_routes)ClientRegistrationOptionsRevocationOptions)
AnyHttpUrlField)
Middleware)AuthenticationMiddleware)Route)
get_loggerc                   @  s$   e Zd ZU dZeedZded< dS )r   z)AccessToken that includes all JWT claims.)default_factoryzdict[str, Any]claimsN)__name__
__module____qualname____doc__r   dictr   __annotations__ r   r   ^/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/fastmcp/server/auth/auth.pyr   $   s   
 r   c                   @  s\   e Zd ZdZ		ddddZdddZ	d d!ddZ	d d!ddZd"ddZd d#ddZ	dS )$AuthProvideraF  Base class for all FastMCP authentication providers.

    This class provides a unified interface for all authentication providers,
    whether they are simple token verifiers or full OAuth authorization servers.
    All providers must be able to verify tokens and can optionally provide
    custom authentication routes.
    Nbase_urlAnyHttpUrl | str | Nonerequired_scopeslist[str] | Nonec                 C  s&   t |tr	t|}|| _|pg | _dS )a4  
        Initialize the auth provider.

        Args:
            base_url: The base URL of this server (e.g., http://localhost:8000).
                This is used for constructing .well-known endpoints and OAuth metadata.
            required_scopes: List of OAuth scopes required for all requests.
        N)
isinstancestrr   r!   r#   selfr!   r#   r   r   r   __init__3   s   
zAuthProvider.__init__tokenr&   returnAccessToken | Nonec                   
   t d)a  Verify a bearer token and return access info if valid.

        All auth providers must implement token verification.

        Args:
            token: The token string to validate

        Returns:
            AccessToken object if valid, None if invalid or expired
        &Subclasses must implement verify_tokenNotImplementedErrorr(   r*   r   r   r   verify_tokenE   s   zAuthProvider.verify_tokenmcp_path
str | Nonelist[Route]c                 C  s   g S )a0  Get all routes for this authentication provider.

        This includes both well-known discovery routes and operational routes.
        Each provider is responsible for creating whatever routes it needs:
        - TokenVerifier: typically no routes (default implementation)
        - RemoteAuthProvider: protected resource metadata routes
        - OAuthProvider: full OAuth authorization server routes
        - Custom providers: whatever routes they need

        Args:
            mcp_path: The path where the MCP endpoint is mounted (e.g., "/mcp")
                This is used to advertise the resource URL in metadata, but the
                provider does not create the actual MCP endpoint route.

        Returns:
            List of all routes for this provider (excluding the MCP endpoint itself)
        r   )r(   r3   r   r   r   
get_routesR   s   zAuthProvider.get_routesc                 C  s   |  |}dd |D S )a  Get well-known discovery routes for this authentication provider.

        This is a utility method that filters get_routes() to return only
        well-known discovery routes (those starting with /.well-known/).

        Well-known routes provide OAuth metadata and discovery endpoints that
        clients use to discover authentication capabilities. These routes should
        be mounted at the root level of the application to comply with RFC 8414
        and RFC 9728.

        Common well-known routes:
        - /.well-known/oauth-authorization-server (authorization server metadata)
        - /.well-known/oauth-protected-resource/* (protected resource metadata)

        Args:
            mcp_path: The path where the MCP endpoint is mounted (e.g., "/mcp")
                This is used to construct path-scoped well-known URLs.

        Returns:
            List of well-known discovery routes (typically mounted at root level)
        c                 S  s&   g | ]}t |tr|jd r|qS )z/.well-known/)r%   r   path
startswith).0router   r   r   
<listcomp>   s    
z6AuthProvider.get_well_known_routes.<locals>.<listcomp>)r6   )r(   r3   
all_routesr   r   r   get_well_known_routesi   s   
z"AuthProvider.get_well_known_routeslistc                 C  s   t tt| dt tgS )zGet HTTP application-level middleware for this auth provider.

        Returns:
            List of Starlette Middleware instances to apply to the HTTP app
        )backend)r   r   r   r   )r(   r   r   r   get_middleware   s   zAuthProvider.get_middlewarer7   AnyHttpUrl | Nonec                 C  sD   | j du rdS |rt| j d}|d}t| d| S | j S )zGet the actual resource URL being protected.

        Args:
            path: The path where the resource endpoint is mounted (e.g., "/mcp")

        Returns:
            The full URL of the protected resource
        N/)r!   r&   rstriplstripr   )r(   r7   prefixsuffixr   r   r   _get_resource_url   s   
	
zAuthProvider._get_resource_urlNNr!   r"   r#   r$   r*   r&   r+   r,   Nr3   r4   r+   r5   )r+   r>   )r7   r4   r+   rA   )
r   r   r   r   r)   r2   r6   r=   r@   rG   r   r   r   r   r    *   s    


 r    c                      s2   e Zd ZdZ		dd fddZdddZ  ZS )r   zBase class for token verifiers (Resource Servers).

    This class provides token verification capability without OAuth server functionality.
    Token verifiers typically don't provide authentication routes by default.
    Nr!   r"   r#   r$   c                   s   t  j||d dS )z
        Initialize the token verifier.

        Args:
            base_url: The base URL of this server
            required_scopes: Scopes that are required for all requests
        r!   r#   N)superr)   r'   	__class__r   r   r)      s   zTokenVerifier.__init__r*   r&   r+   r,   c                   r-   )z6Verify a bearer token and return access info if valid.r.   r/   r1   r   r   r   r2      s   zTokenVerifier.verify_tokenrH   rI   rJ   )r   r   r   r   r)   r2   __classcell__r   r   rO   r   r      s    r   c                      sJ   e Zd ZU dZded< 		dd fddZdddZ	ddddZ  ZS )RemoteAuthProvidera&  Authentication provider for resource servers that verify tokens from known authorization servers.

    This provider composes a TokenVerifier with authorization server metadata to create
    standardized OAuth 2.0 Protected Resource endpoints (RFC 9728). Perfect for:
    - JWT verification with known issuers
    - Remote token introspection services
    - Any resource server that knows where its tokens come from

    Use this when you have token verification logic and want to advertise
    the authorization servers that issue valid tokens.
    r   r!   Ntoken_verifierr   authorization_serverslist[AnyHttpUrl]AnyHttpUrl | strresource_namer4   resource_documentationrA   c                   s.   t  j||jd || _|| _|| _|| _dS )a  Initialize the remote auth provider.

        Args:
            token_verifier: TokenVerifier instance for token validation
            authorization_servers: List of authorization servers that issue valid tokens
            base_url: The base URL of this server
            resource_name: Optional name for the protected resource
            resource_documentation: Optional documentation URL for the protected resource
        rM   N)rN   r)   r#   rS   rT   rW   rX   )r(   rS   rT   r!   rW   rX   rO   r   r   r)      s   
zRemoteAuthProvider.__init__r*   r&   r+   r,   c                   s   | j |I dH S )z1Verify token using the configured token verifier.N)rS   r2   r1   r   r   r   r2      s   zRemoteAuthProvider.verify_tokenr3   r5   c              	   C  s8   g }|  |}|r|t|| j| jj| j| jd |S )zfGet routes for this provider.

        Creates protected resource metadata routes (RFC 9728).
        )resource_urlrT   scopes_supportedrW   rX   )rG   extendr   rT   rS   r#   rW   rX   )r(   r3   routesrY   r   r   r   r6      s   

zRemoteAuthProvider.get_routesrH   )
rS   r   rT   rU   r!   rV   rW   r4   rX   rA   rJ   rK   rL   )	r   r   r   r   r   r)   r2   r6   rQ   r   r   rO   r   rR      s   
 
rR   c                      sL   e Zd ZdZddddddd fddZdddZ	dd fddZ  ZS ) OAuthProviderzOAuth Authorization Server provider.

    This class provides full OAuth server functionality including client registration,
    authorization flows, token issuance, and token verification.
    N)
issuer_urlservice_documentation_urlclient_registration_optionsrevocation_optionsr#   r!   rV   r^   r"   r_   r`    ClientRegistrationOptions | Nonera   RevocationOptions | Noner#   r$   c             	     s   t  j||d |du r| j| _nt|trt|| _n|| _| jdurE| jdurEt| jt| jkrEtd| j d| j d| j d t	|  t|trSt|}|| _
|| _|| _dS )a  
        Initialize the OAuth provider.

        Args:
            base_url: The public URL of this FastMCP server
            issuer_url: The issuer URL for OAuth metadata (defaults to base_url)
            service_documentation_url: The URL of the service documentation.
            client_registration_options: The client registration options.
            revocation_options: The revocation options.
            required_scopes: Scopes that are required for all requests.
        rM   NzOAuth endpoints at z, issuer at z3. Ensure well-known routes are accessible at root (zY/.well-known/). See: https://gofastmcp.com/deployment/http#mounting-authenticated-servers)rN   r)   r!   r^   r%   r&   r   loggerinfor	   r_   r`   ra   )r(   r!   r^   r_   r`   ra   r#   rO   r   r   r)     s(   






zOAuthProvider.__init__r*   r&   r+   r,   c                   s   |  |I dH S )aX  
        Verify a bearer token and return access info if valid.

        This method implements the TokenVerifier protocol by delegating
        to our existing load_access_token method.

        Args:
            token: The token string to validate

        Returns:
            AccessToken object if valid, None if invalid or expired
        N)load_access_tokenr1   r   r   r   r2   L  s   zOAuthProvider.verify_tokenr3   r4   r5   c                   s   | j dusJ | jdusJ t| | j | j| j| jd}| |}|rA| jr-| jjr-| jjn| j}t	|t
t| jg|d}|| |t | |S )at  Get OAuth authorization server routes and optional protected resource routes.

        This method creates the full set of OAuth routes including:
        - Standard OAuth authorization server routes (/.well-known/oauth-authorization-server, /authorize, /token, etc.)
        - Optional protected resource routes

        Returns:
            List of OAuth routes
        N)providerr^   r_   r`   ra   )rY   rT   rZ   )r!   r^   r   r_   r`   ra   rG   valid_scopesr#   r   r   r   r[   rN   r6   )r(   r3   oauth_routesrY   supported_scopesprotected_routesrO   r   r   r6   [  s2   
	

zOAuthProvider.get_routes)r!   rV   r^   r"   r_   r"   r`   rb   ra   rc   r#   r$   rJ   rK   rL   )r   r   r   r   r)   r2   r6   rQ   r   r   rO   r   r]     s    

5r]   N)'
__future__r   typingr   r   'mcp.server.auth.middleware.auth_contextr   &mcp.server.auth.middleware.bearer_authr   mcp.server.auth.providerr   _SDKAccessTokenr   r	   r
   r   TokenVerifierProtocolmcp.server.auth.routesr   r   mcp.server.auth.settingsr   r   pydanticr   r   starlette.middlewarer   #starlette.middleware.authenticationr   starlette.routingr   fastmcp.utilities.loggingr   r   rd   r    rR   r]   r   r   r   r   <module>   s0     
I