a
    !f_?                     @   s   d Z ddlZddl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dlmZ ddlmZ dd	lmZ d
ZdgZdZdZdZdZd
ZdZdddZG dd de
je
je
jZG dd de
jZdS )a  Google Cloud Impersonated credentials.

This module provides authentication for applications where local credentials
impersonates a remote service account using `IAM Credentials API`_.

This class can be used to impersonate a service account as long as the original
Credential object has the "Service Account Token Creator" role on the target
service account.

    .. _IAM Credentials API:
        https://cloud.google.com/iam/credentials/reference/rest/
    N)datetime)http_client)_helpers)credentials)
exceptions)jwt)metricsi  z#https://www.googleapis.com/auth/iamzZhttps://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{}:generateAccessTokenzOhttps://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{}:signBlobzVhttps://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{}:generateIdTokenz*Unable to acquire impersonated credentialsz#https://oauth2.googleapis.com/tokenc              
   C   s   |pt |}t|d}| |d||d}t|jdrF|jdn|j}|jt	j
krdtt|z,t|}|d }	t|d d}
|	|
fW S  ttfy } z*tdt|}t|| W Y d	}~n
d	}~0 0 d	S )
a  Makes a request to the Google Cloud IAM service for an access token.
    Args:
        request (Request): The Request object to use.
        principal (str): The principal to request an access token for.
        headers (Mapping[str, str]): Map of headers to transmit.
        body (Mapping[str, str]): JSON Payload body for the iamcredentials
            API call.
        iam_endpoint_override (Optiona[str]): The full IAM endpoint override
            with the target_principal embedded. This is useful when supporting
            impersonation with regional endpoints.

    Raises:
        google.auth.exceptions.TransportError: Raised if there is an underlying
            HTTP connection error
        google.auth.exceptions.RefreshError: Raised if the impersonated
            credentials are not available.  Common reasons are
            `iamcredentials.googleapis.com` is not enabled or the
            `Service Account Token Creator` is not assigned
    utf-8POST)urlmethodheadersbodydecodeZaccessTokenZ
expireTimez%Y-%m-%dT%H:%M:%SZz6{}: No access token or invalid expiration in response.N)_IAM_ENDPOINTformatjsondumpsencodehasattrdatar   statusr   OKr   ZRefreshError_REFRESH_ERRORloadsr   strptimeKeyError
ValueErrorsix
raise_from)request	principalr   r   iam_endpoint_overrideZiam_endpointresponseZresponse_bodyZtoken_responsetokenexpiryZ
caught_excnew_exc r'   e/var/www/html/python-backend/venv/lib/python3.9/site-packages/google/auth/impersonated_credentials.py_make_iam_token_requestD   s,    


r)   c                       s   e Zd ZdZdeddf fdd	Zdd Zee	j
dd Zd	d
 Zdd Zedd Zedd Zedd Zedd Zee	jdd Zee	jdddZ  ZS )Credentialsa  This module defines impersonated credentials which are essentially
    impersonated identities.

    Impersonated Credentials allows credentials issued to a user or
    service account to impersonate another. The target service account must
    grant the originating credential principal the
    `Service Account Token Creator`_ IAM role:

    For more information about Token Creator IAM role and
    IAMCredentials API, see
    `Creating Short-Lived Service Account Credentials`_.

    .. _Service Account Token Creator:
        https://cloud.google.com/iam/docs/service-accounts#the_service_account_token_creator_role

    .. _Creating Short-Lived Service Account Credentials:
        https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials

    Usage:

    First grant source_credentials the `Service Account Token Creator`
    role on the target account to impersonate.   In this example, the
    service account represented by svc_account.json has the
    token creator role on
    `impersonated-account@_project_.iam.gserviceaccount.com`.

    Enable the IAMCredentials API on the source project:
    `gcloud services enable iamcredentials.googleapis.com`.

    Initialize a source credential which does not have access to
    list bucket::

        from google.oauth2 import service_account

        target_scopes = [
            'https://www.googleapis.com/auth/devstorage.read_only']

        source_credentials = (
            service_account.Credentials.from_service_account_file(
                '/path/to/svc_account.json',
                scopes=target_scopes))

    Now use the source credentials to acquire credentials to impersonate
    another service account::

        from google.auth import impersonated_credentials

        target_credentials = impersonated_credentials.Credentials(
          source_credentials=source_credentials,
          target_principal='impersonated-account@_project_.iam.gserviceaccount.com',
          target_scopes = target_scopes,
          lifetime=500)

    Resource access is granted::

        client = storage.Client(credentials=target_credentials)
        buckets = client.list_buckets(project='your_project')
        for bucket in buckets:
          print(bucket.name)
    Nc                    sr   t t|   t|| _t| jtjr6| jt	| _|| _
|| _|| _|pNt| _d| _t | _|| _|| _dS )aL  
        Args:
            source_credentials (google.auth.Credentials): The source credential
                used as to acquire the impersonated credentials.
            target_principal (str): The service account to impersonate.
            target_scopes (Sequence[str]): Scopes to request during the
                authorization grant.
            delegates (Sequence[str]): The chained list of delegates required
                to grant the final access_token.  If set, the sequence of
                identities must have "Service Account Token Creator" capability
                granted to the prceeding identity.  For example, if set to
                [serviceAccountB, serviceAccountC], the source_credential
                must have the Token Creator role on serviceAccountB.
                serviceAccountB must have the Token Creator on
                serviceAccountC.
                Finally, C must have Token Creator on target_principal.
                If left unset, source_credential must have that role on
                target_principal.
            lifetime (int): Number of seconds the delegated credential should
                be valid for (upto 3600).
            quota_project_id (Optional[str]): The project ID used for quota and billing.
                This project may be different from the project used to
                create the credentials.
            iam_endpoint_override (Optiona[str]): The full IAM endpoint override
                with the target_principal embedded. This is useful when supporting
                impersonation with regional endpoints.
        N)superr*   __init__copy_source_credentials
isinstancer   Scopedwith_scopes
_IAM_SCOPE_target_principal_target_scopes
_delegates_DEFAULT_TOKEN_LIFETIME_SECS	_lifetimer$   r   utcnowr%   _quota_project_id_iam_endpoint_override)selfZsource_credentialstarget_principaltarget_scopes	delegateslifetimequota_project_idr"   	__class__r'   r(   r,      s    &

zCredentials.__init__c                 C   s   t jS N)r   ZCRED_TYPE_SA_IMPERSONATEr;   r'   r'   r(   _metric_header_for_usage   s    z$Credentials._metric_header_for_usagec                 C   s   |  | d S rC   )_update_token)r;   r    r'   r'   r(   refresh   s    zCredentials.refreshc                 C   sn   | j js| j | | j| jt| jd d}ddtjt	 i}| j 
| t|| j||| jd\| _| _dS )zUpdates credentials with a new access_token representing
        the impersonated account.

        Args:
            request (google.auth.transport.requests.Request): Request object
                to use for refreshing credentials.
        s)r>   scoper?   Content-Typeapplication/json)r    r!   r   r   r"   N)r.   ZvalidrG   r5   r4   strr7   r   API_CLIENT_HEADERZ&token_request_access_token_impersonateapplyr)   r3   r:   r$   r%   )r;   r    r   r   r'   r'   r(   rF      s"    

zCredentials._update_tokenc                 C   s   ddl m} t| j}t|d| jd}ddi}|| j	}z|j
|||d}W |  n
|  0 |jtjkrtd| t| d	 S )
Nr   AuthorizedSessionr	   )payloadr>   rJ   rK   )r   r   r   zError calling sign_bytes: {}Z
signedBlob)google.auth.transport.requestsrP   _IAM_SIGN_ENDPOINTr   r3   base64	b64encoder   r5   r.   postclosestatus_coder   r   r   ZTransportErrorr   	b64decode)r;   messagerP   iam_sign_endpointr   r   authed_sessionr#   r'   r'   r(   
sign_bytes  s"    
zCredentials.sign_bytesc                 C   s   | j S rC   r3   rD   r'   r'   r(   signer_email8  s    zCredentials.signer_emailc                 C   s   | j S rC   r^   rD   r'   r'   r(   service_account_email<  s    z!Credentials.service_account_emailc                 C   s   | S rC   r'   rD   r'   r'   r(   signer@  s    zCredentials.signerc                 C   s   | j  S rC   )r4   rD   r'   r'   r(   requires_scopesD  s    zCredentials.requires_scopesc              	   C   s$   | j | j| j| j| j| j|| jdS N)r<   r=   r>   r?   r@   r"   )rB   r.   r3   r4   r5   r7   r:   r;   r@   r'   r'   r(   with_quota_projectH  s    zCredentials.with_quota_projectc              	   C   s(   | j | j| j|p|| j| j| j| jdS rc   )rB   r.   r3   r5   r7   r9   r:   )r;   ZscopesZdefault_scopesr'   r'   r(   r1   T  s    zCredentials.with_scopes)N)__name__
__module____qualname____doc__r6   r,   rE   r   copy_docstringr   r*   rG   rF   r]   propertyr_   r`   ra   rb   CredentialsWithQuotaProjectre   r0   r1   __classcell__r'   r'   rA   r(   r*   {   s.   B7

#






r*   c                       sd   e Zd ZdZd fdd	ZdddZdd	 Zd
d Ze	e
jdd Ze	e
jdd Z  ZS )IDTokenCredentialszAOpen ID Connect ID Token-based service account credentials.

    NFc                    s>   t t|   t|ts"td|| _|| _|| _	|| _
dS )a  
        Args:
            target_credentials (google.auth.Credentials): The target
                credential used as to acquire the id tokens for.
            target_audience (string): Audience to issue the token for.
            include_email (bool): Include email in IdToken
            quota_project_id (Optional[str]):  The project ID used for
                quota and billing.
        z4Provided Credential must be impersonated_credentialsN)r+   rn   r,   r/   r*   r   ZGoogleAuthError_target_credentials_target_audience_include_emailr9   )r;   target_credentialstarget_audienceinclude_emailr@   rA   r'   r(   r,   f  s    
zIDTokenCredentials.__init__c                 C   s   | j ||| j| jdS N)rr   rs   rt   r@   )rB   rq   r9   )r;   rr   rs   r'   r'   r(   from_credentials  s    z#IDTokenCredentials.from_credentialsc                 C   s   | j | j|| j| jdS ru   )rB   ro   rq   r9   )r;   rs   r'   r'   r(   with_target_audience  s    z'IDTokenCredentials.with_target_audiencec                 C   s   | j | j| j|| jdS ru   )rB   ro   rp   r9   )r;   rt   r'   r'   r(   with_include_email  s    z%IDTokenCredentials.with_include_emailc                 C   s   | j | j| j| j|dS ru   )rB   ro   rp   rq   rd   r'   r'   r(   re     s    z%IDTokenCredentials.with_quota_projectc           	      C   s   ddl m} t| jj}| j| jj| jd}ddt	j
t	 i}|| jj|d}|j||t|dd}| d	 }|| _ttj|d
dd | _d S )Nr   rO   )Zaudiencer>   ZincludeEmailrJ   rK   )Zauth_requestr	   )r   r   r   r$   F)verifyexp)rR   rP   _IAM_IDTOKEN_ENDPOINTr   ro   r_   rp   r5   rq   r   rM   Z"token_request_id_token_impersonater.   rV   r   r   r   r$   r   fromtimestampr   r   r%   )	r;   r    rP   r[   r   r   r\   r#   Zid_tokenr'   r'   r(   rG     s,    
zIDTokenCredentials.refresh)NFN)N)rf   rg   rh   ri   r,   rv   rw   rx   r   rj   r   rl   re   r*   rG   rm   r'   r'   rA   r(   rn   a  s      



rn   )N)ri   rT   r-   r   r   r   Z	six.movesr   Zgoogle.authr   r   r   r   r   r6   r2   r   rS   r{   r   Z_DEFAULT_TOKEN_URIr)   r0   rl   ZSigningr*   rn   r'   r'   r'   r(   <module>   s:    
7
 g