
    eB                        S r SSKrSSKrSSKJr  SSKJr  SSKrSSKJ	r	  SSKJ
r
  SSKJr  SSKJr  SSKJr  S	/rS
rSrSrSrSrSr SS jr " S S\
R,                  \
R.                  \
R0                  5      r " S S\
R.                  5      rg)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                    U=(       d    [         R                  U5      n[        R                  " U5      R	                  S5      nU " USX#S9n[        UR                  S5      (       a  UR                  R                  S5      OUR                  nUR                  [        R                  :w  a  [        R                  " [        U5      e [        R                  " U5      nUS   n	[        R                   " US   S5      n
X4$ ! ["        [$        4 a1  n[        R                  " SR                  [        5      U5      nXeS	nAff = f)
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                ?platform/bq/third_party/google/auth/impersonated_credentials.py_make_iam_token_requestr/   A   s   , )KM,@,@,KL::d""7+D<SH
 8==(++ 	W%]]  +..(%%nmDD&M2}-"">,#?AUV}j! &))DKK 	
 %&s   7D   E,D<<Ec                   Z  ^  \ rS rSrSrS\SS4U 4S jjrS r\R                  " \
R                  5      S 5       rS rS r\S	 5       r\S
 5       r\S 5       r\S 5       r\R                  " \
R(                  5      S 5       r\R                  " \
R,                  5      SS j5       rSrU =r$ )Credentialsx   a&  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  > [         [        U ]  5         [        R                  " U5      U l        [        U R                  [        R                  5      (       au  U R                  R                  [        5      U l        [        U R                  S5      (       a6  U R                  R                  (       a  U R                  R                  S5        X l        X0l        X@l        U=(       d    [         U l        SU l        [&        R(                  " 5       U l        X`l        Xpl        g)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 (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_accessr4   _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.   r6   Credentials.__init__   s    L 	k4)+#'99-?#@  d..0B0BCC'+'?'?'K'KJ'WD$ 002KLL,,CC((@@F!1+#!A%A
oo'!1&;#    c                 "    [         R                  $ N)r   CRED_TYPE_SA_IMPERSONATErF   s    r.   _metric_header_for_usage$Credentials._metric_header_for_usage   s    ///rO   c                 &    U R                  U5        g rQ   )_update_token)rF   r#   s     r.   refreshCredentials.refresh   s    7#rO   c                 B   U R                   R                  [        R                  R                  :X  d2  U R                   R                  [        R                  R
                  :X  a  U R                   R                  U5        U R                  U R                  [        U R                  5      S-   S.nSS[        R                  [        R                  " 5       0nU R                   R                  U5        [        UU R                   UUU R"                  S9u  U l        U l        g)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)rJ   scoperK   Content-Typeapplication/json)r#   r$   r   r   r%   N)r8   token_stater   
TokenStateSTALEINVALIDrX   r@   r?   strrB   r   API_CLIENT_HEADER&token_request_access_token_impersonateapplyr/   r>   rE   r*   r+   )rF   r#   r   r   s       r.   rW   Credentials._update_token   s     $$00K4J4J4P4PP''33{7M7M7U7UU$$,,W5 ((DNN+c1
 .%%w'U'U'W
 	  &&w/"9,,"&"="=#

DKrO   c                 8   SSK Jn  [        R                  U R                  5      n[
        R                  " U5      R                  S5      U R                  S.nSS0nU" U R                  5      n UR                  X5US9nUR                  5         UR                  [        R                  :w  a3  [        R                   " SR                  UR#                  5       5      5      e[
        R$                  " UR#                  5       S	   5      $ ! UR                  5         f = f)
Nr   AuthorizedSessionr
   )payloadrJ   r]   r^   )r   r   r   zError calling sign_bytes: {}
signedBlob)google.auth.transport.requestsrj   _IAM_SIGN_ENDPOINTr   r>   base64	b64encoder   r@   r8   postclosestatus_coder   r   r   TransportErrorr   	b64decode)rF   messagerj   iam_sign_endpointr   r   authed_sessionr'   s           r.   
sign_bytesCredentials.sign_bytes#  s    D.55d6L6LM ''077@

 "#56*4+C+CD	#%**%T + H   ";>>1++.55hmmoF   =>>   "s   /D Dc                     U R                   $ rQ   r>   rS   s    r.   signer_emailCredentials.signer_email?      %%%rO   c                     U R                   $ rQ   r|   rS   s    r.   service_account_email!Credentials.service_account_emailC  r   rO   c                     U $ rQ    rS   s    r.   signerCredentials.signerG  s    rO   c                 $    U R                   (       + $ rQ   )r?   rS   s    r.   requires_scopesCredentials.requires_scopesK  s    &&&&rO   c           
          U R                  U R                  U R                  U R                  U R                  U R
                  UU R                  S9$ N)rH   rI   rJ   rK   rL   r%   )rM   r8   r>   r?   r@   rB   rE   rF   rL   s     r.   with_quota_projectCredentials.with_quota_projectO  sM    ~~$$!33--oo^^-"&"="=  
 	
rO   c           
          U R                  U R                  U R                  U=(       d    UU R                  U R                  U R
                  U R                  S9$ r   )rM   r8   r>   r@   rB   rD   rE   )rF   scopesdefault_scopess      r.   r;   Credentials.with_scopes[  sR    ~~$$!33 2Noo^^!33"&"="=  
 	
rO   )	r@   rE   rB   rD   r8   r>   r?   r+   r*   rQ   )__name__
__module____qualname____firstlineno____doc__rA   r6   rT   r   copy_docstringr   r1   rX   rW   ry   propertyr}   r   r   r   CredentialsWithQuotaProjectr   r:   r;   __static_attributes____classcell__rM   s   @r.   r1   r1   x   s    ;D -"<<|0 [445$ 6$$
L?8 & & & &   ' ' [DDE	
 F	
 [//0	
 1	
rO   r1   c                      ^  \ rS rSrSr   S
U 4S jjrSS jrS rS r\	R                  " \R                  5      S 5       r\	R                  " \R                  5      S 5       rS	rU =r$ )IDTokenCredentialsih  zAOpen ID Connect ID Token-based service account credentials.

    c                    > [         [        U ]  5         [        U[        5      (       d  [
        R                  " S5      eXl        X l        X0l	        X@l
        g)aI  
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)r5   r   r6   r9   r1   r   GoogleAuthError_target_credentials_target_audience_include_emailrD   )rF   target_credentialstarget_audienceinclude_emailrL   rM   s        r.   r6   IDTokenCredentials.__init__m  sQ      	 $02,k::,,I  $6  /+!1rO   c                 N    U R                  UUU R                  U R                  S9$ N)r   r   r   rL   )rM   r   rD   )rF   r   r   s      r.   from_credentials#IDTokenCredentials.from_credentials  s0    ~~1+--!33	  
 	
rO   c                 b    U R                  U R                  UU R                  U R                  S9$ r   )rM   r   r   rD   )rF   r   s     r.   with_target_audience'IDTokenCredentials.with_target_audience  s6    ~~#77+--!33	  
 	
rO   c                 b    U R                  U R                  U R                  UU R                  S9$ r   )rM   r   r   rD   )rF   r   s     r.   with_include_email%IDTokenCredentials.with_include_email  s6    ~~#77 11'!33	  
 	
rO   c                 b    U R                  U R                  U R                  U R                  US9$ r   )rM   r   r   r   r   s     r.   r   %IDTokenCredentials.with_quota_project  s6    ~~#77 11---	  
 	
rO   c                 ,   SSK Jn  [        R                  U R                  R
                  5      nU R                  U R                  R                  U R                  S.nSS[        R                  [        R                  " 5       0nU" U R                  R                  US9n UR                  UU[        R                  " U5      R!                  S5      S9nUR#                  5         UR$                  [&        R(                  :w  a3  [*        R,                  " S	R                  UR                  5       5      5      eUR                  5       S
   nXl        [0        R2                  " [4        R6                  " USS9S   5      U l        g ! UR#                  5         f = f)Nr   ri   )audiencerJ   includeEmailr]   r^   )auth_requestr
   )r   r   r   zError getting ID token: {}r*   F)verifyexp)rm   rj   _IAM_IDTOKEN_ENDPOINTr   r   r}   r   r@   r   r   rd   "token_request_id_token_impersonater8   rq   r   r   r   rr   rs   r   r   r   r   r*   r   utcfromtimestampr   r   r+   )	rF   r#   rj   rw   r   r   rx   r'   id_tokens	            r.   rX   IDTokenCredentials.refresh  sY   D188$$11

 --11<< //
 .%%w'Q'Q'S

 +$$88w
	#%**%ZZ%,,W5 + H   ";>>1)),33HMMOD  ==?7+
//JJx.u5
   "s   !4F F)r   rD   r   r   r+   r*   )NFNrQ   )r   r   r   r   r   r6   r   r   r   r   r   r   r   r   r1   rX   r   r   r   s   @r.   r   r   h  sr     26


 [DDE
 F
 [445(
 6(
rO   r   rQ   )r   ro   r7   r   http.clientclientr   r   google.authr   r   r   r   r   r<   r   rn   r   r   rA   _DEFAULT_TOKEN_URIr/   r:   r   Signingr1   r   r   rO   r.   <module>r      s        !    # "  34
0 % 6 
 ># :  >B4&nm
??ATATm
`j
@@ j
rO   