o
    ýÞh‹a  ã                   @   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d	lmZ dd
lmZ ddlmZ dZdZdZdZdZdZejdfdd„ZG dd„ dejejejƒZG dd„ dejƒZg fdd„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)Ú_exponential_backoff)Ú_helpers©Úcredentials)Ú
exceptions)Úiam)Újwt)Úmetrics)Ú_clientz*Unable to acquire impersonated credentialsi  z#https://oauth2.googleapis.com/tokenÚauthorized_userÚservice_accountÚ external_account_authorized_userc              
   C   sÒ   |pt j tj|¡ |¡}t |¡ d¡}| |d||d�}t	|j
dƒr)|j
 d¡n|j
}|jtjkr8t t|¡‚zt |¡}	|	d }
t |	d d¡}|
|fW S  ttfyh } 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)r   Ú_IAM_ENDPOINTÚreplacer   ÚDEFAULT_UNIVERSE_DOMAINÚformatÚjsonÚdumpsÚencodeÚhasattrÚdatar   ÚstatusÚhttp_clientÚOKr   ÚRefreshErrorÚ_REFRESH_ERRORÚloadsr   ÚstrptimeÚKeyErrorÚ
ValueError)ÚrequestÚ	principalr   r   Úuniverse_domainÚiam_endpoint_overrideÚiam_endpointÚresponseÚresponse_bodyÚtoken_responseÚtokenÚexpiryÚ
caught_excÚnew_exc© r7   úd/var/www/html/premium_crap/venv/lib/python3.10/site-packages/google/auth/impersonated_credentials.pyÚ_make_iam_token_request9   s8   
ÿþ
ÿý

ÿü€ùr9   c                       sÜ   e Zd ZdZd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dd„ Ze e	j¡dd„ ƒZe e	j¡ddd„ƒZe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	j
¡| _t| jdƒr,| jjr,| j d¡ |j| _|| _|| _|| _|| _|p?t| _d| _t ¡ | _|| _|| _d| _dS )a$  
        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 (Optional[str]): The full IAM endpoint override
                with the target_principal embedded. This is useful when supporting
                impersonation with regional endpoints.
            subject (Optional[str]): sub field of a JWT. This field should only be set
                if you wish to impersonate as a user. This feature is useful when
                using domain wide delegation.
        Ú_create_self_signed_jwtN)Úsuperr:   Ú__init__ÚcopyÚ_source_credentialsÚ
isinstancer   ÚScopedÚwith_scopesr   Ú
_IAM_SCOPEr    Ú_always_use_jwt_accessr;   r-   Ú_universe_domainÚ_target_principalÚ_target_scopesÚ
_delegatesÚ_subjectÚ_DEFAULT_TOKEN_LIFETIME_SECSÚ	_lifetimer3   r   Úutcnowr4   Ú_quota_project_idÚ_iam_endpoint_overrideÚ_cred_file_path)	ÚselfÚsource_credentialsÚtarget_principalÚtarget_scopesÚ	delegatesÚsubjectÚlifetimeÚquota_project_idr.   ©Ú	__class__r7   r8   r=   ·   s,   *ÿ
ÿþ


zCredentials.__init__c                 C   s   t jS ©N)r
   ÚCRED_TYPE_SA_IMPERSONATE©rP   r7   r7   r8   Ú_metric_header_for_usageÿ   s   z$Credentials._metric_header_for_usagec                 C   s   |   |¡ d S rZ   )Ú_update_token)rP   r+   r7   r7   r8   Ú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  |¡ | jrv| jtjkr@t d¡‚t ¡ }| jt | jpLd¡| jtt |¡t |¡t dœ}t|| j||| jd�}t |t|¡\| _| _}d	S t || j||| 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)rT   ÚscoperV   úContent-Typeúapplication/jsonzNDomain-wide delegation is not supported in universes other than googleapis.comr7   )Úissra   ÚsubÚaudÚiatÚexp)r+   r,   r   ÚpayloadrT   N)r+   r,   r   r   r-   r.   )"r?   Útoken_stater   Ú
TokenStateÚSTALEÚINVALIDr_   rH   rG   ÚstrrK   r
   ÚAPI_CLIENT_HEADERÚ&token_request_access_token_impersonateÚapplyrI   r-   r   r   ÚGoogleAuthErrorr   rL   rF   Úscopes_to_stringÚ_GOOGLE_OAUTH2_TOKEN_ENDPOINTÚdatetime_to_secsrJ   Ú_sign_jwt_requestr   Ú	jwt_grantr3   r4   r9   rN   )rP   r+   r   r   Únowri   Ú	assertionÚ_r7   r7   r8   r^     sV   ý
þÿú	ûÿúzCredentials._update_tokenc           
      C   sà   ddl m} tj tj| j¡ | j	¡}t
 |¡ d¡| jdœ}ddi}|| jƒ}z=t ¡ }|D ]0}|j|||d�}	|	jtjv r@q/|	jtjkrPt d |	 ¡ ¡¡‚t
 |	 ¡ d	 ¡  W | ¡  S W | ¡  n| ¡  w t d
¡‚)Nr   ©ÚAuthorizedSessionr   )ri   rT   rb   rc   )r   r   r   zError calling sign_bytes: {}Ú
signedBlobz#exhausted signBlob endpoint retries)Úgoogle.auth.transport.requestsr|   r   Ú_IAM_SIGN_ENDPOINTr   r   r   r-   r   rF   Úbase64Ú	b64encoder   rH   r?   r   ÚExponentialBackoffÚpostÚstatus_codeÚIAM_RETRY_CODESr#   r$   r   ÚTransportErrorr   Ú	b64decodeÚclose)
rP   Úmessager|   Úiam_sign_endpointr   r   Úauthed_sessionÚretriesrz   r0   r7   r7   r8   Ú
sign_bytesN  s8   ÿþþ
ÿÿ
ó
zCredentials.sign_bytesc                 C   ó   | j S rZ   ©rF   r\   r7   r7   r8   Úsigner_emailp  ó   zCredentials.signer_emailc                 C   rŽ   rZ   r�   r\   r7   r7   r8   Úservice_account_emailt  r‘   z!Credentials.service_account_emailc                 C   s   | S rZ   r7   r\   r7   r7   r8   Úsignerx  s   zCredentials.signerc                 C   s   | j  S rZ   )rG   r\   r7   r7   r8   Úrequires_scopes|  s   zCredentials.requires_scopesc                 C   s   | j r| j d| jdœS d S )Nzimpersonated credentials)Úcredential_sourceÚcredential_typer,   )rO   rF   r\   r7   r7   r8   Úget_cred_info€  s   ýzCredentials.get_cred_infoc              	   C   s2   | j | j| j| j| j| j| j| jd�}| j|_|S )N)rR   rS   rT   rV   rW   r.   )	rY   r?   rF   rG   rH   rK   rM   rN   rO   )rP   Úcredr7   r7   r8   Ú
_make_copyŠ  s   ù	zCredentials._make_copyc                 C   s   |   ¡ }||_|S rZ   )r™   rM   )rP   rW   r˜   r7   r7   r8   Úwith_quota_project—  s   zCredentials.with_quota_projectc                 C   s   |   ¡ }|p||_|S rZ   )r™   rG   )rP   ÚscopesÚdefault_scopesr˜   r7   r7   r8   rB   �  s   
zCredentials.with_scopesc                 C   s  |  d¡}|  d¡}|tkrddlm} |j |¡}n*|tkr,ddlm} |j |¡}n|t	kr=ddl
m} |j |¡}nt d |¡¡‚|  d¡}	|	 d	¡}
|	 d
¡}|
dks`|dks`|
|krht d |	¡¡‚|	|
d |… }|  d¡}|  d¡}| |||||d�S )aè  Creates a Credentials instance from parsed impersonated service account credentials info.

        Args:
            info (Mapping[str, str]): The impersonated service account credentials info in Google
                format.
            scopes (Sequence[str]): Optional list of scopes to include in the
                credentials.

        Returns:
            google.oauth2.credentials.Credentials: The constructed
                credentials.

        Raises:
            InvalidType: If the info["source_credentials"] are not a supported impersonation type
            InvalidValue: If the info["service_account_impersonation_url"] is not in the expected format.
            ValueError: If the info is not in the expected format.
        rQ   Útyper   r   )r   )r   z.source credential of type {} is not supported.Ú!service_account_impersonation_urlú/z:generateAccessTokenéÿÿÿÿz'Cannot extract target principal from {}é   rT   rW   )rW   )ÚgetÚ'_SOURCE_CREDENTIAL_AUTHORIZED_USER_TYPEÚgoogle.oauth2r   r:   Úfrom_authorized_user_infoÚ'_SOURCE_CREDENTIAL_SERVICE_ACCOUNT_TYPEr   Úfrom_service_account_infoÚ8_SOURCE_CREDENTIAL_EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPEÚgoogle.authr   Ú	from_infor   ÚInvalidTyper   ÚrfindÚfindÚInvalidValue)ÚclsÚinfor›   Úsource_credentials_infoÚsource_credentials_typer   rQ   r   r   Úimpersonation_urlÚstart_indexÚ	end_indexrR   rT   rW   r7   r7   r8   Ú&from_impersonated_service_account_info£  sR   

ÿÿÿÿÿÿ


ÿ

ûz2Credentials.from_impersonated_service_account_inforZ   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__rJ   r=   r]   r   Úcopy_docstringr   r:   r_   r^   r�   Úpropertyr�   r’   r“   r”   r—   r™   ÚCredentialsWithQuotaProjectrš   rA   rB   Úclassmethodr¶   Ú__classcell__r7   r7   rX   r8   r:   w   s<    B÷H

H"





	


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)r<   rÀ   r=   r@   r:   r   rr   Ú_target_credentialsÚ_target_audienceÚ_include_emailrM   )rP   Útarget_credentialsÚtarget_audienceÚinclude_emailrW   rX   r7   r8   r=   î  s   
ÿ
zIDTokenCredentials.__init__c                 C   s   | j ||| j| jd�S ©N)rÄ   rÅ   rÆ   rW   )rY   rÃ   rM   )rP   rÄ   rÅ   r7   r7   r8   Úfrom_credentials	  s   üz#IDTokenCredentials.from_credentialsc                 C   s   | j | j|| j| jd�S rÇ   )rY   rÁ   rÃ   rM   )rP   rÅ   r7   r7   r8   Úwith_target_audience  s   üz'IDTokenCredentials.with_target_audiencec                 C   s   | j | j| j|| jd�S rÇ   )rY   rÁ   rÂ   rM   )rP   rÆ   r7   r7   r8   Úwith_include_email  s   üz%IDTokenCredentials.with_include_emailc                 C   s   | j | j| j| j|d�S rÇ   )rY   rÁ   rÂ   rÃ   )rP   rW   r7   r7   r8   rš   !  s   üz%IDTokenCredentials.with_quota_projectc           	      C   sä   ddl m} tj tj| jj¡ 	| 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rZt d	 	| ¡ ¡¡‚| ¡ d
 }|| _t tj |dd�d ¡| _!d S )Nr   r{   )ÚaudiencerT   ÚincludeEmailrb   rc   )Úauth_requestr   )r   r   r!   zError getting ID token: {}r3   F)Úverifyrh   )"r~   r|   r   Ú_IAM_IDTOKEN_ENDPOINTr   r   r   rÁ   r-   r   r�   rÂ   rH   rÃ   r
   ro   Ú"token_request_id_token_impersonater?   rƒ   r   r   r   rˆ   r„   r#   r$   r   r%   r3   r   Úutcfromtimestampr	   r   r4   )	rP   r+   r|   rŠ   r   r   r‹   r0   Úid_tokenr7   r7   r8   r_   *  sB   þ
ýý
þÿýÿ
ÿzIDTokenCredentials.refresh)NFNrZ   )r·   r¸   r¹   rº   r=   rÈ   rÉ   rÊ   r   r»   r   r½   rš   r:   r_   r¿   r7   r7   rX   r8   rÀ   é  s    û



rÀ   c              
   C   sÀ   t j |¡}|t |¡dœ}t |¡ d¡}| |d||d�}t|jdƒr*|j d¡n|j}|j	t
jkr9t t|¡‚zt |¡}	|	d }
|
W S  ttfy_ } zt d t¡|¡}||‚d}~ww )	aû  Makes a request to the Google Cloud IAM service to sign a JWT using a
    service account's system-managed private key.
    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.
        payload (Mapping[str, str]): The JWT payload to sign. Must be a
            serialized JSON object that contains a JWT Claims Set.
        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.

    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
    )rT   ri   r   r   r   r   Ú	signedJwtz{}: No signed JWT in response.N)r   Ú_IAM_SIGNJWT_ENDPOINTr   r   r   r   r    r!   r   r"   r#   r$   r   r%   r&   r'   r)   r*   )r+   r,   r   ri   rT   r/   r   r0   r1   Újwt_responseÚ
signed_jwtr5   r6   r7   r7   r8   rv   W  s*   
ÿý

ÿ€ürv   ) rº   r€   r>   r   Úhttp.clientÚclientr#   r   r©   r   r   r   r   r   r	   r
   r¤   r   r&   rJ   rt   r£   r¦   r¨   r   r9   rA   r½   ÚSigningr:   rÀ   rv   r7   r7   r7   r8   Ú<module>   s>   ÿ

ú
>ÿ  tn