
    @                     L   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ej@                        Z  G d de       Z! G d de       Z"d Z#d Z$ G d d  ejJ                  ejL                  e'            Z( G d! d"e(      Z) G d# d$e(      Z* G d% d&e(      Z+ G d' d(e(      Z, G d) d*e(      Z- G d+ d,e(      Z.d3d-Z/d. Z0d/ Z1	 	 	 	 	 	 	 d4d0Z2d1 Z3d2 Z4y)5z#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y)Errorz A base exception for this class.N__name__
__module____qualname____doc__     'lib/googlecloudsdk/api_lib/auth/util.pyr   r   ;   s    (r   r   c                       e Zd ZdZy)InvalidClientSecretsErrorz:An error for when we fail to load the client secrets file.Nr   r   r   r   r   r   @   s    Br   r   c                       e Zd ZdZy)BadCredentialFileExceptionz,Raised when credentials file cannot be read.Nr   r   r   r   r   r   E   s    4r   r   c                 @   	 t        j                  |       }t        |t              st        dj	                  |             |S # t        $ r }t        dj	                  | |            d}~wt         j
                  $ r }t        dj	                  | |            d}~ww xY w)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es      r   GetCredentialsConfigFromFiler)   J   s    "nnX&G 
GT	"
$&--h79 9	. 
 B
$,33Ha@B B			 
$%H%O%O!&  s#   A 	BA''B=BBc                     ddl m} |j                  |       r.t        j                  |j
                  j                                yt        j                  |       y)z2Prints help messages when auth flow throws errors.r   )context_awareN)googlecloudsdk.corer+   IsContextAwareAccessDeniedErrorr	   errorContextAwareAccessErrorGet)excdefault_help_msgr+   s      r   _HandleFlowErrorr3   m   s=     02237IIm33779:IIr   c                   F    e Zd ZdZdZddZej                  d        Zd Z	y)
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                 X    || _         || _        || _        | j                         | _        y N)_scopes_client_config_redirect_uri_CreateFlow_flow)selfscopesclient_configredirect_uris       r   __init__zFlowRunner.__init__   s)    DL'D%D!!#DJr   c                      y r7   r   )r=   s    r   r;   zFlowRunner._CreateFlow   s    r   c                     ddl m} 	  | j                  j                  di |S # |j                  $ r}t        || j                          d }~ww xY w)Nr   flowr   )googlecloudsdk.core.credentialsrE   r<   Runr   r3   _FLOW_ERROR_HELP_MSG)r=   kwargsc_flowr(   s       r   rG   zFlowRunner.Run   sI    >TZZ^^%f%%<< q$334s   $ AA

Ar7   )
r   r   r   r   rH   rA   abcabstractmethodr;   rG   r   r   r   r5   r5   x   s4     H$ 	 	r   r5   c                       e Zd ZdZd Zy)OobFlowRunnerzA flow runner to run OobFlow.c                     ddl m} |j                  j                  | j                  | j
                  t        j                  j                  j                  j                                S Nr   rD   autogenerate_code_verifier)rF   rE   OobFlowfrom_client_configr9   r8   r
   VALUESauthdisable_code_verifierGetBoolr=   rJ   s     r   r;   zOobFlowRunner._CreateFlow   sQ    >>>,,'1'8'8'='=		wwy$) - * *r   Nr   r   r   r   r;   r   r   r   rN   rN      s
    %*r   rN   c                       e Zd ZdZd Zy)NoBrowserFlowRunnerz#A flow runner to run NoBrowserFlow.c                     ddl m} |j                  j                  | j                  | j
                  t        j                  j                  j                  j                                S rP   )rF   rE   NoBrowserFlowrT   r9   r8   r
   rU   rV   rW   rX   rY   s     r   r;   zNoBrowserFlowRunner._CreateFlow   sS    >22'1'8'8'='=		wwy$) 3 * *r   NrZ   r   r   r   r\   r\      s
    +*r   r\   c                       e Zd ZdZd Zy)"RemoteLoginWithAuthProxyFlowRunnerz2A flow runner to run RemoteLoginWithAuthProxyFlow.c                     ddl m} |j                  j                  | j                  | j
                  t        j                  j                  j                  j                          | j                        S )Nr   rD   )rR   r@   )rF   rE   RemoteLoginWithAuthProxyFlowrT   r9   r8   r
   rU   rV   rW   rX   r:   rY   s     r   r;   z.RemoteLoginWithAuthProxyFlowRunner._CreateFlow   s]    >..AA'1'8'8'='=		wwy$)'' B ) )r   NrZ   r   r   r   r`   r`      s
    :	)r   r`   c                       e Zd ZdZd Zy)NoBrowserHelperRunnerz)A flow runner to run NoBrowserHelperFlow.c                 (   ddl m} 	 |j                  j                  | j                  | j
                  t        j                  j                  j                  j                                S # |j                  $ r t        j                  d        w xY w)Nr   rD   rQ   zCannot start a local server to handle authorization redirection. Please run this command on a machine where gcloud can start a local server.)rF   rE   NoBrowserHelperFlowrT   r9   r8   r
   rU   rV   rW   rX   LocalServerCreationErrorr	   r.   rY   s     r   r;   z!NoBrowserHelperRunner._CreateFlow   s    >
''::



,,)3):):)?)?  &+ ; , ,
 ** 	ii 3 4 	s   A"A+ +&BNrZ   r   r   r   rd   rd      s
    1r   rd   c                       e Zd ZdZdZd Zy) 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                 (   ddl m} 	 |j                  j                  | j                  | j
                  t        j                  j                  j                  j                                S # |j                  $ r}t        j                  |       t        j                  d       |j                  j                  | j                  | j
                  t        j                  j                  j                  j                                cY d }~S d }~ww xY w)Nr   rD   rQ   z"Defaulting to URL copy/paste mode.)rF   rE   FullWebFlowrT   r9   r8   r
   rU   rV   rW   rX   rg   r	   warningrS   r=   rJ   r(   s      r   r;   z,BrowserFlowWithOobFallbackRunner._CreateFlow   s    >,22



,,)3):):)?)?  &+ 3 , ,
 ** ,	kk!n	kk67^^..



,,)3):):)?)?  &+ / , ,,   A"A+ +D:BDDDNr   r   r   r   rH   r;   r   r   r   ri   ri      s    GH,r   ri   c                       e Zd ZdZdZd Zy)&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                 (   ddl m} 	 |j                  j                  | j                  | j
                  t        j                  j                  j                  j                                S # |j                  $ r}t        j                  |       t        j                  d       |j                  j                  | j                  | j
                  t        j                  j                  j                  j                                cY d }~S d }~ww xY w)Nr   rD   rQ   z Defaulting to --no-browser mode.)rF   rE   rk   rT   r9   r8   r
   rU   rV   rW   rX   rg   r	   rl   r^   rm   s      r   r;   z2BrowserFlowWithNoBrowserFallbackRunner._CreateFlow   s    >,22



,,)3):):)?)?  &+ 3 , ,
 ** ,	kk!n	kk45!!44



,,)3):):)?)?  &+ 5 , ,,rn   Nro   r   r   r   rq   rq      s    MA,r   rq   c                     | r4t        j                  |       5 }t        j                  |      cddd       S t	               S # 1 sw Y   t	               S xY w)zECreates a client config from a client id file or gcloud's properties.N)r   
FileReaderjsonload+_CreateGoogleAuthClientConfigFromProperties)client_id_filefs     r   _CreateGoogleAuthClientConfigrz     s@    			.	)QYYq\ 
*	)	4	66 
*	4	66s   AAc                  t   t         j                  j                  j                  j	                  d      } t        j                         }t         j                  j                  j                  j	                  d      }t         j                  j                  j                  j	                  d      }d||| |diS )z1Creates a client config from gcloud's properties.T)requiredr   )	client_idclient_secretauth_uri	token_uri)	r
   rU   rV   	auth_hostr0   r   GetDefaultTokenUrir}   r~   )r   r   r}   r~   s       r   rw   rw     s    ##--1141@(&&()$$..22D2A)##((66::D:I- ( 	
 r   c                 >    | d   d   t         j                  t        fv S )Nr   r}   )r   CLOUDSDK_CLIENT_ID%DEFAULT_CREDENTIALS_DEFAULT_CLIENT_ID)r?   s    r   _IsGoogleOwnedClientIDr   $  s*    

$[
1'')NOP Qr   c                    ddl m} ddlm}	 ddlm}
 |rt        |       |st        |      }|si }t        j                  d      }|r t        | |      j                  di |}n|r2|s|
j                  d       t        | |      j                  dd|i|}n|r t        | ||      j                  di |}nf|sH|r(t        |      s t        | |      j                  di |}n: t        | ||      j                  di |}n t!        | |      j                  di |}|rPt#        ||	j$                        r!dd	lm} |j$                  j)                  |      S t#        ||j$                        r|S y
y
)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)credentialsrD   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.authr   google.oauth2r   rF   rE   !AssertClientSecretIsInstalledTyperz   r   ShouldLaunchBrowserr\   rG   WebBrowserInaccessiblerd   r`   r   rq   r$   Credentialsr   FromGoogleAuthUserCredentials)r>   rx   r?   no_launch_browser
no_browserremote_bootstrapquery_paramsauth_proxy_redirect_urir   oauth2_credentialsrJ   can_launch_browser
user_credsc_google_auths                 r   #DoInstalledAppBrowserFlowGoogleAuthr   )  s   F ;=< %n5	1.AM	L$88!#?$V];??O,OJ))34 4 B&v}=AA ;);-9;J
36	cJ  4]CA&v}=AA j5
-!8j#7"s3%13J*0<<= [&&DDZPP*>JJK L r   c                    d}	 t        j                  t        j                  |             }t        |      dk7  rt        d|       t        |      d   }|t        k7  rt        d	t         d
| d|       y# t        j                  $ r t        d|  d      t         j                  $ r t        d|  d|       w xY w)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)
ru   loadsr   ReadFileContentsr   r   JSONDecodeErrorlentupleCLIENT_SECRET_INSTALLED_TYPE)rx   actionable_messageobjclient_types       r   r   r     s    l 

**U++N;
<C 	X]
#	+,	.  c
1+00
#
#$@#A B""-c2D1E	G  1 
 N
#&9.9I$L
MM			 
#
.) *	! s   (A8 8AB>c                    t         j                  j                  j                  j	                         }|| k(  ryt        j                  d      j                  || |      }t        j                  |      }|rXt        j                  t         j                  j                  j                  |        t        j                  j                  d       yy)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
   rU   coreuniverse_domainr0   textwrapdedentr"   r   PromptContinuePersistPropertyr	   statusPrint)new_universe_domainaccountcurrent_universe_domainr   should_update_universe_domains        r   HandleUniverseDomainConflictr     s     '--22BBFFH 33
OO   VG02IJ	 

 #-";";G"L"..0C JJ?@	 #r   r7   )NNFFNNN)5r   
__future__r   r   r   rK   ru   r   googlecloudsdk.command_lib.utilr   r,   r   r   r	   r
   r   googlecloudsdk.core.consoler   rF   r   googlecloudsdk.core.utilr   sixr   )DEFAULT_CREDENTIALS_DEFAULT_CLIENT_SECRETCLOUD_PLATFORM_SCOPESQL_LOGIN_SCOPEGOOGLE_DRIVE_SCOPEUSER_EMAIL_SCOPEOPENIDDEFAULT_SCOPESr   r   r   r   r)   r3   with_metaclassABCMetaobjectr5   rN   r\   r`   rd   ri   rq   rz   rw   r   r   r   r   r   r   r   <module>r      s[    * '  ' 
   9 & * # * $ 2 1 * 

 )s %,F )G D< C 	 	  + J 
 
 
 F ###CKK8 @*J *** *) )J (,z ,4,Z ,47"Q 8<6::?389=59@DUp:Ar   