
    .                       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Jr  SSKrSSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  S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SK-J.r.  Sr/Sr0Sr1Sr2Sr3Sr4Sr5 " S  S!\Rl                  5      r6 " S" S#\65      r7 " S$ S%\65      r8 " S& S'\85      r9 " S( S)\65      r: " S* S+\65      r; " S, S-\65      r< " S. S/\65      r= " S0 S1\65      r> " S2 S3\65      r?Sr@ " S4 S5\A5      rB\B" 5       rCS6 rD " S7 S8\A5      rE " S9 S:\A5      rF " S; S<\A5      rGS= rHS> rIS?\JS@\\J   4SA jrKSB rLSC rM ShSD jrNSE rOSiSG jrP   SiSH jrQ    SjSI jrR    SjSJ jrS     SkSK jrTSlSL jrUSM rV " SN SO\A5      rW      SmSP jrXSQ rYSR rZSS r[  SnST jr\    SoSU jr]    SoSV jr^\R                   SpSW j5       r`SX ra    SoSY jrb     SqSZ jrcS[ rdS\ reS] rfS^ rgS_ rhSrS` jriSa rjSb rkSsSc jrlS\1SF4Sd jrmStSe jrn " Sf Sg\A5      rog)uzIOne-line documentation for auth module.

A detailed description of auth.
    )absolute_import)division)unicode_literalsN)Optionalexternal_accountutil)config)log)
properties)	transport)named_configscreds
exceptions)gce)encoding)files)times)client)cryptservice_account)reauth_errors)urllibCLOUDSDK_AUTH_ACCESS_TOKENz)https://accounts.google.com/o/oauth2/authz+https://accounts.google.com/o/oauth2/revokez+urn:ietf:params:oauth:grant-type:jwt-bearer300szr    table[title='Credentialed Accounts'](
        status.yesno(yes='*', no=''):label=ACTIVE,
        account
    )z    table[title='Credentialed Accounts'](
        status.yesno(yes='*', no=''):label=ACTIVE,
        account,
        universe_domain
    )c                       \ rS rSrSrSrg)ErrorP   z&Exceptions for the credentials module. N__name__
__module____qualname____firstlineno____doc____static_attributes__r#       ,lib/googlecloudsdk/core/credentials/store.pyr!   r!   P   s    .r+   r!   c                       \ rS rSrSrSrg)NoImpersonationAccountErrorT   z2Exception when there is no account to impersonate.r#   Nr$   r#   r+   r,   r.   r.   T   s    :r+   r.   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )!PrintTokenAuthenticationExceptionX   z1Exceptions that tell the users to run auth login.c                 n   > [         [        U ]  [        R                  " SR                  US95      5        g )Nz        {message}
        Please run:

          $ gcloud auth login

        to obtain new credentials.

        For service account, please activate it first:

          $ gcloud auth activate-service-account ACCOUNT)message)superr1   __init__textwrapdedentformat)selfr4   	__class__s     r,   r6   *PrintTokenAuthenticationException.__init__[   s:    	
+T;HOO 
M< =CF =C ==  !r+   r#   r%   r&   r'   r(   r)   r6   r*   __classcell__r;   s   @r,   r1   r1   X   s    9! !r+   r1   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ ) NoCredentialsForAccountExceptionj   z;Exception for when no credentials are found for an account.c                 F   > [         [        U ]  SR                  US95        g )NzKYour current active account [{account}] does not have any valid credentialsaccount)r5   rA   r6   r9   )r:   rE   r;   s     r,   r6   )NoCredentialsForAccountException.__init__m   s$    	
*D:	#VGV46r+   r#   r=   r?   s   @r,   rA   rA   j   s    C6 6r+   rA   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )InvalidCredentialFileExceptions   zCException for when an external credential file could not be loaded.c                 p   > [         [        U ]  SR                  U[        R
                  " U5      S95        g )Nz1Failed to load credential file: [{f}].  {message})fr4   )r5   rH   r6   r9   six	text_type)r:   rK   er;   s      r,   r6   'InvalidCredentialFileException.__init__v   s-    	
($8;	!S]]1-	.0r+   r#   r=   r?   s   @r,   rH   rH   s   s    K0 0r+   rH   c                       \ rS rSrSrSrg)AccountImpersonationError|   zEException for when attempting to impersonate a service account fails.r#   Nr$   r#   r+   r,   rQ   rQ   |   s    Mr+   rQ   c                       \ rS rSrSrSrg)	FlowError   z8Exception for when something goes wrong with a web flow.r#   Nr$   r#   r+   r,   rT   rT      s    @r+   rT   c                       \ rS rSrSrSrg)RevokeError   z0Exception for when there was a problem revoking.r#   Nr$   r#   r+   r,   rW   rW      s    8r+   rW   c                       \ rS rSrSrSrg)InvalidCodeVerifierError   z-Exception for invalid code verifier for pkce.r#   Nr$   r#   r+   r,   rZ   rZ      s    5r+   rZ   c                       \ rS rSrSrSrg)UnsupportedCredentialsError   z6Exception for when a credential type is not supported.r#   Nr$   r#   r+   r,   r]   r]      s    >r+   r]   c                   :    \ rS rSrSrS rS rS rS
S jrS r	Sr
g	)StaticCredentialProviders   z'Manages a list of credential providers.c                     / U l         g N
_providersr:   s    r,   r6   "StaticCredentialProviders.__init__   s	    DOr+   c                 :    U R                   R                  U5        g rc   )re   appendr:   providers     r,   AddProvider%StaticCredentialProviders.AddProvider       OO8$r+   c                 :    U R                   R                  U5        g rc   )re   removerj   s     r,   RemoveProvider(StaticCredentialProviders.RemoveProvider   rn   r+   c                 Z    U R                    H  nUR                  X5      nUc  M  Us  $    g rc   )re   GetCredentials)r:   rE   use_google_authrk   creds        r,   rt   (StaticCredentialProviders.GetCredentials   s0    OO$$W>d		 $ r+   c                 d    [        5       nU R                   H  nXR                  5       -  nM     U$ rc   )setre   GetAccounts)r:   accountsrk   s      r,   rz   %StaticCredentialProviders.GetAccounts   s-    uHOO&&((h $Or+   rd   NT)r%   r&   r'   r(   r)   r6   rl   rq   rt   rz   r*   r#   r+   r,   r`   r`      s    /%%r+   r`   c                 B   [         R                  R                  R                  nUR	                  5       (       d  UR                  U 5        g[        R                  " X5        UR                  5       U :w  a*  [        R                  " SU UR                  5       S.-  5      eg)ak  Handles the universe domain from GCE metadata.

If core/universe_domain property is not explicitly set, set it with the MDS
universe_domain, but not persist it so it's only used in the current command
invocation.
If core/universe_domain property is explicitly set, but it's different from
the MDS universe_domain, prompt the user to update and persist the
core/universe_domain property. If the user chooses not to update, an error
will be raised to avoid sending GCE credentials to a wrong universe domain.

Args:
  mds_universe_domain: string, The universe domain from metadata server.
  account: string, The account.
Na  Your credentials are from "%(universe_from_mds)s", but your [core/universe_domain] property is set to "%(universe_from_property)s". Update your active account to an account from "%(universe_from_property)s" or update the [core/universe_domain] property to "%(universe_from_mds)s".)universe_from_mdsuniverse_from_property)r   VALUEScoreuniverse_domainIsExplicitlySetSet	auth_utilHandleUniverseDomainConflictGetc_credsInvalidCredentialsError)mds_universe_domainrE   universe_domain_propertys      r,   _HandleGceUniverseDomainr      s     (..33CC	!	1	1	3	3  !45
 (()<F !!#'::

)
)	G "5&>&B&B&D
	

 
 ;r+   c                   F    \ rS rSrSrSS jrS rS rS rS r	S r
S	 rS
rg)GceCredentialProvider   z=Provides account, project and credential data for gce vm env.c                     [         R                  R                  R                  R	                  5       (       a:  U[
        R                  " 5       R                  5       ;   a  U(       + n[        XU5      $ g rc   )	r   r   r   check_gce_metadataGetBoolc_gceMetadataAccountsAcquireFromGCE)r:   rE   ru   refreshs       r,   rt   $GceCredentialProvider.GetCredentials   sU    0088::	ENN$--/	/
 &%g@@r+   c                     [         R                  R                  R                  R	                  5       (       a#  [
        R                  " 5       R                  5       $ g rc   )r   r   r   r   r   r   r   DefaultAccountrf   s    r,   
GetAccount GceCredentialProvider.GetAccount   s<    0088::^^,,..r+   c                     [         R                  R                  R                  R	                  5       (       a,  [        [        R                  " 5       R                  5       5      $ [        5       $ rc   )	r   r   r   r   r   ry   r   r   r   rf   s    r,   rz   !GceCredentialProvider.GetAccounts   sE    0088::!**,--5Lr+   c                     [         R                  R                  R                  R	                  5       (       a#  [
        R                  " 5       R                  5       $ g)zGets the universe domain from GCE metadata.

Returns:
  str: The universe domain from metadata server. Returns None if
    core/check_gce_metadata property is False.
N)r   r   r   r   r   r   r   UniverseDomainrf   s    r,   GetUniverseDomain'GceCredentialProvider.GetUniverseDomain   s>     0088::^^,,..r+   c                     [         R                  R                  R                  R	                  5       (       a#  [
        R                  " 5       R                  5       $ g rc   )r   r   r   r   r   r   r   Projectrf   s    r,   
GetProject GceCredentialProvider.GetProject   s<    0088::^^%%''r+   c                    [         R                  R                  R                  R	                  U R
                  5        [         R                  R                  R                  R	                  U R                  5        [         R                  R                  R                  R	                  U R                  5        [        R                  U 5        g rc   )r   r   r   rE   AddCallbackr   projectr   r   r   STATIC_CREDENTIAL_PROVIDERSrl   rf   s    r,   RegisterGceCredentialProvider.Register   s~    ""..t?""..t?**66t7M7MN++D1r+   c                    [         R                  R                  R                  R	                  U R
                  5        [         R                  R                  R                  R	                  U R                  5        [         R                  R                  R                  R	                  U R                  5        [        R                  U 5        g rc   )r   r   r   rE   RemoveCallbackr   r   r   r   r   r   rq   rf   s    r,   
UnRegister GceCredentialProvider.UnRegister  s    ""11$//B""11$//B**99  ..t4r+   r#   Nr}   )r%   r&   r'   r(   r)   rt   r   rz   r   r   r   r   r*   r#   r+   r,   r   r      s(    E	

	
25r+   r   c                       \ rS rSrSrS rSrg)AcctInfoi  zAn auth command resource list item.

Attributes:
  account: str, The account name.
  status: str, The account status, one of ['ACTIVE', ''].
c                 <    Xl         U(       a  SU l        g SU l        g NACTIVE rE   status)r:   rE   actives      r,   r6   AcctInfo.__init__  s    L$(DK"DKr+   r   Nr%   r&   r'   r(   r)   r6   r*   r#   r+   r,   r   r     s    -r+   r   c                       \ rS rSrSrS rSrg)AcctInfoWithUniverseDomaini  zAn auth command resource list item.

Attributes:
  account: str, The account name.
  status: str, The account status, one of ['ACTIVE', ''].
  universe_domain: str, The universe domain. The default value is
    googleapis.com.
c                     Xl         U(       a  SOSU l        U=(       d.    [        R                  R                  R
                  R                  U l        g r   )rE   r   r   r   r   r   default)r:   rE   r   r   s       r,   r6   #AcctInfoWithUniverseDomain.__init__&  s:    L$("DKI:,,11AAII 	r+   )rE   r   r   Nr   r#   r+   r,   r   r     s    r+   r   c                      [         R                  R                  R                  R	                  5       n [        5        Vs/ s H  n[        XU :H  5      PM     sn$ s  snf )zGet all accounts for the auth command Run() method.

Returns:
  List[AccInfo]: The list of account information for all accounts.
)r   r   r   rE   r   AvailableAccountsr   )active_accountrE   s     r,   AllAccountsr   .  sX     $$))11557. '(
(' w>12(
  
s   Ac            	         [         R                  " 5       n U R                  5       n[        R	                  5       nU Hm  nX1;  d  M
  [        R                  U5      n[        US5      (       a  UR                  O-[        R                  R                  R                  R                  /X'   Mo     [        [        UR                  5       5      5      n[        R                  R                  R                  R!                  5       n[        R                  R                  R                  R!                  5       n/ nU H9  nX    H.  nX5:H  =(       a    Xh:H  n	UR#                  [%        UU	U5      5        M0     M;     U$ )zGet all accounts and universe domains for the auth command Run() method.

Returns:
  List[AccInfoWithUniverseDomain]: The list of account and universe domain
    information for all accounts.
r   )r   GetCredentialStoreGetAccountsWithUniverseDomainr   rz   rt   hasattrr   r   r   r   r   dictsorteditemsrE   r   ri   r   )
storeaccounts_dictstatic_accountsrE   r   r   r   resultr   	is_actives
             r,   AllAccountsWithUniverseDomainsr   ;  sE    
$
$
&%557-
 0;;=/ g #)88Ae U-.. 

  %%55== m ! vm11345-$$))11557.'..33CCGGI&g(1

# :&9  mm
$ 2  
-r+   rE   returnc                 n   ^  [        5       n[        U 4S jU 5       S5      nU(       a  UR                  $ S$ )zGet the universe domain of a credentialed account.

Args:
  account: The account to get the universe domain for.

Returns:
  The credentialed account's universe domain if exists. None otherwise.
c              3   L   >#    U  H  nUR                   T:X  d  M  Uv   M     g 7frc   rD   ).0cred_accountrE   s     r,   	<genexpr>7GetCredentialedAccountUniverseDomain.<locals>.<genexpr>v  s(      /l!!W, ,/s   $	$N)r   nextr   )rE   all_cred_accountsr   s   `  r,   $GetCredentialedAccountUniverseDomainr   k  s?     56/
 , *6	%	%?4?r+   c                      [         R                  " 5       n U R                  5       [        R                  5       -  n[	        U5      $ )zGet all accounts that have credentials stored for the CloudSDK.

This function will also ping the GCE metadata server to see if GCE credentials
are available.

Returns:
  [str], List of the accounts.
)r   r   rz   r   r   )r   r{   s     r,   r   r     s:     
$
$
&% #>#J#J#LL(		r+   c                  f    [         R                  R                  R                  R	                  5       $ )z1Returns True if google-auth is disabled globally.)r   r   authdisable_load_google_authr   r#   r+   r,   GoogleAuthDisabledGloballyr     s#    						8	8	@	@	BBr+   c                 .    [         R                  " U SS9nUR                  U:  a  [        SR	                  U 5      5      e [         R                  " U[        R                  R                  5       S9n[         R                  " [         R                  " [        R                  R                  5       S9U5      nX:*  $ ! [         R
                   aD  n[        R                  " U5      R                  S5      n[        SR	                  X5      5      eSnAff = f)a  Determines if token_expiry_time is within expiry_window_duration.

Calculates the amount of time between utcnow() and token_expiry_time and
returns true, if that amount is less than the provided duration window. All
calculations are done in number of seconds for consistency.


Args:
  expiry_window: string, Duration representing the amount of time between
    now and token_expiry_time to compare against.
  token_expiry_time: datetime, The time when token expires.
  max_window_seconds: int, Maximum size of expiry window, in seconds.

Raises:
  ValueError: If expiry_window is invalid or can not be parsed.

Returns:
  True if token is expired or will expire with in the provided window,
  False otherwise.
s)default_suffixz>Invalid expiry window duration [{}]: Must be between 0s and 1h.z-Error Parsing expiry window duration [{}]: {}N)tzinfo)r   ParseDurationtotal_seconds
ValueErrorr9   r!   rL   rM   rstripLocalizeDateTimedateutiltztzutcGetDateTimePlusDurationNow)expiry_windowtoken_expiry_timemax_window_seconds
min_expiryrN   r4   
window_ends          r,   _TokenExpiresWithinWindowr     s    .@$$]3GJ"44 3396-3HJ J 5 ,,->4<KK4E4E4GI,,iix{{((*+Z9* 
	(( 
 @mmA%%c*G
   &} >@ @@s   ?B< <D?DDc                 p    U c  g [         R                  " U 5      (       a  U R                  $ U R                  $ rc   )r   IsGoogleAuthCredentialstokenaccess_tokenr   s    r,   _GetAccessTokenFromCredsr     s1    
]$$U++;;r+   Tc                 4    [        XSUS5      n[        U5      $ )a;  Returns the access token of the given account or the active account.

GetAccessToken ignores whether credentials have been disabled via properties.
Use this function when the caller absolutely requires credentials.

Args:
  account: str, The account to get the access token for. If None, the
    account stored in the core.account property is used.
  scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES are
    requested.
  allow_account_impersonation: bool, True to allow use of impersonated service
    account credentials (if that is configured).
FT)Loadr   )rE   scopesallow_account_impersonationr   s       r,   GetAccessTokenr     s      w'BD
I%	!%	((r+   c                     [         R                  R                  R                  R	                  5       (       a  g[        XU5      $ )a  Returns the access token of the given account or the active account.

If credentials have been disabled via properties, this will return None.
Otherwise it return the access token of the account like normal. Use this
function when credentials are optional for the caller, or the caller want to
handle the situation of credentials being disabled by properties.

Args:
  account: str, The account to get the access token for. If None, the
    account stored in the core.account property is used.
  scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES are
    requested.
  allow_account_impersonation: bool, True to allow use of impersonated service
    account credentials (if that is configured).
N)r   r   r   disable_credentialsr   r   )rE   r   r   s      r,   GetAccessTokenIfEnabledr    s6    $ //7799	)D	EEr+   c                 4    [        XUUS5      n[        U5      $ )a  Returns a fresh access token of the given account or the active account.

Same as GetAccessToken except that the access token returned by
this function is valid for at least min_expiry_duration.

Args:
  account: str, The account to get the access token for. If None, the
    account stored in the core.account property is used.
  scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES are
    requested.
  min_expiry_duration: Duration str, Refresh the token if they are
    within this duration from expiration. Must be a valid duration between 0
    seconds and 1 hour (e.g. '0s' >x< '1h').
  allow_account_impersonation: bool, True to allow use of impersonated service
    account credentials (if that is configured).
T)LoadFreshCredentialr   )rE   r   min_expiry_durationr   r   s        r,   GetFreshAccessTokenr    s$    ( g/B94A%	!%	((r+   c                     [         R                  R                  R                  R	                  5       (       a  g[        XUU5      $ )a  Returns a fresh access token of the given account or the active account.

Same as GetAccessTokenIfEnabled except that the access token returned by
this function is valid for at least min_expiry_duration.

Args:
  account: str, The account to get the access token for. If None, the
    account stored in the core.account property is used.
  scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES are
    requested.
  min_expiry_duration: Duration str, Refresh the token if they are
    within this duration from expiration. Must be a valid duration between 0
    seconds and 1 hour (e.g. '0s' >x< '1h').
  allow_account_impersonation: bool, True to allow use of impersonated service
    account credentials (if that is configured).
N)r   r   r   r  r   r  )rE   r   r  r   s       r,   GetFreshAccessTokenIfEnabledr	    s=    ( //7799	W.A8
: :r+   c                 4    [        U UUUS9n[        XR5        U$ )a*  Load credentials and force a refresh.

  Will always refresh loaded credential if it is expired or would expire
  within min_expiry_duration.

Args:
  account: str, The account address for the credentials being fetched. If
    None, the account stored in the core.account property is used.
  scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES are
    requested.
  min_expiry_duration: Duration str, Refresh the credentials if they are
    within this duration from expiration. Must be a valid duration between 0
    seconds and 1 hour (e.g. '0s' >x< '1h').
  allow_account_impersonation: bool, True to allow use of impersonated service
    account credentials (if that is configured). If False, the active user
    credentials will always be loaded.
  use_google_auth: bool, True to load credentials as google-auth credentials.
    False to load credentials as oauth2client credentials..

Returns:
  oauth2client.client.Credentials or google.auth.credentials.Credentials.
  When all of the following conditions are met, it returns
  google.auth.credentials.Credentials and otherwise it returns
  oauth2client.client.Credentials.

  * use_google_auth is True
  * google-auth is not globally disabled by auth/disable_load_google_auth.

Raises:
  NoActiveAccountException: If account is not provided and there is no
      active account.
  NoCredentialsForAccountException: If there are no valid credentials
      available for the provided or active account.
  c_gce.CannotConnectToMetadataServerException: If the metadata server cannot
      be reached.
  TokenRefreshError: If the credentials fail to refresh.
  TokenRefreshReauthError: If the credentials fail to refresh due to reauth.
  AccountImpersonationError: If impersonation is requested but an
    impersonation provider is not configured.
 ValueError:
)rE   r   r   ru   )r   RefreshIfExpireWithinWindow)rE   r   r  r   ru   rv   s         r,   r  r  "  s*    \ 
"=%	
'$
 d8	+r+   c                     [         R                  R                  R                  R	                  5       (       a  g[        U US9$ )a7  Get the credentials associated with the current account.

If credentials have been disabled via properties, this will return None.
Otherwise it will load credentials like normal. If credential loading fails
for any reason (including the user not being logged in), the usual exception
is raised.

Args:
  allow_account_impersonation: bool, True to allow use of impersonated service
    account credentials (if that is configured). If False, the active user
    credentials will always be loaded.
  use_google_auth: bool, True to load credentials as google-auth credentials.
  False to load credentials as oauth2client credentials..

Returns:
  oauth2client.client.Credentials or google.auth.credentials.Credentials if
  credentials are enabled. When all of the following conditions are met, it
  returns google.auth.credentials.Credentials and otherwise it returns
  oauth2client.client.Credentials.

  * use_google_auth is True
  * google-auth is not globally disabled by auth/disable_load_google_auth.

Raises:
  NoActiveAccountException: If account is not provided and there is no
      active account.
  c_gce.CannotConnectToMetadataServerException: If the metadata server cannot
      be reached.
  TokenRefreshError: If the credentials fail to refresh.
  TokenRefreshReauthError: If the credentials fail to refresh due to reauth.
Nr   ru   )r   r   r   r  r   r   r  s     r,   LoadIfEnabledr  Z  s<    @ //7799	"=%
' 'r+   c                     U R                  S5      n U  Vs/ s H  oR                  5       PM     n nU (       d  [        S5      eU S   U SS =(       d    S4$ s  snf )a&  Finds the target impersonation principal and the delegates.

Args:
   service_account_ids: str, A list of service account ids separated using
     comma.

Returns:
   A tuple (target_principal, delegates).

Raises:
  NoImpersonationAccountError: if the input does not contain service accounts.
,z"No service account to impersonate.N)splitstripr.   )service_account_idssa_ids     r,   ParseImpersonationAccountsr    sb     ,11#64GH4G54GH	
%&J
KK	R	 #6s#;#Ct	DD Is   Ac                   H    \ rS rSrSr        SS jrS r\S 5       rSr	g)	CredentialInfoi  zCredential information.Nc	                 d    Xl         X l        X0l        X@l        XPl        X`l        Xpl        Xl        g rc   )auth_disabledaccess_token_env_var_setaccess_token_file_setcredential_file_override_setrE   	file_pathimpersonated_accountimpersonated_account_delegates)	r:   r  r  r  r  rE   r  r  impersonated_delegatess	            r,   r6   CredentialInfo.__init__  s2     '$<!!6(D%LN 4*@'r+   c                 8   U R                   (       a   gU R                  (       a  SnOU R                  (       a  SR                  U R                  5      nOSU R
                  (       a'  SR                  U R                  U R                  5      nOSR                  U R                  5      nU R                  (       aa  USR                  U R                  5      -   nU R                  (       a-  USR                  SR                  U R                  5      5      -   nUS	-   nU$ )
zNGet the credential information string.

Returns:
  str: the cred info string.
zXThis command is unauthenticated because the [auth/disable_credentials] property is True.zlThis command is authenticated with an access token from the CLOUDSDK_AUTH_ACCESS_TOKEN environment variable.znThis command is authenticated with an access token from {} specified by the [auth/access_token_file] property.z{This command is authenticated as {} using the credentials in {}, specified by the [auth/credential_file_override] property.ziThis command is authenticated as {} which is the active account specified by the [core/account] property.z( Impersonation is used to impersonate {}z via delegate chain: {}z, r   )
r  r  r  r9   r  r  rE   r  r   join)r:   info_strings     r,   GetInfoStringCredentialInfo.GetInfoString  s    :
 $$>  
	#	#77=vdnn7M  
	*	*HHNllDNNI 77=vdll7K 
   
6==''  
	,	,!$=$D$DIId99:%
 
  #%kr+   c                     [         R                  R                  R                  R	                  5       (       a	  [        SS9$ [        5       n [         R                  R                  R                  R                  5       nU(       a  [        U5      u  U l	        U l
        [        R                  " [        R                  [        5      (       a	  SU l        U $ [         R                  R                  R"                  R                  5       nU(       a  SU l        X l        U $ [         R                  R                  R(                  R                  5       nU(       aL  SU l        X0l        [-        USS5      n[/        USS5      nU(       d  [0        R2                  " U5      nXPl        U $ [         R                  R6                  R4                  R                  5       U l        U $ )zKGet the credential information.

Returns:
  CredentialInfo: the cred info.
T)r  Nservice_account_email)r   r   r   r  r   r  impersonate_service_accountr   r  r  r   r   GetEncodedValueosenvironACCESS_TOKEN_ENV_VAR_NAMEr  access_token_filer  r  credential_file_overrider  _LoadFromFileOverridegetattrauth_external_accountGetExternalAccountIdrE   r   )	cred_infoimpersonationr/  cred_file_overrider   rE   s         r,   GetCredentialInfo CredentialInfo.GetCredentialInfo  sz    1199;;$// I %%**FFJJLM %]
3

(

2 

,EFF+/i( #))..@@DDF(,i%- $**//HHLLN/3i,. $$6dCe 6=g'<<UC! #))..66::<Ir+   )r  r  rE   r  r  r  r  r   )FFFFNNNN)
r%   r&   r'   r(   r)   r6   r&  staticmethodr8  r*   r#   r+   r,   r  r    s?     $!#(!A(0d 4 4r+   r  c                 `   U=(       a    [        5       (       + n[        R                  R                  R                  R                  5       nU(       a  U(       a  [        U5      u  px[        (       d  [        SR                  U5      5      e[        R                  " SR                  U5      5        U(       a;  [        U SUUS9n	[        R                  XX=(       d    [        R                  5      n
U
$ [        R!                  Xa=(       d    [        R                  5      n
 U
$ [#        U UUUUS9n
U
$ )a^	  Get the credentials associated with the provided account.

This loads credentials regardless of whether credentials have been disabled
via properties. Only use this when the functionality of the caller absolutely
requires credentials (like printing out a token) vs logically requiring
credentials (like for an http request).

Credential information may come from the stored credential file (representing
the last gcloud auth command), or the credential cache (representing the last
time the credentials were refreshed). If they come from the cache, the
token_response field will be None, as the full server response from the cached
request was not stored.

Args:
  account: str, The account address for the credentials being fetched. If
    None, the account stored in the core.account property is used.
  scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES are
    requested.
  prevent_refresh: bool, If True, do not refresh the access token even if it
    is out of date. (For use with operations that do not require a current
    access token, such as credential revocation.)
  allow_account_impersonation: bool, True to allow use of impersonated service
    account credentials (if that is configured). If False, the active user
    credentials will always be loaded.
  use_google_auth: bool, True to load credentials as google-auth credentials.
    False to load credentials as oauth2client credentials..
  cache_only_rapt: bool, True to only cache RAPT token.

Returns:
  oauth2client.client.Credentials or google.auth.credentials.Credentials.
  When all of the following conditions are met, it returns
  google.auth.credentials.Credentials and otherwise it returns
  oauth2client.client.Credentials.

  * use_google_auth is True
  * google-auth is not globally disabled by auth/disable_load_google_auth.

Raises:
  NoActiveAccountException: If account is not provided and there is no
      active account.
  NoCredentialsForAccountException: If there are no valid credentials
      available for the provided or active account.
  c_gce.CannotConnectToMetadataServerException: If the metadata server cannot
      be reached.
  TokenRefreshError: If the credentials fail to refresh.
  TokenRefreshReauthError: If the credentials fail to refresh due to reauth.
  AccountImpersonationError: If impersonation is requested but an
    impersonation provider is not configured.
zdgcloud is configured to impersonate service account [{}] but impersonation support is not available.z\This command is using service account impersonation. All API calls will be executed as [{}].F)rE   r   ru   cache_only_raptr<  )r   r   r   r   r*  r   r  IMPERSONATION_TOKEN_PROVIDERrQ   r9   r   warningr   !GetElevationAccessTokenGoogleAuthr   CLOUDSDK_SCOPESGetElevationAccessToken_Load)rE   r   prevent_refreshr   ru   r<  r*  target_principal	delegatesgoogle_auth_source_credsrv   s              r,   r   r     s(   r $J-G-I)I/ 88<<>  %@"<##%''%44:F5 ! ! KK	$$*F+;$<> !%&+))	" *KK
"i B!

 
 "d 
+ *AA
%'G1G1GId 
+ 'D 
+r+   c                 p   [         R                  " SU 5        U(       Gd   [        R                  R	                  U 5      nUR                  5       (       a$  Uc  [        R                  nUR                  U5      n[        R                  R                  R                  R                  5       nU(       a]  [         R"                  R%                  U5      nU[         R"                  R&                  [         R"                  R(                  4;   a  XSl        [         R,                  " U5      nU$ [         R.                  " 5       nSSKJn  SSKJn	  SSKJn
  SSKJn   UR;                  U 5      u  p<Uc  [        R                  nUR?                  X15      n[A        X:RB                  5      (       aj  URD                  (       dY  UR                  n[        RF                  US'   [        RH                  US	'   [K        U5      RM                  U[        R                  S
9n[A        UURB                  5      (       a_  UR                  n[        RF                  US'   [        RH                  US	'   [        RN                  US'   [K        U5      RM                  U5      n[         RP                  R%                  U5      nU[         RP                  R&                  :X  a@  [        R                  R                  R                  R                  5       nU(       a  XSl)        O9U[         RP                  RT                  :X  a  [         RV                  " 5       nXSl)        [         RX                  " U5        [         RZ                  " U5      nU$ ! [        R
                   a  n[        X5      eSnAff = f! U	R<                   a  n[        X5      eSnAff = f)z)Load credentials from cred file override.z+Using alternate credentials from file: [%s]Nr   credentialsr   r    external_account_authorized_user	client_idclient_secret)r   r   ).r   infor   GoogleCredentialsfrom_streamr!   rH   create_scoped_requiredr   rA  create_scopedr   r   r   
token_hostr   r   CredentialTypeFromCredentialsSERVICE_ACCOUNTP12_SERVICE_ACCOUNT	token_uri MaybeAttachAccessTokenCacheStoreGetGoogleAuthDefaultgoogle.authrJ  r   r   rL  load_credentials_from_fileDefaultCredentialsErrorwith_scopes_if_required
isinstanceCredentialsr)  CLOUDSDK_CLIENT_IDCLOUDSDK_CLIENT_NOTSOSECRETtype	from_info CLOUDSDK_EXTERNAL_ACCOUNT_SCOPESCredentialTypeGoogleAuth
_token_uriUSER_ACCOUNTGetDefaultTokenUriEnableSelfSignedJwtIfApplicable*MaybeAttachAccessTokenCacheStoreGoogleAuth)r7  r   ru   rv   rN   token_uri_override	cred_typegoogle_auth_defaultgoogle_auth_credsgoogle_auth_exceptionsgoogle_auth_external_account,google_auth_external_account_authorized_user_	json_infos                 r,   r1  r1  w  s   ((8:LM	B%%112DEd ""$$	'''d $**//::>>@((88>i	w--==--AAC 
C+ 33D9DF 
+C "668 =@LlB#>>
gd ~%%f44TBD4AABB&&))i%88i#)#E#Ei $Z!!)F4J4J!Kd4?KK	M 	M ))i%88i#)#E#Ei "CCi$Z!!),d 00@@FIG44DDD%,,11<<@@B	,	g66CC	C"557*o
 ++D1 ==dCD	+k << B*+=AABJ "99 B*+=AABs/   M. N .NNNN5%N00N5c                 B   [         R                  " S[        5        U(       d  [        SR	                  [        5      5      eU R                  5       n SSKJn  UR                  U 5      n[        R                  R                  R                  R                  5       Ul        U$ )z2Loads an AccessTokenCredentials from access_token.z1Using access token from environment variable [%s]zYou may have passed an access token to gcloud using the environment variable {}. At the same time, google-auth is disabled by auth/disable_load_google_auth. They do not work together. Please unset auth/disable_load_google_auth and retry.r   google_auth_credentials)r   rO  r.  r]   r9   r  googlecloudsdk.core.credentialsrx  AccessTokenCredentialsr   r   r   r   r   _universe_domain)r   ru   c_google_authr   s       r,   _LoadAccessTokenCredsFromValuer}    s    ((>$& 

%	9 :@%:'	  ##%, W

.
.|
<% &,,11AAEEG%	,r+   c                 <   [         R                  " SU 5        U(       d  [        S5      e[        R                  " U 5      R                  5       nSSKJn  UR                  U5      n[        R                  R                  R                  R                  5       Ul        U$ )z0Loads an AccessTokenCredentials from token_file.z"Using access token from file: [%s]zYou may have passed an access token to gcloud using --access-token-file or auth/access_token_file. At the same time, google-auth is disabled by auth/disable_load_google_auth. They do not work together. Please unset auth/disable_load_google_auth and retry.r   rw  )r   rO  r]   r   ReadFileContentsr  ry  rx  rz  r   r   r   r   r   r{  )
token_fileru   contentr|  r   s        r,   _LoadAccessTokenCredsFromFiler    s    ((/< 

%	3  "":.446' W

.
.w
7%%,,11AAEEG%	,r+   c                    [         R                  " [        R                  [        5      n[
        R                  R                  R                  R                  5       n[
        R                  R                  R                  R                  5       nU(       a  [        XS5      nGOSU(       a  [        Xc5      nGO?U(       a  [        XqU5      nGO*U (       d2  [
        R                  R                  R                  R                  5       n U (       d4  [         R"                  " [$        R&                  " S5      R(                  5      e[*        R,                  " US9n	U	R/                  X5      nU(       d  [0        R3                  X5      nU(       d  [5        U 5      e[*        R6                  " U5      (       aF  U	R9                  X5        [*        R:                  " XS9n[=        UR>                  UR@                  5        OU$ U(       d  [C        U5        U$ )zHelper for Load().Fr=  )"r   r+  r,  r-  r.  r   r   r   r/  r   r0  r}  r  r1  r   rE   creds_exceptionsNoActiveAccountExceptionr   ActiveConfigr  r   r   r   r   rt   rA   IsGoogleAuthGceCredentialsStorerl  r   r   r)  RefreshIfAlmostExpire)
rE   r   rD  ru   r<  r   r/  r7  rv   r   s
             r,   rC  rC  	  s    ))"**6OP, '',,>>BBD!((--FFJJL),HD():LD !3_MD!!&&..224g55

$
$U
+
5
57 7 &&'E ::g/D(77
d .w77		+	+D	1	1G" AA
 	!  $"<"<	

 	$	+r+   c                 p    [         R                  " U 5      (       a  [        XX#U5        g[        XX#U5        g)a  Refresh credentials.

Calls credentials.refresh(), unless they're SignedJwtAssertionCredentials.
If the credentials correspond to a service account or impersonated credentials
issue an additional request to generate a fresh id_token.

Args:
  credentials: oauth2client.client.Credentials or
    google.auth.credentials.Credentials, The credentials to refresh.
  is_impersonated_credential: bool, True treat provided credential as an
    impersonated service account credential. If False, treat as service
    account or user credential. Needed to avoid circular dependency on
    IMPERSONATION_TOKEN_PROVIDER.
  include_email: bool, Specifies whether or not the service account email is
    included in the identity token. Only applicable to impersonated service
    account.
  gce_token_format: str, Specifies whether or not the project and instance
    details are included in the identity token. Choices are "standard",
    "full".
  gce_include_license: bool, Specifies whether or not license codes for images
    associated with GCE instance are included in their identity tokens.

Raises:
  TokenRefreshError: If the credentials fail to refresh.
  TokenRefreshReauthError: If the credentials fail to refresh due to reauth.
N)r   IsOauth2ClientCredentials_Refresh_RefreshGoogleAuth)rJ  is_impersonated_credentialinclude_emailgce_token_formatgce_include_licenses        r,   Refreshr  J  s9    > &&{33[.AC {$8KMr+   c                 F   SSK Jn  SSK Jn  SSKnUR	                  [
        R                  S9n U R                  U5        Sn	U(       aT  [        (       d  [        S5      e[        R                  U 5      (       d  [        SR                  U 5      5      e[        XS9n	O|[        U [        R                  5      (       a  [!        X5      n	OQ[        U ["        R$                  5      (       a2  [&        R(                  " 5       R+                  [,        R.                  UUS	9n	U	(       a&  U R0                  (       a  XR0                  S
'   Xl        gg! [4        R6                  UR8                  4 a[  n
UR;                  U
5      (       a  [<        R>                  " U
5      e[<        R@                  " [B        RD                  " U
5      5      eSn
A
f[F        RH                   a    [<        RJ                  " 5       e[F        RL                   a$  n
[<        RN                  " [Q        U
5      5      eSn
A
ff = f)z#Refreshes oauth2client credentials.r   context_awarehttpN)response_encodingagcloud is configured to impersonate a service account but impersonation support is not available.,Invalid impersonation account for refresh {})r  token_formatinclude_licenseid_token))googlecloudsdk.corer  r  httplib2Httpr   ENCODINGr   r>  rQ   IsImpersonationCredentialr9   "_RefreshImpersonatedAccountIdTokenr`  r   ServiceAccountCredentials_RefreshServiceAccountIdTokenoauth2client_gceAppAssertionCredentialsr   r   
GetIdTokenr   rb  token_responseid_tokenb64r   AccessTokenRefreshErrorServerNotFoundErrorIsContextAwareAccessDeniedErrorr  TokenRefreshDeniedByCAAErrorTokenRefreshErrorrL   rM   r   ReauthSamlLoginRequiredErrorWebLoginRequiredReauthErrorReauthErrorTokenRefreshReauthErrorstr)rJ  r  r  r  r  r  r  r  http_clientr  rN   s              r,   r  r  q  s    0& 		I,>,>	?+$;$H!))'67 	7 *CC
 ':AA+NP 	P3
4h 
K!J!J	K	K.{Hh	K!1!I!I	J	J!,,

#
#'- - /h
 		#	#19"":. ( 
 
(
((*F*F	G ?44Q7799!<<

,
,S]]1-=
>>		3	3 9

6
6
88		"	" ;

2
23q6
::;s%   DE  H 'AF==?H <HH c              #     #    SSK Jn  SSKJn  SSKJn   Sv   g! UR                   a    [        R                  " U S9eUR                   a#  n[        R                  " [        U5      U S9eSnAfUR                   a\  nUR                  U5      (       a  [        R                  " U5      e[        R                  " [         R"                  " U5      U UUS9eSnAff = f7f)z=Handles exceptions during refreshing google auth credentials.r   r   r  rw  N)for_adc)r  rE   is_service_account)r\  r   r  r  ry  rx  ReauthSamlChallengeFailErrorr  r  ReauthRequiredErrorr  r  RefreshErrorr  r  r  rL   rM   )r  rE   r  rq  r  r|  rN   s          r,   'HandleGoogleAuthCredentialsRefreshErrorr    s      ?/V			<	< H

6
6w
GG		*	* L

2
23q67
KK		,	, 44Q7799!<<

,
,a-	 s2   C C3CA,,C?ACCCc                    SSK Jn  SSK Jn  [        R                  " 5       (       a  [
        R                  " U 5      (       d  g[        U S5      (       a  [
        R                  " U 5      (       aj   UR                  U R                  SS9n[        R                  R                  US   [        R                  R                  S	9n[!        ["        U5      (       d  gg! UR                   a     gf = f)
as  Determine if ID token refresh is needed.

(1) we don't refresh ID token for non-default universe domain.
(2) for service account with self signed jwt feature enabled, we only refresh
ID token if it's about to expire

Args:
  credentials: google.auth.credentials.Credentials, A google-auth credentials
    to refresh.

Returns:
  bool, Whether ID token refresh is needed.
r   r   )jwtF	_id_token)verifyTexp)r   )r\  r   r  r   IsDefaultUniverser   HasDefaultUniverseDomainr   UseSelfSignedJwtdecoder  GoogleAuthErrordatetimefromtimestamptimezoneutcr   _CREDENTIALS_EXPIRY_WINDOW)rJ  rq  r  payloadexpirys        r,   _ShouldRefreshGoogleAuthIdTokenr    s     ? 
	%	%	'	'w/O/O0 0 [+&&7+C+C, ,

;00
?g
 ,,8,,00 - F %%?HH	 "11 s   0C C-,C-c           
      Z   SnSn[         R                  " U 5      (       a  U R                  nSnSSKJn  UR                  5       n[        XVS9   [         R                  " U 5        [        U 5      (       a  [        U UUUUSS9  U R                  U5        SSS5        g! , (       d  f       g= f)a  Refreshes google-auth credentials.

Args:
  credentials: google.auth.credentials.Credentials, A google-auth credentials
    to refresh.
  is_impersonated_credential: bool, True treat provided credential as an
    impersonated service account credential. If False, treat as service
    account or user credential. Needed to avoid circular dependency on
    IMPERSONATION_TOKEN_PROVIDER.
  include_email: bool, Specifies whether or not the service account email is
    included in the identity token. Only applicable to impersonated service
    account.
  gce_token_format: str, Specifies whether or not the project and instance
    details are included in the identity token. Choices are "standard",
    "full".
  gce_include_license: bool, Specifies whether or not license codes for images
    associated with GCE instance are included in their identity tokens.

Raises:
  AccountImpersonationError: if impersonation support is not available for
    gcloud, or if the provided credentials is not google auth impersonation
    credentials.
NFTr   requests)rE   r  )r  r  r  r   refresh_user_account_credentials)r   IsServiceAccountCredentialsr)  r  r  GoogleAuthRequestr  rk  r  _RefreshGoogleAuthIdTokenr   )	rJ  r  r  r  r  rE   r  r  request_clients	            r,   r  r    s    8 '((55//G +--/.. ++K8&{33
  
%?%+1+0 'E  s   AB
B*c                 J   SSK Js  Jn  SSKJn  SSKJn  UR                  5       n	[        5          Sn
[        R                  " U 5      (       a  U(       a  U R                  U	5        GOU(       a  [        (       d  [        S5      eSSKJs  Jn  [!        U UR"                  5      (       d  [        SR%                  U 5      5      e[        R'                  U [(        R*                  U5      nUR                  U	5        UR,                  n
Or[!        XR"                  5      (       a  [/        X	5      n
OL[!        XR"                  5      (       a2  [0        R2                  " 5       R5                  [(        R*                  UUS9n
U
(       a  Xl        Xl        SSS5        g! , (       d  f       g= f)at  Refreshes the ID token of google-auth credentials.

Args:
  credentials: google.auth.credentials.Credentials, A google-auth credentials
    to refresh.
  is_impersonated_credential: bool, True treat provided credential as an
    impersonated service account credential. If False, treat as service
    account or user credential. Needed to avoid circular dependency on
    IMPERSONATION_TOKEN_PROVIDER.
  include_email: bool, Specifies whether or not the service account email is
    included in the identity token. Only applicable to impersonated service
    account.
  gce_token_format: str, Specifies whether or not the project and instance
    details are included in the identity token. Choices are "standard",
    "full".
  gce_include_license: bool, Specifies whether or not license codes for images
    associated with GCE instance are included in their identity tokens.
  refresh_user_account_credentials: bool, Specifies whether or not to refresh
    user account credentials. Note that when we refresh user account
    credentials access token, the ID token will be refreshed as well.
    Depending on where this function is called, we may not need to refresh
    user account credentials for ID token again.

Raises:
  AccountImpersonationError: if impersonation support is not available for
    gcloud, or if the provided credentials is not google auth impersonation
    credentials.
r   Nr   r  r  r  r  )google.auth.compute_enginer   compute_enginegoogle.oauth2r   r  r  r  r  r   IsUserAccountCredentialsr   r>  rQ   $google.auth.impersonated_credentialsimpersonated_credentialsr`  ra  r9   GetElevationIdTokenGoogleAuthr   rb  r   '_RefreshServiceAccountIdTokenGoogleAuthr   r   r  r  r  )rJ  r  r  r  r  r  google_auth_gcegoogle_auth_service_accountr  r  r  google_auth_impersonated_credsid_token_credss                r,   r  r  =  sa   N 76J* --/..0H((55,.)	#))'67 	7 TS6BBD D':AA+NP 	P '
D
D644mE  ^,%%h	K!H!H	I	I8
'h	K!<!<	=	=!,,

#
#'- - /h  ' (U 100s   EF
F"c                     [         R                  " U 5      (       a  U R                  nOU R                  nU(       + =(       d    [	        X5      nU(       a  [        U 5        gg)a!  Refreshes credentials if they will expire within a time window.

Args:
  credentials: google.auth.credentials.Credentials or
    client.OAuth2Credentials, the credentials to refresh.
  window: string, The threshold of the remaining lifetime of the token which
    can trigger the refresh.
N)r   r  token_expiryr  r   r  )rJ  windowr  almost_expires       r,   r  r    sM     &&{33%%FF:K";F"K-K r+   c                      [        U [        S9  g )N)r  )r  r  rI  s    r,   r  r    s    k2LMr+   c                 d    U R                   n[        R                  U[        R                  U5      $ )z@Get a fresh id_token for the given impersonated service account.)_service_account_idr>  GetElevationIdTokenr   rb  )rv   r  r)  s      r,   r  r    s2     22	%	9	9V66
G Gr+   c                 6   UR                   n[        [        R                  " 5       5      nU R                  UX0R                  -   U R
                  [        R                  S.n[        R                  " U R                  X@R                  S9n[        R                  R                  U[        S.5      nU" U R                  R!                  S5      SUU R#                  5       S9u  pxUR$                  S:X  a(  [&        R(                  " U5      n	U	R+                  SS	5      $ g	)
a9  Get a fresh id_token for the given oauth2client credentials.

Args:
  cred: service_account.ServiceAccountCredentials, the credentials for which
    to refresh the id_token.
  http_client: httplib2.Http, the http transport to refresh with.

Returns:
  str, The id_token if refresh was successful. Otherwise None.
)audiatr  isstarget_audience)key_id)	assertion
grant_typeidnaPOST)methodbodyheaders   r  N)requestinttimerY  MAX_TOKEN_LIFETIME_SECS_service_account_emailr   rb  r   make_signed_jwt_signer_private_key_idr   parse	urlencode_GRANT_TYPEencode!_generate_refresh_request_headersr   jsonloadsget)
rv   r  http_requestnowr  r  r  respr  ds
             r,   r  r    s     $$,DIIK# ^^///((22' ##
llG$8$8:) 
		! 
$
 
nnF#F4468-$ 
[[C

7A55T""r+   c                 T   [         R                  R                  R                  R	                  5       (       a  gSSKJn  SSKJn  SSKJ	n  SSK
Jn  UR                  U R                  U R                  U R                  [         R"                  [         R                  R$                  R&                  R)                  5       S9nUR*                  R-                  UR.                  UR1                  5       5      Ul         UR3                  U5        UR@                  $ ! UR4                   a  n[7        UR8                  5      S:  a  UR8                  S   R;                  S	S
5      OS
nSU;   a+  SUS   ;   a"  Sn	[<        R>                  " SUS   U	5         SnAg SnAUR@                  $ SnAff = f)aN  Get a fresh id_token for the given google-auth credentials.

Args:
  cred: google.oauth2.service_account.Credentials, the credentials for which
    to refresh the id_token.
  request_client: google.auth.transport.Request, the http transport
   to refresh with.

Returns:
  str, The id_token if refresh was successful. Otherwise None.
Nr   r   )iamr   r	   )r      errorr   r4   z"iam.serviceAccounts.getOpenIdTokenzYou can find step-by-step instructions here: https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc on how to resolve this error.z%s %s)!r   r   r   (service_account_disable_id_token_refreshr   r\  r   r  r  r   %googlecloudsdk.api_lib.iamcredentialsr
   IDTokenCredentialssignerr)  rh  r   rb  r   r   r   _IAM_IDTOKEN_ENDPOINTreplaceIAM_ENDPOINT_GDUGetEffectiveIamEndpointr   r  lenargsr
  r   r  r   )
rv   r  rq  google_auth_iamr  iam_credentials_utilid_token_credrN   r  stepss
             r,   r  r    sh    DDLLNN
 ?0JP .@@
kk
  
oo '',,<<@@B A - ++33

/
/

6
6
8 '.). 
		- 
 	,	,  +.aff+/AFF1IMM'2&rEU0E)4DD+ 
 
iiy)51			-s   :D F''A&F""F'c                 R   [         R                  " U 5      (       a?  [         R                  R                  U 5      nUR                  [         R
                  :X  a  gO[         R                  R                  U 5      nUR                  [         R                  [         R                  [         R                  [         R                  [         R                  [         R                  [         R
                  4;  a  gU(       d2  [        R                  R                  R                   R#                  5       nU(       d  [$        R&                  " 5       e[         R(                  " 5       nUR+                  X5        UR                  [         R
                  :w  a  [-        XU5      R/                  5         gg)a  Store credentials according for an account address.

gcloud only stores user account credentials, external account credentials,
external account authorized user credential, service account credentials,
p12 service account credentials, and GCE google-auth credentials. GCE
oauth2client credentials, IAM impersonation, and Devshell credentials are
generated in runtime.
External account credentials do not contain any sensitive credentials. They
only provide hints on how to retrieve local external and exchange them for
Google access tokens.

Args:
  credentials: oauth2client.client.Credentials or
    google.auth.credentials.Credentials, The credentials to be stored.
  account: str, The account address of the account they're being stored for.
    If None, the account stored in the core.account property is used.
  scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES are
    requested.

Raises:
  NoActiveAccountException: If account is not provided and there is no
      active account.
N)r   r  rU  rV  keyGCE_CREDS_NAMErg  USER_ACCOUNT_CREDS_NAMEEXTERNAL_ACCOUNT_CREDS_NAME EXTERNAL_ACCOUNT_USER_CREDS_NAME+EXTERNAL_ACCOUNT_AUTHORIZED_USER_CREDS_NAMESERVICE_ACCOUNT_CREDS_NAMEP12_SERVICE_ACCOUNT_CREDS_NAMEr   r   r   rE   r   r  r  r   r  _LegacyGeneratorWriteTemplate)rJ  rE   r   rn  r   s        r,   r  r  !  s/   2 &&{33&&66{CI }}... / 00@@MI]]%%))..99((,,  	$$,,002G	

3
3
55

$
$
&%++g#]]g,,, W62@@B -r+   c                 p   [        US5      (       a!  [        R                  " UR                  U 5        [        R
                  " 5       (       a&  [        R                  " U5      (       a  [        U5        [        X5        [        R                  " [        R                  R                  R                  U 5        g)z?Validates, stores and activates credentials with given account.r   N)r   r   r   r   r   r  r   r  r  r  PersistPropertyr   r   rE   )rE   rJ  s     r,   ActivateCredentialsr.  \  s~    [+,,**;+F+FP!!##(H(H) ) KZ..33;;WEr+   c                    [         R                  " U 5      (       a6  [         R                  " U 5      (       d  [         R                  " U 5      (       a  [	        S5      e[         R
                  " U 5      (       a&  SSKJn  U R                  UR                  5       5        gSSKJ
n  U R                  UR                  5       5        g)zRevokes the token on the server.

Args:
  credentials: user account credentials from either google-auth or
    oauth2client.
Raises:
  RevokeError: If credentials to revoke is not user account credentials.
zSThe token cannot be revoked from server because it is not user account credentials.r   r  r  N)r   r   IsExternalAccountUserCredentials*IsExternalAccountAuthorizedUserCredentialsrW   r  r  r  revoker  r  r  )rJ  r  r  s      r,   RevokeCredentialsr3  l  s     
*
*;
7
7..{;;88EE
 6 7 7&&{33(tyy{#,x1134r+   c                    SSK Jn  SSK Jn  SSKJn  U (       d2  [
        R                  R                  R                  R                  5       n U (       d  [        R                  " 5       eU [        R                  " 5       R                  5       ;   a  [        S5      e[!        U SSS9nU(       d  [#        U 5      eSn U R%                  S	5      (       dB  ['        XAR(                  5      (       d(  ['        UUR(                  5      (       d  [+        U5        Sn[2        R4                  " 5       nUR7                  U 5        [9        X5      R;                  5         [<        R>                  " 5       RA                  U 5      n[B        RD                  RG                  U5      (       a  [H        RJ                  " U5        U$ ! [,        R.                  UR.                  4 a6  nUR0                  S   S
:X  a   SnANUR0                  S   S:X  a   SnANe SnAff = f)a(  Revoke credentials and clean up related files.

Args:
  account: str, The account address for the credentials to be revoked. If
      None, the currently active account is used.

Returns:
  True if this call revoked the account; False if the account was already
  revoked.

Raises:
  NoActiveAccountException: If account is not provided and there is no
      active account.
  NoCredentialsForAccountException: If the provided account is not tied to any
      known credentials.
  RevokeError: If there was a more general problem revoking the account.
r   r   rK  rw  z'Cannot revoke GCE-provided credentials.T)rD  ru   Fz.gserviceaccount.cominvalid_tokeninvalid_requestN)&r\  r   rL  ry  rx  r   r   r   rE   r   r  r  r   r   r   rW   r   rA   endswithr`  ra  r3  r   TokenRevokeErrorr  r   r   Remover*  Cleanr   PathsLegacyCredentialsDirr,  pathisdirr   RmTree)	rE   rr  rs  r|  rJ  rvrN   r   legacy_creds_dirs	            r,   RevokerB    s   * KjV	$$,,002G	

3
3
55 ))++
?
@@tT;+	
*7
33"344{$L$LMM8DDF F $b 
$
$
&%,,w7(..0\\^88AWW]]#$$	LL!"	)# 
!
!=#A#A	B vvayO#
	
'	'
s%   :AF1 1 HH)HHHc                    U=(       a    [        5       (       + nUc  [        R                  " 5       nU(       a  SSKJn  UR                  SU SU[        R                  R                  R                  R                  SS9[        R                  R                  R                  R                  SS9S9n[        R                  R                  5       Ul        U$ [        R                   " S[        R                  R                  R                  R                  SS9[        R                  R                  R                  R                  SS9U [        R                  R                  5       U["        R$                  US9nU$ )a  Get credentials from an already-valid refresh token.

Args:
  refresh_token: An oauth2 refresh token.
  token_uri: str, URI to use for refreshing.
  revoke_uri: str, URI to use for revoking.
  use_google_auth: bool, True to return google-auth credentials. False to
  return oauth2client credentials..

Returns:
  oauth2client.client.Credentials or google.auth.credentials.Credentials.
  When all of the following conditions are true, it returns
  google.auth.credentials.Credentials and otherwise it returns
  oauth2client.client.Credentials.

  * use_google_auth=True
  * google-auth is not globally disabled by auth/disable_load_google_auth.
Nr   rI  T)required)r   refresh_tokenr  rY  rM  rN  )r   rM  rN  rE  r  rY  
user_agent
revoke_uri)r   r   rj  r  rJ  ra  r   r   r   rM  r   rN  r  utcnowr  r   OAuth2Credentialsr   CLOUDSDK_USER_AGENT)rE  rY  rG  ru   rp  rv   s         r,   AcquireFromTokenrK    s>   , $J-G-I)I/**,I ?((###((22666E '',,::>>>M ) OD ##**,DK 
+ ####((22666E '',,::>>>M#&&--/--	D 
+r+   c                 
   U(       aU  SSK Js  Jn  U =(       d    SnUR                  US9n[        R
                  " 5       R                  5       nUUl        SUl        O[        R                  " U S9nU(       a  [        U5        U$ )a-  Get credentials from a GCE metadata server.

Args:
  account: str, The account name to use. If none, the default is used.
  use_google_auth: bool, True to load credentials of google-auth if it is
    supported in the current authentication scenario. False to load
    credentials of oauth2client.
  refresh: bool, Whether to refresh the credential or not. The default value
    is True.

Returns:
  oauth2client.client.Credentials or google.auth.credentials.Credentials based
  on use_google_auth and whether google-auth is supported in the current
  authentication sceanrio.

Raises:
  c_gce.CannotConnectToMetadataServerException: If the metadata server cannot
    be reached.
  TokenRefreshError: If the credentials fail to refresh.
  TokenRefreshReauthError: If the credentials fail to refresh due to reauth.
r   Nr   )r)  T)email)r  r   r  ra  r   r   r   r{  _universe_domain_cachedr  r  r  )rE   ru   r   r  rM  rJ  r   s          r,   r   r     sw    , 88 yE!--E-JK
 nn&557O  
 +/K'"::IKK	r+   c                   T    \ rS rSrSrSS jr\S 5       r\S 5       rS r	S r
S	 rS
rg)r*  i-  a;  A class to generate the credential file for other tools, like gsutil & bq.

The supported credentials types are user account credentials, service account
credentials, and p12 service account credentials. Gcloud supports two auth
libraries - oauth2client and google-auth. Eventually, we will deprecate
oauth2client.
Nc                 l   X l         U R                  [        R                  [        R                  [        R
                  [        R                  [        R                  [        R                  4;  a8  [        R                  " SR                  [        U R                   5      5      5      eUc  [        R                  U l        OX0l        [        R                  " 5       nUR!                  U5      U l        UR%                  U5      U l        UR)                  U5      U l        UR-                  U5      U l        g )N Unsupported credentials type {0})rJ  
_cred_typer   r$  r(  r%  r&  r'  r)  CredentialFileSaveErrorr9   rd  r   rA  r   r;  LegacyCredentialsBqPath_bq_pathLegacyCredentialsGSUtilPath_gsutil_pathLegacyCredentialsP12KeyPath_p12_key_pathLegacyCredentialsAdcPath	_adc_path)r:   rE   rJ  r   pathss        r,   r6   _LegacyGenerator.__init__6  s    "'')K)K++00;;..0 0 ++
,
3
3D9I9I4J
KM M~**dkkLLNE
 11':DM99'BD::7CD33G<DNr+   c                 B    [         R                  " U R                  5      $ rc   )r   r  rJ  rf   s    r,   _is_oauth2client!_LegacyGenerator._is_oauth2clientO  s    ,,T-=-=>>r+   c                     U R                   (       a3  [        R                  R                  U R                  5      R
                  $ [        R                  R                  U R                  5      R
                  $ rc   )r_  r   rU  rV  rJ  r"  rg  rf   s    r,   rR  _LegacyGenerator._cred_typeS  sU    ##33D4D4DEIII--==


C r+   c                     U R                   U R                  U R                  U R                  /nU H  n [        R
                  " U5        M     g! [         a     M,  f = f)zRemove the credential file.N)rU  rW  rY  r[  r,  rp   OSError)r:   r\  ps      r,   r:  _LegacyGenerator.Clean[  s[     		E 
		!   s   A
AAc           	      6   U R                  5         U R                  [        R                  :X  a  U R                  nUR
                  nUR                  n[        R                  " U R                  USS9  U R                  U R                  SR                  / SQ5      R                  U R                  R                  U R                  US95        g[        R                  " U R                  5      R!                  U R"                  S9  U R                  [        R$                  :X  d  U R                  [        R&                  :X  aE  U R                  U R                  SR                  SS	/5      R                  U R"                  S
95        gU R                  [        R(                  :X  aE  U R                  U R                  SR                  SS/5      R                  U R"                  S
95        gU R                  [        R*                  :X  ay  U R                  U R                  SR                  / SQ5      R                  U R                  R,                  U R                  R.                  U R                  R0                  S95        gU R                  [        R2                  :X  aE  U R                  U R                  SR                  SS/5      R                  U R"                  S95        g[        R4                  " SR                  [7        U R                  5      5      5      e)zWrite the credential file.Tprivate
)[Credentials]z gs_service_client_id = {account} gs_service_key_file = {key_file}z-gs_service_key_file_password = {key_password})rE   key_filekey_passwordN)r  rk  z2gs_external_account_file = {external_account_file})external_account_filezBgs_external_account_authorized_user_file = {external_account_file})z[OAuth2]zclient_id = {cid}zclient_secret = {secret}r   rk  z!gs_oauth2_refresh_token = {token})cidsecretr   rl  )rm  rQ  )r:  rR  r   r)  rJ  _private_key_pkcs12_private_key_passwordr   WriteBinaryFileContentsrY  _WriteFileContentsrW  r$  r9   r)  ADCDumpADCToFiler[  r%  r&  r'  r$  rM  rN  rE  r(  rS  rd  )r:   rv   r"  passwords       r,   r+  _LegacyGenerator.WriteTemplatek  s    	JJL '@@@d$$c++h##D$6$6TJ 


TYY ( 
 VD,,BB!//!)  +, KK'-$..-A7>>>7CCC



TYYB(  V$..V9	;
 
GOO	O
d//

N< 2	 
dnn	57 
G;;	; 



))   V"",,%%33$$22   
G>>	>



TYY0(  VT^^V,	. ++
,
3
3D9I9I4J
KM Mr+   c                     [         R                  R                  [        R                  " U5      5      n[        R
                  " X2SS9  g)zWrites contents to a path, ensuring mkdirs.

Args:
  filepath: str, The path of the file to write.
  contents: str, The contents to write to the file.
Trh  N)r,  r=  realpathr   ExpandHomeDirWriteFileContents)r:   filepathcontents	full_paths       r,   ru  #_LegacyGenerator._WriteFileContents  s3       !4!4X!>?I	I>r+   )r[  rU  rW  rY  rJ  r   rc   )r%   r&   r'   r(   r)   r6   propertyr_  rR  r:  r+  ru  r*   r#   r+   r,   r*  r*  -  sF    =2 ? ?     KMZ	?r+   r*  )i  )NNT)NN1hT)NNr  TT)TT)NNFTTF)TF)FFstandardF)FNF)FFr  FT)NNrc   )NTT)pr)   
__future__r   r   r   
contextlibr  r  r,  r7   r  typingr   r   googlecloudsdk.api_lib.authr   r3  r
   r   r  r   r   r   r   "googlecloudsdk.core.configurationsr   ry  r   r   r   r  r   r   googlecloudsdk.core.utilr   r   r   oauth2clientr   r   r   oauth2client.contribr  r   rL   	six.movesr   r.  (GOOGLE_OAUTH2_PROVIDER_AUTHORIZATION_URI!GOOGLE_OAUTH2_PROVIDER_REVOKE_URIr  r  ACCOUNT_TABLE_FORMAT)ACCOUNT_TABLE_WITH_UNIVERSE_DOMAIN_FORMATr!   r.   r1   rA   rH   rQ   rT   rW   rZ   r]   r>  objectr`   r   r   r   r   r   r   r   r  r   r   r   r   r   r   r  r  r	  r  r  r  r  r   r1  r}  r  rC  r  r  contextmanagerr  r  r  r  r  r  r  r  r  r  r.  r3  rB  rK  r   r*  r#   r+   r,   <module>r     s*   
 '  '    	     Q 9 & # * ) < < J 8 - * *   ( 8 . 
  !  0 ) 2 ";# 	 -	 )/"" /;% ;! !$6'H 60U 0 
A A9% 96u 6?% ?  $  4 89 $N45F 45n
-v 
- $
-`@# @(3- @*C 26&)R)$ %)#'8<F. !%#,048)2 *.(,59=A:4 !%#,048(,	5p$'NE(~V ~D  $^B\~68 >D (-' %	$MP ). (!&	2;j 49 :+^ 38%*(2+0	H(Z  %%)X)v$NG&R>B8CvF 5.AJ  $ A%)5p+\T?v T?r+   