o
    .                    @   s@  d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZ ddlZddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ  ddl!m"Z" ddl!m#Z# ddl!m$Z$ ddl%m&Z& ddl%m'Z' ddl%m(Z( ddl)mZ* ddl)m+Z+ ddl,Z,ddl-m.Z. dZ/dZ0dZ1dZ2dZ3dZ4dZ5G d d! d!ej6Z6G d"d# d#e6Z7G d$d% d%e6Z8G d&d' d'e8Z9G d(d) d)e6Z:G d*d+ d+e6Z;G d,d- d-e6Z<G d.d/ d/e6Z=G d0d1 d1e6Z>G d2d3 d3e6Z?dZ@G d4d5 d5eAZBeB ZCd6d7 ZDG d8d9 d9eAZEG d:d; d;eAZFG d<d= d=eAZGd>d? ZHd@dA ZIdBeJdCeeJ fdDdEZKdFdG ZLdHdI ZM	JddKdLZNdMdN ZOddPdQZP			OddRdSZQ			T	OddUdVZR			T	OddWdXZS			T	O	OddYdZZTdd[d\ZUd]d^ ZVG d_d` d`eAZW			a	O	O	addbdcZXddde ZYdfdg ZZdhdi Z[	O	addjdkZ\	a	a	l	addmdnZ]	a	a	l	addodpZ^ej_	addqdrZ`dsdt Za	a	a	l	addudvZb	a	a	l	a	OddwdxZcdydz Zdd{d| Zed}d~ Zfdd Zgdd ZhdddZidd Zjdd ZkdddZlde1dOfddZmdddZnG dd deAZodS )zIOne-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                   @      e Zd ZdZdS )Errorz&Exceptions for the credentials module.N__name__
__module____qualname____doc__ r&   r&   B/tmp/google-cloud-sdk/lib/googlecloudsdk/core/credentials/store.pyr    P       r    c                   @   r   )NoImpersonationAccountErrorz2Exception when there is no account to impersonate.Nr!   r&   r&   r&   r'   r)   T   r(   r)   c                           e Zd ZdZ fddZ  ZS )!PrintTokenAuthenticationExceptionz1Exceptions that tell the users to run auth login.c                    s"   t t| tdj|d d S )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)superr+   __init__textwrapdedentformat)selfr,   	__class__r&   r'   r.   [   s   
z*PrintTokenAuthenticationException.__init__r"   r#   r$   r%   r.   __classcell__r&   r&   r3   r'   r+   X       r+   c                       r*   ) NoCredentialsForAccountExceptionz;Exception for when no credentials are found for an account.c                    s   t t| dj|d d S )NzKYour current active account [{account}] does not have any valid credentialsaccount)r-   r8   r.   r1   )r2   r:   r3   r&   r'   r.   m   s
   
z)NoCredentialsForAccountException.__init__r5   r&   r&   r3   r'   r8   j   r7   r8   c                       r*   )InvalidCredentialFileExceptionzCException for when an external credential file could not be loaded.c                    s$   t t| dj|t|d d S )Nz1Failed to load credential file: [{f}].  {message})fr,   )r-   r;   r.   r1   six	text_type)r2   r<   er3   r&   r'   r.   v   s
   
z'InvalidCredentialFileException.__init__r5   r&   r&   r3   r'   r;   s   r7   r;   c                   @   r   )AccountImpersonationErrorzEException for when attempting to impersonate a service account fails.Nr!   r&   r&   r&   r'   r@   |   s    r@   c                   @   r   )	FlowErrorz8Exception for when something goes wrong with a web flow.Nr!   r&   r&   r&   r'   rA      r(   rA   c                   @   r   )RevokeErrorz0Exception for when there was a problem revoking.Nr!   r&   r&   r&   r'   rB      r(   rB   c                   @   r   )InvalidCodeVerifierErrorz-Exception for invalid code verifier for pkce.Nr!   r&   r&   r&   r'   rC      r(   rC   c                   @   r   )UnsupportedCredentialsErrorz6Exception for when a credential type is not supported.Nr!   r&   r&   r&   r'   rD      r(   rD   c                   @   s:   e Zd ZdZdd Zdd Zdd Zdd	d
Zdd ZdS )StaticCredentialProvidersz'Manages a list of credential providers.c                 C   s
   g | _ d S N)
_providersr2   r&   r&   r'   r.      s   
z"StaticCredentialProviders.__init__c                 C      | j | d S rF   )rG   appendr2   providerr&   r&   r'   AddProvider      z%StaticCredentialProviders.AddProviderc                 C   rI   rF   )rG   removerK   r&   r&   r'   RemoveProvider   rN   z(StaticCredentialProviders.RemoveProviderTc                 C   s,   | j D ]}|||}|d ur|  S qd S rF   )rG   GetCredentials)r2   r:   use_google_authrL   credr&   r&   r'   rQ      s   
z(StaticCredentialProviders.GetCredentialsc                 C   s"   t  }| jD ]}|| O }q|S rF   )setrG   GetAccounts)r2   accountsrL   r&   r&   r'   rU      s   
z%StaticCredentialProviders.GetAccountsNT)	r"   r#   r$   r%   r.   rM   rP   rQ   rU   r&   r&   r&   r'   rE      s    
rE   c                 C   sT   t jjj}| s||  dS t| | | | kr(t	
d| | d dS )a  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_domainr:   universe_domain_propertyr&   r&   r'   _HandleGceUniverseDomain   s   

rf   c                   @   sJ   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dS )GceCredentialProviderz=Provides account, project and credential data for gce vm env.Tc                 C   s4   t jjj r|t  v r| }t|||S d S rF   )	r   rZ   r[   check_gce_metadataGetBoolc_gceMetadataAccountsAcquireFromGCE)r2   r:   rR   refreshr&   r&   r'   rQ      s
   z$GceCredentialProvider.GetCredentialsc                 C      t jjj rt  S d S rF   )r   rZ   r[   rh   ri   rj   rk   DefaultAccountrH   r&   r&   r'   
GetAccount      z GceCredentialProvider.GetAccountc                 C   s$   t jjj rtt  S t S rF   )	r   rZ   r[   rh   ri   rT   rj   rk   rl   rH   r&   r&   r'   rU      s   z!GceCredentialProvider.GetAccountsc                 C   s   t jjj rt  S dS )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   rZ   r[   rh   ri   rj   rk   UniverseDomainrH   r&   r&   r'   GetUniverseDomain   s   z'GceCredentialProvider.GetUniverseDomainc                 C   ro   rF   )r   rZ   r[   rh   ri   rj   rk   ProjectrH   r&   r&   r'   
GetProject   rr   z GceCredentialProvider.GetProjectc                 C   D   t jjj| j t jjj| j t jjj| j	 t
|  d S rF   )r   rZ   r[   r:   AddCallbackrq   projectrv   r\   rt   STATIC_CREDENTIAL_PROVIDERSrM   rH   r&   r&   r'   Register   s   zGceCredentialProvider.Registerc                 C   rw   rF   )r   rZ   r[   r:   RemoveCallbackrq   ry   rv   r\   rt   rz   rP   rH   r&   r&   r'   
UnRegister  s   
z GceCredentialProvider.UnRegisterNrW   )r"   r#   r$   r%   rQ   rq   rU   rt   rv   r{   r}   r&   r&   r&   r'   rg      s    
rg   c                   @      e Zd ZdZdd ZdS )AcctInfozAn auth command resource list item.

  Attributes:
    account: str, The account name.
    status: str, The account status, one of ['ACTIVE', ''].
  c                 C   s   || _ |r
d| _d S d| _d S NACTIVE )r:   status)r2   r:   activer&   r&   r'   r.     s   zAcctInfo.__init__Nr"   r#   r$   r%   r.   r&   r&   r&   r'   r     s    r   c                   @   r~   )AcctInfoWithUniverseDomainzAn 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                 C   s*   || _ |rdnd| _|ptjjjj| _d S r   )r:   r   r   rZ   r[   r\   default)r2   r:   r   r\   r&   r&   r'   r.   &  s   z#AcctInfoWithUniverseDomain.__init__Nr   r&   r&   r&   r'   r     s    	r   c                      s"   t jjj   fddt D S )zGet all accounts for the auth command Run() method.

  Returns:
    List[AccInfo]: The list of account information for all accounts.
  c                    s   g | ]	}t || kqS r&   )r   ).0r:   active_accountr&   r'   
<listcomp>5  s    zAllAccounts.<locals>.<listcomp>)r   rZ   r[   r:   ra   AvailableAccountsr&   r&   r   r'   AllAccounts.  s   
r   c            
      C   s   t  } |  }t }|D ]}||vr*t|}t|dr!|jntj	j
jjg||< qtt| }tj	j
j }tj	j
j }g }|D ]}|| D ]}||koT||k}	|t||	| qKqE|S )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\   )rb   GetCredentialStoreGetAccountsWithUniverseDomainrz   rU   rQ   hasattrr\   r   rZ   r[   r   dictsorteditemsr:   ra   rJ   r   )
storeaccounts_dictstatic_accountsr:   r   r   re   resultr\   	is_activer&   r&   r'   AllAccountsWithUniverseDomains;  s:   

r   r:   returnc                    s,   t  }t fdd|D d}|r|jS d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   s    | ]
}|j  kr|V  qd S rF   r9   )r   cred_accountr9   r&   r'   	<genexpr>v  s    
z7GetCredentialedAccountUniverseDomain.<locals>.<genexpr>N)r   nextr\   )r:   all_cred_accountsr   r&   r9   r'   $GetCredentialedAccountUniverseDomaink  s   	
r   c                  C   s    t  } |  t B }t|S )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.
  )rb   r   rU   rz   r   )r   rV   r&   r&   r'   r     s   	r   c                   C   s   t jjj S )z1Returns True if google-auth is disabled globally.)r   rZ   authdisable_load_google_authri   r&   r&   r&   r'   GoogleAuthDisabledGlobally  s   r     c              
   C   s   zt j| dd}|j|krtd| W n t jy2 } zt|d}td| |d}~ww t j	|t
j d}t t jt
j d|}||kS )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
ValueErrorr1   r    r=   r>   rstripLocalizeDateTimedateutiltztzutcGetDateTimePlusDurationNow)expiry_windowtoken_expiry_timemax_window_seconds
min_expiryr?   r,   
window_endr&   r&   r'   _TokenExpiresWithinWindow  s*   
r   c                 C   s"   | d u rd S t | r| jS | jS rF   )rb   IsGoogleAuthCredentialstokenaccess_tokenr   r&   r&   r'   _GetAccessTokenFromCreds  s
   
r   Tc                 C   s   t | |d|d}t|S )aO  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   )r:   scopesallow_account_impersonationr   r&   r&   r'   GetAccessToken  s   r   c                 C   s   t jjj r	dS t| ||S )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   rZ   r   disable_credentialsri   r   )r:   r   r   r&   r&   r'   GetAccessTokenIfEnabled  s   r   1hc                 C   s   t | |||d}t|S )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   )r:   r   min_expiry_durationr   r   r&   r&   r'   GetFreshAccessToken  s   r   c                 C   s    t jjj r	dS t| |||S )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   rZ   r   r   ri   r   )r:   r   r   r   r&   r&   r'   GetFreshAccessTokenIfEnabled  s
   r   c                 C   s   t | |||d}t|| |S )ap  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:
  )r:   r   r   rR   )r   RefreshIfExpireWithinWindow)r:   r   r   r   rR   rS   r&   r&   r'   r   "  s   .
r   c                 C   s   t jjj r	dS t| |dS )ai  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   rR   )r   rZ   r   r   ri   r   r   r&   r&   r'   LoadIfEnabledZ  s    r   c                 C   s<   |  d} dd | D } | std| d | dd pdfS )a6  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.
  ,c                 S   s   g | ]}|  qS r&   )strip)r   sa_idr&   r&   r'   r     s    z.ParseImpersonationAccounts.<locals>.<listcomp>z"No service account to impersonate.N)splitr)   )service_account_idsr&   r&   r'   ParseImpersonationAccounts  s
   
r   c                   @   s>   e Zd ZdZ								d
ddZdd Zedd	 ZdS )CredentialInfozCredential information.FNc	           	      C   s4   || _ || _|| _|| _|| _|| _|| _|| _d S rF   )auth_disabledaccess_token_env_var_setaccess_token_file_setcredential_file_override_setr:   	file_pathimpersonated_accountimpersonated_account_delegates)	r2   r   r   r   r   r:   r   r   impersonated_delegatesr&   r&   r'   r.     s   
zCredentialInfo.__init__c                 C   s   | j r	 dS | jrd}n| jrd| j}n| jr"d| j| j}nd| j}| jrE|d| j }| jrA|dd	| j }|d	 }|S )
zZGet 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   r1   r   r   r:   r   r   join)r2   info_stringr&   r&   r'   GetInfoString  s@   
zCredentialInfo.GetInfoStringc                  C   s   t jjj rtddS t } t jjj }|r t|\| _	| _
ttjtr,d| _| S t jjj }|r=d| _|| _| S t jjj }|rdd| _|| _t|dd}t|dd}|s_t|}|| _| S t jjj | _| S )zWGet the credential information.

    Returns:
      CredentialInfo: the cred info.
    T)r   Nservice_account_email)r   rZ   r   r   ri   r   impersonate_service_accountra   r   r   r   r   GetEncodedValueosenvironACCESS_TOKEN_ENV_VAR_NAMEr   access_token_filer   r   credential_file_overrider   _LoadFromFileOverridegetattrauth_external_accountGetExternalAccountIdr:   r[   )	cred_infoimpersonationr   cred_file_overrider   r:   r&   r&   r'   GetCredentialInfo  s:   

z CredentialInfo.GetCredentialInfo)FFFFNNNN)r"   r#   r$   r%   r.   r   staticmethodr   r&   r&   r&   r'   r     s    
2r   Fc                 C   s   |ot   }tjjj }|rJ|rJt|\}}ts td	|t
d	| |r?t| d||d}	t|	|||p;tj}
|
S t||pFtj}
|
S t| ||||d}
|
S )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)r:   r   rR   cache_only_raptr   )r   r   rZ   r   r   ra   r   IMPERSONATION_TOKEN_PROVIDERr@   r1   r   warningr   !GetElevationAccessTokenGoogleAuthr
   CLOUDSDK_SCOPESGetElevationAccessToken_Load)r:   r   prevent_refreshr   rR   r   r   target_principal	delegatesgoogle_auth_source_credsrS   r&   r&   r'   r     sT   9

r   c              
   C   s  t d|  |sVztj| }W n tjy" } zt| |d}~ww | r3|du r.tj	}|
|}tjjj }|rOtj|}|tjjtjjfv rO||_t|}|S t }ddlm} ddlm}	 ddlm}
 ddlm} z	|| \}}W n |	jy } zt| |d}~ww |du rtj	}|||}t ||
j!r|j"s|j}tj#|d< tj$|d	< t%|j&|tj	d
}t ||j!r|j}tj#|d< tj$|d	< tj'|d< t%|&|}tj(|}|tj(jkrtjjj }|r||_)n|tj(j*krt+ }||_)t,| t-|}|S )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    r;   create_scoped_requiredr
   r   create_scopedr   rZ   r   
token_hostra   rb   CredentialTypeFromCredentialsSERVICE_ACCOUNTP12_SERVICE_ACCOUNT	token_uri MaybeAttachAccessTokenCacheStoreGetGoogleAuthDefaultgoogle.authr   r   r   r   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)r   r   rR   rS   r?   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_infor&   r&   r'   r   w  s   


C







r   c                 C   sP   t dt |stdt|  } ddlm} || }t	j
jj |_|S )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   r   r   rD   r1   r   googlecloudsdk.core.credentialsr(  AccessTokenCredentialsr   rZ   r[   r\   ra   _universe_domain)r   rR   c_google_authr   r&   r&   r'   _LoadAccessTokenCredsFromValue  s   
r-  c                 C   sP   t d|  |stdt|  }ddlm} ||}t	j
jj |_|S )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   r'  )r   r   rD   r   ReadFileContentsr   r)  r(  r*  r   rZ   r[   r\   ra   r+  )
token_filerR   contentr,  r   r&   r&   r'   _LoadAccessTokenCredsFromFile  s   
r1  c           
      C   s   t tjt}tjjj	 }tjjj
	 }|rt||}n[|r%t||}nS|r.t|||}nJ| s7tjjj	 } | sBttdjtj|d}	|	| |}|sxt| |}|s\t| t|rv|	| | tj||d}t|j|j  n|S |s~t!| |S )zHelper for Load().Fr   )"r   r   r   r   r   r   rZ   r   r   ra   r   r-  r1  r   r[   r:   creds_exceptionsNoActiveAccountExceptionr   ActiveConfigr   rb   r   r   rz   rQ   r8   IsGoogleAuthGceCredentialsStorer  rf   r\   r   RefreshIfAlmostExpire)
r:   r   r   rR   r   r   r   r   rS   r   r&   r&   r'   r   	  sJ   


r   standardc                 C   s2   t | rt| |||| dS t| |||| dS )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)rb   IsOauth2ClientCredentials_Refresh_RefreshGoogleAuth)r   is_impersonated_credentialinclude_emailgce_token_formatgce_include_licenser&   r&   r'   RefreshJ  s   
r@  c              
   C   sT  ddl m} ddl m} ddl}|jtjd}zR| | d}	|r:ts't	dt
| s3t	d| t| |d}	nt| tjrFt| |}	nt| tjrWt jtj||d	}	|	rg| jra|	| jd
< |	| _W dS W dS  tj|jfy }
 z||
rt|
t t!"|
d}
~
w t#j$y   t%  t#j&y }
 zt't(|
d}
~
ww )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.corerB  rD  httplib2Httpr   ENCODINGrn   r   r@   IsImpersonationCredentialr1   "_RefreshImpersonatedAccountIdTokenr  r   ServiceAccountCredentials_RefreshServiceAccountIdTokenoauth2client_gceAppAssertionCredentialsrj   rk   
GetIdTokenr
   r  token_responseid_tokenb64r   AccessTokenRefreshErrorServerNotFoundErrorIsContextAwareAccessDeniedErrorr2  TokenRefreshDeniedByCAAErrorTokenRefreshErrorr=   r>   r   ReauthSamlLoginRequiredErrorWebLoginRequiredReauthErrorReauthErrorTokenRefreshReauthErrorstr)r   r<  r=  r>  r?  rB  rD  rM  http_clientrK  r?   r&   r&   r'   r:  q  sZ   



r:  c              
   c   s    ddl m} ddlm} ddlm} zdV  W dS  |jy'   tj| d |j	y< } z	tj
t|| dd}~w |jy^ } z||rNt|tjt|| ||dd}~ww )z=Handles exceptions during refreshing google auth credentials.r   r   rA  r'  N)for_adc)rd  r:   is_service_account)r  r   rL  rB  r)  r(  ReauthSamlChallengeFailErrorr2  r_  ReauthRequiredErrorra  rb  RefreshErrorr[  r\  r]  r=   r>   )rd  r:   re  r"  rB  r,  r?   r&   r&   r'   'HandleGoogleAuthCredentialsRefreshError  s,   

ri  c                 C   s   ddl m} ddl m} t rt| sdS t| drJt| rJz
|j	| j
dd}W n |jy6   Y dS w tjj|d tjjd	}tt|sJdS dS )
a  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   rj  r   IsDefaultUniverserb   HasDefaultUniverseDomainr   UseSelfSignedJwtdecoderk  GoogleAuthErrordatetimefromtimestamptimezoneutcr   _CREDENTIALS_EXPIRY_WINDOW)r   r"  rj  payloadexpiryr&   r&   r'   _ShouldRefreshGoogleAuthIdToken  s(   
rz  c           	   	   C   s   d}d}t | r| j}d}ddlm} | }t||d! t |  t| r2t	| ||||dd | 
| W d   dS 1 sBw   Y  dS )a7  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)r:   re  )r<  r=  r>  r?   refresh_user_account_credentials)rb   IsServiceAccountCredentialsr   rL  r|  GoogleAuthRequestri  r  rz  _RefreshGoogleAuthIdTokenrn   )	r   r<  r=  r>  r?  r:   re  r|  request_clientr&   r&   r'   r;    s,   

"r;  c                 C   s4  ddl m  m} ddlm} ddlm} | }	t t d}
t	
| r,|r,| |	 nL|r[ts4tdddlm  m} t| |jsJtd| t| tj|}||	 |j}
nt| |jrgt| |	}
nt| |jrxt jtj||d}
|
r|
| _|
| _W d   dS W d   dS 1 sw   Y  dS )a  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{  rF  rG  rH  )google.auth.compute_enginer   compute_enginegoogle.oauth2r   rL  r|  r  ri  rb   IsUserAccountCredentialsrn   r   r@   $google.auth.impersonated_credentialsimpersonated_credentialsr  r  r1   GetElevationIdTokenGoogleAuthr
   r  r   '_RefreshServiceAccountIdTokenGoogleAuthrj   rk   rV  rk  rX  )r   r<  r=  r>  r?  r}  google_auth_gcegoogle_auth_service_accountr|  r  rK  google_auth_impersonated_credsid_token_credsr&   r&   r'   r  =  sZ   '
%"r  c                 C   s<   t | r	| j}n| j}| pt||}|rt|  dS dS )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)rb   r9  token_expiryry  r   r@  )r   windowry  almost_expirer&   r&   r'   r     s   
	r   c                 C   s   t | td d S )N)r  )r   rw  r   r&   r&   r'   r7    rN   r7  c                 C   s   | j }t|tj|S )z@Get a fresh id_token for the given impersonated service account.)_service_account_idr   GetElevationIdTokenr
   r  )rS   r=  r   r&   r&   r'   rQ    s   rQ  c           
      C   s   |j }tt }| j||| j | jtjd}tj	| j
|| jd}tj|td}|| jdd||  d\}}|jdkrJt|}	|	dd	S d	S )
aG  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iatrm  isstarget_audience)key_id)	assertion
grant_typeidnaPOST)methodbodyheaders   rK  N)requestinttimer
  MAX_TOKEN_LIFETIME_SECS_service_account_emailr
   r  r   make_signed_jwt_signer_private_key_idr   parse	urlencode_GRANT_TYPEencode!_generate_refresh_request_headersr   jsonloadsget)
rS   rc  http_requestnowrx  r  r  respr0  dr&   r&   r'   rS    s.   



rS  c           
   
   C   s(  t jjj r	dS ddlm} ddlm} ddlm	} ddl
m} |j| j| j| jtjt jjj d}|j|j| |_z	|| W |j S  |jy } z>t|jdkra|jd d	d
nd
}d|v rd|d v rd}	td|d |	 W Y d}~dS W Y d}~|j S W Y d}~|j S d}~ww )a^  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   r,   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   rZ   r   (service_account_disable_id_token_refreshri   r  r   r  r  r   %googlecloudsdk.api_lib.iamcredentialsr	   IDTokenCredentialssignerr   r  r
   r  r[   r\   ra   _IAM_IDTOKEN_ENDPOINTreplaceIAM_ENDPOINT_GDUGetEffectiveIamEndpointrn   rh  lenargsr  r   r  r   )
rS   r  r"  google_auth_iamr  iam_credentials_utilid_token_credr?   r  stepsr&   r&   r'   r    sF   $	


r  c                 C   s   t | rt j| }|jt jkrdS nt j| }|jt jt jt j	t j
t jt jt jfvr/dS |s8tjjj }|s>t t  }|||  |jt jkrXt|| |  dS dS )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)rb   r9  r  r  keyGCE_CREDS_NAMEr  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   rZ   r[   r:   ra   r2  r3  r   r6  _LegacyGeneratorWriteTemplate)r   r:   r   r  r   r&   r&   r'   r6  !  s2   
	r6  c                 C   sR   t |drt|j|  t rt|rt| t	||  t
tjjj|  dS )z?Validates, stores and activates credentials with given account.r\   N)r   r_   r`   r\   r   rn  rb   ro  r@  r6  PersistPropertyrZ   r[   r:   )r:   r   r&   r&   r'   ActivateCredentials\  s   

r  c                 C   sl   t | rt | st | rtdt | r'ddlm} | |	  dS ddlm
} | |  dS )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   rC  r{  N)rb   r   IsExternalAccountUserCredentials*IsExternalAccountAuthorizedUserCredentialsrB   r9  rL  rD  revokerN  r|  r  )r   rD  r|  r&   r&   r'   RevokeCredentialsl  s   
	
r  c           	   
   C   sB  ddl m} ddl m} ddlm} | stjjj	 } | s!t
 | t  v r-tdt| ddd}|s:t| d}z| d	sTt||jsTt||jsTt| d}W n' tj|jfy| } z|jd d
krin	|jd dkrqn W Y d}~nd}~ww t }||  t| |  t  | }t!j"#|rt$%| |S )aB  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   r   r'  z'Cannot revoke GCE-provided credentials.T)r   rR   Fz.gserviceaccount.cominvalid_tokeninvalid_requestN)&r  r   r   r)  r(  r   rZ   r[   r:   ra   r2  r3  rj   rk   rl   rB   r   r8   endswithr  r  r  r   TokenRevokeErrorr  rb   r   Remover  Cleanr
   PathsLegacyCredentialsDirr   pathisdirr   RmTree)	r:   r#  r$  r,  r   rvr?   r   legacy_creds_dirr&   r&   r'   Revoke  sT   




r  c              
   C   s   |ot   }|du rt }|r7ddlm} |jd| d|tjjj	j
ddtjjjj
ddd}tj |_|S tjdtjjj	j
ddtjjjj
dd| tj |tj|d}|S )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   r   T)required)r   refresh_tokenrK  r
  r   r   )r   r   r   r  r  r
  
user_agent
revoke_uri)r   rb   r  r  r   r  r   rZ   r   r   ra   r   rs  utcnowry  r   OAuth2Credentialsr
   CLOUDSDK_USER_AGENT)r  r
  r  rR   r!  rS   r&   r&   r'   AcquireFromToken  s4   	
r  c                 C   s`   |r"ddl m  m} | pd}|j|d}t  }||_d|_nt	j
| d}|r.t| |S )aO  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  r  rj   rk   rs   r+  _universe_domain_cachedrT  rU  r@  )r:   rR   rn   r  r  r   r\   r&   r&   r'   rm     s   rm   c                   @   sJ   e Zd ZdZdddZedd Zedd Zd	d
 Zdd Z	dd Z
dS )r  aE  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                 C   s   || _ | jtjtjtjtjtjtjfvrt	d
t| j |d u r(tj| _n|| _t }||| _||| _||| _||| _d S )N Unsupported credentials type {0})r   
_cred_typerb   r  r  r  r  r  r  CredentialFileSaveErrorr1   r  r
   r   r   r  LegacyCredentialsBqPath_bq_pathLegacyCredentialsGSUtilPath_gsutil_pathLegacyCredentialsP12KeyPath_p12_key_pathLegacyCredentialsAdcPath	_adc_path)r2   r:   r   r   pathsr&   r&   r'   r.   6  s&   
z_LegacyGenerator.__init__c                 C   s   t | jS rF   )rb   r9  r   rH   r&   r&   r'   _is_oauth2clientO  s   z!_LegacyGenerator._is_oauth2clientc                 C   s&   | j rtj| jjS tj| jjS rF   )r  rb   r  r  r   r  r  rH   r&   r&   r'   r  S  s   z_LegacyGenerator._cred_typec              	   C   sB   | j | j| j| jg}|D ]}zt| W q ty   Y qw dS )zRemove the credential file.N)r  r  r  r  r   rO   OSError)r2   r  pr&   r&   r'   r  [  s   z_LegacyGenerator.Cleanc                 C   st  |    | jtjkr3| j}|j}|j}tj| j	|dd | 
| jdg dj| jj| j	|d dS t| jj| jd | jtjksJ| jtjkr]| 
| jddd	gj| jd
 dS | jtjkrv| 
| jdddgj| jd
 dS | jtjkr| 
| jdg dj| jj| jj| jjd dS | jtjkr| 
| jdddgj| jd dS tdt| j)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})r:   key_filekey_passwordN)r   r  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   r  z!gs_oauth2_refresh_token = {token})cidsecretr   r   )r  r  )r  r  rb   r  r   _private_key_pkcs12_private_key_passwordr   WriteBinaryFileContentsr  _WriteFileContentsr  r   r1   r   ADCDumpADCToFiler  r  r  r  r  r   r   r  r  r  r  )r2   rS   r  passwordr&   r&   r'   r  k  st   
	z_LegacyGenerator.WriteTemplatec                 C   s&   t jt|}tj||dd dS )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.
    Tr  N)r   r  realpathr   ExpandHomeDirWriteFileContents)r2   filepathcontents	full_pathr&   r&   r'   r	    s   z#_LegacyGenerator._WriteFileContentsrF   )r"   r#   r$   r%   r.   propertyr  r  r  r  r	  r&   r&   r&   r'   r  -  s    


Mr  )r   )NNT)NNr   T)NNr   TT)TT)NNFTTF)TF)FFr8  F)FNF)FFr8  FT)NNrF   )NTT)pr%   
__future__r   r   r   
contextlibrs  r  r   r/   r  typingr   r   googlecloudsdk.api_lib.authr   r   r	   r_   rL  r
   r   r   r   "googlecloudsdk.core.configurationsr   r)  r   rb   r   r2  r   rj   googlecloudsdk.core.utilr   r   r   oauth2clientr   r   r   oauth2client.contribrT  r   r=   	six.movesr   r   (GOOGLE_OAUTH2_PROVIDER_AUTHORIZATION_URI!GOOGLE_OAUTH2_PROVIDER_REVOKE_URIr  rw  ACCOUNT_TABLE_FORMAT)ACCOUNT_TABLE_WITH_UNIVERSE_DOMAIN_FORMATr    r)   r+   r8   r;   r@   rA   rB   rC   rD   r   objectrE   rz   rf   rg   r   r   r   r   rb  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r-  r1  r   r@  r:  contextmanagerri  rz  r;  r  r   r7  rQ  rS  r  r6  r  r  r  r  rm   r  r&   r&   r&   r'   <module>   s"  		'70
)
	




8' 
a_
B
(
5/
M
[	)
A;
E

8.