
    kKj0                        d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	 ddl
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  ee      Zed
   Z G d de      Zy)a!  OAuth 2.0 Token Introspection (RFC 7662) provider for FastMCP.

This module provides token verification for opaque tokens using the OAuth 2.0
Token Introspection protocol defined in RFC 7662. It allows FastMCP servers to
validate tokens issued by authorization servers that don't use JWT format.

Example:
    ```python
    from fastmcp import FastMCP
    from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier

    # Verify opaque tokens via RFC 7662 introspection
    verifier = IntrospectionTokenVerifier(
        introspection_url="https://auth.example.com/oauth/introspect",
        client_id="your-client-id",
        client_secret="your-client-secret",
        required_scopes=["read", "write"]
    )

    mcp = FastMCP("My Protected Server", auth=verifier)
    ```
    )annotationsN)AnyLiteralget_args)
AnyHttpUrl	SecretStr)AccessTokenTokenVerifier)parse_scopes)
get_logger)
TokenCache)client_secret_basicclient_secret_postc                  t     e Zd ZdZdddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
 fdZddZddZdd	Z xZS )IntrospectionTokenVerifiera  
    OAuth 2.0 Token Introspection verifier (RFC 7662).

    This verifier validates opaque tokens by calling an OAuth 2.0 token introspection
    endpoint. Unlike JWT verification which is stateless, token introspection requires
    a network call to the authorization server for each token validation.

    The verifier authenticates to the introspection endpoint using either:
    - HTTP Basic Auth (client_secret_basic, default): credentials in Authorization header
    - POST body authentication (client_secret_post): credentials in request body

    Both methods are specified in RFC 6749 (OAuth 2.0) and RFC 7662 (Token Introspection).

    Use this when:
    - Your authorization server issues opaque (non-JWT) tokens
    - You need to validate tokens from Auth0, Okta, Keycloak, or other OAuth servers
    - Your tokens require real-time revocation checking
    - Your authorization server supports RFC 7662 introspection

    Caching is disabled by default to preserve real-time revocation semantics.
    Set ``cache_ttl_seconds`` to enable caching and reduce load on the
    introspection endpoint (e.g., ``cache_ttl_seconds=300`` for 5 minutes).

    Example:
        ```python
        verifier = IntrospectionTokenVerifier(
            introspection_url="https://auth.example.com/oauth/introspect",
            client_id="my-service",
            client_secret="secret-key",
            required_scopes=["api:read"]
        )
        ```
    r   
   N)client_auth_methodtimeout_secondsrequired_scopesbase_urlcache_ttl_secondsmax_cache_sizehttp_clientc       
           |t        |      nd}t        | 	  ||       || _        || _        t        |t              r|j                         n|| _        t        t              }||vr*dj                  d |D              }t        d|d| d      || _        || _        |
| _        t!        t"              | _        t'        ||	      | _        y)	a{  
        Initialize the introspection token verifier.

        Args:
            introspection_url: URL of the OAuth 2.0 token introspection endpoint
            client_id: OAuth client ID for authenticating to the introspection endpoint
            client_secret: OAuth client secret for authenticating to the introspection endpoint
            client_auth_method: Client authentication method. "client_secret_basic" (default)
                uses HTTP Basic Auth header, "client_secret_post" sends credentials in POST body
            timeout_seconds: HTTP request timeout in seconds (default: 10)
            required_scopes: Required scopes for all tokens (optional)
            base_url: Base URL for TokenVerifier protocol
            cache_ttl_seconds: How long to cache introspection results in seconds.
                Caching is disabled by default (None) to preserve real-time
                revocation semantics. Set to a positive integer to enable caching
                (e.g., 300 for 5 minutes).
            max_cache_size: Maximum number of tokens to cache when caching is
                enabled. Default: 10000.
            http_client: Optional httpx.AsyncClient for connection pooling. When provided,
                the client is reused across calls and the caller is responsible for its
                lifecycle. When None (default), a fresh client is created per call.
        N)r   r   z or c              3  (   K   | ]
  }d | d   yw)'N ).0ms     |/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/server/auth/providers/introspection.py	<genexpr>z6IntrospectionTokenVerifier.__init__.<locals>.<genexpr>   s     !BMqAaS(Ms   zInvalid client_auth_method: z
. Must be .)ttl_secondsmax_size)r   super__init__introspection_url	client_id
isinstancer   get_secret_valueclient_secretr   ClientAuthMethodjoin
ValueErrorr   r   _http_clientr   __name__loggerr   _cache)selfr'   r(   r+   r   r   r   r   r   r   r   parsed_required_scopesvalid_methodsoptions	__class__s                 r    r&   z#IntrospectionTokenVerifier.__init__P   s    L .=-HL)d 	 	(<RS!2" -3 **, 	 !!12]2kk!BM!BBG./A.D E")1&  5G.' * )#
    c                    | j                    d| j                   }t        j                  |j	                  d            j                  d      }d| S )z<Create HTTP Basic Auth header value from client credentials.:zutf-8zBasic )r(   r+   base64	b64encodeencodedecode)r3   credentialsencodeds      r    _create_basic_auth_headerz4IntrospectionTokenVerifier._create_basic_auth_header   sQ    ($*<*<)=>"";#5#5g#>?FFwOy!!r8   c                6   |j                  d      }|g S t        |t              r=|j                         D cg c]#  }|j	                         s|j	                         % c}S t        |t
              r|D cg c]  }|st        |       c}S g S c c}w c c}w )z
        Extract scopes from introspection response.

        RFC 7662 allows scopes to be returned as either:
        - A space-separated string in the 'scope' field
        - An array of strings in the 'scope' field (less common but valid)
        scope)getr)   strsplitstriplist)r3   introspection_responsescope_valuess       r    _extract_scopesz*IntrospectionTokenVerifier._extract_scopes   s     -009I k3''2'8'8':H':!aggiAGGI':HH k4($/5Kq1CFK55	 I 6s   BB7B?Bc           	       K   | j                   j                  |      \  }}|r| j                  j                  d       |S 	 | j                  t        j                  | j                        nt        j                  | j                        4 d{   }|dd}ddd}| j                  d	k(  r| j                         |d
<   n-| j                  dk(  r| j                  |d<   | j                  |d<   |j                  | j                  ||       d{   }|j                   dk7  rT| j                  j                  d|j                   |j"                  r|j"                  dd nd       	 ddd      d{    y|j%                         }|j                  dd      s-| j                  j                  d       	 ddd      d{    y|j                  d      xs |j                  dd      }	|j                  d      }
|
rE|
t'        j&                         k  r.| j                  j                  d|	       	 ddd      d{    y| j)                  |      }| j*                  r`t-        |      }t-        | j*                        }|j/                  |      s/| j                  j                  d||       	 ddd      d{    yt1        |t3        |	      ||
t5        |
      nd|      }| j                   j-                  ||       |cddd      d{    S 7 7 	7 7 ^7 7 h7 # 1 d{  7  sw Y   yxY w# t        j6                  $ r) | j                  j                  d| j                         Y yt        j8                  $ r&}| j                  j                  d|       Y d}~yd}~wt:        $ r&}| j                  j                  d|       Y d}~yd}~ww xY ww)az  
        Verify a bearer token using OAuth 2.0 Token Introspection (RFC 7662).

        This method makes a POST request to the introspection endpoint with the token,
        authenticated using the configured client authentication method (client_secret_basic
        or client_secret_post).

        Results are cached in-memory to reduce load on the introspection endpoint.
        Cache TTL and size are configurable via constructor parameters.

        Args:
            token: The opaque token string to validate

        Returns:
            AccessToken object if valid and active, None if invalid, inactive, or expired
        zToken introspection cache hitN)timeoutaccess_token)tokentoken_type_hintz!application/x-www-form-urlencodedzapplication/json)zContent-TypeAcceptr   Authorizationr   r(   r+   )dataheaders   z(Token introspection failed: HTTP %d - %s activeFz)Token introspection returned active=falsesubunknownexpz4Token validation failed: expired token for client %sz4Token missing required scopes. Has: %s, Required: %s)rP   r(   scopes
expires_atclaimsz.Token introspection timed out after %d secondsz&Token introspection request failed: %szToken introspection error: %s)r2   rD   r1   debugr/   
contextlibnullcontexthttpxAsyncClientr   r   rA   r(   r+   postr'   status_codetextjsontimerL   r   setissubsetr	   rE   intTimeoutExceptionRequestError	Exception)r3   rP   	is_cachedcached_resultclientrT   rU   responseintrospection_datar(   r[   r\   token_scopesr   resultes                   r    verify_tokenz'IntrospectionTokenVerifier.verify_token   s    $ $(;;??5#9 	=KK=>  g	 $$0 &&t'8'89&&t/C/CDE E  #'5 %H0 **.CC/3/M/M/OGO,,,0DD(,D%,0,>,>D)!'**# "- "  ''3.KK%%B ,,/7}}ds+"
  KE E EN &.]]_"
 *--h>KK%%&QR]E E Eb /22 >'++E9= 
 ),,U3TYY[())R%  $}E E EB --.@A ''#&v;L&)$*>*>&?O*33LA))R(+
  $]E E Eb %!)n!+.?s3x- v.sE E E01E E E E E E E Ev %% 	KK@$BVBV !! 	KKFJ 	KK=qA	sI  >O AL= LL= A<L(LAL('L= 2L3L= 7O 8>L(6L= LL= O A,L(3L= >L"?L= O A,L(0L= ;L$<L=  O AL(L= L&L= O L= L(L= L= "L= $L= &L= (L:.L1/L:6L= 9O :L= =9O6O 8O
N+&O +O7OO OO )r'   rE   r(   rE   r+   zstr | SecretStrr   r,   r   rk   r   zlist[str] | Noner   zAnyHttpUrl | str | Noner   
int | Noner   rx   r   zhttpx.AsyncClient | None)returnrE   )rI   zdict[str, Any]ry   z	list[str])rP   rE   ry   zAccessToken | None)	r0   
__module____qualname____doc__r&   rA   rL   rw   __classcell__)r7   s   @r    r   r   -   s     P 0E!,0,0(,%)04D
 D
 	D

 'D
 -D
 D
 *D
 *D
 &D
 #D
 .D
L".~r8   r   )r|   
__future__r   r;   r`   rh   typingr   r   r   rb   pydanticr   r   fastmcp.server.authr	   r
   fastmcp.utilities.authr   fastmcp.utilities.loggingr   fastmcp.utilities.token_cacher   r0   r1   r,   r   r   r8   r    <module>r      sV   . #    ) )  * : / 0 4	H	 FG D Dr8   