
    )`iQ                     @   d 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
Z
ddlZddlmZmZ ddlmZmZmZmZ ddlmZmZ  G d	 d
e          Zdedeegee         f         fdZ G d de          Z G d de          Z G d de          Z G d de          ZdS )a  
OAuth client credential extensions for MCP.

Provides OAuth providers for machine-to-machine authentication flows:
- ClientCredentialsOAuthProvider: For client_credentials with client_id + client_secret
- PrivateKeyJWTOAuthProvider: For client_credentials with private_key_jwt authentication
  (typically using a pre-built JWT from workload identity federation)
- RFC7523OAuthClientProvider: For jwt-bearer grant (RFC 7523 Section 2.1)
    N)	AwaitableCallable)AnyLiteral)uuid4)	BaseModelField)OAuthClientProviderOAuthFlowErrorOAuthTokenErrorTokenStorage)OAuthClientInformationFullOAuthClientMetadatac                        e Zd ZdZ	 	 ddededededed	         d
edz  ddf fdZddZde	j
        fdZde	j
        fdZ xZS )ClientCredentialsOAuthProvidera  OAuth provider for client_credentials grant with client_id + client_secret.

    This provider sets client_info directly, bypassing dynamic client registration.
    Use this when you already have client credentials (client_id and client_secret).

    Example:
        ```python
        provider = ClientCredentialsOAuthProvider(
            server_url="https://api.example.com",
            storage=my_token_storage,
            client_id="my-client-id",
            client_secret="my-client-secret",
        )
        ```
    client_secret_basicN
server_urlstorage	client_idclient_secrettoken_endpoint_auth_method)r   client_secret_postscopesreturnc                     t          ddg||          }t                                          |||ddd           t          d||dg||          | _        dS )a  Initialize client_credentials OAuth provider.

        Args:
            server_url: The MCP server URL.
            storage: Token storage implementation.
            client_id: The OAuth client ID.
            client_secret: The OAuth client secret.
            token_endpoint_auth_method: Authentication method for token endpoint.
                Either "client_secret_basic" (default) or "client_secret_post".
            scopes: Optional space-separated list of scopes to request.
        Nclient_credentialsredirect_urisgrant_typesr   scope     r@)r   r   r   r   r   r    )r   super__init__r   _fixed_client_info)	selfr   r   r   r   r   r   client_metadata	__class__s	           /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/mcp/client/auth/extensions/client_credentials.pyr#   z'ClientCredentialsOAuthProvider.__init__)   s~    * .-.'A	
 
 
 	_gtT5QQQ"<'-.'A#
 #
 #
    c                    K   | j         j                                         d{V | j         _        | j        | j         _        d| _        dS z6Load stored tokens and set pre-configured client_info.NTcontextr   
get_tokenscurrent_tokensr$   client_info_initializedr%   s    r(   _initializez*ClientCredentialsOAuthProvider._initializeO   N      ,0L,@,K,K,M,M&M&M&M&M&M&M##'#:  r)   c                 :   K   |                                   d{V S )z)Perform client_credentials authorization.N"_exchange_token_client_credentialsr2   s    r(   _perform_authorizationz5ClientCredentialsOAuthProvider._perform_authorizationU   *      <<>>>>>>>>>r)   c                 t  K   ddi}ddi}| j                             ||          \  }}| j                             | j         j                  r| j                                         |d<   | j         j        j        r| j         j        j        |d<   |                                 }t          j	        d|||          S )	z:Build token exchange request for client_credentials grant.
grant_typer   Content-Type!application/x-www-form-urlencodedresourcer    POSTdataheaders)
r-   prepare_token_authshould_include_resource_paramprotocol_versionget_resource_urlr&   r    _get_token_endpointhttpxRequestr%   
token_datarB   	token_urls       r(   r7   zAClientCredentialsOAuthProvider._exchange_token_client_credentialsY   s       .&

 $23V"W #l==j'RR
G<55dl6STT 	E%)\%B%B%D%DJz"<'- 	E"&,">"DJw,,..	}VYZQQQQr)   )r   Nr   N)__name__
__module____qualname____doc__strr   r   r#   r3   rH   rI   r8   r7   __classcell__r'   s   @r(   r   r      s         , \q!$
 $
$
 $
 	$

 $
 %,,W$X$
 d
$
 
$
 $
 $
 $
 $
 $
L! ! ! !?em ? ? ? ?R%- R R R R R R R Rr)   r   tokenr   c                 0     dt           dt           f fd}|S )a  Create an assertion provider that returns a static JWT token.

    Use this when you have a pre-built JWT (e.g., from workload identity federation)
    that doesn't need the audience parameter.

    Example:
        ```python
        provider = PrivateKeyJWTOAuthProvider(
            server_url="https://api.example.com",
            storage=my_token_storage,
            client_id="my-client-id",
            assertion_provider=static_assertion_provider(my_prebuilt_jwt),
        )
        ```

    Args:
        token: The pre-built JWT assertion string.

    Returns:
        An async callback suitable for use as an assertion_provider.
    audiencer   c                    K   S N )rW   rU   s    r(   providerz+static_assertion_provider.<locals>.provider   s      r)   rR   )rU   r[   s   ` r(   static_assertion_providerr]   n   s6    .        Or)   c                   &   e Zd ZU dZ ed          Zeed<    ed          Zeed<    ed          Z	eed<    ed	d
          Z
eed<    edd          Zeed<    edd          Zeeef         dz  ed<   deegee         f         fdZdS )SignedJWTParametersa  Parameters for creating SDK-signed JWT assertions.

    Use `create_assertion_provider()` to create an assertion provider callback
    for use with `PrivateKeyJWTOAuthProvider`.

    Example:
        ```python
        jwt_params = SignedJWTParameters(
            issuer="my-client-id",
            subject="my-client-id",
            signing_key=private_key_pem,
        )
        provider = PrivateKeyJWTOAuthProvider(
            server_url="https://api.example.com",
            storage=my_token_storage,
            client_id="my-client-id",
            assertion_provider=jwt_params.create_assertion_provider(),
        )
        ```
    z0Issuer for JWT assertions (typically client_id).)descriptionissuerz<Subject identifier for JWT assertions (typically client_id).subjectz)Private key for JWT signing (PEM format).signing_keyRS256%Algorithm for signing JWT assertions.defaultr`   signing_algorithm,  %Lifetime of generated JWT in seconds.lifetime_secondsNzAdditional claims.additional_claimsr   c                 0     dt           dt           f fd}|S )zCreate an assertion provider callback for use with PrivateKeyJWTOAuthProvider.

        Returns:
            An async callback that takes the audience (authorization server issuer URL)
            and returns a signed JWT assertion.
        rW   r   c           	      4  K   t          t          j                              }j        j        | |j        z   |t          t                                d}j        r|                    j                   t          j
        |j        j                  S )Nisssubaudexpiatjti	algorithm)inttimera   rb   rk   rR   r   rl   updatejwtencoderc   rh   )rW   nowclaimsr%   s      r(   r[   z?SignedJWTParameters.create_assertion_provider.<locals>.provider   s      dikk""C{|T22577||& &F % 6d4555:fd&6$BXYYYYr)   r\   )r%   r[   s   ` r(   create_assertion_providerz-SignedJWTParameters.create_assertion_provider   s>    	ZS 	ZS 	Z 	Z 	Z 	Z 	Z 	Z r)   )rN   rO   rP   rQ   r	   ra   rR   __annotations__rb   rc   rh   rk   rx   rl   dictr   r   r   r   rZ   r)   r(   r_   r_      s         * %$VWWWFCWWW5%cdddGSdddu)TUUUKUUU"U7@ghhhshhh!E#;bccccccc/4uTOc/d/d/dtCH~,ddd8SE9S>4I+J      r)   r_   c                        e Zd ZdZ	 ddedededeegee         f         dedz  ddf fd	Zdd
Z	de
j        fdZdeeef         ddfdZde
j        fdZ xZS )PrivateKeyJWTOAuthProvideraq  OAuth provider for client_credentials grant with private_key_jwt authentication.

    Uses RFC 7523 Section 2.2 for client authentication via JWT assertion.

    The JWT assertion's audience MUST be the authorization server's issuer identifier
    (per RFC 7523bis security updates). The `assertion_provider` callback receives
    this audience value and must return a JWT with that audience.

    **Option 1: Pre-built JWT via Workload Identity Federation**

    In production scenarios, the JWT assertion is typically obtained from a workload
    identity provider (e.g., GCP, AWS IAM, Azure AD):

        ```python
        async def get_workload_identity_token(audience: str) -> str:
            # Fetch JWT from your identity provider
            # The JWT's audience must match the provided audience parameter
            return await fetch_token_from_identity_provider(audience=audience)

        provider = PrivateKeyJWTOAuthProvider(
            server_url="https://api.example.com",
            storage=my_token_storage,
            client_id="my-client-id",
            assertion_provider=get_workload_identity_token,
        )
        ```

    **Option 2: Static pre-built JWT**

    If you have a static JWT that doesn't need the audience parameter:

        ```python
        provider = PrivateKeyJWTOAuthProvider(
            server_url="https://api.example.com",
            storage=my_token_storage,
            client_id="my-client-id",
            assertion_provider=static_assertion_provider(my_prebuilt_jwt),
        )
        ```

    **Option 3: SDK-signed JWT (for testing/simple setups)**

    For testing or simple deployments, use `SignedJWTParameters.create_assertion_provider()`:

        ```python
        jwt_params = SignedJWTParameters(
            issuer="my-client-id",
            subject="my-client-id",
            signing_key=private_key_pem,
        )
        provider = PrivateKeyJWTOAuthProvider(
            server_url="https://api.example.com",
            storage=my_token_storage,
            client_id="my-client-id",
            assertion_provider=jwt_params.create_assertion_provider(),
        )
        ```
    Nr   r   r   assertion_providerr   r   c                     t          ddgd|          }t                                          |||ddd           || _        t	          d|dgd|          | _        dS )a  Initialize private_key_jwt OAuth provider.

        Args:
            server_url: The MCP server URL.
            storage: Token storage implementation.
            client_id: The OAuth client ID.
            assertion_provider: Async callback that takes the audience (authorization
                server's issuer identifier) and returns a JWT assertion. Use
                `SignedJWTParameters.create_assertion_provider()` for SDK-signed JWTs,
                `static_assertion_provider()` for pre-built JWTs, or provide your own
                callback for workload identity federation.
            scopes: Optional space-separated list of scopes to request.
        Nr   private_key_jwtr   r!   )r   r   r   r   r    )r   r"   r#   _assertion_providerr   r$   )r%   r   r   r   r   r   r&   r'   s          r(   r#   z#PrivateKeyJWTOAuthProvider.__init__   s    , .-.'8	
 
 
 	_gtT5QQQ#5 "<-.'8#
 #
 #
r)   c                    K   | j         j                                         d{V | j         _        | j        | j         _        d| _        dS r+   r,   r2   s    r(   r3   z&PrivateKeyJWTOAuthProvider._initialize%  r4   r)   c                 :   K   |                                   d{V S )z>Perform client_credentials authorization with private_key_jwt.Nr6   r2   s    r(   r8   z1PrivateKeyJWTOAuthProvider._perform_authorization+  r9   r)   rK   c                   K   | j         j        st          d          t          | j         j        j                  }|                     |           d{V }||d<   d|d<   dS )IAdd JWT assertion for client authentication to token endpoint parameters./Missing OAuth metadata for private_key_jwt flowNclient_assertion6urn:ietf:params:oauth:client-assertion-type:jwt-bearerclient_assertion_type)r-   oauth_metadatar   rR   ra   r   )r%   rK   rW   	assertions       r(   _add_client_authentication_jwtz9PrivateKeyJWTOAuthProvider._add_client_authentication_jwt/  s}      |* 	T !RSSS t|29::228<<<<<<<<	 *3
%&.f
*+++r)   c                 p  K   ddi}ddi}|                      |           d{V  | j                            | j        j                  r| j                                        |d<   | j        j        j        r| j        j        j        |d<   |                                 }t          j	        d	|||
          S )zOBuild token exchange request for client_credentials grant with private_key_jwt.r;   r   r<   r=   rK   Nr>   r    r?   r@   )
r   r-   rD   rE   rF   r&   r    rG   rH   rI   rJ   s       r(   r7   z=PrivateKeyJWTOAuthProvider._exchange_token_client_credentials=  s       .&

 $23V"W 11Z1HHHHHHHHH<55dl6STT 	E%)\%B%B%D%DJz"<'- 	E"&,">"DJw,,..	}VYZQQQQr)   rY   rM   )rN   rO   rP   rQ   rR   r   r   r   r#   r3   rH   rI   r8   r   r   r   r7   rS   rT   s   @r(   r   r      s)       9 9B "%
 %
%
 %
 	%

 %cUIcN%:;%
 d
%
 
%
 %
 %
 %
 %
 %
N! ! ! !?em ? ? ? ?g$sCx. gUY g g g gR%- R R R R R R R Rr)   r   c                      e Zd ZU dZ edd          Zedz  ed<    edd          Zedz  ed<    edd          Z	edz  ed	<    edd
          Z
edz  ed<    edd          Zeeef         dz  ed<    edd          Zedz  ed<    edd          Zedz  ed<    edd          Zeed<   ddedz  defdZdS )JWTParameterszJWT parameters.NzeJWT assertion for JWT authentication. Will be used instead of generating a new assertion if provided.rf   r   zIssuer for JWT assertions.ra   z&Subject identifier for JWT assertions.rb   zAudience for JWT assertions.rW   z%Additional claims for JWT assertions.r~   rd   re   jwt_signing_algorithmzPrivate key for JWT signing.jwt_signing_keyri   rj   jwt_lifetime_secondswith_audience_fallbackr   c           	         | j         | j         }n| j        st          d          | j        st          d          | j        st          d          | j        r| j        n|}|st          d          t          t          j                              }| j        | j        ||| j        z   |t          t                                d}|                    | j        pi            t          j        || j        | j        pd          }|S )Nz(Missing signing key for JWT bearer grantz#Missing issuer for JWT bearer grantz$Missing subject for JWT bearer grantz%Missing audience for JWT bearer grantro   rd   rv   )r   r   r   ra   rb   rW   rx   ry   r   rR   r   rz   r~   r{   r|   r   )r%   r   r   rW   r}   r~   s         r(   to_assertionzJWTParameters.to_assertionc  s!   >%II' Q$%OPPP; L$%JKKK< M$%KLLL(,Qt}};QH N$%LMMMdikk""C{|T66577||& &F MM$++,,,
$4?  I
 r)   rY   )rN   rO   rP   rQ   r	   r   rR   r   ra   rb   rW   r~   r   r   r   r   r   rx   r   rZ   r)   r(   r   r   R  s        !EJ  IsTz    t9UVVVFC$JVVV%:bcccGS4Zccc 5;YZZZHcDjZZZ$)E$Dk$l$l$lFDcNT!lll(-gKr(s(s(s3:sss"'%B`"a"a"aOS4Zaaa %c?f g g g#ggg   3:              r)   r   c                   >    e Zd ZdZ	 	 	 	 ddedededeeged         f         dz  deg ee	eedz  f                  f         dz  d	e
d
edz  ddf fdZdddededeeef         dz  dej        f fdZdej        f fdZdeeef         fdZdej        fdZ xZS )RFC7523OAuthClientProvidera  OAuth client provider for RFC 7523 jwt-bearer grant.

    .. deprecated::
        Use :class:`ClientCredentialsOAuthProvider` for client_credentials with
        client_id + client_secret, or :class:`PrivateKeyJWTOAuthProvider` for
        client_credentials with private_key_jwt authentication instead.

    This provider supports the jwt-bearer authorization grant (RFC 7523 Section 2.1)
    where the JWT itself is the authorization grant.
    Nr!   r   r&   r   redirect_handlercallback_handlertimeoutjwt_parametersr   c                     dd l }|                    dt          d           t                                          ||||||           || _        d S )Nr   zsRFC7523OAuthClientProvider is deprecated. Use ClientCredentialsOAuthProvider or PrivateKeyJWTOAuthProvider instead.   )
stacklevel)warningswarnDeprecationWarningr"   r#   r   )
r%   r   r&   r   r   r   r   r   r   r'   s
            r(   r#   z#RFC7523OAuthClientProvider.__init__  si     	5	 	 	
 	
 	
 	_g?OQacjkkk,r)   r   	auth_codecode_verifierrK   c                   K   |pi }| j         j        j        dk    r|                     |           t	                                          |||           d{V S )z9Build token exchange request for authorization_code flow.r   r   N)r-   r&   r   r   r"   "_exchange_token_authorization_code)r%   r   r   rK   r'   s       r(   r   z=RFC7523OAuthClientProvider._exchange_token_authorization_code  sp        %2
<'BFWWW//:/FFFWW??	=eo?pppppppppr)   c                    K   d| j         j        j        v r|                                  d{V }|S t	                                                       d{V S )zPerform the authorization flow.+urn:ietf:params:oauth:grant-type:jwt-bearerN)r-   r&   r   _exchange_token_jwt_bearerr"   r8   )r%   token_requestr'   s     r(   r8   z1RFC7523OAuthClientProvider._perform_authorization  sk      8DL<X<ddd"&"A"A"C"CCCCCCCM  77999999999r)   c                &   | j         st          d          | j        j        st          d          t	          | j        j        j                  }| j                             |          }||d<   d|d<   | j                                        |d<   dS )	r   z/Missing JWT parameters for private_key_jwt flowr   r   r   r   r   rW   N)r   r   r-   r   rR   ra   r   rF   )r%   rK   ra   r   s       r(   r   z9RFC7523OAuthClientProvider._add_client_authentication_jwt  s    " 	U!"STTT|* 	U!"STTT T\0788'44F4SS	 *3
%&.f
*+ "&!>!>!@!@
:r)   c                 @  K   | j         j        st          d          | j        st          d          | j         j        st          d          t          | j         j        j                  }| j                            |          }d|d}| j         	                    | j         j
                  r| j                                         |d<   | j         j        j        r| j         j        j        |d<   |                                 }t          j        d	||d
di          S )z2Build token exchange request for JWT bearer grant.zMissing client infozMissing JWT parameterszMissing OAuth metadatar   r   )r;   r   r>   r    r?   r<   r=   r@   )r-   r0   r   r   r   r   rR   ra   r   rD   rE   rF   r&   r    rG   rH   rI   )r%   ra   r   rK   rL   s        r(   r   z5RFC7523OAuthClientProvider._exchange_token_jwt_bearer  s1     |' 	8 !6777" 	; !9:::|* 	<!":;;; T\0788'44F4SS	 H"
 


 <55dl6STT 	E%)\%B%B%D%DJz"<'- 	E"&,">"DJw,,..	}IJIl8m
 
 
 	
r)   )NNr!   N)rN   rO   rP   rQ   rR   r   r   r   r   tuplefloatr   r#   r   r   rH   rI   r   r8   r   r   rS   rT   s   @r(   r   r     s       	 	  EISW/3- -- -- 	-
 #C5)D/#9:TA- #2ysC$J1G'H#HIDP- - &,- 
- - - - - -, Z^q q qq-0qAEc3hRVAVq	q q q q q q:em : : : : : :ADcN A A A A&
%- 
 
 
 
 
 
 
 
r)   r   )rQ   ry   collections.abcr   r   typingr   r   uuidr   rH   r{   pydanticr   r	   mcp.client.authr
   r   r   r   mcp.shared.authr   r   r   rR   r]   r_   r   r   r   rZ   r)   r(   <module>r      s     / / / / / / / /                



 % % % % % % % % ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ K K K K K K K KSR SR SR SR SR%8 SR SR SRlS XseYs^6K-L    :4 4 4 4 4) 4 4 4nMR MR MR MR MR!4 MR MR MR`1 1 1 1 1I 1 1 1ha
 a
 a
 a
 a
!4 a
 a
 a
 a
 a
r)   