
    4                     j   d 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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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# ejH                  Z% ejL                         rdZ'ndZ' G d de(      Z)y)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                   Z     e Zd ZdZd fd	Zd Zd ZddZd ZddZ	d Z
d	 Zdd
Z xZS )KmsApiz7Wraps calls to the Cloud KMS v1 interface via apitools.c                    t         t        |           || _        t	               | _        t               | _        d| _        t        j                  ddd      | _        t        j                  ddd      }|rd|z   nd| _        | j                  | j                  z   | j                  z   | _        t        | ||	       |d
k\  }|d
k\  }t        j                   | j                  | j                  ||| j"                        | _        t'               | _        | j(                  | j$                  _        t+               | _        | j,                  | j$                  _        t/        | j"                  t0              r| j$                  j3                  dd       yy)a  Performs 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(   zKmsApi.__init__:   s?    
&$ "DK"nDODIDNZZ} 9;DN**]M4@K,7cK'RDN^^dnn4t~~EDM v;GA:KQJL%00T]]6:ii=H>J=A=M=M	ODO %D"&"2"2DOO*,D%)%8%8DOO"$""O4 oo$$
;= 5    c                     t        j                  |      }	 | j                  j                  j	                  |      S # t
        $ r}| j                  ||       Y d }~y d }~ww xY w)N)resourcekey_name)apitools_messages>CloudkmsProjectsLocationsKeyRingsCryptoKeysGetIamPolicyRequestr2   &projects_locations_keyRings_cryptoKeysGetIamPolicy TRANSLATABLE_APITOOLS_EXCEPTIONS_TranslateExceptionAndRaise)r7   r?   requestes       r:   GetKeyIamPolicyzKmsApi.GetKeyIamPolicye   s\     MM$&G=ooDDl7#%+ =
&&q8&<<=s   $= 	A#AA#c                     t        j                  |      }t        j                  ||      }	 | j                  j                  j                  |      S # t        $ r}| j                  ||       Y d }~y d }~ww xY w)N)policy)r=   setIamPolicyRequestr>   )r@   SetIamPolicyRequest>CloudkmsProjectsLocationsKeyRingsCryptoKeysSetIamPolicyRequestr2   rB   SetIamPolicyrD   rE   )r7   r?   rJ   policy_requestrF   rG   s         r:   SetKeyIamPolicyzKmsApi.SetKeyIamPolicyo   so    &::&IN MM$.JG=ooDDl7#%+ =
&&q8&<<=s   $A 	A:A55A:c                 *   t        j                  d|d|d|      }t        j                  ||d|d|      }	 | j                  j                  j                  |       d|d|d|S # t        $ r}|j                  dk7  r Y d}~)d}~ww xY w)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)r@   KeyRing.CloudkmsProjectsLocationsKeyRingsCreateRequestr2   projects_locations_keyRingsCreaterD   status_code)r7   projectkeyring_namelocationkeyring_msgkeyring_create_requestrG   s          r:   CreateKeyRingzKmsApi.CreateKeyRingz   s    & $++	(L*+K 	HH"18(C	E 

oo11889OP 6=h5AC C , 	
#	 
s   %A/ /	B8BBc                 f   t        j                  t         j                  j                  j                        }t        j                  |||      }	 | j
                  j                  j                  |       |j                  d      d|S # t        $ r}|j                  dk7  r Y d}~4d}~ww xY w)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cryptoKeyIdrU   rV   N/z/cryptoKeys/)r@   	CryptoKeyPurposeValueValuesEnumENCRYPT_DECRYPT8CloudkmsProjectsLocationsKeyRingsCryptoKeysCreateRequestr2   rB   rZ   rD   r[   rstrip)r7   keyring_fqnr?   cryptokey_msgcryptokey_create_requestrG   s         r:   CreateCryptoKeyzKmsApi.CreateCryptoKey   s    $ &//##::JJMM 	@@#+	O 
oo<<CC
"$
 "-!3!3C!8(CC , 	
#	 
s   %B 	B0B++B0c                     | j                   j                  t        j                        r.| j                   j	                  dt        j                                | j                  ||      }|r| )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DEBUGr8   	traceback
format_exc_TranslateApitoolsException)r7   rG   r?   translated_exceptions       r:   rE   z"KmsApi._TranslateExceptionAndRaise   sc     {{.
kk8!,,.0;;AEM < O  r;   c                     t        |t        j                        rCt        |dd       r5	 t	        j
                  |j                        }d|v rd|d   v r|d   d   S y y y y # t        $ r Y y w xY w)Ncontenterrormessage)r5   apitools_exceptions	HttpErrorgetattrjsonloadsry   	Exception)r7   
http_errorjson_objs      r:   _GetMessageFromHttpErrorzKmsApi._GetMessageFromHttpError   s    *1;;<	Y	-	ZZ
 2 23( Y(72C%CG$Y// &D  
. =  	
	s   1A 	A+*A+c                     	 |j                   d   }|j                  d      }|dk\  r||d  j                  d      d   }d|z  S y # t        $ r Y y w xY w)Nzwww-authenticatezscope="r   "   zAcceptable scopes: %s)responsefindsplitr   )r7   r   www_authenticate	scope_idxscopess        r:   !_GetAcceptableScopesFromHttpErrorz(KmsApi._GetAcceptableScopesFromHttpError   sr    #,,-?@ #''	2i	a!)*-33C8;&// 
  
s   A A 	AAc                    t        |t        j                        rO| j                  |      }|j                  dk(  rt        |xs d|j                        S |j                  dk(  radt        |      v rt        |xs d|j                        S dt        |      v rt        t        |j                  | j                  |            S |j                  d	k(  rd
t        |      v rt        |xs d|j                        S dt        |      v rt        |xs d|j                        S dt        |      v rt        d|j                        S dt        |      v rt        d|j                        S dt        |      v r+t        t        |j                  | j                  |            S t        |xs |j                  xs ||j                        S |j                  dk(  r%t        |xs |j                  |j                        S |j                  dk(  r|rt        d|z  |j                        S |j                  dk(  rt        ||j                        S t        ||j                        S y)a8  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  rV   zThe key %s already exists.i  N)r5   r|   r}   r   r[   r
   strr	   "_INSUFFICIENT_OAUTH2_SCOPE_MESSAGEr   r{   r   r   r   )r7   rG   r?   r{   s       r:   rv   z"KmsApi._TranslateApitoolsException   sM    !(22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$WQ]]CCgamm<<w 4r;   )NNr   )global)N)__name__
__module____qualname____doc__r(   rH   rP   ra   ro   rE   r   r   rv   __classcell__)r9   s   @r:   r   r   7   s9    ?)=V=	=!CFD@*	(G=r;   r   )*r   
__future__r   r   r   r   r   rr   rt   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   r0   r   r@   gslib.utilsr   gslib.utils.boto_utilr   r   r   r   r}   rD   InvokedViaCloudSdkr   objectr    r;   r:   <module>r      s    E & %  '    >  1 / - 1 , C 3 P T # . 2 , /$7$A$A  !;!!#* %
& %
A=V A=r;   