o
    i                     @  s   d 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	 ddl
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dZedddZedddZddddddZG dd dZdS )a"  JWT token issuance and verification for FastMCP OAuth Proxy.

This module implements the token factory pattern for OAuth proxies, where the proxy
issues its own JWT tokens to clients instead of forwarding upstream provider tokens.
This maintains proper OAuth 2.0 token audience boundaries.
    )annotationsN)Anyoverload)JsonWebToken)	JoseError)hashes)HKDF)
PBKDF2HMAC)
get_loggeri@B high_entropy_materialstrsaltreturnbytesc                 C     dS )zHDerive JWT signing key from a high-entropy key material and server salt.N )r   r   r   r   d/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/fastmcp/server/auth/jwt_issuer.pyderive_jwt_key       r   low_entropy_materialc                 C  r   )zGDerive JWT signing key from a low-entropy key material and server salt.Nr   )r   r   r   r   r   r       r   )r   r   
str | Nonec                 C  s   | dur|durt d| dur'tt d| ddj|  d}t|S |durBtt d| t	dj| d}t|S t d)	zWDerive JWT signing key from a high-entropy or low-entropy key material and server salt.NzSEither high_entropy_material or low_entropy_material must be provided, but not both    s   Fernet)	algorithmlengthr   info)key_material)r   r   r   
iterationszEEither high_entropy_material or low_entropy_material must be provided)

ValueErrorr   r   SHA256encodederivebase64urlsafe_b64encoder	   KDF_ITERATIONS)r   r   r   derived_keypbkdf2r   r   r   r   %   s6   

c                   @  s<   e Zd ZdZdddZ		ddddZdddZdddZdS )	JWTIssuera  Issues and validates FastMCP-signed JWT tokens using HS256.

    This issuer creates JWT tokens for MCP clients with proper audience claims,
    maintaining OAuth 2.0 token boundaries. Tokens are signed with HS256 using
    a key derived from the upstream client secret.
    issuerr   audiencesigning_keyr   c                 C  s"   || _ || _|| _tdg| _dS )zInitialize JWT issuer.

        Args:
            issuer: Token issuer (FastMCP server base URL)
            audience: Token audience (typically {base_url}/mcp)
            signing_key: HS256 signing key (32 bytes)
        HS256N)r'   r(   _signing_keyr   _jwt)selfr'   r(   r)   r   r   r   __init__R   s   zJWTIssuer.__init__  	client_idscopes	list[str]jti
expires_inintr   c           
      C  st   t t }ddd}| j| j|d||| ||d}| j||| j}|d}	t	
d||dd	 |d
  |	S )a  Issue a minimal FastMCP access token.

        FastMCP tokens are reference tokens containing only the minimal claims
        needed for validation and lookup. The JTI maps to the upstream token
        which contains actual user identity and authorization data.

        Args:
            client_id: MCP client ID
            scopes: Token scopes
            jti: Unique token identifier (maps to upstream token)
            expires_in: Token lifetime in seconds

        Returns:
            Signed JWT token
        r*   JWTalgtyp )issaudr0   scopeexpiatr3   utf-8z/Issued access token for client=%s jti=%s exp=%dN   r>   r5   timer'   r(   joinr,   r   r+   decodeloggerdebug
r-   r0   r1   r3   r4   nowheaderpayloadtoken_bytestokenr   r   r   issue_access_tokend   s&   



zJWTIssuer.issue_access_tokenc           
   	   C  sv   t t }ddd}| j| j|d||| ||dd}| j||| j}|d}	t	
d||d	d
 |d  |	S )a7  Issue a minimal FastMCP refresh token.

        FastMCP refresh tokens are reference tokens containing only the minimal
        claims needed for validation and lookup. The JTI maps to the upstream
        token which contains actual user identity and authorization data.

        Args:
            client_id: MCP client ID
            scopes: Token scopes
            jti: Unique token identifier (maps to upstream token)
            expires_in: Token lifetime in seconds (should match upstream refresh expiry)

        Returns:
            Signed JWT token
        r*   r6   r7   r:   refresh)r;   r<   r0   r=   r>   r?   r3   	token_user@   z0Issued refresh token for client=%s jti=%s exp=%dNrA   r>   rB   rH   r   r   r   issue_refresh_token   s(   


zJWTIssuer.issue_refresh_tokenrM   dict[str, Any]c              
   C  s   zL| j || j}|d}|r|t k rtd td|d| jkr0td td|d| j	krAtd td	td
|d |W S  ty_ } ztd|  d}~ww )a3  Verify and decode a FastMCP token.

        Validates JWT signature, expiration, issuer, and audience.

        Args:
            token: JWT token to verify

        Returns:
            Decoded token payload

        Raises:
            JoseError: If token is invalid, expired, or has wrong claims
        r>   zToken expiredzToken has expiredr;   zToken has invalid issuerzInvalid token issuerr<   zToken has invalid audiencezInvalid token audiencez*Token verified successfully for subject=%ssubzToken validation failed: %sN)
r,   rE   r+   getrC   rF   rG   r   r'   r(   )r-   rM   rK   r>   er   r   r   verify_token   s*   




zJWTIssuer.verify_tokenN)r'   r   r(   r   r)   r   )r/   )
r0   r   r1   r2   r3   r   r4   r5   r   r   )rM   r   r   rR   )__name__
__module____qualname____doc__r.   rN   rQ   rV   r   r   r   r   r&   J   s    

/0r&   )r   r   r   r   r   r   )r   r   r   r   r   r   )r   r   r   r   r   r   r   r   )rZ   
__future__r   r!   rC   typingr   r   authlib.joser   authlib.jose.errorsr   cryptography.hazmat.primitivesr   'cryptography.hazmat.primitives.kdf.hkdfr   )cryptography.hazmat.primitives.kdf.pbkdf2r	   fastmcp.utilities.loggingr
   rW   rF   r#   r   r&   r   r   r   r   <module>   s*    %