o
    ~j6h}                     @   s   d 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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ZdZG dd dejejejejZG dd dejejejZdS )a
  Service Accounts: JSON Web Token (JWT) Profile for OAuth 2.0

This module implements the JWT Profile for OAuth 2.0 Authorization Grants
as defined by `RFC 7523`_ with particular support for how this RFC is
implemented in Google's infrastructure. Google refers to these credentials
as *Service Accounts*.

Service accounts are used for server-to-server communication, such as
interactions between a web application server and a Google service. The
service account belongs to your application instead of to an individual end
user. In contrast to other OAuth 2.0 profiles, no users are involved and your
application "acts" as the service account.

Typically an application uses a service account when the application uses
Google APIs to work with its own data rather than a user's data. For example,
an application that uses Google Cloud Datastore for data persistence would use
a service account to authenticate its calls to the Google Cloud Datastore API.
However, an application that needs to access a user's Drive documents would
use the normal OAuth 2.0 profile.

Additionally, Google Apps domain administrators can grant service accounts
`domain-wide delegation`_ authority to access user data on behalf of users in
the domain.

This profile uses a JWT to acquire an OAuth 2.0 access token. The JWT is used
in place of the usual authorization token returned during the standard
OAuth 2.0 Authorization Code grant. The JWT is only used for this purpose, as
the acquired access token is used as the bearer token when making requests
using these credentials.

This profile differs from normal OAuth 2.0 profile because no user consent
step is required. The use of the private key allows this profile to assert
identity directly.

This profile also differs from the :mod:`google.auth.jwt` authentication
because the JWT credentials use the JWT directly as the bearer token. This
profile instead only uses the JWT to obtain an OAuth 2.0 access token. The
obtained OAuth 2.0 access token is used as the bearer token.

Domain-wide delegation
----------------------

Domain-wide delegation allows a service account to access user data on
behalf of any user in a Google Apps domain without consent from the user.
For example, an application that uses the Google Calendar API to add events to
the calendars of all users in a Google Apps domain would use a service account
to access the Google Calendar API on behalf of users.

The Google Apps administrator must explicitly authorize the service account to
do this. This authorization step is referred to as "delegating domain-wide
authority" to a service account.

You can use domain-wise delegation by creating a set of credentials with a
specific subject using :meth:`~Credentials.with_subject`.

.. _RFC 7523: https://tools.ietf.org/html/rfc7523
    N)_helpers)_service_account_info)credentials)
exceptions)iam)jwt)metrics)_clienti  z#https://oauth2.googleapis.com/tokenc                	       s|  e Zd ZdZdddddddejdf	 fdd	Zedd Zedd	 Z	ed
d Z
edd Zedd Zedd Zdd Zeejd4ddZdd Zeejdd Zdd Zdd Zeejdd Zeejd d! Zd"d# Zd$d% Zd&d' Zeej d(d) Z!d*d+ Z"eej#d,d- Z$eeej#d.d/ Z%eeej#d0d1 Z&eej d2d3 Z'  Z(S )5Credentialsa"  Service account credentials

    Usually, you'll create these credentials with one of the helper
    constructors. To create credentials using a Google service account
    private key JSON file::

        credentials = service_account.Credentials.from_service_account_file(
            'service-account.json')

    Or if you already have the service account file loaded::

        service_account_info = json.load(open('service_account.json'))
        credentials = service_account.Credentials.from_service_account_info(
            service_account_info)

    Both helper methods pass on arguments to the constructor, so you can
    specify additional scopes and a subject if necessary::

        credentials = service_account.Credentials.from_service_account_file(
            'service-account.json',
            scopes=['email'],
            subject='user@example.com')

    The credentials are considered immutable. If you want to modify the scopes
    or the subject used for delegation, use :meth:`with_scopes` or
    :meth:`with_subject`::

        scoped_credentials = credentials.with_scopes(['email'])
        delegated_credentials = credentials.with_subject(subject)

    To add a quota project, use :meth:`with_quota_project`::

        credentials = credentials.with_quota_project('myproject-123')
    NFc                    s   t t|   d| _|| _|| _|| _|| _|| _|| _	|| _
|| _|
| _|p)tj| _|tjkr3d| _d| _|	dur>|	| _ni | _g dd| _dS )a=  
        Args:
            signer (google.auth.crypt.Signer): The signer used to sign JWTs.
            service_account_email (str): The service account's email.
            scopes (Sequence[str]): User-defined scopes to request during the
                authorization grant.
            default_scopes (Sequence[str]): Default scopes passed by a
                Google client library. Use 'scopes' for user-defined scopes.
            token_uri (str): The OAuth 2.0 Token URI.
            subject (str): For domain-wide delegation, the email address of the
                user to for which to request delegated access.
            project_id  (str): Project ID associated with the service account
                credential.
            quota_project_id (Optional[str]): The project ID used for quota and
                billing.
            additional_claims (Mapping[str, str]): Any additional claims for
                the JWT assertion used in the authorization grant.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be always used.
            universe_domain (str): The universe domain. The default
                universe domain is googleapis.com. For default value self
                signed jwt is used for token refresh.
            trust_boundary (str): String representation of trust boundary meta.

        .. note:: Typically one of the helper constructors
            :meth:`from_service_account_file` or
            :meth:`from_service_account_info` are used instead of calling the
            constructor directly.
        NT0x0)	locationsencoded_locations)superr
   __init___cred_file_path_scopes_default_scopes_signer_service_account_email_subject_project_id_quota_project_id
_token_uri_always_use_jwt_accessr   DEFAULT_UNIVERSE_DOMAIN_universe_domain_jwt_credentials_additional_claims_trust_boundary)selfsignerservice_account_email	token_uriscopesdefault_scopessubject
project_idquota_project_idadditional_claimsalways_use_jwt_accessuniverse_domaintrust_boundary	__class__ l/var/www/html/chefvision.cloud.itp360.com/venv/lib/python3.10/site-packages/google/oauth2/service_account.pyr      s&   ,
zCredentials.__init__c              	   K   s:   | |f|d |d | d| dtj| dd|S )a  Creates a Credentials instance from a signer and service account
        info.

        Args:
            signer (google.auth.crypt.Signer): The signer used to sign JWTs.
            info (Mapping[str, str]): The service account info.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            google.auth.jwt.Credentials: The constructed credentials.

        Raises:
            ValueError: If the info is not in the expected format.
        client_emailr"   r&   r*   r+   )r!   r"   r&   r*   r+   )getr   r   clsr    infokwargsr.   r.   r/   _from_signer_and_info   s   	z!Credentials._from_signer_and_infoc                 K   &   t j|ddgd}| j||fi |S )a  Creates a Credentials instance from parsed service account info.

        Args:
            info (Mapping[str, str]): The service account info in Google
                format.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            google.auth.service_account.Credentials: The constructed
                credentials.

        Raises:
            ValueError: If the info is not in the expected format.
        r0   r"   requirer   	from_dictr6   r3   r4   r5   r    r.   r.   r/   from_service_account_info      z%Credentials.from_service_account_infoc                 K   *   t j|ddgd\}}| j||fi |S )aX  Creates a Credentials instance from a service account json file.

        Args:
            filename (str): The path to the service account json file.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            google.auth.service_account.Credentials: The constructed
                credentials.
        r0   r"   r8   r   from_filenamer6   r3   filenamer5   r4   r    r.   r.   r/   from_service_account_file      
z%Credentials.from_service_account_filec                 C      | j S zThe service account email.r   r   r.   r.   r/   r!   	     z!Credentials.service_account_emailc                 C   rF   )z+Project ID associated with this credential.)r   rI   r.   r.   r/   r&     rJ   zCredentials.project_idc                 C   s   | j sdS dS )zChecks if the credentials requires scopes.

        Returns:
            bool: True if there are no scopes set otherwise False.
        TF)r   rI   r.   r.   r/   requires_scopes  s   zCredentials.requires_scopesc                 C   sR   | j | j| jt| jt| j| j| j| j| j	| j
 | j| jd}| j|_|S )N)
r!   r#   r$   r"   r%   r&   r'   r(   r)   r*   )r-   r   r   copyr   r   r   r   r   r   r   r   r   r   r   credr.   r.   r/   
_make_copy  s   

zCredentials._make_copyc                 C   s   |   }||_||_|S N)rO   r   r   )r   r#   r$   rN   r.   r.   r/   with_scopes-  s   zCredentials.with_scopesc                 C   ,   |   }|jtjkr|std||_|S )a  Create a copy of these credentials with the specified always_use_jwt_access value.

        Args:
            always_use_jwt_access (bool): Whether always use self signed JWT or not.

        Returns:
            google.auth.service_account.Credentials: A new credentials
                instance.
        Raises:
            google.auth.exceptions.InvalidValue: If the universe domain is not
                default and always_use_jwt_access is False.
        zDalways_use_jwt_access should be True for non-default universe domain)rO   r   r   r   r   InvalidValuer   )r   r)   rN   r.   r.   r/   with_always_use_jwt_access4  s   z&Credentials.with_always_use_jwt_accessc                 C   s"   |   }||_|tjkrd|_|S )NT)rO   r   r   r   r   )r   r*   rN   r.   r.   r/   with_universe_domainL  s
   
z Credentials.with_universe_domainc                 C      |   }||_|S )zCreate a copy of these credentials with the specified subject.

        Args:
            subject (str): The subject claim.

        Returns:
            google.auth.service_account.Credentials: A new credentials
                instance.
        )rO   r   )r   r%   rN   r.   r.   r/   with_subjectT  s   
zCredentials.with_subjectc                 C   s,   t | j}||pi  |  }||_|S )az  Returns a copy of these credentials with modified claims.

        Args:
            additional_claims (Mapping[str, str]): Any additional claims for
                the JWT payload. This will be merged with the current
                additional claims.

        Returns:
            google.auth.service_account.Credentials: A new credentials
                instance.
        )rL   deepcopyr   updaterO   )r   r(   new_additional_claimsrN   r.   r.   r/   with_claimsb  s
   zCredentials.with_claimsc                 C   rV   rP   rO   r   r   r'   rN   r.   r.   r/   with_quota_projectt     zCredentials.with_quota_projectc                 C   rV   rP   rO   r   r   r"   rN   r.   r.   r/   with_token_uriz  r_   zCredentials.with_token_uric                 C   sx   t  }tjtd}|| }t |t || jtt | j	pdd}|
| j | jr3|d| j t| j|}|S )zCreate the OAuth 2.0 assertion.

        This assertion is used during the OAuth 2.0 grant to acquire an
        access token.

        Returns:
            bytes: The authorization grant assertion.
        secondsr.   )iatexpissaudscopesub)r   utcnowdatetime	timedelta_DEFAULT_TOKEN_LIFETIME_SECSdatetime_to_secsr   _GOOGLE_OAUTH2_TOKEN_ENDPOINTscopes_to_stringr   rY   r   r   
setdefaultr   encoder   r   nowlifetimeexpirypayloadtokenr.   r.   r/   #_make_authorization_grant_assertion  s   	
z/Credentials._make_authorization_grant_assertionc                 C   s   | j d u o	| jd uS rP   )r   r   rI   r.   r.   r/   _use_self_signed_jwt  s   z Credentials._use_self_signed_jwtc                 C   s   |   rtjS tjS rP   )r{   r   CRED_TYPE_SA_JWTCRED_TYPE_SA_ASSERTIONrI   r.   r.   r/   _metric_header_for_usage  s   z$Credentials._metric_header_for_usagec                 C   s   | j r| js| d  | jtjkr| jrtd| 	 r1| j
| | jj | _| jj| _d S |  }t|| j|\}}}|| _|| _d S )NzGdomain wide delegation is not supported for non-default universe domain)r   r   _create_self_signed_jwtr   r   r   r   r   RefreshErrorr{   refreshry   decoderw   rz   r	   	jwt_grantr   r   request	assertionaccess_tokenrw   _r.   r.   r/   r     s$   


zCredentials.refreshc                 C   s   | j rf| jr'dd| ji}| jdu s| jj|kr%tjj| d|d| _dS dS |r@| jdu s4| jj|kr>tj| || _dS dS | j	rbdd| j	i}| jdu sV|| jjkrdtjj| d|d| _dS dS dS | jsu|rwtj| || _dS dS dS )zCreate a self-signed JWT from the credentials if requirements are met.

        Args:
            audience (str): The service URL. ``https://[API_ENDPOINT]/``
        ri    Nr(   )
r   r   joinr   r(   r   r
   from_signing_credentials	_audiencer   )r   audiencer(   r.   r.   r/   r     s<   





z#Credentials._create_self_signed_jwtc                 C      | j |S rP   r   signr   messager.   r.   r/   
sign_bytes     zCredentials.sign_bytesc                 C   rF   rP   r   rI   r.   r.   r/   r      rJ   zCredentials.signerc                 C   rF   rP   rH   rI   r.   r.   r/   signer_email  rJ   zCredentials.signer_emailc                 C   s   | j r| j d| jdS d S )Nzservice account credentials)credential_sourcecredential_type	principal)r   r!   rI   r.   r.   r/   get_cred_info  s   zCredentials.get_cred_inforP   ))__name__
__module____qualname____doc__r   r   r   classmethodr6   r=   rD   propertyr!   r&   rK   rO   r   copy_docstringScopedrQ   rT   CredentialsWithUniverseDomainrU   rW   r[   CredentialsWithQuotaProjectr^   CredentialsWithTokenUrirb   rz   r{   r~   r
   r   r   Signingr   r    r   r   __classcell__r.   r.   r,   r/   r
   Y   sh    (E












!


(



r
   c                       s  e Zd ZdZddejf fdd	Zedd Zedd Z	ed	d
 Z
dd Zdd Zdd Zeejdd Zeejdd Zdd Zdd Zeejdd Zedd Zeejdd Zeeejdd  Zeeejd!d" Z  ZS )#IDTokenCredentialsa_  Open ID Connect ID Token-based service account credentials.

    These credentials are largely similar to :class:`.Credentials`, but instead
    of using an OAuth 2.0 Access Token as the bearer token, they use an Open
    ID Connect ID Token as the bearer token. These credentials are useful when
    communicating to services that require ID Tokens and can not accept access
    tokens.

    Usually, you'll create these credentials with one of the helper
    constructors. To create credentials using a Google service account
    private key JSON file::

        credentials = (
            service_account.IDTokenCredentials.from_service_account_file(
                'service-account.json'))


    Or if you already have the service account file loaded::

        service_account_info = json.load(open('service_account.json'))
        credentials = (
            service_account.IDTokenCredentials.from_service_account_info(
                service_account_info))


    Both helper methods pass on arguments to the constructor, so you can
    specify additional scopes and a subject if necessary::

        credentials = (
            service_account.IDTokenCredentials.from_service_account_file(
                'service-account.json',
                scopes=['email'],
                subject='user@example.com'))


    The credentials are considered immutable. If you want to modify the scopes
    or the subject used for delegation, use :meth:`with_scopes` or
    :meth:`with_subject`::

        scoped_credentials = credentials.with_scopes(['email'])
        delegated_credentials = credentials.with_subject(subject)

    Nc                    s   t t|   || _|| _|| _|| _|| _d| _|s t	j
| _n|| _tjd| j| _| jt	j
kr5d| _|dur>|| _dS i | _dS )a  
        Args:
            signer (google.auth.crypt.Signer): The signer used to sign JWTs.
            service_account_email (str): The service account's email.
            token_uri (str): The OAuth 2.0 Token URI.
            target_audience (str): The intended audience for these credentials,
                used when requesting the ID Token. The ID Token's ``aud`` claim
                will be set to this string.
            additional_claims (Mapping[str, str]): Any additional claims for
                the JWT assertion used in the authorization grant.
            quota_project_id (Optional[str]): The project ID used for quota and billing.
            universe_domain (str): The universe domain. The default
                universe domain is googleapis.com. For default value IAM ID
                token endponint is used for token refresh. Note that
                iam.serviceAccountTokenCreator role is required to use the IAM
                endpoint.
        .. note:: Typically one of the helper constructors
            :meth:`from_service_account_file` or
            :meth:`from_service_account_info` are used instead of calling the
            constructor directly.
        Fzgoogleapis.comTN)r   r   r   r   r   r   _target_audiencer   _use_iam_endpointr   r   r   r   _IAM_IDTOKEN_ENDPOINTreplace_iam_id_token_endpointr   )r   r    r!   r"   target_audiencer(   r'   r*   r,   r.   r/   r   8  s$   


zIDTokenCredentials.__init__c                 K   sD   | d|d  | d|d  d|v r|d |d< | |fi |S )a  Creates a credentials instance from a signer and service account
        info.

        Args:
            signer (google.auth.crypt.Signer): The signer used to sign JWTs.
            info (Mapping[str, str]): The service account info.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            google.auth.jwt.IDTokenCredentials: The constructed credentials.

        Raises:
            ValueError: If the info is not in the expected format.
        r!   r0   r"   r*   )rr   r2   r.   r.   r/   r6   o  s
   z(IDTokenCredentials._from_signer_and_infoc                 K   r7   )a  Creates a credentials instance from parsed service account info.

        Args:
            info (Mapping[str, str]): The service account info in Google
                format.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            google.auth.service_account.IDTokenCredentials: The constructed
                credentials.

        Raises:
            ValueError: If the info is not in the expected format.
        r0   r"   r8   r:   r<   r.   r.   r/   r=     r>   z,IDTokenCredentials.from_service_account_infoc                 K   r?   )a_  Creates a credentials instance from a service account json file.

        Args:
            filename (str): The path to the service account json file.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            google.auth.service_account.IDTokenCredentials: The constructed
                credentials.
        r0   r"   r8   r@   rB   r.   r.   r/   rD     rE   z,IDTokenCredentials.from_service_account_filec              	   C   s6   | j | j| j| j| j| j | j| jd}| j	|_	|S )N)r!   r"   r   r(   r'   r*   )
r-   r   r   r   r   r   rL   r'   r   r   rM   r.   r.   r/   rO     s   
zIDTokenCredentials._make_copyc                 C   rV   )a_  Create a copy of these credentials with the specified target
        audience.

        Args:
            target_audience (str): The intended audience for these credentials,
            used when requesting the ID Token.

        Returns:
            google.auth.service_account.IDTokenCredentials: A new credentials
                instance.
        )rO   r   )r   r   rN   r.   r.   r/   with_target_audience  s   z'IDTokenCredentials.with_target_audiencec                 C   rR   )a  Create a copy of these credentials with the use_iam_endpoint value.

        Args:
            use_iam_endpoint (bool): If True, IAM generateIdToken endpoint will
                be used instead of the token_uri. Note that
                iam.serviceAccountTokenCreator role is required to use the IAM
                endpoint. The default value is False. This feature is currently
                experimental and subject to change without notice.

        Returns:
            google.auth.service_account.IDTokenCredentials: A new credentials
                instance.
        Raises:
            google.auth.exceptions.InvalidValue: If the universe domain is not
                default and use_iam_endpoint is False.
        z?use_iam_endpoint should be True for non-default universe domain)rO   r   r   r   r   rS   r   )r   use_iam_endpointrN   r.   r.   r/   _with_use_iam_endpoint  s   z)IDTokenCredentials._with_use_iam_endpointc                 C   rV   rP   r\   r]   r.   r.   r/   r^     r_   z%IDTokenCredentials.with_quota_projectc                 C   rV   rP   r`   ra   r.   r.   r/   rb     r_   z!IDTokenCredentials.with_token_uric                 C   sZ   t  }tjtd}|| }t |t || jt| jd}|	| j
 t| j|}|S )zCreate the OAuth 2.0 assertion.

        This assertion is used during the OAuth 2.0 grant to acquire an
        ID token.

        Returns:
            bytes: The authorization grant assertion.
        rc   )re   rf   rg   rh   r   )r   rk   rl   rm   rn   ro   r!   rp   r   rY   r   r   rs   r   rt   r.   r.   r/   rz     s   	z6IDTokenCredentials._make_authorization_grant_assertionc                 C   sN   t jj| dddid}|| t|| j| j| j|j	
 | j\| _	| _dS )a  Use IAM generateIdToken endpoint to obtain an ID token.

        It works as follows:

        1. First we create a self signed jwt with
        https://www.googleapis.com/auth/iam being the scope.

        2. Next we use the self signed jwt as the access token, and make a POST
        request to IAM generateIdToken endpoint. The request body is:
            {
                "audience": self._target_audience,
                "includeEmail": "true",
                "useEmailAzp": "true",
            }

        If the request is succesfully, it will return {"token":"the ID token"},
        and we can extract the ID token and compute its expiry.
        Nri   z#https://www.googleapis.com/auth/iamr   )r   r
   r   r   r	   #call_iam_generate_id_token_endpointr   r   r   ry   r   r   rw   )r   r   jwt_credentialsr.   r.   r/   _refresh_with_iam_endpoint  s   
z-IDTokenCredentials._refresh_with_iam_endpointc                 C   sB   | j r
| | d S |  }t|| j|\}}}|| _|| _d S rP   )r   r   rz   r	   id_token_jwt_grantr   ry   rw   r   r.   r.   r/   r   2  s   

zIDTokenCredentials.refreshc                 C   rF   rG   rH   rI   r.   r.   r/   r!   >  rJ   z(IDTokenCredentials.service_account_emailc                 C   r   rP   r   r   r.   r.   r/   r   C  r   zIDTokenCredentials.sign_bytesc                 C   rF   rP   r   rI   r.   r.   r/   r    G  rJ   zIDTokenCredentials.signerc                 C   rF   rP   rH   rI   r.   r.   r/   r   L  rJ   zIDTokenCredentials.signer_email)r   r   r   r   r   r   r   r   r6   r=   rD   rO   r   r   r   r   r   r^   r   rb   rz   r   r
   r   r   r!   r   r   r    r   r   r.   r.   r,   r/   r     sB    27







"





r   )r   rL   rl   google.authr   r   r   r   r   r   r   google.oauth2r	   rn   rp   r   r   r   r   r
   r   r.   r.   r.   r/   <module>   s6   :
   
1