o
    ÔèFhOB  ã                   @   sÊ   d Z ddlZddlZddlmZ ddlm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	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)Ú_helpers)Úcredentials)Ú
exceptions)Újwt)Úmetricsz#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 credentialsi  z#https://oauth2.googleapis.com/tokenc              
   C   sÆ   |pt  |¡}t |¡ d¡}| |d||d�}t|jdƒr#|j d¡n|j}|jt	j
kr2t t|¡‚zt |¡}|d }	t |d d¡}
|	|
fW S  ttfyb } zt d t¡|¡}||‚d	}~ww )
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ÚdecodeÚaccessTokenÚ
expireTimez%Y-%m-%dT%H:%M:%SZz6{}: No access token or invalid expiration in response.N)Ú_IAM_ENDPOINTÚformatÚjsonÚdumpsÚencodeÚhasattrÚdatar   ÚstatusÚhttp_clientÚOKr   ÚRefreshErrorÚ_REFRESH_ERRORÚloadsr   ÚstrptimeÚKeyErrorÚ
ValueError)ÚrequestÚ	principalr   r   Úiam_endpoint_overrideÚiam_endpointÚresponseÚresponse_bodyÚtoken_responseÚtokenÚexpiryÚ
caught_excÚnew_exc© r,   ú]/var/www/html/loop/nvenv/lib/python3.10/site-packages/google/auth/impersonated_credentials.pyÚ_make_iam_token_request@   s0   
ÿý

ÿü€ù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                    s’   t t| ƒ ¡  t |¡| _t| jtjƒr+| j t	¡| _t
| jdƒr+| jjr+| j d¡ || _|| _|| _|p7t| _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.
        Ú_create_self_signed_jwtN)Úsuperr/   Ú__init__ÚcopyÚ_source_credentialsÚ
isinstancer   ÚScopedÚwith_scopesÚ
_IAM_SCOPEr   Ú_always_use_jwt_accessr0   Ú_target_principalÚ_target_scopesÚ
_delegatesÚ_DEFAULT_TOKEN_LIFETIME_SECSÚ	_lifetimer(   r   Úutcnowr)   Ú_quota_project_idÚ_iam_endpoint_override)ÚselfÚsource_credentialsÚtarget_principalÚtarget_scopesÚ	delegatesÚlifetimeÚquota_project_idr#   ©Ú	__class__r,   r-   r2   ·   s"   &
ÿþ


zCredentials.__init__c                 C   s   t jS ©N)r   ÚCRED_TYPE_SA_IMPERSONATE©rB   r,   r,   r-   Ú_metric_header_for_usageõ   s   z$Credentials._metric_header_for_usagec                 C   s   |   |¡ d S rK   )Ú_update_token)rB   r!   r,   r,   r-   Úrefreshø   s   zCredentials.refreshc                 C   s†   | j jtjjks| j jtjjkr| j  |¡ | j| jt	| j
ƒd dœ}ddtjt ¡ i}| j  |¡ t|| j||| jd�\| _| _dS )zòUpdates 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)rF   ÚscoperG   úContent-Typeúapplication/json)r!   r"   r   r   r#   N)r4   Útoken_stater   Ú
TokenStateÚSTALEÚINVALIDrP   r<   r;   Ústrr>   r   ÚAPI_CLIENT_HEADERÚ&token_request_access_token_impersonateÚapplyr.   r:   rA   r(   r)   )rB   r!   r   r   r,   r,   r-   rO   ü   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| ¡  w |jtjkrEt d | ¡ ¡¡‚t | ¡ d	 ¡S )
Nr   ©ÚAuthorizedSessionr   )ÚpayloadrF   rS   rT   )r
   r   r   zError calling sign_bytes: {}Ú
signedBlob)Úgoogle.auth.transport.requestsr^   Ú_IAM_SIGN_ENDPOINTr   r:   Úbase64Ú	b64encoder   r<   r4   ÚpostÚcloseÚstatus_coder   r   r   ÚTransportErrorr   Ú	b64decode)rB   Úmessager^   Úiam_sign_endpointr   r   Úauthed_sessionr%   r,   r,   r-   Ú
sign_bytes"  s"   þ
ÿÿzCredentials.sign_bytesc                 C   ó   | j S rK   ©r:   rM   r,   r,   r-   Úsigner_email>  ó   zCredentials.signer_emailc                 C   rn   rK   ro   rM   r,   r,   r-   Úservice_account_emailB  rq   z!Credentials.service_account_emailc                 C   s   | S rK   r,   rM   r,   r,   r-   ÚsignerF  s   zCredentials.signerc                 C   s   | j  S rK   )r;   rM   r,   r,   r-   Úrequires_scopesJ  s   zCredentials.requires_scopesc              	   C   s$   | j | j| j| j| j| j|| jd�S ©N)rD   rE   rF   rG   rH   r#   )rJ   r4   r:   r;   r<   r>   rA   ©rB   rH   r,   r,   r-   Úwith_quota_projectN  s   ùzCredentials.with_quota_projectc              	   C   s(   | j | j| j|p	|| j| j| j| jd�S ru   )rJ   r4   r:   r<   r>   r@   rA   )rB   ÚscopesÚdefault_scopesr,   r,   r-   r7   Z  s   ùzCredentials.with_scopesrK   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r=   r2   rN   r   Úcopy_docstringr   r/   rP   rO   rm   Úpropertyrp   rr   rs   rt   ÚCredentialsWithQuotaProjectrw   r6   r7   Ú__classcell__r,   r,   rI   r-   r/   w   s0    Bø>

&






r/   c                       sj   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)r1   r‚   r2   r5   r/   r   ÚGoogleAuthErrorÚ_target_credentialsÚ_target_audienceÚ_include_emailr@   )rB   Útarget_credentialsÚtarget_audienceÚinclude_emailrH   rI   r,   r-   r2   l  s   
ÿ
zIDTokenCredentials.__init__c                 C   s   | j ||| j| jd�S ©N)r‡   rˆ   r‰   rH   )rJ   r†   r@   )rB   r‡   rˆ   r,   r,   r-   Úfrom_credentials‡  s   üz#IDTokenCredentials.from_credentialsc                 C   s   | j | j|| j| jd�S rŠ   )rJ   r„   r†   r@   )rB   rˆ   r,   r,   r-   Úwith_target_audience�  s   üz'IDTokenCredentials.with_target_audiencec                 C   s   | j | j| j|| jd�S rŠ   )rJ   r„   r…   r@   )rB   r‰   r,   r,   r-   Úwith_include_email—  s   üz%IDTokenCredentials.with_include_emailc                 C   s   | j | j| j| j|d�S rŠ   )rJ   r„   r…   r†   rv   r,   r,   r-   rw   Ÿ  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�}z|j||t |¡ d¡d�}W | ¡  n| ¡  w |jtjkrRt d	 | ¡ ¡¡‚| ¡ d
 }|| _t tj|dd�d ¡| _d S )Nr   r]   )ÚaudiencerF   ÚincludeEmailrS   rT   )Úauth_requestr   )r
   r   r   zError getting ID token: {}r(   F)ÚverifyÚexp)ra   r^   Ú_IAM_IDTOKEN_ENDPOINTr   r„   rp   r…   r<   r†   r   rZ   Ú"token_request_id_token_impersonater4   re   r   r   r   rf   rg   r   r   r   r   r(   r   Úutcfromtimestampr   r   r)   )	rB   r!   r^   rk   r   r   rl   r%   Úid_tokenr,   r,   r-   rP   ¨  s<   ÿý
þÿýÿ
ÿzIDTokenCredentials.refresh)NFNrK   )rz   r{   r|   r}   r2   r‹   rŒ   r�   r   r~   r   r€   rw   r/   rP   r�   r,   r,   rI   r-   r‚   g  s    û



r‚   rK   )r}   rc   r3   r   Úhttp.clientÚclientr   r   Úgoogle.authr   r   r   r   r   r8   r   rb   r“   r   r=   Ú_DEFAULT_TOKEN_URIr.   r6   r€   ÚSigningr/   r‚   r,   r,   r,   r-   Ú<module>   s8   ÿÿÿ
ÿ
7ÿ q