
    g#/                         d Z ddlmZ ddlZddlZddlmZ ddlmZ ddlm	Z	 dZ
dZdd	gZd
 Zde
dfdZddZddZddZd Zy)a  Google ID Token helpers.

Provides support for verifying `OpenID Connect ID Tokens`_, especially ones
generated by Google infrastructure.

To parse and verify an ID Token issued by Google's OAuth 2.0 authorization
server use :func:`verify_oauth2_token`. To verify an ID Token issued by
Firebase, use :func:`verify_firebase_token`.

A general purpose ID Token verifier is available as :func:`verify_token`.

Example::

    from google.oauth2 import id_token
    from google.auth.transport import requests

    request = requests.Request()

    id_info = id_token.verify_oauth2_token(
        token, request, 'my-client-id.example.com')

    userid = id_info['sub']

By default, this will re-fetch certificates for each verification. Because
Google's public keys are only changed infrequently (on the order of once per
day), you may wish to take advantage of caching to reduce latency and the
potential for network errors. This can be accomplished using an external
library like `CacheControl`_ to create a cache-aware
:class:`google.auth.transport.Request`::

    import cachecontrol
    import google.auth.transport.requests
    import requests

    session = requests.session()
    cached_session = cachecontrol.CacheControl(session)
    request = google.auth.transport.requests.Request(session=cached_session)

.. _OpenID Connect ID Tokens:
    http://openid.net/specs/openid-connect-core-1_0.html#IDToken
.. _CacheControl: https://cachecontrol.readthedocs.io
    N)environment_vars)
exceptions)jwtz*https://www.googleapis.com/oauth2/v1/certszXhttps://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.comzaccounts.google.comzhttps://accounts.google.comc                      | |d      }|j                   t        j                  k7  r$t        j                  dj                  |            t        j                  |j                  j                  d            S )a  Fetches certificates.

    Google-style cerificate endpoints return JSON in the format of
    ``{'key id': 'x509 certificate'}``.

    Args:
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        certs_url (str): The certificate endpoint URL.

    Returns:
        Mapping[str, str]: A mapping of public key ID to x.509 certificate
            data.
    GET)methodz"Could not fetch certificates at {}zutf-8)
statushttp_clientOKr   TransportErrorformatjsonloadsdatadecode)request	certs_urlresponses      S/var/www/django_project/virt/lib/python3.12/site-packages/google/oauth2/id_token.py_fetch_certsr   Q   sa     y/H+..(''077	B
 	
 ::hmm**7344    c                 L    t        ||      }t        j                  | |||      S )a  Verifies an ID token and returns the decoded token.

    Args:
        id_token (Union[str, bytes]): The encoded token.
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        audience (str or list): The audience or audiences that this token is
            intended for. If None then the audience is not verified.
        certs_url (str): The URL that specifies the certificates to use to
            verify the token. This URL should return JSON in the format of
            ``{'key id': 'x509 certificate'}``.
        clock_skew_in_seconds (int): The clock skew used for `iat` and `exp`
            validation.

    Returns:
        Mapping[str, Any]: The decoded token.
    )certsaudienceclock_skew_in_seconds)r   r   r   )id_tokenr   r   r   r   r   s         r   verify_tokenr   j   s-    0 ),E::3	 r   c                     t        | ||t        |      }|d   t        vr(t        j                  dj                  t                    |S )a  Verifies an ID Token issued by Google's OAuth 2.0 authorization server.

    Args:
        id_token (Union[str, bytes]): The encoded token.
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        audience (str): The audience that this token is intended for. This is
            typically your application's OAuth 2.0 client ID. If None then the
            audience is not verified.
        clock_skew_in_seconds (int): The clock skew used for `iat` and `exp`
            validation.

    Returns:
        Mapping[str, Any]: The decoded token.

    Raises:
        exceptions.GoogleAuthError: If the issuer is invalid.
        ValueError: If token verification fails
    r   r   r   issz6Wrong issuer. 'iss' should be one of the following: {})r   _GOOGLE_OAUTH2_CERTS_URL_GOOGLE_ISSUERSr   GoogleAuthErrorr   )r   r   r   r   idinfos        r   verify_oauth2_tokenr%      sV    ( *3F e}O+((DKK
 	
 Mr   c                 *    t        | ||t        |      S )a>  Verifies an ID Token issued by Firebase Authentication.

    Args:
        id_token (Union[str, bytes]): The encoded token.
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        audience (str): The audience that this token is intended for. This is
            typically your Firebase application ID. If None then the audience
            is not verified.
        clock_skew_in_seconds (int): The clock skew used for `iat` and `exp`
            validation.

    Returns:
        Mapping[str, Any]: The decoded token.
    r   )r   _GOOGLE_APIS_CERTS_URL)r   r   r   r   s       r   verify_firebase_tokenr(      s       (3 r   c                    t         j                  j                  t        j                        }|rt         j
                  j                  |      rt         j
                  j                  |      st        j                  d      	 t        |d      5 }ddlm} t        j                  |      }|j                  d      dk(  r&|j                  j!                  ||       cddd       S 	 ddd       	 dd
lm} ddlm}	 |s2ddl}
|
j.                  j0                  j2                  j5                         }|	j7                  |      r|j                  || d      S 	 t        j                  d      # 1 sw Y   xY w# t"        $ r}t        j                  d	|      }||d}~ww xY w# t8        t        j:                  f$ r Y fw xY w)a  Create the ID Token credentials from the current environment.

    This function acquires ID token from the environment in the following order.
    See https://google.aip.dev/auth/4110.

    1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
       to the path of a valid service account JSON file, then ID token is
       acquired using this service account credentials.
    2. If the application is running in Compute Engine, App Engine or Cloud Run,
       then the ID token are obtained from the metadata server.
    3. If metadata server doesn't exist and no valid service account credentials
       are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will
       be raised.

    Example::

        import google.oauth2.id_token
        import google.auth.transport.requests

        request = google.auth.transport.requests.Request()
        target_audience = "https://pubsub.googleapis.com"

        # Create ID token credentials.
        credentials = google.oauth2.id_token.fetch_id_token_credentials(target_audience, request=request)

        # Refresh the credential to obtain an ID token.
        credentials.refresh(request)

        id_token = credentials.token
        id_token_expiry = credentials.expiry

    Args:
        audience (str): The audience that this ID token is intended for.
        request (Optional[google.auth.transport.Request]): A callable used to make
            HTTP requests. A request object will be created if not provided.

    Returns:
        google.auth.credentials.Credentials: The ID token credentials.

    Raises:
        ~google.auth.exceptions.DefaultCredentialsError:
            If metadata server doesn't exist and no valid service account
            credentials are found.
    zCGOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid.rr   )service_accounttyper+   )target_audienceNzHGOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials.)compute_engine)	_metadataT)use_metadata_identity_endpointzGNeither metadata server or valid service account credentials are found.)osenvirongetr   CREDENTIALSpathexistsisfiler   DefaultCredentialsErroropengoogle.oauth2r+   r   loadIDTokenCredentialsfrom_service_account_info
ValueErrorgoogle.authr.   google.auth.compute_enginer/   google.auth.transport.requestsauth	transportrequestsRequestpingImportErrorr   )r   r   credentials_filenamefr+   info
caught_excnew_excr.   r/   googles              r   fetch_id_token_credentialsrN      s   ^ ::>>*:*F*FGGGNN/03444U 	**C0 A9yy|88F#'88*==WWh X   9	".8 1kk++44<<>G>>'"!44$ 5   # 
,
,Q E   	* 88ZG z)	*. 223 sJ   E7 AE+	E7 'E7 0A$F! +E40E7 7	F FF!F=<F=c                 V    t        ||       }|j                  |        |j                  S )a  Fetch the ID Token from the current environment.

    This function acquires ID token from the environment in the following order.
    See https://google.aip.dev/auth/4110.

    1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
       to the path of a valid service account JSON file, then ID token is
       acquired using this service account credentials.
    2. If the application is running in Compute Engine, App Engine or Cloud Run,
       then the ID token are obtained from the metadata server.
    3. If metadata server doesn't exist and no valid service account credentials
       are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will
       be raised.

    Example::

        import google.oauth2.id_token
        import google.auth.transport.requests

        request = google.auth.transport.requests.Request()
        target_audience = "https://pubsub.googleapis.com"

        id_token = google.oauth2.id_token.fetch_id_token(request, target_audience)

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        audience (str): The audience that this ID token is intended for.

    Returns:
        str: The ID token.

    Raises:
        ~google.auth.exceptions.DefaultCredentialsError:
            If metadata server doesn't exist and no valid service account
            credentials are found.
    )r   )rN   refreshtoken)r   r   id_token_credentialss      r   fetch_id_tokenrS   ,  s,    L 6hP  )%%%r   )Nr   )N)__doc__http.clientclientr
   r   r1   r?   r   r   r   r!   r'   r"   r   r   r%   r(   rN   rS    r   r   <module>rX      sl   )V "  	 ( " 
 H 
. 
 )*GH58 &D#L2^B(&r   