
    4                     t   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	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#  \RH                  r%\RL                  " 5       (       a  Sr'OSr' " S S\(5      r)g)z>JSON gsutil Cloud API implementation for Google Cloud Storage.    )absolute_import)print_function)division)unicode_literalsN)
exceptions)config)AccessDeniedException)BadRequestException)NotFoundException)PreconditionException)ServiceException)SetUpJsonCredentialsAndCache)NoOpCredentials)cloudkms_v1_client)cloudkms_v1_messages)system_util)GetCertsFile)GetMaxRetryDelay)
GetNewHttp)GetNumRetrieszVInsufficient OAuth2 scope to perform this operation. Please re-run `gcloud auth login`zRInsufficient OAuth2 scope to perform this operation. Please re-run `gsutil config`c                   l   ^  \ rS rSrSrSU 4S jjrS rS rSS jrS r	SS jr
S	 rS
 rSS jrSrU =r$ )KmsApi7   z7Wraps calls to the Cloud KMS v1 interface via apitools.c                 $  > [         [        U ]  5         Xl        [	        5       U l        [        5       U l        SU l        [        R                  " SSS5      U l        [        R                  " SSS5      nU(       a  SU-   OSU l        U R                  U R                  -   U R                  -   U l        [        XUS	9  US
:  nUS
:  n[        R                   " U R                  U R                  UUU R"                  S9U l        ['        5       U l        U R(                  U R$                  l        [+        5       U l        U R,                  U R$                  l        [/        U R"                  [0        5      (       a  U R$                  R3                  SS5        gg)zPerforms necessary setup for interacting with Google Cloud KMS.

Args:
  logger: logging.logger for outputting log messages.
  credentials: Credentials to be used for interacting with Cloud KMS
  debug: Debug level for the API implementation (0..3).
zhttps://Credentialsgs_kms_hostzcloudkms.googleapis.comgs_kms_portN: )credentials   )urlhttplog_requestlog_responser    key'AIzaSyDnacJHrKma0048b13sh8cgxNUwulubmJM)superr   __init__loggerr   
certs_filer   r#   	http_baser   get	host_base	host_porturl_baser   apitools_client
CloudkmsV1r    
api_clientr   num_retriesr   max_retry_wait
isinstancer   AddGlobalParam)selfr*   r    debugr   r$   r%   	__class__s           platform/gsutil/gslib/kms_api.pyr)   KmsApi.__init__:   s>    
&$ "K"nDODIDNZZ} 9;DN**]M4@K,7cK'RDN^^dnn4t~~EDM ;GA:KQJL%00T]]6:ii=H>J=A=M=M	ODO %D"&"2"2DOO*,D%)%8%8DOO"$""O44 oo$$
;= 5    c                     [         R                  " US9n U R                  R                  R	                  U5      $ ! [
         a  nU R                  X1S9   S nAg S nAff = f)N)resourcekey_name)apitools_messages>CloudkmsProjectsLocationsKeyRingsCryptoKeysGetIamPolicyRequestr3   &projects_locations_keyRings_cryptoKeysGetIamPolicy TRANSLATABLE_APITOOLS_EXCEPTIONS_TranslateExceptionAndRaise)r8   rA   requestes       r;   GetKeyIamPolicyKmsApi.GetKeyIamPolicye   s]     MMN$&G=ooDDl7#%+ =
&&q&<=s   $; 
AAAc                     [         R                  " US9n[         R                  " XS9n U R                  R                  R                  U5      $ ! [         a  nU R                  XQS9   S nAg S nAff = f)N)policy)r?   setIamPolicyRequestr@   )rB   SetIamPolicyRequest>CloudkmsProjectsLocationsKeyRingsCryptoKeysSetIamPolicyRequestr3   rD   SetIamPolicyrF   rG   )r8   rA   rM   policy_requestrH   rI   s         r;   SetKeyIamPolicyKmsApi.SetKeyIamPolicyo   sn    &::&IN MMN$JG=ooDDl7#%+ =
&&q&<=s   $A 
A2A--A2c                 6   [         R                  " SU< SU< SU< 3S9n[         R                  " UUSU< SU< 3S9n U R                  R                  R                  U5        SU< SU< SU< 3$ ! [         a  nUR                  S:w  a  e  SnAN.SnAff = f)a  Attempts to create the specified keyRing.

Args:
  project: (str) The project id in which to create the keyRing and key.
  keyring_name: (str) The name of the keyRing, e.g. my-keyring. Note
      that this must be unique within the location.
  location: (str) The location in which to create the keyRing. Defaults to
      'global'.

Returns:
  (str) The fully-qualified name of the keyRing, e.g.:
  projects/my-project/locations/global/keyRings/my-keyring

Raises:
  Translated CloudApi exception if we were unable to create the keyRing.
  Note that in the event of a 409 status code (resource already exists) when
  attempting creation, we continue and treat this as a success.
z	projects/z/locations/z
/keyRings/)name)keyRing	keyRingIdparent  N)rB   KeyRing.CloudkmsProjectsLocationsKeyRingsCreateRequestr3   projects_locations_keyRingsCreaterF   status_code)r8   projectkeyring_namelocationkeyring_msgkeyring_create_requestrI   s          r;   CreateKeyRingKmsApi.CreateKeyRingz   s    & $++	(L*+K 	HH"18(C	E 

oo11889OP 6=h5AC C , 	
#	 
s    %A3 3
B=BBc                 d   [         R                  " [         R                  R                  R                  S9n[         R                  " X2US9n U R
                  R                  R                  U5        UR                  S5      < SU< 3$ ! [         a  nUR                  S:w  a  e  SnAN8SnAff = f)a  Attempts to create the specified cryptoKey.

Args:
  keyring_fqn: (str) The fully-qualified name of the keyRing, e.g.
      projects/my-project/locations/global/keyRings/my-keyring.
  key_name: (str) The name of the desired key, e.g. my-key. Note that
      this must be unique within the keyRing.

Returns:
  (str) The fully-qualified name of the cryptoKey, e.g.:
  projects/my-project/locations/global/keyRings/my-keyring/cryptoKeys/my-key

Raises:
  Translated CloudApi exception if we were unable to create the cryptoKey.
  Note that in the event of a 409 status code (resource already exists) when
  attempting creation, we continue and treat this as a success.
)purpose)	cryptoKeycryptoKeyIdrY   rZ   N/z/cryptoKeys/)rB   	CryptoKeyPurposeValueValuesEnumENCRYPT_DECRYPT8CloudkmsProjectsLocationsKeyRingsCryptoKeysCreateRequestr3   rD   r^   rF   r_   rstrip)r8   keyring_fqnrA   cryptokey_msgcryptokey_create_requestrI   s         r;   CreateCryptoKeyKmsApi.CreateCryptoKey   s    $ &//##::JJMM 	@@	A#+	O 
oo<<CC
"$
 "-!3!3C!8(CC , 	
#	 
s   %B
 

B/B**B/c                     U R                   R                  [        R                  5      (       a/  U R                   R	                  S[
        R                  " 5       5        U R                  UUS9nU(       a  Uee )a  Translates an HTTP exception and raises the translated or original value.

Args:
  e: Any Exception.
  key_name: Optional key name in request that caused the exception.

Raises:
  Translated CloudApi exception, or the original exception if it was not
  translatable.
zTranslateExceptionAndRaise: %sr@   )r*   isEnabledForloggingDEBUGr9   	traceback
format_exc_TranslateApitoolsException)r8   rI   rA   translated_exceptions       r;   rG   "KmsApi._TranslateExceptionAndRaise   sf     {{..
kk8!,,.0;;AEM < O  r=   c                     [        U[        R                  5      (       aM  [        USS 5      (       a:   [        R
                  " UR                  5      nSU;   a  SUS   ;   a  US   S   $ g g g g ! [         a     g f = f)Ncontenterrormessage)r6   apitools_exceptions	HttpErrorgetattrjsonloadsr   	Exception)r8   
http_errorjson_objs      r;   _GetMessageFromHttpErrorKmsApi._GetMessageFromHttpError   s    *1;;<<	Y	-	-	ZZ
 2 23( Y(72C%CG$Y// &D  
. =  	
	s   6A. .
A;:A;c                      UR                   S   nUR                  S5      nUS:  a  X#S  R                  S5      S   nSU-  $ g ! [         a     g f = f)Nzwww-authenticatezscope="r   "   zAcceptable scopes: %s)responsefindsplitr   )r8   r   www_authenticate	scope_idxscopess        r;   !_GetAcceptableScopesFromHttpError(KmsApi._GetAcceptableScopesFromHttpError   sp    #,,-?@ #''	2i	a!*-33C8;&// 
  
s   A A 
AAc                    [        U[        R                  5      (       Gad  U R                  U5      nUR                  S:X  a  [        U=(       d    SUR                  S9$ UR                  S:X  ae  S[        U5      ;   a  [        U=(       d    SUR                  S9$ S[        U5      ;   a(  [        [        UR                  U R                  U5      S9$ GOUR                  S	:X  Ga  S
[        U5      ;   a  [        U=(       d    SUR                  S9$ S[        U5      ;   a  [        U=(       d    SUR                  S9$ S[        U5      ;   a  [        SUR                  S9$ S[        U5      ;   a  [        SUR                  S9$ S[        U5      ;   a(  [        [        UR                  U R                  U5      S9$ [        U=(       d    UR                  =(       d    UUR                  S9$ UR                  S:X  a'  [        U=(       d    UR                  UR                  S9$ UR                  S:X  a  U(       a  [        SU-  UR                  S9$ UR                  S:X  a  [        X1R                  S9$ [        X1R                  S9$ g)a  Translates apitools exceptions into their gsutil equivalents.

Args:
  e: Any exception in TRANSLATABLE_APITOOLS_EXCEPTIONS.
  key_name: Optional key name in request that caused the exception.

Returns:
  CloudStorageApiServiceException for translatable exceptions, None
  otherwise.
i  zBad Request)statusi  zLogin RequiredzAccess denied: login required.insufficient_scope)r   bodyi  z7The account for the specified project has been disabledzAccount disabled.z,Daily Limit for Unauthenticated Use Exceededz8Access denied: quota exceeded. Is your project ID valid?zUser Rate Limit Exceededz5Rate limit exceeded. Please retry this request later.zAccess Not ConfiguredzAccess Not Configured. Please go to the Google Cloud Platform Console (https://cloud.google.com/console#/project) for your project, select APIs & services, and enable the Google Cloud KMS API.i  rZ   zThe key %s already exists.i  N)r6   r   r   r   r_   r
   strr	   "_INSUFFICIENT_OAUTH2_SCOPE_MESSAGEr   r   r   r   r   )r8   rI   rA   r   s       r;   r|   "KmsApi._TranslateApitoolsException   sQ    !(2233--a0g	
#	 #7#;m*+--9 	9==Cs1v%&w (H'G./mm= = "SV+ '0]]99!<> > , ==CDAN&w'E2E./mm= =;s1vE&w (C(C./mm= = (3q61&]]$ $ %A.& ]]$ $ "SV+ '0]]99!<> >
 'w'G!))'Gx./mm= ===C !5AIIammLL==CH <x G'(}}6 	6==C$W]]CCgmm<<w 4r=   )
r3   r+   r.   r/   r#   r,   r*   r5   r4   r0   )NNr   )global)N)__name__
__module____qualname____firstlineno____doc__r)   rJ   rS   re   rt   rG   r   r   r|   __static_attributes____classcell__)r:   s   @r;   r   r   7   s?    ?)=V=	=!CFD@*	(G= G=r=   r   )*r   
__future__r   r   r   r   r   rx   rz   apitools.base.pyr   r   botor   gslib.cloud_apir	   r
   r   r   r   gslib.gcs_json_credentialsr   gslib.no_op_credentialsr   gslib.third_party.kms_apitoolsr   r1   r   rB   gslib.utilsr   gslib.utils.boto_utilr   r   r   r   r   rF   InvokedViaCloudSdkr   objectr    r=   r;   <module>r      s    E & %  '    >  1 / - 1 , C 3 P T # . 2 , /$7$A$A  !!##* %
& %
A=V A=r=   