
    g#E                     4   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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y)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)metricsz*Unable to acquire impersonated credentialsi  c                    |xs= t         j                  j                  t        j                  |      j                  |      }t        j                  |      j                  d      } | |d||      }t        |j                  d      r|j                  j                  d      n|j                  }|j                  t        j                  k7  rt        j                   t"        |      	 t        j$                  |      }	|	d   }
t'        j(                  |	d   d      }|
|fS # t*        t,        f$ r1}t        j                   dj                  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                 Y/var/www/openai/venv/lib/python3.12/site-packages/google/auth/impersonated_credentials.py_make_iam_token_requestr4   0   s=   6 ) C,=,=,E,E++_-fY  ::d""7+D<dSH
 8==(+ 	W%]]  +..(%%nmDD&M2}-"">,#?AUVf}j! &))DKK 	
 :%&s   '6D E-,EEc                       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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                 d   t         t        |           t        j                  |      | _        t        | j                  t        j                        ru| j                  j                  t        j                        | _        t        | j                  d      r1| j                  j                  r| j                  j                  d       |j                  | _        || _        || _        || _        |xs t&        | _        d| _        t-        j.                         | _        || _        || _        d| _        y)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)superr6   __init__copy_source_credentials
isinstancer   Scopedwith_scopesr   
_IAM_SCOPEr   _always_use_jwt_accessr8   r)   _universe_domain_target_principal_target_scopes
_delegates_DEFAULT_TOKEN_LIFETIME_SECS	_lifetimer/   r   utcnowr0   _quota_project_id_iam_endpoint_override_cred_file_path)	selfsource_credentialstarget_principaltarget_scopes	delegateslifetimequota_project_idr*   	__class__s	           r3   r:   zCredentials.__init__   s    L 	k4)+#'99-?#@  d..0B0BC'+'?'?'K'K(D$ 002KL,,CC((@@F 2 B B!1+#!A%A
oo'!1&;##    c                 "    t         j                  S N)r
   CRED_TYPE_SA_IMPERSONATErL   s    r3   _metric_header_for_usagez$Credentials._metric_header_for_usage   s    ///rT   c                 &    | j                  |       y rV   )_update_token)rL   r'   s     r3   refreshzCredentials.refresh   s    7#rT   c                 X   | j                   j                  t        j                  j                  k(  s1| j                   j                  t        j                  j
                  k(  r| j                   j                  |       | j                  | j                  t        | j                        dz   d}ddt        j                  t        j                         i}| j                   j                  |       t        || j                   ||| j"                  | j$                        \  | _        | _        y)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)rP   scoperQ   Content-Typeapplication/json)r'   r(   r   r   r)   r*   N)r<   token_stater   
TokenStateSTALEINVALIDr\   rE   rD   strrG   r
   API_CLIENT_HEADER&token_request_access_token_impersonateapplyr4   rC   r)   rJ   r/   r0   )rL   r'   r   r   s       r3   r[   zCredentials._update_token   s     $$00K4J4J4P4PP''33{7M7M7U7UU$$,,W5 ((DNN+c1
 .%%w'U'U'W
 	  &&w/"9,, 00"&"="=#

DKrT   c                 Z   ddl m} t        j                  j	                  t
        j                  | j                        j                  | j                        }t        j                  |      j                  d      | j                  d}ddi} || j                        }	 t        j                          }|D ]  }|j#                  |||      }	|	j$                  t        j&                  v r4|	j$                  t(        j*                  k7  r2t-        j.                  dj                  |	j1                                     t        j2                  |	j1                         d	         c |j5                          S  	 |j5                          t-        j.                  d
      # |j5                          w xY w)Nr   AuthorizedSessionr   )payloadrP   r`   ra   )r   r   r   zError calling sign_bytes: {}
signedBlobz#exhausted signBlob endpoint retries)google.auth.transport.requestsrl   r   _IAM_SIGN_ENDPOINTr   r   r   r)   r   rC   base64	b64encoder   rE   r<   r   ExponentialBackoffpoststatus_codeIAM_RETRY_CODESr   r    r   TransportErrorr   	b64decodeclose)
rL   messagerl   iam_sign_endpointr   r   authed_sessionretries_r,   s
             r3   
sign_byteszCredentials.sign_bytes  sj   D22:://1E1E

&''
( 	
 ''077@

 "#56*4+C+CD	#*==?G)..)7 /  ''3+>+>>'';>>9$336==hmmoN  ''(EFF  "    "''(MNN   "s    C F 1F F*c                     | j                   S rV   rC   rX   s    r3   signer_emailzCredentials.signer_emailA      %%%rT   c                     | j                   S rV   r   rX   s    r3   service_account_emailz!Credentials.service_account_emailE  r   rT   c                     | S rV    rX   s    r3   signerzCredentials.signerI  s    rT   c                     | j                    S rV   )rD   rX   s    r3   requires_scopeszCredentials.requires_scopesM  s    &&&&rT   c                 P    | j                   r| j                   d| j                  dS y )Nzimpersonated credentials)credential_sourcecredential_typer(   )rK   rC   rX   s    r3   get_cred_infozCredentials.get_cred_infoQ  s/    %)%9%9#=!33 
 rT   c           	          | j                  | j                  | j                  | j                  | j                  | j
                  | j                  | j                        }| j                  |_        |S )N)rN   rO   rP   rQ   rR   r*   )	rS   r<   rC   rD   rE   rG   rI   rJ   rK   )rL   creds     r3   
_make_copyzCredentials._make_copy[  se    ~~$$!33--oo^^!33"&"="=  
  $33rT   c                 4    | j                         }||_        |S rV   )r   rI   )rL   rR   r   s      r3   with_quota_projectzCredentials.with_quota_projecth  s     !1rT   c                 <    | j                         }|xs ||_        |S rV   )r   rD   )rL   scopesdefault_scopesr   s       r3   r?   zCredentials.with_scopesn  s      $6rT   rV   )__name__
__module____qualname____doc__rF   r:   rY   r   copy_docstringr   r6   r\   r[   r   propertyr   r   r   r   r   r   CredentialsWithQuotaProjectr   r>   r?   __classcell__rS   s   @r3   r6   r6   n   s"   ;D -"A$F0 X[445$ 6$%
N OD & & & &   ' ' X[445 6 X[DDE F
 X[//0 1rT   r6   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.

    c                     t         t        |           t        |t              st        j                  d      || _        || _        || _	        || _
        y)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)r9   r   r:   r=   r6   r   GoogleAuthError_target_credentials_target_audience_include_emailrI   )rL   target_credentialstarget_audienceinclude_emailrR   rS   s        r3   r:   zIDTokenCredentials.__init__z  sV      	 $02,k:,,I  $6  /+!1rT   c                 T    | j                  ||| j                  | j                        S N)r   r   r   rR   )rS   r   rI   )rL   r   r   s      r3   from_credentialsz#IDTokenCredentials.from_credentials  s0    ~~1+--!33	  
 	
rT   c                 h    | j                  | j                  || j                  | j                        S r   )rS   r   r   rI   )rL   r   s     r3   with_target_audiencez'IDTokenCredentials.with_target_audience  s6    ~~#77+--!33	  
 	
rT   c                 h    | j                  | j                  | j                  || j                        S r   )rS   r   r   rI   )rL   r   s     r3   with_include_emailz%IDTokenCredentials.with_include_email  s6    ~~#77 11'!33	  
 	
rT   c                 h    | j                  | j                  | j                  | j                  |      S r   )rS   r   r   r   )rL   rR   s     r3   r   z%IDTokenCredentials.with_quota_project  s6    ~~#77 11---	  
 	
rT   c                    ddl m} t        j                  j	                  t
        j                  | j                  j                        j                  | j                  j                        }| j                  | j                  j                  | j                  d}ddt        j                  t        j                          i} || j                  j"                  |      }	 |j%                  ||t'        j(                  |      j+                  d            }|j-                          |j.                  t0        j2                  k7  r2t5        j6                  d	j                  |j'                                     |j'                         d
   }|| _        t;        j<                  t?        j@                  |d      d         | _!        y # |j-                          w xY w)Nr   rk   )audiencerP   includeEmailr`   ra   )auth_requestr   )r   r   r   zError getting ID token: {}r/   F)verifyexp)"ro   rl   r   _IAM_IDTOKEN_ENDPOINTr   r   r   r   r)   r   r   r   rE   r   r
   rg   "token_request_id_token_impersonater<   rt   r   r   r   ry   ru   r   r    r   r!   r/   r   utcfromtimestampr	   r   r0   )	rL   r'   rl   r{   r   r   r|   r,   id_tokens	            r3   r\   zIDTokenCredentials.refresh  s   D55==//$$44
 &))66
7 	 --11<< //
 .%%w'Q'Q'S

 +$$88w
	#%**%ZZ%,,W5 + H   ";>>1)),33HMMOD  ==?7+
//JJx.u5
   "s   6G G)NFNrV   )r   r   r   r   r:   r   r   r   r   r   r   r   r   r6   r\   r   r   s   @r3   r   r   u  sv     26


 X[DDE
 F
 X[445)
 6)
rT   r   )r   rq   r;   r   http.clientclientr   r   google.authr   r   r   r   r   r	   r
   r"   rF   r   r4   r>   r   Signingr6   r   r   rT   r3   <module>r      s       !  ,   # "    >#   77;&|D??ATATDNk
@@ k
rT   