
    ha                     6   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Z G d dej        ej        ej                  Z G d dej                  Zg f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                    |p<t           j                            t          j        |                              |          }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)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_excs                 h/var/www/html/e360mart/e360mart_env/lib/python3.11/site-packages/google/auth/impersonated_credentials.py_make_iam_token_requestr:   9   sf   6 ) C,=,E,E+_- -fY  :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   :D E(0EEc                       e Zd ZdZd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d Z ej        e	j                  d             Z ej        e	j                  dd            Ze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	                 b   t          t          |                                            t          j        |          | _        t          | j        t          j                  rd| j                            t          j
                  | _        t          | j        d          r&| j        j        r| j                            d           |j        | _        || _        || _        || _        || _        |pt(          | _        d| _        t/          j                    | _        || _        || _        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	_lifetimer5   r   utcnowr6   _quota_project_id_iam_endpoint_override_cred_file_path)
selfsource_credentialstarget_principaltarget_scopes	delegatessubjectlifetimequota_project_idr0   	__class__s
            r9   r@   zCredentials.__init__   s   T 	k4  ))+++#'9-?#@#@  d.0BCC 
	G'+'?'K'K( (D$ 02KLLG,CG (@@FFF 2 B!1+#!A%A
o''!1&;##    c                     t           j        S N)r   CRED_TYPE_SA_IMPERSONATErS   s    r9   _metric_header_for_usagez$Credentials._metric_header_for_usage   s    //r\   c                 0    |                      |           d S r^   )_update_token)rS   r-   s     r9   refreshzCredentials.refresh  s    7#####r\   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                             |           | j        r| j        t          j        k    rt%          j        d          t)          j                    }| j        t)          j        | j        pd          | j        t0          t)          j        |          t)          j        |          t4          z   d}t7          || j        ||| j                  }t9          j        |t0          |          \  | _        | _        }d	S tA          || j        ||| 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)rW   scoperY   Content-Typeapplication/jsonzNDomain-wide delegation is not supported in universes other than googleapis.com )issrg   subaudiatexp)r-   r.   r   payloadrW   N)r-   r.   r   r   r/   r0   )"rB   token_stater   
TokenStateSTALEINVALIDrd   rK   rJ   strrN   r   API_CLIENT_HEADER&token_request_access_token_impersonateapplyrL   r/   r   r   GoogleAuthErrorr   rO   rI   scopes_to_string_GOOGLE_OAUTH2_TOKEN_ENDPOINTdatetime_to_secsrM   _sign_jwt_requestr   	jwt_grantr5   r6   r:   rQ   )rS   r-   r   r   nowrp   	assertion_s           r9   rc   zCredentials._update_token  s    $0K4J4PPP'3{7M7UUU$,,W555 (DN++c1
 
 .%w'U'W'W
 	 &&w/// = 	#{'JJJ 0,  
 /##C-!243F3L"MM}40550558TT G *0/  I *1):6	* *&DJQ F"9, 0"&"=#
 #
 #

DKKKr\   c                 P   ddl m} t          j                            t
          j        | j                                      | j	                  }t          j        |                              d          | j        d}ddi} || j                  }	 t          j                    }|D ]}|                    |||          }	|	j        t          j        v r.|	j        t(          j        k    r9t-          j        d                    |	                                                    t          j        |	                                d	                   c |                                 S 	 |                                 n# |                                 w xY wt-          j        d
          )Nr   AuthorizedSessionr   )rp   rW   rh   ri   )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   rI   base64	b64encoder   rK   rB   r   ExponentialBackoffpoststatus_codeIAM_RETRY_CODESr%   r&   r   TransportErrorr   	b64decodeclose)
rS   messager   iam_sign_endpointr   r   authed_sessionretriesr   r2   s
             r9   
sign_byteszCredentials.sign_bytesN  s   DDDDDD2::/1E
 

&'
(
( 	
 '0077@@
 

 "#56**4+CDD	#*=??G G G)..)7 /   '3+>>>';>99$36==hmmooNN   '(EFFFF  """"G   """"N  """"'(MNNNs   B>E; ;Fc                     | j         S r^   rI   r`   s    r9   signer_emailzCredentials.signer_emailp      %%r\   c                     | j         S r^   r   r`   s    r9   service_account_emailz!Credentials.service_account_emailt  r   r\   c                     | S r^   rj   r`   s    r9   signerzCredentials.signerx  s    r\   c                     | j          S r^   )rJ   r`   s    r9   requires_scopeszCredentials.requires_scopes|  s    &&&r\   c                 4    | j         r| j         d| j        dS d S )Nzimpersonated credentials)credential_sourcecredential_typer.   )rR   rI   r`   s    r9   get_cred_infozCredentials.get_cred_info  s2     	%)%9#=!3  
 tr\   c           	          |                      | j        | j        | j        | j        | j        | j        | j                  }| j        |_        |S )N)rU   rV   rW   rY   rZ   r0   )	r[   rB   rI   rJ   rK   rN   rP   rQ   rR   )rS   creds     r9   
_make_copyzCredentials._make_copy  sT    ~~$!3-o^!3"&"=  
 
  $3r\   c                 <    |                                  }||_        |S r^   )r   rP   )rS   rZ   r   s      r9   with_quota_projectzCredentials.with_quota_project  s      !1r\   c                 @    |                                  }|p||_        |S r^   )r   rJ   )rS   scopesdefault_scopesr   s       r9   rE   zCredentials.with_scopes  s#      $6r\   c                 *   |                     d          }|                     d          }|t          k    r!ddlm} |j                            |          }n|t          k    r!ddlm} |j                            |          }nS|t          k    r!ddl
m} |j                            |          }n't          j        d                    |                    |                     d          }	|	                    d	          }
|	                    d
          }|
dk    s|dk    s|
|k    r't          j        d                    |	                    |	|
dz   |         }|                     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.
        rT   typer   r   )r   )r   z.source credential of type {} is not supported.!service_account_impersonation_url/z:generateAccessTokenz'Cannot extract target principal from {}   rW   rZ   )rZ   )get'_SOURCE_CREDENTIAL_AUTHORIZED_USER_TYPEgoogle.oauth2r   r<   from_authorized_user_info'_SOURCE_CREDENTIAL_SERVICE_ACCOUNT_TYPEr   from_service_account_info8_SOURCE_CREDENTIAL_EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPEgoogle.authr   	from_infor   InvalidTyper   rfindfindInvalidValue)clsinfor   source_credentials_infosource_credentials_typer   rT   r   r   impersonation_urlstart_index	end_indexrU   rW   rZ   s                  r9   &from_impersonated_service_account_infoz2Credentials.from_impersonated_service_account_info  s   ( #'((+?"@"@"9"="=f"E"E"&MMM111111!,!8!R!R'" " %(OOO555555!0!<!V!V'" " $GH H EDDDDD!A!M!W!W'" " (@GG+    !HH%HII'--c22%**+ABB	"	R;3J3J)9@@ARSS   -[1_y-HIHH[))	88$677s-
 
 
 	
r\   r^   )__name__
__module____qualname____doc__rM   r@   ra   r   copy_docstringr   r<   rd   rc   r   propertyr   r   r   r   r   r   CredentialsWithQuotaProjectr   rD   rE   classmethodr   __classcell__r[   s   @r9   r<   r<   w   s       ; ;D -"F$ F$ F$ F$ F$ F$P0 0 0 X[455$ $ 65$F
 F
 F
P O  O  OD & & X& & & X&   X ' ' X' X[455  65   X[DEE  FE
 X[/00   10
 B
 B
 B
 [B
 B
 B
 B
 B
r\   r<   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)r?   r   r@   rC   r<   r   ry   _target_credentials_target_audience_include_emailrP   )rS   target_credentialstarget_audienceinclude_emailrZ   r[   s        r9   r@   zIDTokenCredentials.__init__  su      	 $''00222,k:: 	,I   $6  /+!1r\   c                 H    |                      ||| j        | j                  S N)r   r   r   rZ   )r[   r   rP   )rS   r   r   s      r9   from_credentialsz#IDTokenCredentials.from_credentials	  s/    ~~1+-!3	  
 
 	
r\   c                 R    |                      | j        || j        | j                  S r   )r[   r   r   rP   )rS   r   s     r9   with_target_audiencez'IDTokenCredentials.with_target_audience  s2    ~~#7+-!3	  
 
 	
r\   c                 R    |                      | j        | j        || j                  S r   )r[   r   r   rP   )rS   r   s     r9   with_include_emailz%IDTokenCredentials.with_include_email  s2    ~~#7 1'!3	  
 
 	
r\   c                 R    |                      | j        | j        | j        |          S r   )r[   r   r   r   )rS   rZ   s     r9   r   z%IDTokenCredentials.with_quota_project!  s2    ~~#7 1--	  
 
 	
r\   c                 t   ddl m} t          j                            t
          j        | j        j                  	                    | 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        t0          j        k    r9t5          j        d		                    |                                                    |                                d
         }|| _        t;          j        t?          j         |d          d                   | _!        d S )Nr   r   )audiencerW   includeEmailrh   ri   )auth_requestr   )r   r   r#   zError getting ID token: {}r5   F)verifyro   )"r   r   r	   _IAM_IDTOKEN_ENDPOINTr   r   r   r   r/   r   r   r   rK   r   r   rv   "token_request_id_token_impersonaterB   r   r   r    r!   r   r   r%   r&   r   r'   r5   r   utcfromtimestampr
   r   r6   )	rS   r-   r   r   r   r   r   r2   id_tokens	            r9   rd   zIDTokenCredentials.refresh*  s   DDDDDD5==/$4
 
 &)6
7
7 	 -1< /
 
 .%w'Q'S'S

 +*$8w
 
 
	#%**%Z%%,,W55 +  H   """"N  """";>11),33HMMOODD   ==??7+
/Jx...u5
 
s   +=C= =D)NFNr^   )r   r   r   r   r@   r   r   r   r   r   r   r   r   r<   rd   r   r   s   @r9   r   r     s          2 2 2 2 2 26
 
 
 

 
 

 
 
 X[DEE
 
 FE
 X[455)
 )
 65)
 )
 )
 )
 )
r\   r   c                 t   t           j                            |          }|t          j        |          d}t          j        |                              d          } | |d||          }t          |j        d          r|j                            d          n|j        }|j	        t          j        k    rt          j        t          |          	 t          j        |          }	|	d         }
|
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 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
    )rW   rp   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   rp   rW   r1   r   r2   r3   jwt_response
signed_jwtr7   r8   s                r9   r}   r}   W  s6   : ,33I>>L"tz'/B/BCCD:d""7++Dw<dSSSH
 8=(++	W%%%]  +.((%nmDDD	&z-00!+.
j! & & &),33NCC]
 
 :%	&s   C1 1D70D22D7) r   r   rA   r   http.clientclientr%   r   r   r   r   r   r   r	   r
   r   r   r   r(   rM   r{   r   r   r   r   r:   rD   r   Signingr<   r   r}   rj   r\   r9   <module>r      s            ! ! ! ! ! !  , , , , , ,             # # # # # # " " " " " "                   ! ! ! ! ! ! >#  E *; '*; '& 9  7;& ;& ;& ;&|o
 o
 o
 o
 o
?ATo
 o
 o
dk
 k
 k
 k
 k
@ k
 k
 k
\ GI 7& 7& 7& 7& 7& 7&r\   