
    $                       S r SSKJr  SSKJr  SSKJr  SSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKrSSK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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'  SSK(J)r)  SSK(J*r*  SSK+J,r-  SSK.r.Sr/Sr0Sr1Sr2Sr3Sr4Sr5Sr6Sr7Sr8Sr9S r: " S! S"\Rv                  5      r; " S# S$\;5      r< " S% S&\;5      r= " S' S(\;5      r> " S) S*\;5      r?S+ r@S, rAS- rBS. rCS/ rDS0 rES1 rFS2 rGS3 rHS4 rIS5 rJS6 rKS7 rLS8 rMSjS9 jrNS: rOS; rPS< rQ " S= S>\R5      rS\.R                  " \R                  5       " S? S@\R5      5       rVSArW " SB SC\R5      rX " SD SE\V5      rYSFrZ " SG SH\R5      r[ " SI SJ\)R                  5      r] " SK SL\R5      r^ SkSM jr_ SlSN jr` " SO SP\V5      ra   SmSQ jrb " SR SS\
R                  5      rd " ST SU\
R                  5      reSV rfSW rgSX rhSY riSZ rjS[ rkS\ rl   SmS] jrmSkS^ jrnS_ roSnS` jrp " Sa Sb\R5      rqSc rrSd rsSert SkSf jruSg rvSqw\R                  Sh   rySi rzg)oz Utilities to manage credentials.    )absolute_import)division)unicode_literalsN)compute_enginecredentials)
exceptions)external_account) external_account_authorized_user)impersonated_credentials)config)log)
properties)devshell)
introspect)files)clientservice_account)gcequota_project_idz$https://oauth2.googleapis.com/revokeunknownauthorized_userr   service_account_p12r   r   impersonated_accountr
   external_account_userr   c                       \ rS rSrSrSrg)ErrorD   zExceptions for this module. N__name__
__module____qualname____firstlineno____doc____static_attributes__r        ,lib/googlecloudsdk/core/credentials/creds.pyr   r   D   s    #r(   r   c                       \ rS rSrSrSrg)UnknownCredentialsTypeH   zCAn error for when we fail to determine the type of the credentials.r    Nr!   r    r(   r)   r+   r+   H   s    Kr(   r+   c                       \ rS rSrSrSrg)InvalidCredentialsErrorL   zGException for when the provided credentials are invalid or unsupported.r    Nr!   r    r(   r)   r.   r.   L   s    Or(   r.   c                       \ rS rSrSrSrg)CredentialFileSaveErrorP   z4An error for when we fail to save a credential file.r    Nr!   r    r(   r)   r1   r1   P   s    <r(   r1   c                       \ rS rSrSrSrg)ADCErrorT   z9An error when processing application default credentials.r    Nr!   r    r(   r)   r4   r4   T   s    Ar(   r4   c                 6    [        U [        R                  5      $ N)
isinstancer   OAuth2Credentialscredss    r)   IsOauth2ClientCredentialsr<   X   s    	E633	44r(   c                 6    [        U [        R                  5      $ r7   )r8   google_auth_credsCredentialsr:   s    r)   IsGoogleAuthCredentialsr@   \   s    	E,88	99r(   c                 6    [        U [        R                  5      $ r7   )r8   google_auth_compute_enginer?   r:   s    r)   IsGoogleAuthGceCredentialsrC   `   s    	E5AA	BBr(   c                     [         R                  U 5      R                  (       a  g[        R                  " 5       (       a&  [         R                  U 5      [         R
                  :H  $ gNTF)CredentialTypeFromCredentialsis_user
c_devshellIsDevshellEnvironmentGCEr:   s    r)   %_IsUserAccountCredentialsOauth2clientrL   d   sG    ##E*22%%''))%0N4F4FFFr(   c                     [         R                  U 5      R                  (       a  g[        R                  " 5       (       a&  [         R                  U 5      [         R
                  :H  $ grE   )CredentialTypeGoogleAuthrG   rH   rI   rJ   rK   r:   s    r)   #_IsUserAccountCredentialsGoogleAuthrO   m   sQ    --e4<<%%''#33*../ / r(   c                 N    [        U 5      (       a  [        U 5      $ [        U 5      $ r7   )r<   rL   rO   r:   s    r)   IsUserAccountCredentialsrQ   w   s#    u%%077.u55r(   c                 N    [         R                  U 5      [         R                  :H  $ r7   )rF   rG   P12_SERVICE_ACCOUNTr:   s    r)   #IsOauth2clientP12AccountCredentialsrT   ~   s#    

(
(
/

,
,- .r(   c                    [        U 5      (       a8  [        R                  U 5      nU[        R                  [        R                  4;   $ [
        R                  U 5      nU[
        R                  [
        R                  4;   $ r7   )r<   rF   rG   SERVICE_ACCOUNTrS   rN   r;   	cred_types     r)   IsServiceAccountCredentialsrY      sy    u%%..u5I77';;= = = )88?I1AA1EEG G Gr(   c                 p    [        U 5      (       a&  [        R                  U 5      [        R                  :H  $ gNF)r@   rN   rG   EXTERNAL_ACCOUNTr:   s    r)   IsExternalAccountCredentialsr]      s1    U##$44U;$556 7	r(   c                 p    [        U 5      (       a&  [        R                  U 5      [        R                  :H  $ gr[   )r@   rN   rG   EXTERNAL_ACCOUNT_USERr:   s    r)    IsExternalAccountUserCredentialsr`      s1    U##$44U;$::; <	r(   c                 p    [        U 5      (       a&  [        R                  U 5      [        R                  :H  $ gr[   )r@   rN   rG    EXTERNAL_ACCOUNT_AUTHORIZED_USERr:   s    r)   *IsExternalAccountAuthorizedUserCredentialsrc      s3    U##$44U;$EEF G	r(   c                 p    [        U 5      (       a&  [        R                  U 5      [        R                  :H  $ gr[   )r@   rN   rG   IMPERSONATED_ACCOUNTr:   s    r)    IsImpersonatedAccountCredentialsrf      s1    U##$44U;$99: ;	r(   c                     [        U 5      (       a;  U R                  [        R                  R                  R                  R
                  :H  $ g)a  Check if the given credential has default universe domain.

For google-auth credential, we check its universe_domain property. The
deprecated oauth2client credentials only work in default universe domain so
we return True (Note that they are no longer used in gcloud, but not yet
removed from the code base).

Args:
  credentials: google.auth.credentials.Credentials or
    client.OAuth2Credentials, the credentials to be checked.

Returns:
  bool, Whether or not the given credential has default universe domain.
T)r@   universe_domainr   VALUEScoredefaultr   s    r)   HasDefaultUniverseDomainrl      sB     [))##!!1199	: 
r(   c                  4   [         R                  R                  R                  R	                  5       (       a1  [         R                  R
                  R                  R                  SS9$ [         R                  R
                  R                  R                  SS9$ )zEGet default token URI for credential based on context aware settings.T)required)	r   ri   context_awareuse_client_certificateGetBoolauthmtls_token_hostGet
token_hostr    r(   r)   GetDefaultTokenUrirv      so    $$;;CCEE!!1155t5DD!!,,00$0??r(   c                 .   [         R                  R                  R                  R	                  5       (       a2  [         R                  R                  R                  R                  5       $ U R                  U5      (       a  U R                  U5      [         R                  R                  R                  :w  aV  U R                  U5      [         R                  R                  R                  R                  5       :w  a  U R                  U5      $ [        5       $ )z5Get the effective token URI for the given credential.)
r   ri   rr   ru   IsExplicitlySetrt   getDEFAULT_TOKEN_HOSTrs   rv   )	cred_jsonkeys     r)   GetEffectiveTokenUriFromCredsr}      s    &&6688!!,,0022 mmC
--

 1 1 6 6 I I
I
--

 1 1 6 6 F F J J L
L== 
	r(   c                 x   [         R                  U 5      nU[         R                  :w  a  gU R                  [        R
                  R                  R                  R                  :w  a  g[        R
                  R                  R                  R                  5       (       a  g[        R                  " 5       (       d  gg)a  Check if self signed jwt should be used.

Only use self signed jwt for google-auth service account creds, and only when
service_account_use_self_signed_jwt property is true or the universe is not
the default one.

Args:
  creds: google.auth.credentials.Credentials, The credentials to check if
    self signed jwt should be used.

Returns:
  bool, Whether or not self signed jwt should be used.
FT)rN   rG   rV   rh   r   ri   rj   rk   rr   #service_account_use_self_signed_jwtrq   IsDefaultUniverserW   s     r)   UseSelfSignedJwtr      s     '66u=)*:::
j//44DDLLL??GGII		%	%	'	'	r(   c                 V    [        U 5      (       a  SU l        U R                  S 5        g g )NT)r   _always_use_jwt_access_create_self_signed_jwtr:   s    r)   EnableSelfSignedJwtIfApplicabler      s(    e#'E 	!!$' r(   c                 z    [         R                  U 5      nU[         R                  :X  a  U R                  U5      n U $ )aD  Add user account to credential.

The user account field is used to determine ADC caching.
Only User Account credential types will be modified.

Args:
  creds: google.auth.credentials.Credentials, The credentials to add the
    account field
  account: str, the authorized user email

Returns:
  google_auth_creds.Credential
)rN   rG   USER_ACCOUNTwith_account)r;   accountrX   s      r)   WithAccountr      s8     '66u=)*777w'E	,r(   c                   <    \ rS rSrSr\S 5       r\SS j5       rSrg)_AccountIdFormatteri  a  Account ID formatter.

In this file, when we say "account id" or "account_id", it means principal;
when we say "formatted_account_id" or "formatted account id", it means:
  - the account_id or principal, if the universe domain is GDU
  - the "account_id#universe_domain" string, otherwise

In credentials and access token sqlite3 database, the account_id column saves
the formatted account id.

This class provides utility functions to handle the formatting.
c                     U R                  S5      nUS   n[        U5      S:X  a1  [        R                  R                  R
                  R                  nX#4$ US   nX#4$ )zGet account_id/principal and universe domain from formatted account id.

Args:
  formatted_account_id: str, the formatted account id string.

Returns:
  tuple: The principal and universe domain tuple.
#r      )splitlenr   ri   rj   rh   rk   )formatted_account_idsplits	principalrh   s       r)   GetAccountIdAndUniverseDomain1_AccountIdFormatter.GetAccountIdAndUniverseDomain  se     "'',Fq	I
6{a"))..>>FFo %% q	o%%r(   Nc                     [         R                  R                  R                  nU(       a  [	        US5      (       a  UR                  nOUR                  5       nX2R                  :X  a  U $ U S-   U-   $ )a   Calculate the formatted account id.

If the universe_domain is GDU, return the account_id as is; otherwise,
return "account_id#universe_domain". Here the universe_domain value comes
from the credentials if it's provided, otherwise it comes from the
core/universe_domain property.

Args:
  account_id: str, the account id or principal string.
  credentials: google.auth.credentials.Credentials, The optional credentials
    provided to derive the universe_domain value.

Returns:
  str: The formatted account id.
rh   r   )r   ri   rj   rh   hasattrrt   rk   )
account_idr   universe_domain_propertyrh   s       r)   GetFormattedAccountId)_AccountIdFormatter.GetFormattedAccountId/  sg    "  *0055EEw{,=>>#33o0446o:::#//r(   r    r7   )	r"   r#   r$   r%   r&   staticmethodr   r   r'   r    r(   r)   r   r     s/     & &" 0 0r(   r   c                       \ rS rSrSr\R                  S 5       r\R                  S 5       r\R                  S 5       r	\R                  S 5       r
Srg)	CredentialStoreiM  z(Abstract definition of credential store.c                     [         $ )zdGet all accounts that have credentials stored for the CloudSDK.

Returns:
  {str}, Set of accounts.
NotImplementedselfs    r)   GetAccountsCredentialStore.GetAccountsQ  s
     r(   c                     [         $ r7   r   r   r   s     r)   LoadCredentialStore.LoadZ      r(   c                     [         $ r7   r   )r   r   r   s      r)   StoreCredentialStore.Store^  r   r(   c                     [         $ r7   r   r   s     r)   RemoveCredentialStore.Removeb  r   r(   r    N)r"   r#   r$   r%   r&   abcabstractmethodr   r   r   r   r'   r    r(   r)   r   r   M  sk    0       r(   r   r   c                   0    \ rS rSrSrS rS rS rS rSr	g)	
_SqlCursorii  z'Context manager to access sqlite store.c                 ,    Xl         S U l        S U l        g r7   )_store_file_connection_cursor)r   
store_files     r)   __init___SqlCursor.__init__l  s    !DDLr(   c                     [         R                  " U R                  S[         R                  S SS9U l        U R                  R                  5       U l        U $ )Ng      @T)timeoutdetect_typesisolation_levelcheck_same_thread)sqlite3connectr   PARSE_DECLTYPESr   cursorr   r   s    r)   	__enter___SqlCursor.__enter__q  sM     ,,D ##**,DLKr(   c                 z    U(       d  U R                   R                  5         U R                   R                  5         g r7   )r   commitclose)r   exc_typeunused_valueunused_tracebacks       r)   __exit___SqlCursor.__exit__  s)    
r(   c                 4    U R                   R                  " U6 $ r7   )r   execute)r   argss     r)   Execute_SqlCursor.Execute  s    <<&&r(   )r   r   r   N)
r"   r#   r$   r%   r&   r   r   r   r   r'   r    r(   r)   r   r   i  s    /
'r(   r   c                   L    \ rS rSrSrS rS rS rS rS r	SS jr
S	 rS
 rSrg)SqliteCredentialStorei  z Sqllite backed credential store.c                     [        U5      U l        U R                  SR                  [        5      5        [
        R                  " 5       nUR                  S5      (       d  U R                  5         g g )NzICREATE TABLE IF NOT EXISTS "{}" (account_id TEXT PRIMARY KEY, value BLOB)cred_token_store_formatted)	r   r   _Executeformat_CREDENTIAL_TABLE_NAMEr   GetConfigStorert   FormatAccountIdColumn)r   r   config_stores      r)   r   SqliteCredentialStore.__init__  s]    j)DLMM	4	&	') ((*L899
  " :r(   c                 n    U R                    nUR                  " U6 sS S S 5        $ ! , (       d  f       g = fr7   r   r   r   r   curs      r)   r   SqliteCredentialStore._Execute  s!    	[[$ 
s   &
4c                    U R                    nUR                  SR                  [        5      5      R	                  5       nU H  nUS   US   pTSU;  d  M  [        U5      n[        R                  XF5      nXG:w  d  M;  UR                  SR                  [        5      U45        UR                  SR                  [        5      Xu45        M     [        R                  " 5       nUR                  SS5        S	S	S	5        g	! , (       d  f       g	= f)
zFormat the account id column.

Before we introduce the formatted account id concept, the existing table
uses the account id value as the key. Therefore we need to load the table
and replace these account ids with formatted account ids.
z"SELECT account_id, value FROM "{}"r   r   r   %DELETE FROM "{}" WHERE account_id = ?z1INSERT INTO "{}" (account_id, value) VALUES (?,?)r   TN)r   r   r   r   fetchallFromJsonGoogleAuthr   r   r   r   Set)	r   r   tablerowr   r{   r;   r   r   s	            r)   r   +SqliteCredentialStore.FormatAccountIdColumn  s     
kk
.
5
56L
M
  # #AAIj $Y/%!4!J!J"
 /KK7>>* 	 KKCJJ* &1	# 0 **,l3T:= 
s   AC=#C==A7C==
Dc                    U R                    n[        5       nUR                  SR                  [        5      5       H-  u  n[
        R                  U5      u  pEUR                  U5        M/     SSS5        U$ ! , (       d  f       W$ = f)z>Get all accounts.

Returns:
  set[str], A set of account ids.
*SELECT account_id FROM "{}" ORDER BY rowidN)r   setr   r   r   r   r   add)r   r   accountsr   r   _s         r)   r   !SqliteCredentialStore.GetAccounts  s|     
h%([[
6
=
=$&
!
 ,II 

 	Z & 
 O 
 Os   A A77
Bc                 8   [         R                  " [        5      nU R                   nUR	                  SR                  [        5      5       H0  n[        R                  US   5      u  pEX   R                  U5        M2     SSS5        U$ ! , (       d  f       U$ = f)zGet all accounts and their corresponding universe domains.

Returns:
  collections.defaultdict, A dictionary where the key is the account_id and
    the value is the universe domain list.
r   r   N)
collectionsdefaultdictlistr   r   r   r   r   r   append)r   accounts_dictr   r   r   rh   s         r)   GetAccountsWithUniverseDomain3SqliteCredentialStore.GetAccountsWithUniverseDomain  s      ++D1M	"%++
6
=
=$#
  ==$Q' 	$

 	!((9# 
  
 s   AB


Bc           	      *   U(       d[  U R                    nUR                  SR                  [        5      U45      R	                  5       nSSS5        Wc  g[        US   5      $ U R                    nUR                  SR                  [        5      XS-   45      R                  5       nSSS5        W(       d  g[        R                  R                  R                  n/ nSnU HM  u  p[        R                  U	5      u  pUR                  U5        XR                  5       :X  d  MB  [        U5      nMO     U(       d7  [!        SR                  UUR                  5       SR#                  U5      S95      eU$ ! , (       d  f       GN0= f! , (       d  f       N= f)	a  Load the credentials for the account_id.

Args:
  account_id: str, The account_id of the credential to load.
  use_google_auth: bool, Whether google-auth lib should be used. Default is
    True.

Returns:
  google.auth.credentials.Credentials or client.OAuth2Credentials, The
    loaded credentials.

Raises:
  googlecloudsdk.core.credentials.creds.InvalidCredentialsError: If problem
    happens when loading credentials.
z+SELECT value FROM "{}" WHERE account_id = ?Nr   zLSELECT account_id, value FROM "{}" WHERE account_id = ? OR account_id LIKE ?z#%a^  The account [{account_id}] is available in the following universe domain(s): [{universe_domains}], but it is not available in [{universe_property}] which is specified by the [core/universe_domain] property. Update your active account to an account from {universe_property} or update the [core/universe_domain] property to one of [{universe_domains}].z, )r   universe_propertyuniverse_domains)r   r   r   r   fetchoneFromJsonr   r   ri   rj   rh   r   r   r   rt   r   r.   join)r   r   use_google_authr   r{   r   r   r   r;   r   r   rh   s               r)   r   SqliteCredentialStore.Load  s{     <<3KK9@@& M	

 (* 	  
	il##	kk%v&<=D(
) 	
	  
 )0055EE E+0'.LL
a o.	88:	:"9- ,1 #M 6# 8 < < > ${{+;<    Lc < 
s   5E2/8F2
F
Fc                    [        U5      (       a2  [        U5      nU R                  SR                  [        5      X45        g[        U5      n[        R                  X5      nU R                  SR                  [        5      XC45        g)zStores the input credentials to the record of account_id in the cache.

Args:
  account_id: string, the account ID of the input credentials.
  credentials: google.auth.credentials.Credentials or
    client.OAuth2Credentials, the credentials to be stored.
z2REPLACE INTO "{}" (account_id, value) VALUES (?,?)N)r<   ToJsonr   r   r   ToJsonGoogleAuthr   r   )r   r   r   valuer   s        r)   r   SqliteCredentialStore.Store.  s     !--[!e
mm
>
E
E$ 
	 {+e0FF
 mm
>
E
E$  
'	r(   c                 |    [         R                  US 5      nU R                  SR                  [        5      U45        g )Nr   )r   r   r   r   r   )r   r   r   s      r)   r   SqliteCredentialStore.RemoveJ  s;    .DDD 	MM/667MN	r(   )r   NT)r"   r#   r$   r%   r&   r   r   r   r   r   r   r   r   r'   r    r(   r)   r   r     s0    (# %;N&,BH8r(   r   access_tokensc                   :    \ rS rSrSrS
S jrS rS rS rS r	Sr
g	)AccessTokenCacheiW  a  Sqlite implementation of for access token cache.

AccessTokenCache uses formatted_account_id instead of account_id in its APIs.
The reason is that AccessTokenCache is used by AccessTokenStoreGoogleAuth,
which is tied to a specific credential object. Either we let
AccessTokenStoreGoogleAuth pass the credential's universe_domain to
AccessTokenCache, or pass the formatted account id (which contains
universe_domain). The latter is better since it is backward compatible and
there is no need to introduce a new universe_domain parameter to all
AccessTokenCache Load/Store/Remove APIs.
See go/gcloud-multi-universe-auth-cache section 3.2, 3.3 for more details.
c                 >   X l         [        U5      U l        U R                  SR	                  [
        5      5         U R                  SR	                  [
        5      5        g ! [        R                   a'    U R                  SR	                  [
        5      5         g f = f)NzCREATE TABLE IF NOT EXISTS "{}" (account_id TEXT PRIMARY KEY, access_token TEXT, token_expiry TIMESTAMP, rapt_token TEXT, id_token TEXT)z!SELECT id_token FROM "{}" LIMIT 1z)ALTER TABLE "{}" ADD COLUMN id_token TEXT)_cache_only_raptr   r   r   r   _ACCESS_TOKEN_TABLEr   OperationalError)r   r   cache_only_rapts      r)   r   AccessTokenCache.__init__e  s    +j)DLMM	
   346 
mm
-
4
45H
IK##  
mm?FF
   s   $A! !8BBc                 n    U R                    nUR                  " U6   S S S 5        g ! , (       d  f       g = fr7   r   r   s      r)   r   AccessTokenCache._Executey  s!    		kk4 
s   &
4c                     U R                    nUR                  SR                  [        5      U45      R	                  5       sSSS5        $ ! , (       d  f       g= f)zLoad the tokens from the access token cache.

Args:
  formatted_account_id: str, The formatted account id.

Returns:
  tuple: The access_token, token_expiry, rapt_token, id_token tuple.
zVSELECT access_token, token_expiry, rapt_token, id_token FROM "{}" WHERE account_id = ?N)r   r   r   r  r   )r   r   r   s      r)   r   AccessTokenCache.Load}  sB     
[[++162E+F
! 	
 
s   4A
Ac                 b   U R                   (       a$  U R                  U5      nU(       a  Uu  p#puOSnSnSn U R                  SR                  [        5      UUUUU45        g! [
        R                   a8  n[        R                  " SR                  [        U5      5      5         SnAgSnAff = f)a;  Stores the tokens into the access token cache.

Args:
  formatted_account_id: str, The formatted account id.
  access_token: str, The access token string to store.
  token_expiry: datetime.datetime, The token expiry.
  rapt_token: str, The rapt token string to store.
  id_token: str, The ID token string to store.
NzcREPLACE INTO "{}" (account_id, access_token, token_expiry, rapt_token, id_token) VALUES (?,?,?,?,?)z)Could not store access token in cache: {})
r  r   r   r   r  r   r  r   warningstr)	r   r   access_tokentoken_expiry
rapt_tokenid_tokenresultr   es	            r)   r   AccessTokenCache.Store  s    ( yy-.f	28/Ax N
mm%v&9:"	 ## N	kk=DDSVLMMNs   *A" "B.6.B))B.c                      U R                  SR                  [        5      U45        g! [        R                   a8  n[
        R                  " SR                  [        U5      5      5         SnAgSnAff = f)zxRemoves the tokens from the access token cache.

Args:
  formatted_account_id: str, The formatted account id to remove.
r   z,Could not delete access token from cache: {}N)r   r   r  r   r  r   r  r  )r   r   r!  s      r)   r   AccessTokenCache.Remove  sb    Q
mm
1
8
89L
M
! ## Q	kk@GGAOPPQs   &) A5.A00A5)r  r   NF)r"   r#   r$   r%   r&   r   r   r   r   r   r'   r    r(   r)   r  r  W  s#     ( ,N\Qr(   r  c                   >   ^  \ rS rSrSrU 4S jrS rS rS rSr	U =r
$ )AccessTokenStorei  a  Oauth2client adapted for access token cache.

This class works with Oauth2client model where access token is part of
credential serialization format and get captured as part of that.
By extending client.Storage this class pretends to serialize credentials, but
only serializes access token.

When fetching the more recent credentials from the cache, this does not return
token_response, as it is now out of date.
c                 L   > [         [        U ]  SS9  Xl        X l        X0l        g)a  Sets up token store for given acount.

Args:
  access_token_cache: AccessTokenCache, cache for access tokens.
  account_id: str, account for which token is stored.
  credentials: oauth2client.client.OAuth2Credentials, they are auto-updated
    with cached access token.
N)lock)superr'  r   _access_token_cache_account_id_credentials)r   access_token_cacher   r   	__class__s       r)   r   AccessTokenStore.__init__  s*     

D**51!#r(   c                 $   U R                   R                  U R                  5      nU(       aY  Uu  p#pEX R                  l        X0R                  l        Ub  X@R                  l        XPR                  l        S U R                  l        U R                  $ r7   )	r+  r   r,  r-  r  r  r  id_tokenb64token_responser   
token_datar  r  r  r  s         r)   
locked_getAccessTokenStore.locked_get  s{    ))..t/?/?@J9C6l*'3$'3$		'1$&.#)-d&r(   c           
      X   [        U R                  S5      (       a'  U R                  R                  R                  SS 5      nOS nU R                  R                  U R                  U R                  R                  U R                  R                  [        U R                  SS 5      U5        g )Nr3  r  r  )	getattrr-  r3  ry   r+  r   r,  r  r  )r   r   r  s      r)   
locked_putAccessTokenStore.locked_put  s    t  "233""1155j$Ghh""&&&&!!<6r(   c                 N    U R                   R                  U R                  5        g r7   )r+  r   r,  r   s    r)   locked_deleteAccessTokenStore.locked_delete  s    ##D$4$45r(   )r+  r,  r-  )r"   r#   r$   r%   r&   r   r6  r:  r=  r'   __classcell__)r/  s   @r)   r'  r'    s!    	$
6 6r(   r'  c                   0    \ rS rSrSrS rS rS rS rSr	g)	AccessTokenStoreGoogleAuthi  zgoogle-auth adapted for access token cache.

This class works with google-auth credentials and serializes its short lived
tokens, including access token, token expiry, rapt token, id token into the
access token cache.
c                 P    Xl         [        R                  X#5      U l        X0l        g)a  Sets up token store for given account.

Args:
  access_token_cache: AccessTokenCache, cache for access tokens.
  account_id: str, account for which token is stored.
  credentials: google.auth.credentials.Credentials, credentials of account
    of account_id.
N)r+  r   r   _formatted_account_idr-  )r   r.  r   r   s       r)   r   #AccessTokenStoreGoogleAuth.__init__	  s(      2!4!J!J"D $r(   c                    U R                   R                  U R                  5      nU(       a  Uu  p#pE[        U R                  5      (       a4  SU R                  l        SU R                  l        SU R                  l        O0X R                  l        X0R                  l        X@R                  l        XPR                  l        XPR                  l	        U R                  $ )a  Gets credentials with short lived tokens from the internal cache.

Retrieves the short lived tokens from the internal access token cache,
populates the credentials with these tokens and returns the credentials.

Returns:
   google.auth.credentials.Credentials
N)
r+  r   rC  r   r-  tokenexpiry_rapt_token	_id_tokenr2  r4  s         r)   rt   AccessTokenStoreGoogleAuth.Get  s     ))..t/I/IJJ9C6l*	$++	,	, #'#' (,%".#/ (2%
 %-!&.#r(   c                    [        U R                  SS5      =(       d    [        U R                  SS5      n[        U R                  SS5      n[        U R                  SS5      n[        U R                  SS5      n[        U R                  5      (       a7  SnSnSnU R                  R	                  U R
                  5      nU(       a  Uu  pBp6U R                  R                  U R
                  XBX15        g)zEPuts the short lived tokens of the credentials to the internal cache.r2  NrI  rG  r  rF  )r9  r-  r   r+  r   rC  r   )r   r  rG  r  r  r5  r   s          r)   PutAccessTokenStoreGoogleAuth.Put6  s    t((-> ';CH T&&$7F**L$?J4,,gt<L))** lfj++001K1KLj	.8+j""""L*r(   c                 N    U R                   R                  U R                  5        g)z:Removes the tokens of the account from the internal cache.N)r+  r   rC  r   s    r)   Delete!AccessTokenStoreGoogleAuth.DeleteR  s    ##D$>$>?r(   )r+  r-  rC  N)
r"   r#   r$   r%   r&   r   rt   rL  rO  r'   r    r(   r)   rA  rA    s    $<8@r(   rA  c                    U R                   b  U $ [        U SS5      nU(       dB  [        R                  " [        R
                  " U R                  5      5      R                  5       n[        U=(       d    [        R                  " 5       R                  5      n[        X2U 5      nU R                  U5        UR                  5       $ )a  Attaches access token cache to given credentials if no store set.

Note that credentials themselves will not be persisted only access token. Use
this whenever access token caching is desired, yet credentials themselves
should not be persisted.

Args:
  credentials: oauth2client.client.OAuth2Credentials.
  access_token_file: str, optional path to use for access token storage.
Returns:
  oauth2client.client.OAuth2Credentials, reloaded credentials.
Nservice_account_email)storer9  hashlibsha256sixensure_binaryrefresh_token	hexdigestr  r   Pathsaccess_token_db_pathr'  	set_storery   )r   access_token_filer   r.  rS  s        r)    MaybeAttachAccessTokenCacheStorer^  W  s     "{$;TB*	 1 1!!!# $$-IK  (>6<<>>>@
-;
G%	r(   c                 >  ^ ^^ [        T SS5      nU(       dU  [        T [        R                  5      (       d  [        T [        R                  5      (       a  [
        R                  " T 5      nOIU(       dB  [        R                  " [        R                  " T R                  5      5      R                  5       n[        U=(       d    [        R                  " 5       R                   US9n[#        XCT 5      mTR%                  5       m T R&                  mU UU4S jnUT l        T $ )a  Attaches access token cache to given credentials if no store set.

Note that credentials themselves will not be persisted only access token. Use
this whenever access token caching is desired, yet credentials themselves
should not be persisted.

For external account and external account authorized user non-impersonated
credentials, the provided credentials should have been instantiated with
the client_id and client_secret in order to retrieve the account ID from the
3PI token instrospection endpoint.

Args:
  credentials: google.auth.credentials.Credentials.
  access_token_file: str, optional path to use for access token storage.
  cache_only_rapt: bool, True to only cache RAPT token.

Returns:
  google.auth.credentials.Credentials, reloaded credentials.
rR  N)r  c                 Z   > T" U 5        [        TSS 5      Tl        TR                  5         g )NrI  )r9  r2  rL  )requestr   orig_refreshrS  s    r)   _WrappedRefreshCMaybeAttachAccessTokenCacheStoreGoogleAuth.<locals>._WrappedRefresh  s'    %k;EK 
IIKr(   )r9  r8   google_auth_external_accountr?   ,google_auth_external_account_authorized_userc_introspectGetExternalAccountIdrT  rU  rV  rW  rX  rY  r  r   rZ  r[  rA  rt   refresh)r   r]  r  r   r.  rc  rb  rS  s   `     @@r)   *MaybeAttachAccessTokenCacheStoreGoogleAuthrj  t  s    , {$;TB* 
:FFGG=IIK K22;?J 1 1!!!# $$-IK  (>6<<>>>% %%7%02%		+ $$, (+	r(   c                   F    \ rS rSrSrS rS rS rS rSS jr	S r
S	 rS
rg)CredentialStoreWithCachei  a  Implements CredentialStore for caching credentials information.

Static credentials information, such as client ID and service account email,
are stored in credentials.db. The short lived credentials tokens, such as
access token, are cached in access_tokens.db.
c                     Xl         X l        g)a2  Sets up credentials store for caching credentials.

Args:
  credential_store: SqliteCredentialStore, for caching static credentials
    information, such as client ID, service account email, etc.
  access_token_cache: AccessTokenCache, for caching short lived credentials
    tokens, such as access token.
N)_credential_storer+  )r   credential_storer.  s      r)   r   !CredentialStoreWithCache.__init__  s     .1r(   c                 <   ^^ UR                   mUU4S jnX1l         U$ )a  Wraps the refresh method of credentials with auto caching logic.

For auto caching short lived tokens of google-auth credentials, such as
access token, on credentials refresh.

Args:
  credentials: google.auth.credentials.Credentials, the credentials updated
    by this method.
  store: AccessTokenStoreGoogleAuth, the store that caches the tokens of the
    input credentials.

Returns:
  google.auth.credentials.Credentials, the updated credentials.
c                 6   > T" U 5        TR                  5         g r7   )rL  )ra  rb  rS  s    r)   rc  XCredentialStoreWithCache._WrapCredentialsRefreshWithAutoCaching.<locals>._WrappedRefresh  s    7 iikr(   ri  )r   r   rS  rc  rb  s     ` @r)   &_WrapCredentialsRefreshWithAutoCaching?CredentialStoreWithCache._WrapCredentialsRefreshWithAutoCaching  s#     &&L *r(   c                 6    U R                   R                  5       $ )z-Returns all the accounts stored in the cache.)rn  r   r   s    r)   r   $CredentialStoreWithCache.GetAccounts  s    !!--//r(   c                 6    U R                   R                  5       $ )zHReturns all the accounts stored in the cache with their universe domain.)rn  r   r   s    r)   r   6CredentialStoreWithCache.GetAccountsWithUniverseDomain  s    !!??AAr(   c                 @   U R                   R                  X5      nUc  g[        U5      (       a8  [        U R                  UU5      nUR                  U5        UR                  5       $ [        U R                  UU5      nUR                  5       nU R                  X45      $ )a  Loads the credentials of account_id from the cache.

Args:
  account_id: string, ID of the account to load.
  use_google_auth: bool, True to load google-auth credentials if the type of
    the credentials is supported by the cache. False to load oauth2client
    credentials.

Returns:
  1. None, if credentials are not found in the cache.
  2. google.auth.credentials.Credentials, if use_google_auth is true.
  3. client.OAuth2Credentials.
N)
rn  r   r<   r'  r+  r\  ry   rA  rt   ru  )r   r   r  r   rS  s        r)   r   CredentialStoreWithCache.Load  s     ((--jJK !--t77*,eE"YY[()A)A:)46eIIKk 88LLr(   c                    [        U5      (       a:  [        U R                  UU5      nUR                  U5        UR	                  U5        O'[        U R                  UU5      nUR                  5         U R                  R                  X5        g)a  Stores credentials into the cache with account of account_id.

Args:
  account_id: string, the account that will be associated with credentials
    in the cache.
  credentials: google.auth.credentials.Credentials or
    client.OAuth2Credentials, the credentials to be stored.
N)	r<   r'  r+  r\  putrA  rL  rn  r   )r   r   r   rS  s       r)   r   CredentialStoreWithCache.Store  sv     !--t77*,eE"ii()A)A:)46eiik 	  9r(   c                     U R                   R                  U5        U R                  R                  [        R	                  U5      5        g)z1Removes credentials of account_id from the cache.N)rn  r   r+  r   r   r   s     r)   r   CredentialStoreWithCache.Remove  s8    !!*-##11*=r(   )r+  rn  Nr  )r"   r#   r$   r%   r&   r   ru  r   r   r   r   r   r'   r    r(   r)   rl  rl    s-    
240B MD:.r(   rl  c                     [        XU5      $ )a  Constructs credential store.

Args:
  store_file: str, optional path to use for storage. If not specified
    config.Paths().credentials_path will be used.
  access_token_file: str, optional path to use for access token storage. Note
    that some implementations use store_file to also store access_tokens, in
    which case this argument is ignored.
  cache_only_rapt: bool, True to only cache RAPT token.

Returns:
  CredentialStore object.
)_GetSqliteStoreWithCache)r   r]  r  s      r)   GetCredentialStorer  $  s    $ 
"_
 r(   c                       \ rS rSrSrS\SS4rS\SS4rS\	SS4r
S\SS4rS	\SS4rS
\SS4rS r\S 5       r\S 5       rSrg)rF   i;  z8Enum of oauth2client credential types managed by gcloud.r   Fr   T            c                 4    Xl         X l        X0l        X@l        g r7   type_idr|   is_serializablerH   r   r  r|   r  rH   s        r)   r   CredentialType.__init__E  s    LH* Lr(   c                 d    [          H  nUR                  U :X  d  M  Us  $    [         R                  $ r7   )rF   r|   UNKNOWNr|   rX   s     r)   FromTypeKeyCredentialType.FromTypeKeyM  s,    #		#	 $ !!!r(   c                 V   [        U [        R                  5      (       a  [        R                  $ [        U [
        R                  5      (       a.  [        U SS 5      b  [        R                  $ [        R                  $ [        U SS 5      b  [        R                  $ [        R                  $ )N_private_key_pkcs12rX  )r8   oauth2client_gceAppAssertionCredentialsrF   rK   r   ServiceAccountCredentialsr9  rS   rV   r   r  r:   s    r)   rG   CredentialType.FromCredentialsT  s    %)AABB%BBCC	-t	4	@111+++uot,8(((!!!r(   r  rH   r|   r  N)r"   r#   r$   r%   r&   UNKNOWN_CREDS_NAMEr  USER_ACCOUNT_CREDS_NAMEr   SERVICE_ACCOUNT_CREDS_NAMErV   P12_SERVICE_ACCOUNT_CREDS_NAMErS   DEVSHELL_CREDS_NAMEDEVSHELLGCE_CREDS_NAMErK   r   r   r  rG   r'   r    r(   r)   rF   rF   ;  s    @"E51',dD9,2D%@/:D%H$eT2(	
NE5)# " " 	" 	"r(   rF   c                       \ rS rSrSrS\SS4rS\SS4rS\	SS4r
S\SS4rS	\SS4rS
\SS4rS\SS4rS\SS4rS\SS4rS\SS4rS r\S 5       r\S 5       rSrg)rN   ia  z7Enum of google-auth credential types managed by gcloud.r   Fr   Tr  r  r  r           	   c                 4    Xl         X l        X0l        X@l        g)a  Builds a credentials type instance given the credentials information.

Args:
  type_id: string, ID for the credentials type, based on the enum constant
    value of the type.
  key: string, key of the credentials type, based on the enum constant value
    of the type.
  is_serializable: bool, whether the type of the credentials is
    serializable, based on the enum constant value of the type.
  is_user: bool, True if the credentials are of user account. False
    otherwise.

Returns:
  CredentialTypeGoogleAuth, an instance of CredentialTypeGoogleAuth which
    is a gcloud internal representation of type of the google-auth
    credentials.
Nr  r  s        r)   r   !CredentialTypeGoogleAuth.__init__y  s    $ LH* Lr(   c                 d    [          H  nUR                  U :X  d  M  Us  $    [         R                  $ )z4Returns the credentials type based on the input key.)rN   r|   r  r  s     r)   r  $CredentialTypeGoogleAuth.FromTypeKey  s.     .		#	 . $+++r(   c                 8   [        U [        R                  5      (       a  [        R                  $ [        U [
        R                  5      (       a  [        R                  $ [        U [        R                  5      (       a!  U R                  (       d  [        R                  $ [        U [        R                  5      (       a!  U R                  (       a  [        R                  $ [        U [        R                  5      (       a  [        R                  $ SSKJn  SSKJn  [        XR                  5      (       a  [        R"                  $ [        XR                  5      (       a  [        R$                  $ ['        U SS5      b  [        R(                  $ [        R*                  $ )z<Returns the credentials type based on the input credentials.r   r   p12_service_accountrX  N)r8   rB   r?   rN   rK   google_auth_impersonatedre   re  rH   r\   r_   rf  rb   google.oauth2r   googlecloudsdk.core.credentialsr  rS   rV   r9  r   r  )r;   google_auth_service_accountgoogle_auth_p12_service_accounts      r)   rG   (CredentialTypeGoogleAuth.FromCredentials  s"    %3??@@%)))%1==>>%:::56BBCCMM%66656BBCC%;;;5?KK	M 	M%FFF Mf%DDEE%999%@@AA%555uot,8%222#+++r(   r  N)r"   r#   r$   r%   r&   r  r  r  r   r  rV   r  rS   r  r  r  rK   IMPERSONATED_ACCOUNT_CREDS_NAMEre   EXTERNAL_ACCOUNT_CREDS_NAMEr\    EXTERNAL_ACCOUNT_USER_CREDS_NAMEr_   +EXTERNAL_ACCOUNT_AUTHORIZED_USER_CREDS_NAMErb   r   r   r  rG   r'   r    r(   r)   rN   rN   a  s    ?"E51',dD9,2D%@/:E5I$dD1(	
ND%(#<dEJ 4dEB >dK
 	4dD&B"2 , , , ,r(   rN   c                    [         R                  U 5      nU[         R                  :X  ar  UR                  U R                  U R
                  U R                  S.nS H<  n[        XS5      nU(       d  M  [        U[        5      (       a  [        U5      nXBU'   M>     OU[         R                  :X  a  U R                  nOrU[         R                  :X  aS  U R                  UR                  [        R                   " U R"                  5      R%                  S5      U R&                  S.nO[)        U5      e[*        R,                  " USSSS	9$ )
zFGiven Oauth2client credentials return library independent json for it.)type	client_idclient_secretrX  )r  invalid
revoke_uriscopesr3  	token_uri
user_agentr  Nascii)client_emailr  private_keypasswordTr  ,z: 	sort_keysindent
separators)rF   rG   r   r|   r  r  rX  r9  r8   r   r   rV   serialization_datarS   _service_account_emailbase64	b64encoder  decode_private_key_passwordr+   jsondumps)r   
creds_type
creds_dictfieldr  s        r)   r  r    s   --k:*>... **$22$22	JMk$/e	eS!!u+%!5M ^333//J^777 $:: (()H)HI55	J !
,,	J$
6 6r(   c                    [         R                  U 5      nU[         R                  :X  aR  UR                  U R                  U R
                  U R                  U R                  U R                  U R                  S.nGOU[         R                  :X  d  U[         R                  :X  a?  U R                  nU R                  (       a   [        U S5      (       a  U R                  US'   GO~U[         R                   :X  aR  UR                  U R"                  U R                  U R$                  U R&                  U R(                  U R*                  S.nGOU[         R,                  :X  aK  UR                  U R                  U R$                  U R&                  [.        U R0                  U R2                  S.nOU[         R4                  :X  aS  UR                  U R                  [6        R8                  " U R:                  5      R=                  S5      U R>                  S.nORU[         R@                  :X  a  UR                  U R                  S.nO$[C        S	RE                  UR                  5      5      eU RF                  US
'   [H        RJ                  " USSSS9$ )zFGiven google-auth credentials, return library independent json for it.)r  r  private_key_idr  r  r  
project_idinteractiveexternal_account_id)r  audiencer  r  rX  	token_urltoken_info_url)r  r  r  rX  r  r  r  r  )r  r  r  r  )r  rR  =Google auth does not support serialization of {} credentials.rh   Tr  r  r  )&rN   rG   rV   r|   rR  r  r  r  
_token_urir  r\   r_   infois_workforce_poolr   r  rb   r  r  rX  r  r  r   _REVOKE_URI_scopesr  rS   r  r  private_key_pkcs12r  private_key_passwordrK   r+   r   rh   r  r  )r   r  r  s      r)   r  r    s,   '77D*+;;;#99%44".. ** !++!,,J 	.???.DDD !!J $$m)L)L*5*I*Ij&'-NNN(( **$22$22 **%44J -::: **$22$22!%% **J -AAA#99
 k<<=DDWM44	J -111!,!B!BJ
 !GNNNN	 
 #."="=*	D{
D Dr(   c                 F    [        U 5      n[        R                  " USSSS9$ )a  Given google-auth credentials, return serialized json string.

This method is added because google-auth credentials are not serializable
natively.

Args:
  credentials: google-auth credential object.

Returns:
  Json string representation of the credential.
Tr  r  r  )ToDictGoogleAuthr  r  )r   r  s     r)   SerializeCredsGoogleAuthr  ,  s*      ,*	D{
D Dr(   c           	         [         R                  U 5      nUR                  (       d$  [        SR	                  UR
                  5      5      eSUR
                  0n[        U 5       Vs/ s H%  nUR                  S5      (       a  M  US;  d  M#  UPM'     nnU Vs/ s H&  nUR                  S5      (       a  USS U;  d  M$  UPM(     nn[        U5      nU H  n[        X5      (       d  M  [        X5      n[        U5      nU[        R                  :X  a  UR                  S5      nOy[        U[        R                   5      (       a   [#        U5      nOMUbJ  [%        U[&        R(                  5      (       d+  U[*        [,        [.        [0        [2        [4        [6        4;  a  M  XbU'   M     U$ s  snf s  snf ! [         a     M  f = f)	am  Given google-auth credentials, recursively return dict representation.

This method is added because google-auth credentials are not serializable
natively.

Args:
  credentials: google-auth credential object.

Returns:
  Dict representation of the credential.

Raises:
  UnknownCredentialsType: An error for when we fail to determine the type
  of the credentials.
r  r  __)signer_abc_negative_cache_versionr   r   Nz%m-%d-%Y %H:%M:%S)rN   rG   r  r+   r   r|   dir
startswithsortedr   r9  r  datetimestrftime
issubclassr>   r?   r  r8   rV  string_typesintfloatboolr  r   dicttuple)r   r  r  attrfiltered_list	attr_listvalval_types           r)   r  r  =  s     (77D*		#	#
 GNNNN	  
'* %($4 J$4D//$/ HH $4- J
 !. Mooc**d12hm.K ) MY)d{!!K&cch	X&&	&ll./h 1 = =>>	 %# OJsC4D4D$E$ES%sD$FF! $ 
5J
M & 	
	s0   &F(F(F(#F-?F-F22
G ?G c                    [         R                  " U 5      n[        R                  US   5      n[	        U5      US'   U[        R
                  :X  aJ  [        R                  R                  U[        R                  S9n[        R                  =Ul        Ul        U$ U[        R                  :X  a  [        R                   " SUS   US   US   SUR#                  S5      UR#                  S5      UR#                  S	5      UR#                  S
5      UR#                  S5      UR#                  S5      UR#                  S5      UR#                  S5      S9nU$ U[        R$                  :X  am  [        R                  R'                  US   [(        R*                  " US   5      US   US   [        R                  S9n[        R                  =Ul        Ul        U$ [-        US   5      e)zFReturns Oauth2client credentials from library independent json format.r  r  r  Nr  r  rX  r  r  r  r3  r  token_info_urir  )r  r  r  rX  r  r  r  r  r  r3  r  r  r  r  r  r  )rR  r  r  r  r  )r  loadsrF   r  r}   rV   r   r  from_json_keyfile_dictr   CLOUDSDK_SCOPESCLOUDSDK_USER_AGENTr  _user_agentr   r   r9   ry   rS   _from_p12_keyfile_contentsr  	b64decoder+   )
json_valuejson_keyrX   creds       r)   r   r   x  s   ZZ
#(((&)9:)7A(;.00044KK// L 1D)/)C)CCDOd&8 
+7 N///##;'//,,{+<<-<<-j)||$45||H%||$45<<-D4 
+ N66644OO&~6!++H],CD%j1;'%% P 'D *0)C)CCDOd& 
+ !&!1
22r(   c                 ,	   [         R                  " U 5      n[        R                  US   5      nU[        R                  :X  a  [        U5      US'   SSKJn  UR                  R                  nU" U[        R                  S9nUR                  S5      Ul        UR                  S5      Ul        UR                  S5      Ul        [!        U5        U$ U[        R"                  :X  aW  [        U5      US'   SS	KJn  UR)                  [*        R,                  " US   5      US
   US   US   [        R                  S9nU$ U[        R.                  :X  Ga  SU;  a&  [        R0                  US'   [        R2                  US'    UR                  S5      S:X  a0  SSKJn  UR                  R9                  U[        R                  S9nGOUR                  S5      b  UR                  S5      R                  S5      b  SSKJn  UR                  S5      R                  S5      n	UR                  R9                  U[        R                  S9nUR<                  (       aB  U	R                  S5      (       a,  SUl        [A        USUR                  S5      =(       d    S5        O/SSKJ!n
  U
R                  R9                  U[        R                  S9n [O        U5      $ U[        RP                  :X  ad  [        R0                  US'   [        R2                  US'   [        RR                  US'    [T        R                  R9                  U5      n[O        U5      $ U[        RV                  :X  aH  [        U5      US'   SSKJ,n  UR                  R[                  XR                  S5      S9nUS   Ul.        U$ U[        R^                  :X  ac  [`        R                  " US   S 9nUR                  S![b        Rd                  Rf                  Rh                  Rj                  5      Ul6        SUl7        U$ [q        S"Rs                  US   5      5      e! [D        [F        [H        RJ                  4 a    [M        S5      ef = f! [D        [F        [H        RJ                  4 a    [M        S5      ef = f)#a  Returns google-auth credentials from library independent json format.

The type of the credentials could be service account, external account
(workload identity pool or workforce pool), external account authorized user
(workforce), user account, p12 service account, or compute engine.

Args:
  json_value: string, A string of the JSON representation of the credentials.

Returns:
  google.auth.credentials.Credentials if the credentials type is supported
  by this method.

Raises:
  UnknownCredentialsType: when the type of the credentials is not service
    account, user account or external account.
  InvalidCredentialsError: when the provided credentials are malformed or
    unsupported external account credentials.
r  r  r   r   r   r  r  r  r  r  r  )rR  r  r  !service_account_impersonation_urlr  subject_token_typez+urn:ietf:params:aws:token-type:aws4_request)awscredential_source
executable)	pluggableinteractive_timeout_millisT_tokeninfo_usernamer   )identity_poolzDThe provided external account credentials are invalid or unsupportedr  zTThe provided external account authorized user credentials are invalid or unsupported)google_auth_credentialsrR  )rR  rh   z?Google auth does not support deserialization of {} credentials.):r  r  rN   r  rV   r}   r  r   r?   from_service_account_infor   r  ry   r  r  r  r   rS   r  r  CreateP12ServiceAccountr  r  r\   CLOUDSDK_CLIENT_IDCLOUDSDK_CLIENT_NOTSOSECRETgoogle.authr  	from_infor  r  r  setattrr  
ValueError	TypeErrorgoogle_auth_exceptionsRefreshErrorr.   $WrapGoogleAuthExternalAccountRefreshrb    CLOUDSDK_EXTERNAL_ACCOUNT_SCOPESrf  r   r  from_authorized_user_infor  rK   rB   r   ri   rj   rh   rk   _universe_domain_universe_domain_cachedr+   r   )r	  r
  rX   r  service_account_credentialsr  r  r  r  r  r  c_google_auths               r)   r   r     sI   ( ZZ
#(&228F3CD)*:::9(CH[ M 	$//II  &x8N8NOD  ||M2D",,'78D\\+.DN#D)K*>>>9(CH[C66-01&~6;'%% 7 'D K*;;; +(:$77h{"("D"Dh	* 
G
H 	$((V33 ) 5LL,-9LL,-11,?K)\\"56::<H
$$..V33 / 5!!jnn('* '*!$
 $-,,45;= 	.((22V33 3 5 055*KKK #55H[ & B BH_@@HX$9EEOO
d 055*7779(CH[ Y $$>>h/ ? 1D {+DOK*...%11&'>?D %LL:,,11AAIID
 $(D KGNN
6
	 m 	#9#F#FG # , 	#9#F#FG $##$ $$s&   >AP: CP: .P:  Q( :+Q%(+Rc                 8   ^ U R                   mU4S jnXl         U $ )a  Returns a wrapped External Account credentials.

We wrap the refresh method to make sure that any errors raised can be caught
in a consistent way by downstream consumers.

Args:
  cred: google.auth.credentials.Credentials

Returns:
  google.auth.credentials.Credentials
c                    >  T" U 5        g ! [         [        [        R                  4 a  n[        R
                  " U5      eS nAff = fr7   )r  r   r!  r"  c_exceptionsTokenRefreshError)ra  r!  rb  s     r)   rc  =WrapGoogleAuthExternalAccountRefresh.<locals>._WrappedRefreshB  s?    .7	#9#F#FG .**1--.s    AAArt  )r  rc  rb  s     @r)   r#  r#  3  s     ,. !,	+r(   c                     [        U 5      nU=(       d    [        R                  " 5       R                  n[        R
                  " U5        [        X5      n[        X45      $ )z$Get a sqlite-based Credential Store.)_GetSqliteStorer   rZ  r[  r   PrivatizeFiler  rl  )sqlite_credential_filesqlite_access_token_filer  ro  r.  s        r)   r  r  L  sX     %%;<6 B$llnAA ./' 
""2	GGr(   c                     U =(       d    [         R                  " 5       R                  n [        R                  " U 5        [        U 5      nU$ )zFGet a sqlite-based Credential Store with using the access token cache.)r   rZ  credentials_db_pathr   r1  r   )r2  ro  s     r)   r0  r0  ^  s?    2 ?"LLN>> ,-*+AB	r(   c                     U [         R                  R                  R                  [         R                  R                  R                  4;   $ r7   )r   ri   billingCURRENT_PROJECTCURRENT_PROJECT_WITH_FALLBACK)quota_projects    r)   _QuotaProjectIsCurrentProjectr;  g  s>    	//==? 
? ?r(   c                    U c  g[         R                  R                  R                  R	                  5       n[        U5      (       aC  [        U 5      (       a2  [         R                  R                  R                  R	                  5       $ gU[         R                  R                  R                  :X  a:  U(       a2  [         R                  R                  R                  R	                  5       $ gU$ )a  Gets the value to use for the X-Goog-User-Project header.

Args:
  credentials: The credentials that are going to be used for requests.
  force_resource_quota: bool, If true, resource project quota will be used
    even if gcloud is set to use legacy mode for quota. This should be set
    when calling newer APIs that would not work without resource quota.

Returns:
  str, The project id to send in the header or None to not populate the
  header.
N)
r   ri   r7  r:  rt   r;  rQ   rj   projectLEGACY)r   force_resource_quotar:  s      r)   GetQuotaProjectr@  m  s     ##++99==?-"=11,,##++//11 
))11888##++//11	r(   c                   b    \ rS rSrSr   SS jr\S 5       r\S 5       rSS jr	SS jr
S	 rS
rg)ADCi  z&Application default credential object.Nc                 4    Xl         X l        X0l        X@l        g r7   )r-  _impersonated_service_account
_delegatesr  )r   r   impersonated_service_account	delegatesr  s        r)   r   ADC.__init__  s    
 $)E&OLr(   c                 V    [        U R                  5      =(       a    U R                  S L $ r7   )rQ   r-  rD  r   s    r)   rH   ADC.is_user  s(    $T%6%67 7..$68r(   c                 n    [        U R                  U R                  U R                  U R                  5      $ )z/Json representation of the credentials for ADC.)_ConvertCredentialsToADCr-  rD  rE  r  r   s    r)   adcADC.adc  s0     $D$5$5$($F$F$(OO$(LL2 2r(   c                 j    U=(       d    [         R                  " 5       n[        U R                  U5      $ )z+Dumps the credentials to the ADC json file.)r   ADCFilePath_DumpADCJsonToFilerM  )r   	file_paths     r)   DumpADCToFileADC.DumpADCToFile  s&    1V//1Idhh	22r(   c                     U R                   (       d  [        S5      eU=(       d    [        R                  " 5       nU(       d  [	        U R
                  SS9nU R                  U5      n[        X15      $ )zADumps the credentials and the quota project to the ADC json file.zoThe credential is not a user credential, so we cannot insert a quota project to application default credential.T)r?  )rH   r1   r   rP  r@  r-  _ExtendADCWithQuotaProjectrQ  )r   rR  r:  extended_adcs       r)   DumpExtendedADCToFileADC.DumpExtendedADCToFile  sc    <<#=> > 1V//1I%


$8m22=ALl66r(   c                     [         R                  " U R                  5      nU(       a
  X[        '   U$ [        R
                  " S5        U$ )z'Add quota_project_id field to ADC json.zCannot find a project to insert into application default credentials (ADC) as a quota project.
Run $gcloud auth application-default set-quota-project to insert a quota project to ADC.)copydeepcopyrM  ADC_QUOTA_PROJECT_FIELD_NAMEr   r  )r   r:  rW  s      r)   rV  ADC._ExtendADCWithQuotaProject  sC    ==*L3@/0  
kk"#
 r(   )r-  rE  rD  r  )NNNr7   )NN)r"   r#   r$   r%   r&   r   propertyrH   rM  rS  rX  rV  r'   r    r(   r)   rB  rB    sL    . -1	 8 8 2 23
7r(   rB  c                 @    [         R                  " U SSSS9n[        R                  " XSS9  [        R                  R                  U5      $ ! [        R                   a<  n[
        R                  " USS9  [        S[        R                  " U5      -   5      eSnAff = f)	zDumps ADC json object to file.Tr  r  r  )private)exc_infoz.Error saving Application Default Credentials: N)r  r  r   WriteFileContentsr   r   debugr1   rV  	text_typeospathabspath)rM  rR  contentsr!  s       r)   rQ  rQ    s    Mzz#aKPH	I>
 
	##	 
 MIIa$
!83==;KKM MMs   ,A B!7BBc           
         [         R                  U 5      nU[         R                  [         R                  4;  a#  [	        SR                  [        U 5      5      5      eU[         R                  :X  am  [        R                  " U R                  U R                  U R                  U R                  U R                  U R                  U R                  U R                   5      n U R"                  $ )zHConverts an oauth2client credentials to application default credentials.ICannot convert credentials of type {} to application default credentials.)rF   rG   r   rV   r4   r   r  r   GoogleCredentialsr  r  r  rX  r  r  r  r  r  )r   r  s     r)   $_ConvertOauth2ClientCredentialsToADCrm    s    --k:*33&668 8
 **0&k1B*CE E>...**  +"7"7!!;#<#<  +"7"79O9O	 K
 
	'	''r(   zNhttps://iamcredentials.{}/v1/projects/-/serviceAccounts/{}:generateAccessTokenc                 \   [        U 5      (       a  [        U 5      nO[        U 5      nU(       d  U$ [        U S5      (       a  U R                  nO.[
        R                  R                  R                  R                  nU[        R                  UU5      U=(       d    / SS.nU(       a  X6S'   U$ )z<Convert credentials with impersonation to a json dictionary.rh   rF  )source_credentialsr  rG  r  r  )r<   rm  "_ConvertGoogleAuthCredentialsToADCr   rh   r   ri   rj   rk   IMPERSONATION_TOKEN_URLr   )r   rF  rG  r  r  rh   impersonated_creds_dicts          r)   rL  rL    s     {++5kBJ3K@J	%[+,,!11O '',,<<DDO 
!
(
(*, /r
( (.H%	  r(   c                 2   [         R                  U 5      nU[         R                  :X  a6  U R                  SS9n[        R
                  " U5      nUR                  US'   U$ U[         R                  :X  aP  UR                  U R                  U R                  U R                  U R                  U R                  U R                  S.$ U[         R                  :X  d  U[         R                  :X  a2  U R                   nUR#                  SS5        UR#                  SS5        U$ U[         R$                  :X  aD  U R                  SS9n[        R
                  " U5      n['        U S	S5      b  U R                  US	'   U$ [)        S
R+                  [-        U 5      5      5      e)zFConverts a google-auth credentials to application default credentials.)rF  r  r  rG  )stripr  )r  r  r  r  r  r  rh   r  Nr  )rF  rG  r  rh   rk  )rN   rG   r   to_jsonr  r  r|   rV   rR  r  r  r  r  rh   r\   r_   r  poprb   r9  r4   r   r  )r   r  rM  adc_jsons       r)   rp  rp    sr   '77D*+888


$N

OC
**S/C..CKJ+;;;#99%44".. ** ++&66  ,===,BBB HLLd#LL$'O+LLL"")F"GHzz(#H{-t4@$/$?$?h !O ((.tK/@(A	C Cr(   nonec                      [         (       a  [         $ SSKJn   SSKnUR	                  S[
        SS9  U R                  R                  [        5        U q [        5       $ )a`  Get the google.auth._default module.

All messages from logging and warnings are muted because they are for
ADC consumers (client libraries). The message are irrelevant and confusing to
gcloud auth application-default users. gcloud auth application-default
are the ADC producer.

Returns:
  The google.auth._default module with logging/warnings muted.
r   )_defaultNignorezgoogle.auth._default)categorymodule)
GOOGLE_AUTH_DEFAULTr  rz  warningsfilterwarningsWarning_LOGGERsetLevelVERBOSITY_MUTEDGetGoogleAuthDefault)rz  r  s     r)   r  r  1  sU     "
)?  A
O, 		r(   )r  r7   r[   )NNFr%  ){r&   
__future__r   r   r   r   r  r   r[  r  enumrT  r  rf  r   r  r   rB   r   r>   r	   r!  r
   re  r   rf  r   r  googlecloudsdk.corer   r   r   r  r   rI   r,  r   rg  googlecloudsdk.core.utilr   oauth2clientr   r   oauth2client.contribr   r  rV  r]  r  r  r  r  r  r  r  r  r  r  r  r   r+   r.   r1   r4   r<   r@   rC   rL   rO   rQ   rT   rY   r]   r`   rc   rf   rl   rv   r}   r   r   r   objectr   add_metaclassABCMetar   r   r   r   r  r  Storager'  rA  r^  rj  rl  r  EnumrF   rN   r  r  r  r  r   r   r#  r  r0  r;  r@  rB  rQ  rm  rq  rL  rp  r~  VALID_VERBOSITY_STRINGSr  r  r    r(   r)   <module>r     s    ' &  ' 
        	  D 8 < H h L & * # * B F F *  ( 8 
1 4 + . !6   "8 0 #:  .P +$J $LU LPe P=e =Bu B5:C6.
G.@"6((;0& ;0| 3;;f   0 ' ' '@HO HV & pQv pQf46v~~ 46nS@ S@n 8<< :?6rt tp .#"TYY #"LU,tyy U,p&6RGDTD"8v$NQh4  !H$?<7& 7t	$(  k  04 !F#CL  --f5 r(   