
    @fOB                        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Z G d de
j        e
j        e
j                  Z G 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                 z   |pt                               |          }t          j        |                              d          } | |d||          }t          |j        d          r|j                            d          n|j        }|j        t          j
        k    rt          j        t          |          	 t          j        |          }|d         }	t          j        |d         d          }
|	|
fS # t"          t$          f$ r5}t          j        d                    t                    |          }||d	}~ww xY 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_excs                s/home/panchajanya/Development/work/volatility3/lib/python3.11/site-packages/google/auth/impersonated_credentials.py_make_iam_token_requestr/   @   sE   , )KM,@,@,K,KL:d""7++Dw<dSSSH
 8=(++	W%%%]  +.((%nmDDD&M22}-">,#?AUVVf}j! & & &)DKK  	
 
 :%&s   9:C4 4D:0D55D:c                   L    e Zd ZdZdeddf fd	Zd Z ej        e	j
                  d             Zd Zd Zed             Zed	             Zed
             Zed             Z ej        e	j                  d             Z ej        e	j                  dd            Z x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                 $   t          t          |                                            t          j        |          | _        t          | j        t          j                  r_| j                            t                    | _        t          | j        d          r&| j        j        r| j                            d           || _        || _        || _        |pt           | _        d| _        t'          j                    | _        || _        || _        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)superr1   __init__copy_source_credentials
isinstancer   Scopedwith_scopes
_IAM_SCOPEr   _always_use_jwt_accessr3   _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__s	           r.   r5   zCredentials.__init__   s    L 	k4  ))+++#'9-?#@#@  d.0BCC 	G'+'?'K'KJ'W'WD$ 02KLLG,CG (@@FFF!1+#!A%A
o''!1&;###    c                     t           j        S N)r   CRED_TYPE_SA_IMPERSONATErE   s    r.   _metric_header_for_usagez$Credentials._metric_header_for_usage   s    //rM   c                 0    |                      |           d S rO   )_update_token)rE   r#   s     r.   refreshzCredentials.refresh   s    7#####rM   c                    | j         j        t          j        j        k    s| j         j        t          j        j        k    r| j                             |           | j        | j        t          | j
                  dz   d}ddt          j        t          j                    i}| j                             |           t          || j        ||| j                  \  | _        | _        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)rI   scoperJ   Content-Typeapplication/json)r#   r$   r   r   r%   N)r7   token_stater   
TokenStateSTALEINVALIDrU   r?   r>   strrA   r   API_CLIENT_HEADER&token_request_access_token_impersonateapplyr/   r=   rD   r*   r+   )rE   r#   r   r   s       r.   rT   zCredentials._update_token   s     $0K4J4PPP'3{7M7UUU$,,W555 (DN++c1
 
 .%w'U'W'W
 	 &&w///"9,"&"=#
 #
 #

DKKKrM   c                 T   ddl m} t                              | j                  }t          j        |                              d          | j        d}ddi} || j	                  }	 |
                    |||          }|                                 n# |                                 w xY w|j        t          j        k    r9t          j        d                    |                                                    t          j        |                                d	                   S )
Nr   AuthorizedSessionr
   )payloadrI   rY   rZ   )r   r   r   zError calling sign_bytes: {}
signedBlob)google.auth.transport.requestsre   _IAM_SIGN_ENDPOINTr   r=   base64	b64encoder   r?   r7   postclosestatus_coder   r   r   TransportErrorr   	b64decode)rE   messagere   iam_sign_endpointr   r   authed_sessionr'   s           r.   
sign_byteszCredentials.sign_bytes"  s-   DDDDDD.55d6LMM '0077@@
 

 "#56**4+CDD	#%**%wT +  H   """"N  """";>11+.55hmmooFF    =>>>s   *B B-c                     | j         S rO   r=   rQ   s    r.   signer_emailzCredentials.signer_email>      %%rM   c                     | j         S rO   rv   rQ   s    r.   service_account_emailz!Credentials.service_account_emailB  rx   rM   c                     | S rO    rQ   s    r.   signerzCredentials.signerF  s    rM   c                     | j          S rO   )r>   rQ   s    r.   requires_scopeszCredentials.requires_scopesJ  s    &&&rM   c           	      v    |                      | j        | j        | j        | j        | j        || j                  S N)rG   rH   rI   rJ   rK   r%   )rL   r7   r=   r>   r?   rA   rD   rE   rK   s     r.   with_quota_projectzCredentials.with_quota_projectN  sB    ~~$!3-o^-"&"=  
 
 	
rM   c           	      z    |                      | j        | j        |p|| j        | j        | j        | j                  S r   )rL   r7   r=   r?   rA   rC   rD   )rE   scopesdefault_scopess      r.   r:   zCredentials.with_scopesZ  sG    ~~$!3 2No^!3"&"=  
 
 	
rM   rO   )__name__
__module____qualname____doc__r@   r5   rR   r   copy_docstringr   r1   rU   rT   rt   propertyrw   rz   r}   r   CredentialsWithQuotaProjectr   r9   r:   __classcell__rL   s   @r.   r1   r1   w   s{       ; ;D -"<< << << << << <<|0 0 0 X[455$ $ 65$$
 $
 $
L? ? ?8 & & X& & & X&   X ' ' X' X[DEE	
 	
 FE	
 X[/00	
 	
 	
 10	
 	
 	
 	
 	
rM   r1   c                        e Zd ZdZ	 	 	 d
 fd	ZddZd Zd Z ej	        e
j                  d             Z ej	        e
j                  d	             Z xZS )IDTokenCredentialszAOpen ID Connect ID Token-based service account credentials.

    NFc                     t          t          |                                            t          |t                    st          j        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)r4   r   r5   r8   r1   r   GoogleAuthError_target_credentials_target_audience_include_emailrC   )rE   target_credentialstarget_audienceinclude_emailrK   rL   s        r.   r5   zIDTokenCredentials.__init__l  su      	 $''00222,k:: 	,I   $6  /+!1rM   c                 H    |                      ||| j        | j                  S N)r   r   r   rK   )rL   r   rC   )rE   r   r   s      r.   from_credentialsz#IDTokenCredentials.from_credentials  s/    ~~1+-!3	  
 
 	
rM   c                 R    |                      | j        || j        | j                  S r   )rL   r   r   rC   )rE   r   s     r.   with_target_audiencez'IDTokenCredentials.with_target_audience  s2    ~~#7+-!3	  
 
 	
rM   c                 R    |                      | j        | j        || j                  S r   )rL   r   r   rC   )rE   r   s     r.   with_include_emailz%IDTokenCredentials.with_include_email  s2    ~~#7 1'!3	  
 
 	
rM   c                 R    |                      | j        | j        | j        |          S r   )rL   r   r   r   r   s     r.   r   z%IDTokenCredentials.with_quota_project  s2    ~~#7 1--	  
 
 	
rM   c                    ddl m} t                              | j        j                  }| j        | j        j        | j        d}ddt          j
        t          j                    i} || j        j        |          }	 |                    ||t          j        |                              d                    }|                                 n# |                                 w xY w|j        t&          j        k    r9t+          j        d	                    |                                                    |                                d
         }|| _        t1          j        t5          j        |d          d                   | _        d S )Nr   rd   )audiencerI   includeEmailrY   rZ   )auth_requestr
   )r   r   r   zError getting ID token: {}r*   F)verifyexp)rh   re   _IAM_IDTOKEN_ENDPOINTr   r   rw   r   r?   r   r   r`   "token_request_id_token_impersonater7   rl   r   r   r   rm   rn   r   r   r   r   r*   r   utcfromtimestampr   r   r+   )	rE   r#   re   rr   r   r   rs   r'   id_tokens	            r.   rU   zIDTokenCredentials.refresh  s   DDDDDD188$1
 

 -1< /
 
 .%w'Q'S'S

 +*$8w
 
 
	#%**%Z%%,,W55 +  H   """"N  """";>11),33HMMOODD   ==??7+
/Jx...u5
 
s   >=C C&)NFNrO   )r   r   r   r   r5   r   r   r   r   r   r   r   r   r1   rU   r   r   s   @r.   r   r   g  s          2 2 2 2 2 26
 
 
 

 
 

 
 
 X[DEE
 
 FE
 X[455(
 (
 65(
 (
 (
 (
 (
rM   r   rO   )r   rj   r6   r   http.clientclientr   r   google.authr   r   r   r   r   r;   r   ri   r   r   r@   _DEFAULT_TOKEN_URIr/   r9   r   Signingr1   r   r|   rM   r.   <module>r      s            ! ! ! ! ! !              # # # # # # " " " " " "            34
0 % 6 
 ># :  >B4& 4& 4& 4&nm
 m
 m
 m
 m
?ATm
 m
 m
`j
 j
 j
 j
 j
@ j
 j
 j
 j
 j
rM   