
    k7i                        S r SSKJr  SSKrSSKrSSKJrJr  SSKJ	r	  SSK
Jr  SSKJr  SSKJr  SS	KJr  SS
KJr  \" \5      rSr\SS j5       r\SS j5       rSSS.       SS jjr " S S5      rg)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 c                    g)zHDerive JWT signing key from a high-entropy key material and server salt.N )high_entropy_materialsalts     X/home/james-whalen/.local/lib/python3.13/site-packages/fastmcp/server/auth/jwt_issuer.pyderive_jwt_keyr              c                    g)zGDerive JWT signing key from a low-entropy key material and server salt.Nr   )low_entropy_materialr   s     r   r   r       r   r   )r   r   c                   U b  Ub  [        S5      eU b^  [        [        R                  " 5       SUR	                  5       SS9R                  U R	                  5       S9n[        R                  " U5      $ Ubb  [        [        R                  " 5       SUR	                  5       [        S9R                  UR	                  5       S9n[        R                  " U5      $ [        S5      e)zWDerive JWT signing key from a high-entropy or low-entropy key material and server salt.zSEither 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pbkdf2s        r   r   r   %   s     (-A-Ma
 	
 (mmo	

 &3::<&
= 	 ''44'mmo%	

 &299;&
< 	 ''//
O r   c                  x    \ rS rSrSr      S	S jr S
         SS jjr          SS jrSS jrSr	g)	JWTIssuerJ   a  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.
c                J    Xl         X l        X0l        [        S/5      U l        g)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)issueraudience_signing_keyr   _jwt)selfr+   r,   signing_keys       r   __init__JWTIssuer.__init__R   s"      ' '+	r   c                T   [        [        R                  " 5       5      nSSS.nU R                  U R                  USR	                  U5      XT-   UUS.nU R
                  R                  XgU R                  5      nUR                  S5      n	[        R                  SUUSS	 US
   5        U	$ )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aud	client_idscopeexpiatjtiutf-8z/Issued access token for client=%s jti=%s exp=%dN   r=   inttimer+   r,   joinr.   r   r-   decodeloggerdebug
r/   r;   scopesr?   
expires_innowheaderpayloadtoken_bytestokens
             r   issue_access_tokenJWTIssuer.issue_access_tokend   s    , $))+ /;;=="XXf%#
 ii&&v8I8IJ""7+=GEN		
 r   c           	     V   [        [        R                  " 5       5      nSSS.nU R                  U R                  USR	                  U5      XT-   UUSS.nU R
                  R                  XgU R                  5      nUR                  S5      n	[        R                  SUUS	S
 US   5        U	$ )a  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*   r4   r5   r8   refresh)r9   r:   r;   r<   r=   r>   r?   	token_user@   z0Issued refresh token for client=%s jti=%s exp=%dNrA   r=   rB   rI   s
             r   issue_refresh_tokenJWTIssuer.issue_refresh_token   s    , $))+ /;;=="XXf%#"	
 ii&&v8I8IJ""7+>GEN		
 r   c                    U R                   R                  XR                  5      nUR                  S5      nU(       a9  U[        R                  " 5       :  a   [
        R                  S5        [        S5      eUR                  S5      U R                  :w  a   [
        R                  S5        [        S5      eUR                  S5      U R                  :w  a   [
        R                  S5        [        S	5      e[
        R                  S
UR                  S5      5        U$ ! [         a  n[
        R                  SU5        e SnAff = f)zVerify 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 expiredr9   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.   rF   r-   getrD   rG   rH   r   r+   r,   )r/   rP   rN   r=   es        r   verify_tokenJWTIssuer.verify_token   s    	ii&&u.?.?@G ++e$CsTYY[(_- 344 {{5!T[[078 677 {{5!T]]29: 899LL<gkk%>P N 	LL6:	s   DD 
E'D>>E)r.   r-   r,   r+   N)r+   strr,   r^   r0   bytes)i  )
r;   r^   rJ   z	list[str]r?   r^   rK   rC   returnr^   )rP   r^   r`   zdict[str, Any])
__name__
__module____qualname____firstlineno____doc__r1   rQ   rV   r\   __static_attributes__r   r   r   r'   r'   J   s    ,, , 	,. -- - 	-
 - 
-^.. . 	.
 . 
.`)r   r'   )r   r^   r   r^   r`   r_   )r   r^   r   r^   r`   r_   )r   
str | Noner   rg   r   r^   r`   r_   )re   
__future__r   r!   rD   typingr   r   authlib.joser   authlib.jose.errorsr   cryptography.hazmat.primitivesr   'cryptography.hazmat.primitives.kdf.hkdfr	   )cryptography.hazmat.primitives.kdf.pbkdf2r
   fastmcp.utilities.loggingr   ra   rG   r#   r   r'   r   r   r   <module>rp      s    #     % ) 1 8 @ 0	H	 
S 
S 
R 
R )-'+"%" %" 	"
 "Jb br   