
    OjFl                        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rSSK	J
r
J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S
KJr  SSKJr  SSKJr  SSKJr  \(       a  SSKr\R2                  " \5      rSrSrSrSrSr Sr!\RD                  S4S jr# " S S\RH                  \RJ                  \RL                  \RN                  5      r( " S S\RJ                  5      r)/ 4S j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)OptionalTYPE_CHECKING)_exponential_backoff)_helpers)_regional_access_boundary_utils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                    U=(       d=    [         R                  R                  [        R                  U5      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)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                 f/var/www/html/leaf-doctor-v1/venv/lib/python3.13/site-packages/google/auth/impersonated_credentials.py_make_iam_token_requestr=   B   s:   6 ) C,=,=,E,E++_-fY  ::d""7+D<SH
 8==(++ 	W%]]  +..(%%nmDD&M2}-"">,#?AUV}j! &))DKK 	
 %&s   07D( (E)8,E$$E)c                     ^  \ rS rSrSrSS\SSS4U 4S jjrS rS r S SS jjr	S r
\S	 5       r\S
 5       r\S 5       r\S 5       r\R"                  " \R&                  5      S 5       rS r\R"                  " \R,                  5      S 5       r\R"                  " \R0                  5      SS j5       r\SS j5       rSrU =r$ )Credentials   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)

**IMPORTANT**:
This class does not validate the credential configuration. A security
risk occurs when a credential configuration configured with malicious urls
is used.
When the credential configuration is accepted from an
untrusted source, you should validate it before using.
Refer https://cloud.google.com/docs/authentication/external/externally-sourced-credentials for more details.
Nc
                   > [         [        U ]  5         [        R                  " U5      U l        [        U R                  [        R                  5      (       a  U R                  R                  [        R                  5      U l        [        U R                  S5      (       a6  U R                  R                  (       a  U R                  R                  S5        UR                  U l        X l        X0l        X@l        XPl        U=(       d    [(        U l        SU l        [.        R0                  " 5       U l        Xpl        Xl        SU l        Xl        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 (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.
    trust_boundary (Mapping[str,str]): A credential trust boundary.
_create_self_signed_jwtN)superr?   __init__copy_source_credentials
isinstancer
   Scopedwith_scopesr   
_IAM_SCOPEr%   _always_use_jwt_accessrB   r2   _universe_domain_target_principal_target_scopes
_delegates_subject_DEFAULT_TOKEN_LIFETIME_SECS	_lifetimer8   r   utcnowr9   _quota_project_id_iam_endpoint_override_cred_file_path_trust_boundary)selfsource_credentialstarget_principaltarget_scopes	delegatessubjectlifetimequota_project_idr3   trust_boundary	__class__s             r<   rD   Credentials.__init__   s    X 	k4)+#'99-?#@  d..0B0BCC'+'?'?'K'K(D$ 002KLL,,CC((@@F 2 B B!1+#!A%A
oo'!1&;##-    c                 "    [         R                  $ N)r   CRED_TYPE_SA_IMPERSONATErX   s    r<   _metric_header_for_usage$Credentials._metric_header_for_usage  s    ///rc   c           	         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 R                  (       Ga  U R                   [        R"                  :w  a  [$        R&                  " S5      e[(        R*                  " 5       nU R,                  [(        R.                  " U R                  =(       d    S5      U R                  [0        [(        R2                  " U5      [(        R2                  " U5      [4        -   S.n[7        UU R,                  UUU R                  S9n[8        R:                  " U[0        U5      u  U l        U l        ng	[A        UU R,                  UUU R                   U RB                  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)r\   scoper^   Content-Typeapplication/jsonzNDomain-wide delegation is not supported in universes other than googleapis.com )issrl   subaudiatexp)r0   r1   r   payloadr\   N)r0   r1   r   r   r2   r3   )"rF   token_stater
   
TokenStateSTALEINVALIDrefreshrO   rN   strrR   r   API_CLIENT_HEADER&token_request_access_token_impersonateapplyrP   r2   r    r   GoogleAuthErrorr   rS   rM   scopes_to_string_GOOGLE_OAUTH2_TOKEN_ENDPOINTdatetime_to_secsrQ   _sign_jwt_requestr   	jwt_grantr8   r9   r=   rU   )rX   r0   r   r   nowru   	assertion_s           r<   _perform_refresh_token"Credentials._perform_refresh_token  s    $$00K4J4J4P4PP''33{7M7M7U7UU$$,,W5 ((DNN+c1
 .%%w'U'U'W
 	  &&w/ ===##{'J'JJ 00, 
 //#C--!2243F3F3L"M}}40050058TTG *00//I *1):):6	*&DJQ "9,, 00"&"="=#

DKrc   c                     U R                   (       d  [        R                  S5        g[        R                  " U R                   5      $ )a  Builds and returns the URL for the Regional Access Boundary lookup API.

This method constructs the specific URL for the IAM Credentials API's
`allowedLocations` endpoint, using the credential's universe domain
and service account email.

Returns:
    Optional[str]: The URL for the Regional Access Boundary lookup endpoint, or None
         if the service account email is missing.
zpService account email is required to build the Regional Access Boundary lookup URL for impersonated credentials.N)service_account_email_LOGGERerrorr    get_service_account_rab_endpoint)rX   r0   s     r<   *_build_regional_access_boundary_lookup_url6Credentials._build_regional_access_boundary_lookup_urlb  s@     ))MM C .OO&&
 	
rc   c                    SSK Jn  [        R                  R	                  [
        R                  U R                  5      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                  5          [         R"                  " 5       nU H  nUR%                  X5US9n	U	R&                  [        R(                  ;   a  M3  U	R&                  [*        R,                  :w  a3  [.        R0                  " SR                  U	R3                  5       5      5      e[        R4                  " U	R3                  5       S	   5      s  UR7                  5         $    UR7                  5         [.        R0                  " S
5      e! UR7                  5         f = f)Nr   AuthorizedSessionr   )ru   r\   rm   rn   )r   r   r"   zError calling sign_bytes: {}
signedBlobz#exhausted signBlob endpoint retries)google.auth.transport.requestsr   r   _IAM_SIGN_ENDPOINTr   r
   r    r2   r!   rM   base64	b64encoder   rO   rF   configure_mtls_channelr   ExponentialBackoffpoststatus_codeIAM_RETRY_CODESr(   r)   r   TransportErrorr"   	b64decodeclose)
rX   messager   iam_sign_endpointr   r   authed_sessionretriesr   r5   s
             r<   
sign_bytesCredentials.sign_bytesx  st   D22:://1E1E

&''
( 	
 ''077@

 "#56*4+C+CD--/	#*==?G)..) /  ''3+>+>>'';>>9$336==hmmoN  ''(EFF  "    "''(MNN   "s   1CF- F- -F?c                     U R                   $ re   rM   rg   s    r<   signer_emailCredentials.signer_email      %%%rc   c                     U R                   $ re   r   rg   s    r<   r   !Credentials.service_account_email  r   rc   c                     U $ re   ro   rg   s    r<   signerCredentials.signer  s    rc   c                 $    U R                   (       + $ re   )rN   rg   s    r<   requires_scopesCredentials.requires_scopes  s    &&&&rc   c                 Z    U R                   (       a  U R                   SU R                  S.$ g )Nzimpersonated credentials)credential_sourcecredential_typer1   )rV   rM   rg   s    r<   get_cred_infoCredentials.get_cred_info  s/    %)%9%9#=!33 
 rc   c                    U R                  U R                  U R                  U R                  U R                  U R
                  U R                  U R                  U R                  S9nU R                  Ul	        U R                  U5        U$ )N)rZ   r[   r\   r^   r_   r3   r`   )ra   rF   rM   rN   rO   rR   rT   rU   rW   rV   &_copy_regional_access_boundary_manager)rX   creds     r<   
_make_copyCredentials._make_copy  s|    ~~$$!33--oo^^!33"&"="=//  	
  $3333D9rc   c                 2    U R                  5       nXl        U$ re   )r   rT   )rX   r_   r   s      r<   with_quota_projectCredentials.with_quota_project  s     !1rc   c                 F    U R                  5       nU=(       d    UUl        U$ re   )r   rN   )rX   scopesdefault_scopesr   s       r<   rI   Credentials.with_scopes  s      $6rc   c           	      (   UR                  S5      nUR                  S5      nU[        :X  a"  SSKJn  UR                  R                  U5      nO}U[        :X  a"  SSKJn  UR                  R                  U5      nOQU[        :X  a"  SSK
Jn  UR                  R                  U5      nO%[        R                  " SR                  U5      5      eUR                  S5      n	U	R!                  S	5      n
U	R#                  S
5      nU
S:X  d  US:X  d  X:  a%  [        R$                  " SR                  U	5      5      eXS-   U nUR                  S5      nUR                  S5      nU=(       d    UR                  S5      nUR                  S5      nU " UUUUUUS9$ )a  Creates a Credentials instance from parsed impersonated service account credentials info.

**IMPORTANT**:
This method does not validate the credential configuration. A security
risk occurs when a credential configuration configured with malicious urls
is used.
When the credential configuration is accepted from an
untrusted source, you should validate it before using with this method.
Refer https://cloud.google.com/docs/authentication/external/externally-sourced-credentials for more details.

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.
rY   typer   r	   )r   )r   z.source credential of type {} is not supported.!service_account_impersonation_url/z:generateAccessTokenz'Cannot extract target principal from {}   r\   r_   r   r`   )r_   r`   )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
   rY   r   r   impersonation_urlstart_index	end_indexrZ   r\   r_   r`   s                   r<   &from_impersonated_service_account_info2Credentials.from_impersonated_service_account_info  s   8 #'((+?"@"9"="=f"E"&MM1!,!8!8!R!R'" %(OO5!0!<!<!V!V'" $GH E!A!M!M!W!W'" ((@GG+  !HH%HI'--c2%**+AB	"	R;3J))9@@ARS  -1_yIHH[)	88$67-488H-"23-)
 	
rc   )rV   rO   rU   rR   rT   rF   rP   rM   rN   rW   rL   r9   r8   re   )r0   z'Optional[google.auth.transport.Request])__name__
__module____qualname____firstlineno____doc__rQ   rD   rh   r   r   r   propertyr   r   r   r   r   copy_docstringr
   r?   r   r   CredentialsWithQuotaProjectr   rH   rI   classmethodr   __static_attributes____classcell__ra   s   @r<   r?   r?      s'   CT -"J.X0F
R DH
@
,!OF & & & &   ' ' [445 6 [DDE F
 [//0 1
 M
 M
rc   r?   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$ )IDTokenCredentialsi!  z;Open 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)rC   r   rD   rG   r?   r   r   _target_credentials_target_audience_include_emailrT   )rX   target_credentialstarget_audienceinclude_emailr_   ra   s        r<   rD   IDTokenCredentials.__init__$  sQ      	 $02,k::,,I  $6  /+!1rc   c                 N    U R                  UUU R                  U R                  S9$ N)r   r   r   r_   )ra   r   rT   )rX   r   r   s      r<   from_credentials#IDTokenCredentials.from_credentials?  s0    ~~1+--!33	  
 	
rc   c                 b    U R                  U R                  UU R                  U R                  S9$ r   )ra   r   r   rT   )rX   r   s     r<   with_target_audience'IDTokenCredentials.with_target_audienceG  s6    ~~#77+--!33	  
 	
rc   c                 b    U R                  U R                  U R                  UU R                  S9$ r   )ra   r   r   rT   )rX   r   s     r<   with_include_email%IDTokenCredentials.with_include_emailO  s6    ~~#77 11'!33	  
 	
rc   c                 b    U R                  U R                  U R                  U R                  US9$ r   )ra   r   r   r   )rX   r_   s     r<   r   %IDTokenCredentials.with_quota_projectW  s6    ~~#77 11---	  
 	
rc   c                 D   SSK Jn  [        R                  R	                  [
        R                  U R                  R                  5      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%                  5          UR'                  UU[(        R*                  " U5      R-                  S5      S9nUR/                  5         UR0                  [2        R4                  :w  a3  [6        R8                  " S	R                  UR)                  5       5      5      e UR)                  5       S
   nXl        [@        RB                  " [D        RF                  " USS9S   5      U l$        g ! UR/                  5         f = f! [:        [<        4 a,  n	[6        R8                  " SUR)                  5       5      n
XeS n	A	ff = f)Nr   r   )audiencer\   includeEmailrm   rn   )auth_requestr   )r   r   r&   zError getting ID token: {}r8   zNo ID token in response.F)verifyrt   )%r   r   r   _IAM_IDTOKEN_ENDPOINTr   r
   r    r   r2   r!   r   r   rO   r   r   r|   "token_request_id_token_impersonaterF   r   r   r"   r#   r$   r   r   r(   r)   r   r*   r.   r/   r8   r   utcfromtimestampr   r   r9   )rX   r0   r   r   r   r   r   r5   id_tokenr:   r;   s              r<   rz   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 	*}}w/H 
//JJx.u5
!   " *% 	* --*HMMOG )		*s$   -4G G# G #H3'HH)r   rT   r   r   r9   r8   )NFNre   )r   r   r   r   r   rD   r   r   r   r   r   r
   r   r   r?   rz   r   r   r   s   @r<   r   r   !  sp    E
 26


 [DDE
 F
 [4451
 61
rc   r   c                    [         R                  R                  U5      nU[        R                  " U5      S.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
U
$ ! [         ["        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 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
)r\   ru   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/   )r0   r1   r   ru   r\   r4   r   r5   r6   jwt_response
signed_jwtr:   r;   s                r<   r   r     s   : ,,33I>L"tzz'/BCD::d""7+D<SH
 8==(++ 	W%]]  +..(%%nmDD	&zz-0!+.
j! &)),33NC]
 %	&s   "C? ?E ,D;;E )+r   r   rE   r   http.clientclientr(   r"   loggingtypingr   r   r   r   r   r   r
   r   r   r   r   r   r   google.auth.transportgoogle	getLoggerr   r   r+   rQ   r   r   r   r   r    r=   rH   r   Signing%CredentialsWithRegionalAccessBoundaryr?   r   r   ro   rc   r<   <module>r     s       !   * -   7 # "    ! 


H
%=#  E  +< '*; '& 9  77;&|^
++55	^
Bq
@@ q
h GI 7&rc   