
    lKjO$                         d dl 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
 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 d
dlmZ d
dlmZ ddlmZ  e j0                  e      ZdZ G d dee      Zy)    N)jwk)jws)jwt)	JoseError)to_bytes)import_any_key)
json_loads)	deprecate   )	BaseGrant)InvalidClientError)InvalidGrantError)InvalidRequestError)TokenEndpointMixin)UnauthorizedClientError   sign_jwt_bearer_assertionz+urn:ietf:params:oauth:grant-type:jwt-bearerc                       e Zd ZeZddiddiddidZdZe	 	 	 	 dd       Zde	j                  fdZd	 Zd
efdZd Zd Zd Zdej&                  ej(                  z  fdZd Zd Zd Zy)JWTBearerGrant	essentialT)issaudexp<   Nc           	      &    t        | ||||||fi |S )Nr   )keyissueraudiencesubject	issued_at
expires_atclaimskwargss           r/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/authlib/oauth2/rfc7523/jwt_bearer.pysignzJWTBearerGrant.sign(   s(     )7Iz6
MS
 	
    r#   c                 `   t        | j                        }| j                         }|r	d|d|d<   nt        dd       t	        j
                  d
d| j                  i|}	 |j                  |       y # t        $ r2}t        j                  d|       t        |j                  	      |d }~ww xY w)NT)r   valuesr   zX'get_audiences' must return a non-empty list. Audience validation will become mandatory.1.8versionleewayAssertion Error: %rdescription )dictCLAIMS_OPTIONSget_audiencesr
   r   JWTClaimsRegistryLEEWAYvalidater   logdebugr   r0   )selfr#   options	audiencesclaims_requestses         r%   verify_claimszJWTBearerGrant.verify_claims7   s    t**+&&(	+/9EGEN= //Nt{{NgN	F$$V, 	FII+Q/#>AE	Fs    A2 2	B-;-B((B-c                 F   | j                  |      \  }}| j                  |d         }t        | d      r*t        | j	                  |||            }t        dd       nt        | j                  |            }	 t        j                  ||      }| j                  |j                          |j                   S # t        $ r2}t        j                  d|       t        |j                        |d}~wt        $ r'}t        j                  d|       t        d	      dd}~ww xY w)
a#  Extract JWT payload claims from request "assertion", per
        `Section 3.1`_.

        :param assertion: assertion string value in the request
        :return: JWTClaims
        :raise: InvalidGrantError

        .. _`Section 3.1`: https://tools.ietf.org/html/rfc7523#section-3.1
        r   resolve_client_keyz<Use resolve_client_public_key instead of resolve_client_key.r*   r+   r.   r/   NzInvalid JWT assertion)extract_assertionresolve_issuer_clienthasattrr   rA   r
   resolve_client_public_keyr   decoder   r8   r9   r   r0   
ValueErrorr?   r#   )r:   	assertionheadersr#   clientr   tokenr>   s           r%   process_assertion_claimsz'JWTBearerGrant.process_assertion_claimsJ   s    00;++F5M:4-. !8!8&!QRCN
 !!?!?!GHC	GJJy#.E 	5<<(||  	FII+Q/#>AE 	GII+Q/#$;<$F	Gs$   :B7 7	D  -C--D 9"DD rH   c                     t        j                  t        |            }	 t        |j                        }|j                         |fS # t
        $ r t        d      d w xY w)NzInvalid JWT payload.r/   )r   extract_compactr   r	   payloadrG   r   rI   )r:   rH   objr#   s       r%   rB   z JWTBearerGrant.extract_assertionl   s_    !!(9"56	R,F {{}f$$  	R#0FGTQ	Rs   A Ac                 z   | j                   j                  j                  d      }|st        d      | j	                  |      }| j                  |d         }t        j                  d|       |j                  | j                        st        d| j                   d      || j                   _        | j                          |j                  d      }|rf| j                  |      }|st        d	      t        j                  d
||       | j                  ||      st!        d	      || j                   _        yy)a  The client makes a request to the token endpoint by sending the
        following parameters using the "application/x-www-form-urlencoded"
        format per `Section 2.1`_:

        grant_type
             REQUIRED.  Value MUST be set to
             "urn:ietf:params:oauth:grant-type:jwt-bearer".

        assertion
             REQUIRED.  Value MUST contain a single JWT.

        scope
            OPTIONAL.

        The following example demonstrates an access token request with a JWT
        as an authorization grant:

        .. code-block:: http

            POST /token.oauth2 HTTP/1.1
            Host: as.example.com
            Content-Type: application/x-www-form-urlencoded

            grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer
            &assertion=eyJhbGciOiJFUzI1NiIsImtpZCI6IjE2In0.
            eyJpc3Mi[...omitted for brevity...].
            J9l-ZhwP[...omitted for brevity...]

        .. _`Section 2.1`: https://tools.ietf.org/html/rfc7523#section-2.1
        rH   zMissing 'assertion' in requestr   zValidate token request of %sz0The client is not authorized to use 'grant_type='subz Invalid 'sub' value in assertionr/   z'Check client(%s) permission to User(%s)z,Client has no permission to access user dataN)requestformgetr   rL   rC   r8   r9   check_grant_type
GRANT_TYPEr   rJ   validate_requested_scopeauthenticate_userr   has_granted_permissionr   user)r:   rH   r#   rJ   r    r\   s         r%   validate_token_requestz%JWTBearerGrant.validate_token_requestt   s   > LL%%))+6	%&FGG..y9++F5M:		0&9&&t7)B4??BSSTU  %%%'**U#))'2D'4VWWII?N..vt<( N  !%DLL r'   c                 $   | j                  | j                  j                  j                  | j                  j                  d      }t
        j                  d|| j                  j                         | j                  |       d|| j                  fS )zZIf valid and authorized, the authorization server issues an access
        token.
        F)scoper\   include_refresh_tokenzIssue token %r to %r   )
generate_tokenrT   rO   r_   r\   r8   r9   rJ   
save_tokenTOKEN_RESPONSE_HEADER)r:   rK   s     r%   create_token_responsez$JWTBearerGrant.create_token_response   sx     ##,,&&,,"""' $ 

 			(%1D1DEE45555r'   c                     t               )a1  Fetch client via "iss" in assertion claims. Developers MUST
        implement this method in subclass, e.g.::

            def resolve_issuer_client(self, issuer):
                return Client.query_by_iss(issuer)

        :param issuer: "iss" value in assertion
        :return: Client instance
        NotImplementedError)r:   r   s     r%   rC   z$JWTBearerGrant.resolve_issuer_client        "##r'   returnc                     t               )a  Resolve client key to decode assertion data. Developers MUST
        implement this method in subclass. For instance, there is a
        "jwks" column on client table, e.g.::

            def resolve_client_public_key(self, client):
                from joserfc import KeySet

                key_set = KeySet.import_key_set(client.jwks)
                return key_set

        :param client: instance of OAuth client model
        :return: OctKey, RSAKey, ECKey, OKPKey or KeySet instance
        rg   )r:   rJ   s     r%   rE   z(JWTBearerGrant.resolve_client_public_key   s     "##r'   c                     t               )a%  Authenticate user with the given assertion claims. Developers MUST
        implement it in subclass, e.g.::

            def authenticate_user(self, subject):
                return User.get_by_sub(subject)

        :param subject: "sub" value in claims
        :return: User instance
        rg   )r:   r    s     r%   rZ   z JWTBearerGrant.authenticate_user   ri   r'   c                     g S )a  Return a list of valid audience identifiers for this authorization
        server. Per RFC 7523 Section 3:

            The authorization server MUST reject any JWT that does not
            contain its own identity as the intended audience.

        Developers SHOULD implement this method to return the list of valid
        audience values, typically including the token endpoint URL and/or
        the issuer identifier. For example::

            def get_audiences(self):
                return ["https://example.com/oauth/token", "https://example.com"]

        If this method returns an empty list, audience value validation is
        skipped (only presence is checked).

        :return: list of valid audience strings
        r1   )r:   s    r%   r4   zJWTBearerGrant.get_audiences   s	    & 	r'   c                     t               )a  Check if the client has permission to access the given user's resource.
        Developers MUST implement it in subclass, e.g.::

            def has_granted_permission(self, client, user):
                permission = ClientUserGrant.query(client=client, user=user)
                return permission.granted

        :param client: instance of OAuth client model
        :param user: instance of User model
        :return: bool
        rg   )r:   rJ   r\   s      r%   r[   z%JWTBearerGrant.has_granted_permission   s     "##r'   )NNNN)__name__
__module____qualname__JWT_BEARER_GRANT_TYPErX   r3   r6   staticmethodr&   r   Claimsr?   rL   strrB   r]   re   rC   r   KeyKeySetrE   rZ   r4   r[   r1   r'   r%   r   r      s    &J
 T"T"T"N F
 
 
FCJJ F& D%3 %:%x6
$$377SZZ3G $ 
$*$r'   r   )loggingjoserfcr   r   r   joserfc.errorsr   joserfc.utilr   authlib._joserfc_helpersr   authlib.common.encodingr	   authlib.deprecater
   rfc6749r   r   r   r   r   r   rH   r   	getLoggerro   r8   rr   r   r1   r'   r%   <module>r      s^        $ ! 3 . '  ( ' ) ( - 0g!E m$Y 2 m$r'   