
    9Q                     d   S r SSKJr  SSKJr  SSKJr  SSKJr  SSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKrSSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJ r   SSKJ!r!  SSKJ"r"  SSK#J$r$  SSK%J&r&  SSK'J(r(  SSK)J*r+  SSK,J-r-  SSK.J/r/  SSK0r0SSK1J2r2  SSK3J4r4  SSK5J6r6  SSK7J8r8  SSK3J9r9  SSKJ:r:  S r;S!r<\Rz                  R|                  \Rz                  R~                  \Rz                  R                  \Rz                  R                  \Rz                  R                  /rCS"rDS# rE " S$ S%\+R                  \+R                  5      rH " S& S'\/R                  5      rJS9S( jrKS) rLS9S* jrMS+ rNS, rOS- rPS. rQS/ rRS0 rSS1 rTS2 rUS3 rVS4 rWS5 rXS6 rYS7 rZS8 r[g):z3Credentials logic for JSON CloudApi implementation.    )absolute_import)print_function)division)unicode_literalsN)credentials_lib)
exceptions)config)	CredTypes)CommandException)ImpersonationCredentials)NoOpCredentials)	constants)system_util)GetFriendlyConfigFilePaths)GetCredentialStoreFilename)GetGceCredentialCacheFilename)GetGcsJsonApiVersion)UTF8)WrappedCredentials)_helpers)baseAuthorizedHttp)service_account)
HAS_CRYPTO)devshell)ServiceAccountCredentials)reauth_creds)multiprocess_file_storage)BytesIOz)https://accounts.google.com/o/oauth2/authz#https://oauth2.googleapis.com/token
notasecretc                 "    [        U [        5      $ N)
isinstanceP12Credentials)credentialss    -platform/gsutil/gslib/gcs_json_credentials.pyisP12Credentialsr(   O   s    	K	00    c                   H    \ rS rSrSrS r\S 5       rS r\	S	S j5       r
Srg)
PKCS12SignerR   z%Signer for a p12 service account key.c                     Xl         g r#   _key)selfkeys     r'   __init__PKCS12Signer.__init__U   s    Ir)   c                     g r#    )r0   s    r'   key_idPKCS12Signer.key_idZ   s    r)   c                     [         R                  " U5      nSSKJn  U R                  R                  UUR                  UR                  5      $ )Nr   )_cryptography_rsa)r   to_bytesgoogle.auth.cryptr9   r/   sign_PADDING_SHA256)r0   messager9   s      r'   r<   PKCS12Signer.sign^   s?    (G399>>""!!# #r)   Nc                     AS U 5       u  p4SSK Jn   UR                  X45      u  n  nU " U5      $ !   [        S5      e= f)Nc              3   N   #    U  H  n[         R                  " U5      v   M     g 7fr#   )r   r:   ).0ks     r'   	<genexpr>+PKCS12Signer.from_string.<locals>.<genexpr>i   s     F+QH--a00+s   #%r   )pkcs12z<Unable to load the keyfile, Invalid password or PKCS12 data.),cryptography.hazmat.primitives.serializationrG   load_key_and_certificatesr   )clskey_stringsr6   
key_stringpasswordrG   r1   _s           r'   from_stringPKCS12Signer.from_stringf   sN    F+FJC]22:Hic1aXo][\\s   1 >r.   r#   )__name__
__module____qualname____firstlineno____doc__r2   propertyr6   r<   classmethodrO   __static_attributes__r5   r)   r'   r+   r+   R   s9    -
  # 	] 	]r)   r+   c                   8    \ rS rSrSrSrS r\ SS j5       rSr	g)	r%   s   a  google-auth service account credentials  for p12 keys.
p12 keys are not supported by the google-auth service account credentials.
gsutil uses oauth2client to support p12 key users. Since oauth2client was
deprecated and bundling it is security concern, we decided to support p12
in gsutil codebase. We prefer not adding it to the google-auth library
because p12 is not supported from the beginning by google-auth. GCP strongly
suggests users to use the JSON format. gsutil has to support it to not
break users.
)service_account_email	token_uriscopesc                     [        XS9$ )N)httpr   )r0   r_   s     r'   	authorizeP12Credentials.authorize   s    $**r)   Nc                    U=(       d    [         n[        R                  X45      nU R                   Vs/ s H  oUU;  d  M
  UPM     nnU(       a)  [	        SR                  SR                  U5      5      5      eU " U40 UD6nU$ s  snf )NzMissing fields: {}.z, )#GOOGLE_OAUTH2_DEFAULT_FILE_PASSWORDr+   rO   _REQUIRED_FIELDSr   formatjoin)rJ   rL   rM   kwargssignerfmissing_fieldscredss           r'   %from_service_account_pkcs12_keystring4P12Credentials.from_service_account_pkcs12_keystring   s    
 >>H%%z&<=F!$!5!5I!5A&a!5NI299
))N
#% & &!&!EL Js   	BBr5   r#   )
rQ   rR   rS   rT   rU   rd   r`   rW   rl   rX   r5   r)   r'   r%   r%   s   s.     F+  6: r)   r%   c                 d     [         R                  " X40 UD6$ ! [         a    [        S5      ef = f)zCCreates a service account from a p12 key and handles import errors.zapyca/cryptography is not available. Either install it, or please consider using the .json keyfile)r%   rl   ImportErrorr   )rL   rM   rg   s      r'   CreateP12ServiceAccountrp      sI    q??( &( (	 qnq qqs    /c                    U/n[        U [        R                  5      (       a  UR                  U R                  5        GO>[        U [
        5      (       a  UR                  U R                  5        [        U SS5      (       a  UR                  U R                  5        O[        U SS5      (       a2  UR                  [        R                  " U R                  5      SS 5        O[        U [        R                  R                  5      (       ar  U R                  (       a,  U R                  S:w  a  UR                  U R                  5        OUR                  S5        UR                  U R                   =(       d    S5        [        U SS5      (       a  UR                  U R"                  5        U Vs/ s H  n[$        R&                  " U5      PM     nnS	R)                  U5      $ s  snf )
a  Disambiguates a credential for caching in a credential store.

Different credential types have different fields that identify them.  This
function assembles relevant information in a string to be used as the key for
accessing a credential.  Note that in addition to uniquely identifying the
entity to which a credential corresponds, we must differentiate between two or
more of that entity's credentials that have different attributes such that the
credentials should not be treated as interchangeable, e.g. if they target
different API versions (happens for developers targeting different test
environments), have different private key IDs (for service account JSON
keyfiles), or target different provider token (refresh) URIs.

Args:
  credentials: An OAuth2Credentials object.
  api_version: JSON API version being used.

Returns:
  A string that can be used as the key to identify a credential, e.g.
  "v1-909320924072.apps.googleusercontent.com-1/rEfrEshtOkEn-https://..."
_private_key_idN_private_key_pkcs12   null
noclientidnorefreshtokenr\   -)r$   r   DevshellCredentialsappend
user_emailr   _service_account_emailgetattrrr   base64	b64encoders   oauth2clientclientOAuth2Credentials	client_idrefresh_tokenr\   sixensure_textrf   )r&   api_version	key_partsparts       r'   GetCredentialStoreKeyr      st   6 m)X99::[++,+899[778{-t44 {223	3T	:	:
 v''(G(GH"MN+|22DDEE!6!6&!@{,,-|$[..B2BC [+t,,[**+1:;st$);	)	 <s   / G"c                    U=(       d    [        U5      =(       d
    [        5       U l        [        U R                  [        5      (       a  UR                  S[        5       5        [        U R                  5      (       d  [        U R                  [        5       5      nU R                  R                  [        R                  " [        5       U5      5        Sn[        U R                  [        5      (       d$  U R                  R                  R                  5       nU(       a/  [!        U5      ["        R$                  R&                  :w  a  X@l        gggg)zAHelper to ensure each GCS API client shares the same credentials.zeWARNING: This command is using service account impersonation. All API calls will be executed as [%s].N)_CheckAndGetCredentialsr   r&   r$   r   warn_GetImpersonateServiceAccountr(   r   r   	set_storer   MultiprocessFileStorager   storegettyper   r   r   )apiloggerr&   credential_store_keycached_creds        r'   SetUpJsonCredentialsAndCacher      s	     '$;F$C '$& / !9::
KK	./L/NP
 
#//	*	* 2#//2F2HJOO!99&(*>	@A Kcoo77OO))--/k 	[\00BBB#o 	C 	3 
+r)   c                    / nSn [        5       (       a  UR                  [        R                  5        [	        5       (       a  UR                  [        R
                  5        [        U5      S:  a  [        SU< S[        5       < S35      e[        R                  n[        5       n[        R
                  n[        5       n[        R                  n[        5       n[        R                  n[        5       n[        R                  n[!        5       n[        R"                  n[%        5       nU=(       d&    U=(       d    U=(       d    U=(       d    U=(       d    Un	['        5       (       a"  U	(       a  [        R(                  n[+        X5      $ U	$ ! [,         a  n
U(       a  U R/                  [0        R2                  5      (       a$  U R5                  [6        R8                  " 5       5        U[        R(                  :X  a  U
e[:        R<                  " 5       (       a  U R?                  SU5        e U R?                  SU5        e Sn
A
ff = f)zReturns credentials from the configuration file, if any are present.

Args:
  logger: logging.Logger instance for outputting messages.

Returns:
  OAuth2Credentials object if any valid ones are found, otherwise None.
N   z3You have multiple types of configured credentials (z), which is not supported. One common way this happens is if you run gsutil config to create credentials and later run gcloud auth, and create a second set of credentials. Your boto config path is: z). For more help, see "gsutil help creds".zCYour "%s" credentials are invalid. Please run
  $ gcloud auth loginzYour "%s" credentials are invalid. For more help, see "gsutil help creds", or re-run the gsutil config command (see "gsutil help config").) _HasOauth2UserAccountCredsrz   r
   OAUTH2_USER_ACCOUNT_HasOauth2ServiceAccountCredsOAUTH2_SERVICE_ACCOUNTlenr   r    _GetOauth2UserAccountCredentials#_GetOauth2ServiceAccountCredentialsEXTERNAL_ACCOUNT_GetExternalAccountCredentials EXTERNAL_ACCOUNT_AUTHORIZED_USER,_GetExternalAccountAuthorizedUserCredentialsGCE_GetGceCredsDEVSHELL_GetDevshellCreds_HasImpersonateServiceAccountIMPERSONATION_GetImpersonationCredentials	ExceptionisEnabledForloggingDEBUGdebug	traceback
format_excr   InvokedViaCloudSdkr   )r   configured_cred_typesfailed_cred_type
user_credsservice_account_credsexternal_account_creds&external_account_authorized_user_creds	gce_credsdevshell_credsrk   es              r'   r   r     s    E
!##""9#@#@A$&&""9#C#CD
 !A%  !"<">@A A !4413J 77?A 11;= AA-Y .* }}I ))&(N  S/  S9  S@V  S  [A  S  ESE %&&5"00)%88l	 
 			W]]	+	+Y))+, 
Y44	4))++$%5	7 
 	%&6	8 
1
s   FF 	F 
H?B%H::H?c                  :    [         R                  " SS[        5      $ )NOAuth2provider_token_uri)r	   r   (DEFAULT_GOOGLE_OAUTH2_PROVIDER_TOKEN_URIr5   r)   r'   _GetProviderTokenUrir   U  s    	H2<
> >r)   c                  0    [         R                  " SS5      $ )NCredentialsgs_service_key_filer	   
has_optionr5   r)   r'   r   r   Z  s    			=*?	@@r)   c                  0    [         R                  " SS5      $ )Nr   gs_oauth2_refresh_tokenr   r5   r)   r'   r   r   ^  s    			=*C	DDr)   c                  0    [         R                  " SS5      $ )NGoogleComputer   r   r5   r)   r'   _HasGceCredsr   b  s    			?,=	>>r)   c                      [        5       S;  $ )N)N )r   r5   r)   r'   r   r   f  s    	&	(
	::r)   c                  n    [         R                  " SSS 5      n U (       d  g [        R                  " U 5      $ )Nr   gs_external_account_file)r	   r   r   for_external_account)external_account_filenames    r'   r   r   j  s1    $jj)CTK	"		0	01J	KKr)   c                  n    [         R                  " SSS 5      n U (       d  g [        R                  " U 5      $ )Nr   (gs_external_account_authorized_user_file)r	   r   r   $for_external_account_authorized_user))external_account_authorized_user_filenames    r'   r   r   s  s6    .4jj?/G+	2		@	@/
1 1r)   c                      [         R                  =(       d5    [        R                  " SS[        R
                  R                  S5      5      $ )Nr   gs_impersonate_service_account)CLOUDSDK_AUTH_IMPERSONATE_SERVICE_ACCOUNT)r   IMPERSONATE_SERVICE_ACCOUNTr	   r   osenvironr5   r)   r'   r   r   }  s:    

/
/ C6::5jjnn@A4C Dr)   c                     [        5       (       d  g[        5       n [        R                  " SSS5      n[        R                  " SSS5      n[        R
                  " US5       nUR                  5       nSSS5        Sn WR                  [        5      nSnU(       aR   [        R                  " W5      nS
 H  nXv;  d  M
  [        SU< SU< 35      e   [        R                  " U[         U S9$ [        R                  " SS["        5      n[%        WU[         XS9$ ! , (       d  f       N= f! [         a     Nf = f! [         a    [        S	U-  5      ef = f)zDRetrieves OAuth2 service account credentials for a private key file.Nr   gs_service_client_idr   r   rbFTz/Could not parse JSON keyfile "%s" as valid JSON)r   client_emailprivate_key_idprivate_keyzThe JSON private key file at z% did not contain the required entry: )r]   r\   gs_service_key_file_password)r]   r[   r\   )r   r   r	   r   ioopenreaddecoder   UnicodeDecodeErrorjsonloads
ValueErrorr   r   from_json_keyfile_dictDEFAULT_SCOPESrc   rp   )	r   service_client_idprivate_key_filenameprivate_key_filer   keyfile_is_utf8json_key_dict
json_entrykey_file_passs	            r'   r   r     sZ   	&	(	(
+-jj0FKM3H"M	ww#T*.>"'')K + /	$$T*KO ,jj-m
&
		(-z; < 	<& %;;n8JL L JJ}.L!DFM";nl}  ]  ]= +* 
 		  ,G*+ , ,,s*   "D>D+ D; 
D(+
D87D8;Ec                     [        5       (       d  g[        5       n [        R                  " 5       u  p[        R
                  " SS[        R                  R                  SU5      5      n[        R
                  " SS[        R                  R                  SU5      5      n[        R                  R                  [        R                  R                  /n[        R                  " SUU[        R
                  " SS5      SU SUS	9$ )
zARetrieves OAuth2 service account credentials for a refresh token.Nr   r   OAUTH2_CLIENT_IDclient_secretOAUTH2_CLIENT_SECRETr   r   )r]   )r   r   r   GetGsutilClientIdAndSecretr	   r   r   r   r   ScopesCLOUD_PLATFORMREAUTHr   Oauth2WithReauthCredentials)r   gsutil_client_idgsutil_client_secretr   r   scopes_for_reauth_challenges         r'   r   r     s    	#	%	%
+-,,. )jj;(:<LMO)**jjnn+-ABD- %%y'7'7'>'>! 
	1	1
jj 9:

(
* *r)   c                  
   [        5       (       d  g  [        R                  " [        R                  " SSS5      [        5       S9$ ! [        R                   a)  n S[        U 5      ;   a  S[        U 5      ;   a   S n A g e S n A ff = f)Nr   r   default)service_account_namecache_filenamezservice accountzdoes not exist)	r   r   GceAssertionCredentialsr	   r   r   apitools_exceptionsResourceUnavailableErrorstr)r   s    r'   r   r     st    	

22#ZZ9J(13468 8 
	5	5 
CF"'73q6'A	
s   2A BA=<A==Bc                  d     [         R                  " 5       $ ! [         R                   a     g   e = fr#   )r   ry   NoDevshellServerr5   r)   r'   r   r     s1    
''))		"	" 
	s    //c                     [        U [        5      (       a  g[        [        5       [        R                  R
                  /X5      $ )z?Retrieves temporary credentials impersonating a service accountN)r$   r   r   r   r   r   )r&   r   s     r'   r   r     s=     566
	!"?"A#,#3#3#B#B"C"-
7 7r)   r#   )\rU   
__future__r   r   r   r   r~   r   r   r   r   r   r   apitools.base.pyr   r   r  botor	   gslib.cred_typesr
   gslib.exceptionr   gslib.impersonation_credentialsr   gslib.no_op_credentialsr   gslib.utilsr   r   gslib.utils.boto_utilr   r   r   r   gslib.utils.constantsr   gslib.utils.wrapped_credentialsr   google.authr   r;   r   
crypt_basegoogle_auth_httplib2r   google.oauth2r   r   oauth2client.clientr   oauth2client.contribr   oauth2client.service_accountr   google_reauthr   r   r    0DEFAULT_GOOGLE_OAUTH2_PROVIDER_AUTHORIZATION_URIr   r   r   CLOUD_PLATFORM_READ_ONLYFULL_CONTROL	READ_ONLY
READ_WRITEr   rc   r(   SignerFromServiceAccountMixinr+   r   r%   rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r5   r)   r'   <module>r&     s   : ' %  '    	 	 
  - >  & , D 3 ! # < < ? 6 & >   0 / )  * ) B & :  0 1 * ) ##--!! '3 #1]:$$j&H&H ]B_00 >q:z'$TP
f>
AE?;L1D']T*<

	7r)   