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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ZdZdZdZdZdZdZeeeegZdZG dd dej Z G dd de Z!G dd de Z"dd Z#dd  Z$G d!d" d"e%ej&e'Z(G d#d$ d$e(Z)G d%d& d&e(Z*G d'd( d(e(Z+G d)d* d*e(Z,G d+d, d,e(Z-G d-d. d.e(Z.d<d/d0Z/d1d2 Z0d3d4 Z1			5	5			d=d6d7Z2d8d9 Z3d:d; Z4dS )>z#A library to support auth commands.    )absolute_import)division)unicode_literalsN)check_browser)config)
exceptions)log)
properties)yaml)
console_io)creds)fileszH764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.comzd-FL95Q19q7MQmFpd7hHD0Tyz.https://www.googleapis.com/auth/cloud-platformz0https://www.googleapis.com/auth/sqlservice.loginz%https://www.googleapis.com/auth/drivez.https://www.googleapis.com/auth/userinfo.emailopenid	installedc                   @      e Zd ZdZdS )Errorz A base exception for this class.N__name__
__module____qualname____doc__ r   r   =/tmp/google-cloud-sdk/lib/googlecloudsdk/api_lib/auth/util.pyr   ;       r   c                   @   r   )InvalidClientSecretsErrorz:An error for when we fail to load the client secrets file.Nr   r   r   r   r   r   @   r   r   c                   @   r   )BadCredentialFileExceptionz,Raised when credentials file cannot be read.Nr   r   r   r   r   r   E   r   r   c              
   C   s|   zt | }W n( ty } ztd| |d}~w t jy/ } ztd| |d}~ww t|ts<td| |S )a  Returns the JSON content of a credentials config file.

  This function is useful when the content of a file need to be inspected first
  before determining how to handle it (how to initialize the underlying
  credentials). Only UTF-8 JSON files are supported.

  Args:
    filename (str): The filepath to the ADC file representing credentials.

  Returns:
    Optional(Mapping): The JSON content.

  Raises:
    BadCredentialFileException: If JSON parsing of the file fails.
  z"File {0} is not utf-8 encoded: {1}Nz!Could not read json file {0}: {1}zCould not read json file {0})r
   	load_pathUnicodeDecodeErrorr   formatYAMLParseError
isinstancedict)filenamecontenter   r   r   GetCredentialsConfigFromFileJ   s$   

r%   c                 C   s8   ddl m} || rt|j  dS t| dS )z2Prints help messages when auth flow throws errors.r   )context_awareN)googlecloudsdk.corer&   IsContextAwareAccessDeniedErrorr   errorContextAwareAccessErrorGet)excdefault_help_msgr&   r   r   r   _HandleFlowErrorm   s   
r.   c                   @   s4   e Zd ZdZdZd
ddZejdd Zdd	 Z	dS )
FlowRunnerzBase auth flow runner class.

  Attributes:
     _scopes: [str], The list of scopes to authorize.
     _client_config: The client configuration in the Google client secrets
       format.
  z,There was a problem with web authentication.Nc                 C   s    || _ || _|| _|  | _d S N)_scopes_client_config_redirect_uri_CreateFlow_flow)selfscopesclient_configredirect_urir   r   r   __init__   s   zFlowRunner.__init__c                 C   s   d S r0   r   )r6   r   r   r   r4      s   zFlowRunner._CreateFlowc              
   K   sJ   ddl m} z
| jjdi |W S  |jy$ } zt|| j  d }~ww )Nr   flowr   )googlecloudsdk.core.credentialsr<   r5   Runr   r.   _FLOW_ERROR_HELP_MSG)r6   kwargsc_flowr$   r   r   r   r>      s   zFlowRunner.Runr0   )
r   r   r   r   r?   r:   abcabstractmethodr4   r>   r   r   r   r   r/   x   s    

r/   c                   @      e Zd ZdZdd ZdS )OobFlowRunnerzA flow runner to run OobFlow.c                 C   .   ddl m} |jj| j| jtjjj	
  dS Nr   r;   autogenerate_code_verifier)r=   r<   OobFlowfrom_client_configr2   r1   r	   VALUESauthdisable_code_verifierGetBoolr6   rA   r   r   r   r4         zOobFlowRunner._CreateFlowNr   r   r   r   r4   r   r   r   r   rE          rE   c                   @   rD   )NoBrowserFlowRunnerz#A flow runner to run NoBrowserFlow.c                 C   rF   rG   )r=   r<   NoBrowserFlowrK   r2   r1   r	   rL   rM   rN   rO   rP   r   r   r   r4      rQ   zNoBrowserFlowRunner._CreateFlowNrR   r   r   r   r   rT      rS   rT   c                   @   rD   )"RemoteLoginWithAuthProxyFlowRunnerz2A flow runner to run RemoteLoginWithAuthProxyFlow.c                 C   s2   ddl m} |jj| j| jtjjj	
  | jdS )Nr   r;   )rI   r9   )r=   r<   RemoteLoginWithAuthProxyFlowrK   r2   r1   r	   rL   rM   rN   rO   r3   rP   r   r   r   r4      s   z.RemoteLoginWithAuthProxyFlowRunner._CreateFlowNrR   r   r   r   r   rV      rS   rV   c                   @   rD   )NoBrowserHelperRunnerz)A flow runner to run NoBrowserHelperFlow.c                 C   sN   ddl m} z|jj| j| jtjjj	
  dW S  |jy&   td  w )Nr   r;   rH   zCannot start a local server to handle authorization redirection. Please run this command on a machine where gcloud can start a local server.)r=   r<   NoBrowserHelperFlowrK   r2   r1   r	   rL   rM   rN   rO   LocalServerCreationErrorr   r)   rP   r   r   r   r4      s   
z!NoBrowserHelperRunner._CreateFlowNrR   r   r   r   r   rX      rS   rX   c                   @      e Zd ZdZdZdd ZdS ) BrowserFlowWithOobFallbackRunnerz?A flow runner to try normal web flow and fall back to oob flow.zXThere was a problem with web authentication. Try running again with --no-launch-browser.c              
   C      ddl m} z|jj| j| jtjjj	
  dW S  |jyF } z!t| td |jj| j| jtjjj	
  dW  Y d }~S d }~ww )Nr   r;   rH   z"Defaulting to URL copy/paste mode.)r=   r<   FullWebFlowrK   r2   r1   r	   rL   rM   rN   rO   rZ   r   warningrJ   r6   rA   r$   r   r   r   r4      *   

z,BrowserFlowWithOobFallbackRunner._CreateFlowNr   r   r   r   r?   r4   r   r   r   r   r\          r\   c                   @   r[   )&BrowserFlowWithNoBrowserFallbackRunnerzEA flow runner to try normal web flow and fall back to NoBrowser flow.zQThere was a problem with web authentication. Try running again with --no-browser.c              
   C   r]   )Nr   r;   rH   z Defaulting to --no-browser mode.)r=   r<   r^   rK   r2   r1   r	   rL   rM   rN   rO   rZ   r   r_   rU   r`   r   r   r   r4      ra   z2BrowserFlowWithNoBrowserFallbackRunner._CreateFlowNrb   r   r   r   r   rd      rc   rd   c                 C   s>   | rt | }t|W  d   S 1 sw   Y  t S )zECreates a client config from a client id file or gcloud's properties.N)r   
FileReaderjsonload+_CreateGoogleAuthClientConfigFromProperties)client_id_filefr   r   r   _CreateGoogleAuthClientConfig  s
    rk   c                  C   sP   t jjjjdd} t }t jjjjdd}t jjjjdd}d||| |diS )z1Creates a client config from gcloud's properties.T)requiredr   )	client_idclient_secretauth_uri	token_uri)	r	   rL   rM   	auth_hostr+   r   GetDefaultTokenUrirm   rn   )ro   rp   rm   rn   r   r   r   rh     s   rh   c                 C   s   | d d t jtfv S )Nr   rm   )r   CLOUDSDK_CLIENT_ID%DEFAULT_CREDENTIALS_DEFAULT_CLIENT_ID)r8   r   r   r   _IsGoogleOwnedClientID$  s   
ru   Fc                 C   sP  ddl m} ddlm}	 ddlm}
 |rt| |st|}|s"i }tj	dd}|r6t
| |jdi |}nR|rM|s?|
dt| |jdd|i|}n;|r\t| ||jdi |}n,|s}|rpt|spt
| |jdi |}nt| ||jdi |}nt| |jdi |}|rt||	jrdd	lm} |j|S t||jr|S d
S d
S )a/  Launches a 3LO oauth2 flow to get google-auth credentials.

  Args:
    scopes: [str], The list of scopes to authorize.
    client_id_file: str, The path to a file containing the client id and secret
      to use for the flow.  If None, the default client id for the Cloud SDK is
      used.
    client_config: Optional[Mapping], the client secrets and urls that should be
      used for the OAuth flow.
    no_launch_browser: bool, True if users specify --no-launch-browser flag to
      use the remote login with auth proxy flow.
    no_browser: bool, True if users specify --no-browser flag to ask another
      gcloud instance to help with authorization.
    remote_bootstrap: str, The auth parameters specified by --remote-bootstrap
      flag. Once used, it means the command is to help authorize another
      gcloud (i.e. gcloud without access to browser).
    query_params: Optional[Mapping], extra params to pass to the flow during
      `Run`. These params end up getting used as query
      params for authorization_url.
    auth_proxy_redirect_uri: str, The uri where OAuth service will redirect the
      user to once the authentication is complete for a remote login with auth
      proxy flow.
  Returns:
    core.credentials.google_auth_credentials.Credentials, The credentials
      obtained from the flow.
  r   ) external_account_authorized_user)credentialsr;   T)attempt_launch_browserzbCannot launch browser. Please run this command on a machine where gcloud can launch a web browser.partial_auth_url)google_auth_credentialsNr   )google.authrv   google.oauth2rw   r=   r<   !AssertClientSecretIsInstalledTyperk   r   ShouldLaunchBrowserrT   r>   WebBrowserInaccessiblerX   rV   ru   rd   r    Credentialsrz   FromGoogleAuthUserCredentials)r7   ri   r8   no_launch_browser
no_browserremote_bootstrapquery_paramsauth_proxy_redirect_urirv   oauth2_credentialsrA   can_launch_browser
user_credsc_google_authr   r   r   #DoInstalledAppBrowserFlowGoogleAuth)  sv   #r   c                 C   s   d}z
t t| }W n! tjy   td|  d t jy-   td|  d| w t|dkr;td| t|d }|t	krRtd	t	 d
| d| dS )zDAssert that the file is a valid json file for installed application.zTo obtain a valid client ID file, create a Desktop App following the steps outlined in https://support.google.com/cloud/answer/6158849?hl=en#zippy=%2Cnative-applications%2Cdesktop-apps.zCannot read file: "z".zClient ID file z is not a valid JSON file.    zNExpected a JSON object with a single property for an "installed" application. r   zOnly client IDs of type 'z%' are allowed, but encountered type 'z'. N)
rf   loadsr   ReadFileContentsr   r   JSONDecodeErrorlentupleCLIENT_SECRET_INSTALLED_TYPE)ri   actionable_messageobjclient_typer   r   r   r}     s:   r}   c                 C   sd   t jjj }|| krdS td|| |}tj	|d}|r0t 
t jjj|  tjd dS dS )aK  Prompt the user to update the universe domain if there is conflict.

  If the given universe domain is different from the core/universe_domain
  property, prompt the user to update the core/universe_domain property.

  Args:
    new_universe_domain: str, The given new universe domain.
    account: str, The account name to use.
  Nz        WARNING: This account [{0}] is from the universe domain [{1}],
        which does not match the current core/universe property [{2}].

        Do you want to set property [core/universe_domain] to [{1}]? [Y/N]
        )messagez(Updated property [core/universe_domain].)r	   rL   coreuniverse_domainr+   textwrapdedentr   r   PromptContinuePersistPropertyr   statusPrint)new_universe_domainaccountcurrent_universe_domainr   should_update_universe_domainr   r   r   HandleUniverseDomainConflict  s   


r   r0   )NNFFNNN)5r   
__future__r   r   r   rB   rf   r   googlecloudsdk.command_lib.utilr   r'   r   r   r   r	   r
   googlecloudsdk.core.consoler   r=   r   googlecloudsdk.core.utilr   sixrt   )DEFAULT_CREDENTIALS_DEFAULT_CLIENT_SECRETCLOUD_PLATFORM_SCOPESQL_LOGIN_SCOPEGOOGLE_DRIVE_SCOPEUSER_EMAIL_SCOPEOPENIDDEFAULT_SCOPESr   r   r   r   r%   r.   with_metaclassABCMetaobjectr/   rE   rT   rV   rX   r\   rd   rk   rh   ru   r   r}   r   r   r   r   r   <module>   sn   # 

X