
    WN                     ~   d 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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 Z(d Z)d Z*ejV                   G d dejX                               Z-d Z.d Z/d Z0d Z1y) z(The auth command gets tokens via oauth2.    )absolute_import)division)unicode_literalsN)external_account)service_account)util)actions)base)
exceptions)	auth_util)flags)workforce_login_config)config)log)
properties)
console_io)creds)devshell)gce)storec                 >   t        j                         r+t        j                  d      }t	        j
                  |      S t        j                         j                  r@t        j                  |       s+t        j                  d      }t	        j
                  |      S y)zPrompts users if they try to login in managed environments.

  Args:
    cred_config: Json object loaded from the file specified in --cred-file.

  Returns:
    True if users want to continue the login command.
  z
          You are already authenticated with gcloud when running
          inside the Cloud Shell and so do not need to run this
          command. Do you wish to proceed anyway?
          )messagea  
          You are running on a Google Compute Engine virtual machine.
          It is recommended that you use service accounts for authentication.

          You can run:

            $ gcloud config set account `ACCOUNT`

          to switch accounts if necessary.

          Your credentials may be visible to others with access to this
          virtual machine. Are you sure you want to authenticate with
          your personal account?
          T)
c_devshellIsDevshellEnvironmenttextwrapdedentr   PromptContinuec_gceMetadata	connectedauth_external_accountIsExternalAccountConfig)cred_configr   s     lib/surface/auth/login.pyShouldContinueLoginr%   ,   s}     %%'oo  G
 $$W55""!99+Foo  G $$W55    c                     t         j                  }|t         j                  fz  }| j                  r|t        j
                  fz  }|S N)r   CLOUDSDK_SCOPESREAUTH_SCOPEenable_gdrive_accessr   GOOGLE_DRIVE_SCOPE)argsscopess     r$   	GetScopesr/   Q   sC    !!& 	V  ""&	
y++--F	-r&   c                    | j                   r| j                  ry	 t        j                  | j                   |      }|syt        j                  dj                  | j                                y# t        j
                  $ r Y yw xY w)z3If the login should use the locally cached account.Faccountr.   zsRe-using locally stored credentials for [{}]. To fetch new credentials, re-run the command with the `--force` flag.T)	r2   forcec_storeLoadcreds_exceptionsErrorr   warningformat)r-   r.   r   s      r$   ShouldUseCachedCredentialsr:   \   sq    
,,4::LLf=E 
++   &t|| 46 
 
		 s   !A. .BBc                   *    e Zd ZdZdZed        Zd Zy)Logina
	  Authorize gcloud to access the Cloud Platform with Google user credentials.

  Obtains access credentials for your user account via a web-based authorization
  flow. When this command completes successfully, it sets the active account
  in the current configuration to the account specified. If no configuration
  exists, it creates a configuration named default.

  If valid credentials for an account are already available from a prior
  authorization, the account is set to active without rerunning the flow.

  Use `gcloud auth list` to view credentialed accounts.

  If you'd rather authorize without a web browser but still interact with
  the command line, use the `--no-browser` flag. To authorize without
  a web browser and non-interactively, create a service account with the
  appropriate scopes using the
  [Google Cloud Console](https://console.cloud.google.com) and use
  `gcloud auth activate-service-account` with the corresponding JSON key file.

  In addition to Google user credentials, authorization using workload identity
  federation, workforce identity federation, or service account keys is also
  supported.

  For authorization with external accounts or service accounts, the
  `--cred-file` flag must be specified with the path
  to the workload identity credential configuration file or service account key
  file (JSON).

  Login with workload and workforce identity federation is also supported in
  both gsutil and bq. This command is the recommended way of using external
  accounts.

  For more information on workload identity federation, see:
  [](https://cloud.google.com/iam/docs/workload-identity-federation).

  For more information on workforce identity federation, see:
  [](https://cloud.google.com/iam/docs/workforce-identity-federation).

  For more information on authorization and credential types, see:
  [](https://cloud.google.com/sdk/docs/authorizing).

  ## EXAMPLES

  To obtain access credentials for your user account, run:

    $ {command}

  To obtain access credentials using workload or workforce identity federation,
  run:

    $ {command} --cred-file=/path/to/configuration/file

  To obtain access credentials using a browser-based sign-in flow with workforce
  identity federation, run:

    $ {command} --login-config=/path/to/configuration/file
  Fc                 h   | j                  dddd       | j                  ddddd	
       | j                  ddd       | j                  ddd       | j                  ddd       | j                  dddd       | j                  ddddd       | j                  ddd       | j                  dd       | j                  dd t        j                  t        j                  j
                  j                        !       t        j                  |        | j                  j                  d"       y#)$zSet args for gcloud auth.z
--activate
store_trueTzSet the new account to active.)actiondefaulthelpz--do-not-activatestore_falseactivatezTHIS ARGUMENT NEEDS HELP TEXT.)r?   desthiddenrA   z--briefzMinimal user output.)r?   rA   z--forcezRRe-run the web authorization flow even if the given account has valid credentials.z--enable-gdrive-accesszEnable Google Drive access.z--update-adcFa  Write the obtained credentials to the well-known location for Application Default Credentials (ADC). Run $ gcloud auth application-default --help to learn more about ADC. Any credentials previously generated by `gcloud auth application-default login` will be overwritten.--add-quota-project-to-adczRead the project from gcloud's context and write to application default credentials as the quota project. Use this flag only when --update-adc is specified.)r?   r@   rE   rA   r2   ?a=  User account used for authorization. When the account specified has valid credentials in the local credential store these credentials will be re-used, otherwise a new credential will be fetched. If you need to fetch a new credential for an account with valid credentials stored, run the command with the --force flag.)nargsrA   --cred-filezPath to the external account configuration file (workload identity pool, generated by the Cloud Console or `gcloud iam workload-identity-pools create-cred-config`) or service account credential key file (JSON).)rA   z--login-configzPath to the workforce identity federation login configuration file which can be generated using the `gcloud iam workforce-pools create-login-config` command.)rA   r?   noneN)add_argumentr	   StorePropertyr   VALUESauthlogin_config_file
auth_flagsAddRemoteLoginFlagsdisplay_info	AddFormat)parsers    r$   Argsz
Login.Args   s    -	   -   ,-C   !	    *  
 K   $.  
 	   +   = $$Z%6%6%;%;%M%MN   ""6*
!!&)r&   c           
      \   |j                   rA|j                  rt        j                  d      t	        j
                  |j                         }nd}t        |      }t        |      sy|j                   rNt        |||j                  |j                  |j                  |j                  |j                  |j                        S t        ||      rnt!        j"                  |j                  |      }t%        |j                  ||j                  |j                  |j                  |j                  |j                        S t'        |j(                   |j*                   |j,                        }|j,                  rd|j,                  v rt	        j.                  t0        j2                  fddi|}t4        j6                  j8                  j:                  }|r^t=        |d      rR|j:                  |j?                         k7  r5tA        jB                  |      }t	        jD                  |j:                  |       ytG        jH                         }|r|j                  rt        j                  d	      |j                  rt        j                  d
      tG        jJ                  |fi |}tA        jB                  |      }t!        jL                  ||t0        j2                         t%        |||j                  |j                  |j                  |j                  |j                        S t	        j.                  |fddi|}|sytO        jP                  |j                  |      }t!        jL                  |||       t%        |||j                  |j                  |j                  |j                  |j                        S )zRun the authentication command.z4--login-config cannot be specified with --cred-file.Nr1   )no_launch_browser
no_browserremote_bootstrapprovider_nameauth_proxy_redirect_uriz&https://sdk.cloud.google/authcode.htmluniverse_domainzl--update-adc cannot be used in a third party login flow. Please use `gcloud auth application-default login`.zF--add-quota-project-to-adc cannot be used in a third party login flow.z*https://sdk.cloud.google.com/authcode.html))	cred_filelogin_configcalliope_exceptionsConflictingArgumentsExceptionr   GetCredentialsConfigFromFiler/   r%   LoginWithCredFileConfigprojectrC   brief
update_adcadd_quota_project_to_adcr2   r:   r4   r5   LoginAsdictlaunch_browserbrowserrY   #DoInstalledAppBrowserFlowGoogleAuthr    CLOUDSDK_EXTERNAL_ACCOUNT_SCOPESr   rM   corer\   hasattrGetr!   GetExternalAccountIdHandleUniverseDomainConflictworkforce_login_config_utilGetWorkforceLoginConfigDoWorkforceHeadfulLoginStorecommand_auth_utilExtractAndValidateAccount)	selfr-   r]   r.   r   flow_paramsuniverse_domain_propertyr2   rO   s	            r$   Runz	Login.Run  s"   ~~			!??BD 	D88Hiit_Fy)~~$Y%)]]DJJ%)%B%B%)\\3 3 "$/ll4<<?eT\\5$,,ZZ$2O2OQ Q "111||#..0K D4I4I!I;;

1
1"J e
 ",!2!2!7!7!G!G
e./##'?'C'C'EE (<<UC..u/D/DgN3KKM	!??BC 	C 
	&	&!?? 	 *AA
e &::5AgmmE7F$K$KLWeT\\4==$**__d&C&CE E 99 L E 99$,,NGMM%&)7E4<<

??D$A$AC Cr&   N)__name__
__module____qualname____doc___remote_login_with_auth_proxystaticmethodrU   r{    r&   r$   r<   r<   m   s,    8t #(X* X*tRCr&   r<   c           	      F   t        d |D              }|rt        j                  d      t        j                  |       rPt        j
                  |       }t        j                  |      }	t        |d      rg|j                  r[t        |d|	       nMt        j                  |       r"t        j
                  |       }|j                  }	nt        j                  dd      |r||	k7  rt        j                  dd      	 t        j                  |	|d	
      }
|
rK|
j$                  |j$                  k(  r2t'        j(                  d      }t+        j,                  ||	z  d	      }|syt        j.                  ||	|       t1        |	|||||d      S # t         j"                  $ r d}
Y w xY w)a  Login with the provided configuration loaded from --cred-file.

  Args:
    cred_config (Mapping): The configuration dictionary representing the
      credentials. This is loaded from the --cred-file argument.
    scopes (Tuple[str]): The default OAuth scopes to use.
    project (Optional[str]): The optional project ID to activate / persist.
    activate (bool): Whether to set the new account associated with the
      credentials to active.
    brief (bool): Whether to use minimal user output.
    update_adc (bool): Whether to write the obtained credentials to the
      well-known location for Application Default Credentials (ADC).
    add_quota_project_to_adc (bool): Whether to add the quota project to the
      application default credentials file.
    args_account (Optional[str]): The optional ACCOUNT argument. When provided,
      this should match the account ID on the authenticated credentials.

  Returns:
    google.auth.credentials.Credentials: The authenticated stored credentials.

  Raises:
    calliope_exceptions.ConflictingArgumentsException: If conflicting arguments
      are provided.
    calliope_exceptions.InvalidArgumentException: If invalid arguments are
      provided.
  c              3   H   K   | ]  }|t         j                  k7  s|  y wr(   )r   r*   ).0xs     r$   	<genexpr>z*LoginWithCredFileConfig.<locals>.<genexpr>x  s     ?Fqa6+>+>&>Fs   ""zA[--add-quota-project-to-adc] cannot be specified with --cred-fileinteractive_tokeninfo_usernamerI   zROnly external account or service account JSON credential file types are supported.ACCOUNTzThe given account name does not match the account name in the credential file. This argument can be omitted when using credential files.T)r2   r.   prevent_refreshNzw
      You are already authenticated with '%s'.
      Do you wish to proceed and overwrite existing credentials?
      )r   r@   )r.   F)tupler_   r`   r!   r"    CredentialsFromAdcDictGoogleAuthrp   rn   r   setattrauth_service_accountIsServiceAccountConfigservice_account_emailInvalidArgumentExceptionr4   r5   r6   r7   r\   r   r   r   r   ru   rg   )r#   r.   rc   rC   rd   re   rf   args_accountr   r2   exist_credsr   answers                r$   rb   rb   [  s   : ?F??&

;
;KM M22;?!BB;OE#88?G um$):):e*G422;? AA+NE))G

6
6	 
 lg-

6
6	 
 ,,>K [00E4I4IIoo 
 G &&w/@$OF	--wv.	%(E:u	MM 
		 Ks   :F F F c                    t        |d      r t        j                  |j                  |        t	        ||       |rt        ||       |s|S t        j                  t        j                  j                  j                  |        |r8t        j                  t        j                  j                  j                  |       |st        j                  |      rdj                  |       }nt        j                  |      rdj                  |       }n_t        j                   |      rdj                  |       }n8t        j"                  |      rdj                  |       }ndj                  |       }t$        j&                  j)                  dj                  |t        j                  j                  j                  j+                                      |S )	zLogs in with valid credentials.r\   z;Authenticated with external account credentials for: [{0}].z@Authenticated with external account user credentials for: [{0}].z:Authenticated with service account credentials for: [{0}].zKAuthenticated with external account authorized user credentials for: [{0}].zYou are now logged in as [{0}].z
{confirmation_msg}
Your current project is [{project}].  You can change this setting by running:
  $ gcloud config set project PROJECT_ID
)confirmation_msgrc   )rn   r   rq   r\   _ValidateADCFlags
_UpdateADCr   PersistPropertyrM   rm   r2   rc   c_credsIsExternalAccountCredentialsr9    IsExternalAccountUserCredentialsIsServiceAccountCredentials*IsExternalAccountAuthorizedUserCredentialsr   statuswritero   )r2   r   rc   rC   rd   re   rf   r   s           r$   rg   rg     s    U%&**5+@+@'JJ 89u./	LZ..33;;WEz0055==wG	++E2
G
N
N  
	1	1%	86'?  
	,	,U	3
F
M
M  
	;	;E	Bw  ;AA'JJJ	BBH&-%%**22668 CI C:; 
,r&   c                 (   t        j                         }t        j                  | |       t        j                         }|rR||k7  rLd}t        j                         }|r|dj	                  |      z   }t
        j                  j                  |       yyy)z0Updates the ADC json with the credentials creds.z4
Application Default Credentials (ADC) were updated.z
'{}' is added to ADC as the quota project.
To just update the quota project in ADC, use $gcloud auth application-default set-quota-project.N)rv   GetADCAsJsonWriteGcloudCredentialsToADCGetQuotaProjectFromADCr9   r   r   Print)r   rf   old_adc_jsonnew_adc_jsonadc_msgquota_projects         r$   r   r     s    "//1,//7OP"//1,ll2EG%<<>M3396-3HJg JJW 3\r&   c                 :    | s|rt        j                  dd      y y )NrF   zO--add-quota-project-to-adc cannot be specified without specifying --update-adc.)r_   r   )re   rf   s     r$   r   r     s*    	0

6
6$	  1r&   )2r   
__future__r   r   r   r   googlecloudsdk.api_lib.authr   r!   r   r   r   r   googlecloudsdk.callioper	   r
   r   r_   googlecloudsdk.command_lib.authrv   r   rP   r   rr   googlecloudsdk.corer   r   r   googlecloudsdk.core.consoler   googlecloudsdk.core.credentialsr   r   r   r   r6   r   r   r   r4   r%   r/   r:   UniverseCompatibleCommandr<   rb   rg   r   r   r   r&   r$   <module>r      s     / &  '  Q O 9 + ( E J ? a & # * 2 < B J 8 <"J" jCDLL jC jCZMN`(V r&   