
    R                     \   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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r,Sr-Sr.\,\-R_                  S5      -   \.R_                  S5      -   S-   r0Sr1Sr2S r3S!\1\2-   \3-   -   r4\" \0\45      r5\" \,\15      r6\" \-\25      r7\" \.\35      r8\+" S"S#/\*" S$5      \*" S%5      S&.S'9r9\+" S"S#/S(\*" S$5      0S'9r: " S) S*\5      r;g)+z/This module provides the kms command to gsutil.    )absolute_import)print_function)division)unicode_literalsN)metrics)AccessDeniedException)ServiceException)Command)CommandArgument)ApiSelector)CommandException)NO_URLS_MATCHED_TARGET)CreateHelpText)KmsApi)PopulateProjectId)Binding)storage_v1_messages)	text_util)NO_MAX)ValidateCMEK)Retry)GcloudStorageFlag)GcloudStorageMapz4
  gsutil kms authorize [-p <proj_id>] -k <kms_key>
zJ
  gsutil kms encryption [(-d|[-k <kms_key>])] [-w] gs://<bucket_name>...
z,
  gsutil kms serviceaccount [-p <proj_id>]

a  
<B>AUTHORIZE</B>
  The authorize sub-command checks that the default (or supplied) project has a
  Cloud Storage service agent created for it, and if not, it creates one. It then
  adds appropriate encrypt/decrypt permissions to Cloud KMS resources such that the
  service agent can write and read Cloud KMS-encrypted objects in buckets associated
  with the service agent's project.

<B>AUTHORIZE EXAMPLES</B>
  Authorize "my-project" to use a Cloud KMS key:

    gsutil kms authorize -p my-project \
        -k projects/key-project/locations/us-east1/keyRings/key-ring/cryptoKeys/my-key

<B>AUTHORIZE OPTIONS</B>
  -k <key>      The path to the KMS key to use. The path has
                the following form:
                ``projects/[project-id]/locations/[location]/keyRings/[key-ring]/cryptoKeys/[my-key]``

  -p <project>  The ID or number of the project being authorized to use the Cloud
                KMS key. If this flag is not included, your
                default project is authorized.

a  
<B>ENCRYPTION</B>
  The encryption sub-command is used to set, display, or clear a bucket's
  default KMS key, which is used to encrypt newly-written objects if no other
  key is specified.

<B>ENCRYPTION EXAMPLES</B>
  Set the default KMS key for my-bucket:

    gsutil kms encryption \
        -k projects/key-project/locations/us-east1/keyRings/key-ring/cryptoKeys/my-key \
        gs://my-bucket

  Show the default KMS key for my-bucket, if one is set:

    gsutil kms encryption gs://my-bucket

  Clear the default KMS key so newly-written objects are not encrypted using it:

    gsutil kms encryption -d gs://my-bucket

  Once you clear the default KMS key, newly-written objects are encrypted with
  Google-managed encryption keys by default.

<B>ENCRYPTION OPTIONS</B>
  -k <key>      Set the default KMS key for my-bucket using the
                full path to the key, which has the following
                form:
                ``projects/[project-id]/locations/[location]/keyRings/[key-ring]/cryptoKeys/[my-key]``

  -w            (used with -k key) Display a warning rather than
                failing if gsutil is unable to verify that
                the specified key contains the correct IAM bindings
                for encryption/decryption. This is useful for
                users that do not have getIamPolicy permission
                but know that the key has the correct IAM policy
                for encryption in the user's project.

  -d            Clear the default KMS key.

a"  
<B>SERVICEACCOUNT</B>
  The serviceaccount sub-command displays the Cloud Storage service agent
  that is used to perform Cloud KMS operations against your default project
  (or a supplied project).

<B>SERVICEACCOUNT EXAMPLES</B>
  Show the service account for my-project:

    gsutil kms serviceaccount -p my-project

<B>SERVICEACCOUNT OPTIONS</B>
  -p <project>  The ID or number of the project whose Cloud Storage service
                agent is being requested. If this flag is not
                included, your default project is used.

aS  
  The kms command is used to configure Google Cloud Storage and Cloud KMS
  resources to support encryption of Cloud Storage objects with
  `Cloud KMS keys
  <https://cloud.google.com/storage/docs/encryption/customer-managed-keys>`_.

  The kms command has three sub-commands that deal with configuring Cloud
  Storage's integration with Cloud KMS: ``authorize``, ``encryption``,
  and ``serviceaccount``.

  Before using this command, read the `prerequisites
  <https://cloud.google.com/storage/docs/encryption/using-customer-managed-keys#prereqs>`_.
  for using Cloud KMS with Cloud Storage.
storagezservice-agentz	--projectz--authorize-cmek)-p-kgcloud_commandflag_mapr   c                   L  ^  \ rS rSrSr\R                  " S\S\SSSS\	R                  /\	R                  / \R                  " S5      // S.S9r\R                  " S/ S	S
\\\\S.S9r\" \\S.0 S9rU 4S jrS r\" \SSS9S 5       rS rS rS rS r S r!S r"S r#S r#Sr$U =r%$ )
KmsCommand   z!Implements of gsutil kms command.kms   zdk:p:wF	authorize
encryptionserviceaccount)
usage_synopsismin_argsmax_argssupported_sub_argsfile_url_okprovider_url_okurls_start_arggs_api_supportgs_default_apiargparse_argumentscommand_helpzConfigure Cloud KMS encryption)	help_namehelp_name_aliases	help_typehelp_one_line_summary	help_textsubcommand_help_text)r'   r)   r   c                   > U R                   S   S:X  a  [        S[        SS/[        S5      [        S5      [        S5      S.S	900 S	9nS
U R                   ;   d  SU R                   ;   a$  UR                  S   =R                  S/-  sl        O5UR                  S   =R                  / SQ-  sl        O[        R
                  n[        TU ]  U5      $ )Nr   r(   r   bucketsz--clear-default-encryption-keyz--default-encryption-key )-dr   -wr   r>   r   update)describezi--format=value[separator=": "](name, encryption.defaultKmsKeyName.yesno(no="No default encryption key."))z--raw)argsr   r   r   r"   gcloud_storage_mapsuperget_gcloud_storage_args)selfrC   	__class__s     %platform/gsutil/gslib/commands/kms.pyrE   "KmsCommand.get_gcloud_storage_args   s    yy||#+
"+Y!7-.NO-.HI-b1	< 68
9 
	ddii/)),7FFK
 	
F 	)),7FF K
 	
F &887*+=>>    c                 <   U R                  5         SU l        S U l        SU l        U R                  (       ad  U R                   HT  u  p#US:X  a  X0l        M  US:X  a  X0l        [        U R                  5        M6  US:X  a	  SU l        ME  US:X  d  MM  SU l        MV     U R                  (       aO  U R                  S:w  d  U R                  (       d.  [        SR                  [        R                  " S	5      5      5      eU R
                  (       d  [        S 5      U l        g g )
NFr   r   r>   Tr?   r(   r   zoThe "-w" option should only be specified for the "encryption" subcommand and must be used with the "-k" option.)CheckArgumentsclear_kms_keykms_keywarn_on_key_authorize_failuresub_opts
project_idr   subcommand_namer   jointextwrapwrapr   )rF   rR   oas       rH   _GatherSubOptionsKmsCommand._GatherSubOptions   s    DDL).D&}}--$!9/$Y,
t||
$$Y#$
$Y/3$
,   )),DLLTYY
--BCD E E ??)$/do rJ      )triestimeout_secsc                 b   U R                   R                  USS9R                  n[        U R                  S9nU R                  R                  SU5         UR                  U5      nU R                  R                  SU5        Sn[        SSU-  /S	9nXuR                  ;  a.  UR                  R                  U5        UR                  X%5        S
nX64$ ! [         aR    U R                  (       a?  [        R                  " SR                  [         R"                  " S5      5      5        US4s $ e f = f)a  Authorizes a project's service account to be used with a KMS key.

Authorizes the Cloud Storage-owned service account for project_id to be used
with kms_key.

Args:
  project_id: (str) Project id string (not number).
  kms_key: (str) Fully qualified resource name for the KMS key.

Returns:
  (str, bool) A 2-tuple consisting of:
  1) The email address for the service account associated with the project,
     which is authorized to encrypt/decrypt with the specified key.
  2) A bool value - True if we had to grant the service account permission
     to encrypt/decrypt with the given key; False if the required permission
     was already present.
gsprovider)loggerzGetting IAM policy for %szCurrent policy is %sFz*roles/cloudkms.cryptoKeyEncrypterDecrypterzserviceAccount:%s)rolemembersTr   a  Warning: Check that your Cloud Platform project's service account has the "cloudkms.cryptoKeyEncrypterDecrypter" role for the specified key. Without this role, you may not be able to encrypt or decrypt objects using the key which will prevent you from uploading or downloading objects.)
gsutil_apiGetProjectServiceAccountemail_addressr   ra   debugGetKeyIamPolicyr   bindingsappendSetKeyIamPolicyr   rO   r   print_to_fdrS   rT   rU   )rF   rQ   rN   service_accountkms_apipolicyadded_new_bindingbindings           rH   _AuthorizeProjectKmsCommand._AuthorizeProject  s)   * oo>>T ? ##0=  DKK(GKK17;&&w/f
kk.7  I!4!F GIg		'w'0 11  		+	+diiMMEFG 	H  ''s   A<C AD.,D.c                    U R                  S5        U R                  (       d'  [        U R                  < SU R                  < S35      eU R                  U R                  U R                  5      u  pU(       a(  [        SU R                  < SU R                  < 35        g	[        SU R                  < SU R                  < S35        g	)
Nr'    z' requires a key to be specified with -kzAuthorized project z" to encrypt and decrypt with key:
zProject z9 was already authorized to encrypt and decrypt with key:
.r   )rX   rN   r   command_namerR   rr   rQ   print)rF   _newly_authorizeds      rH   
_AuthorizeKmsCommand._AuthorizeS  s    ;'<<"//1E1EG H H 00$,,OA__dll, -
  ??DLL: ;rJ   c                     [         R                  R                  5       Ul        [	        S[        U5      R                  S5      -  5        U R                  R                  UR                  US/UR                  S9  g)zClears the defaultKmsKeyName on a Cloud Storage bucket.

Args:
  bucket_metadata: (apitools_messages.Bucket) Metadata for the given bucket.
  bucket_url: (gslib.storage_url.StorageUrl) StorageUrl of the given bucket.
z)Clearing default encryption key for %s.../r(   fieldsr`   N)apitools_messagesBucketEncryptionValuer(   rx   strrstriprd   PatchBucketbucket_namescheme)rF   bucket_metadata
bucket_urls      rH   _EncryptionClearKeyKmsCommand._EncryptionClearKeyb  sm     "3!9!9!I!I!KO	
5
j/
 
 
%& 'OO
 6 6 /(4~)3):):   <rJ   c                    UR                   n X4   SpeU(       a(  [        R
                  " SU< SU R                  < 35        [        R                  R                  U R                  S9Ul	        [        S[        U5      R                  S5      -  5        U R                  R                  UR                  US/UR                   S9  g	! [         a$    U R                  X@R                  5      u  pVXSU'    Nf = f)
aI  Sets defaultKmsKeyName on a Cloud Storage bucket.

Args:
  bucket_metadata: (apitools_messages.Bucket) Metadata for the given bucket.
  bucket_url: (gslib.storage_url.StorageUrl) StorageUrl of the given bucket.
  svc_acct_for_project_num: (Dict[int, str]) Mapping of project numbers to
      their corresponding service account.
FzAuthorized service account z to use key:
)defaultKmsKeyNamez(Setting default KMS key for bucket %s...r~   r(   r   N)projectNumberKeyErrorrr   rN   r   rl   r   r   r   r(   rx   r   r   rd   r   r   r   )rF   r   r   svc_acct_for_project_numbucket_project_numberrm   rz   s          rH   _EncryptionSetKeyKmsCommand._EncryptionSetKeyq  s     ,99H #
95 ( ,dll< = "3!9!9!I!I,, "J "(O	
4
j/
 
 
%& 'OO
 6 6 /(4~)3):):   <  H*.*@*@
+/'o8G45Hs   C +C43C4c                 $  ^ ^ T R                  S5        0 mU U4S jnSnT R                  nU(       d  T R                  5         U H'  nT R                  U5      nU H  nSnU" U5        M     M)     U(       d  [	        [
        [        U5      -  5      eg)Nr(   c                 V  > U R                   nUR                  S:w  a  [        STR                  -  5      eTR                  R                  UR                  SS/UR                  S9nTR                  (       a  TR                  X!5        gTR                  (       a  TR                  X!T5        g[        U5      R                  S5      nUR                  (       aC  UR                  R                  (       a(  [        SU< S	UR                  R                  < 35        g[        S
U-  5        g)z6Set, clear, or get the defaultKmsKeyName for a bucket.r^   z7The %s command can only be used with gs:// bucket URLs.r(   r   r   r   r~   zDefault encryption key for z:
z'Bucket %s has no default encryption key)storage_urlr   r   rw   rd   	GetBucketr   rM   r   rN   r   r   r   r(   r   rx   )blrr   r   bucket_url_stringrF   r   s       rH   _EncryptionForBucket4KmsCommand._Encryption.<locals>._EncryptionForBucket  s   ??j			d	"E 	
 11

 
 0$$ 2 &o 
		  =	7	9 j/005

$
$

$
$
6
6 /"<"<"N"NP 	Q  	7:KKLrJ   FTr   )rX   rB   $RaiseWrongNumberOfArgumentsExceptionGetBucketUrlIterFromArgr   r   list)rF   r   some_matchedurl_argsurl_strbucket_iterbucket_listing_refr   s   `      @rH   _EncryptionKmsCommand._Encryption  s    <(  "!J LyyH
//1009k +
/0 !,  3d8nDEErJ   c                    U R                  5         U R                  (       d  S/U l        U R                  (       a#  U R                   H  u  pUS:X  d  M  X l        M     U R                  (       d  [	        S 5      U l        U R
                  R                  SU R                  5        U R                  R                  U R                  SS9R                  n[        U5        g)Nzgs://r   z'Checking service account for project %sr^   r_   r   )rL   rB   rP   rQ   r   ra   rg   rd   re   rf   rx   )rF   rV   rW   rm   s       rH   _ServiceAccountKmsCommand._ServiceAccount  s    99)di}}--$!9/   ??)$/do 	KK?oo' oo>>$ ? ((5  
/rJ   c                 (    [         R                   " U R                  U R                  R                  5      u  U l        U l        [
        R                  " U R                  S9  U" U 5      $ ! [         R                   a    U R                  5          g f = f)N)rP   )	getoptrB   command_specr-   rP   r   LogCommandParamsGetoptErrorRaiseInvalidArgumentException)rF   funcs     rH   _RunSubCommandKmsCommand._RunSubCommand  sr    +!'
))T&&99";dmTY 6$Z +
((*+s   A'A* *$BBc                     U R                   R                  SS9[        R                  :w  a;  [	        SR                  [        R                  " SU R                  -  5      5      5      eg)(Command entry point for the kms command.r^   r_   r   zThe "%s" command can only be used with the GCS JSON API. If you have only supplied hmac credentials in your boto file, please instead supply a credential type that can be used with the JSON API.N)	rd   GetApiSelectorr   JSONr   rS   rT   rU   rw   )rF   s    rH   
RunCommandKmsCommand.RunCommand  sc    
 %%t%48H8HHTYY
-- (()*+ , , IrJ   c                 V   U R                   R                  SS9[        R                  :w  a;  [	        SR                  [        R                  " SU R                  -  5      5      5      e[        R                  [        R                  [        R                  S.nU R                  R                  S5      U l        U R                  U;   a<  [         R"                  " U R                  /S9  U R%                  XR                     5      $ [	        SU R                  < S	U R                  < S
35      e)r   r^   r_   r   zThe "%s" command can only be used with the GCS JSON API, which cannot use HMAC credentials. Please supply a credential type that is compatible with the JSON API (e.g. OAuth2) in your boto config file.r&   r   )subcommandszInvalid subcommand "z
" for the z	 command.)rd   r   r   r   r   rS   rT   rU   rw   r"   r{   r   r   rB   poprR   r   r   r   )rF   method_for_subcommands     rH   r   r     s    
 %%t%48H8HHTYY
--" %)$5$5678 9 9  ** ,,$44
  99==+D44D,@,@+AB  !67K7K!LMM"22D4E4EG H HrJ   )rB   rM   rN   rQ   rP   rR   rO   )&__name__
__module____qualname____firstlineno____doc__r
   CreateCommandSpec	_SYNOPSISr   r   r   r   MakeNCloudBucketURLsArgumentr   HelpSpec_DETAILED_HELP_TEXT_authorize_help_text_encryption_help_text_serviceaccount_help_text	help_specr   _AUTHORIZE_COMMAND_SERVICEACCOUNT_COMMANDrC   rE   rX   r   r	   rr   r{   r   r   r   r   r   r   __static_attributes____classcell__)rG   s   @rH   r"   r"      s   )**!!&&' %%(EEaHI	," <#+-5) ()3
 ?:0< 		32 42h<<B9v0	+,H HrJ   r"   )<r   
__future__r   r   r   r   r   rT   gslibr   gslib.cloud_apir   r	   gslib.commandr
   gslib.command_argumentr   gslib.cs_api_mapr   gslib.exceptionr   r   gslib.help_providerr   gslib.kms_apir   gslib.project_idr   3gslib.third_party.kms_apitools.cloudkms_v1_messagesr   "gslib.third_party.storage_apitoolsr   r   gslib.utilsr   gslib.utils.constantsr   gslib.utils.encryption_helperr   gslib.utils.retry_utilr   gslib.utils.shim_utilr   r   _AUTHORIZE_SYNOPSIS_ENCRYPTION_SYNOPSIS_SERVICEACCOUNT_SYNOPSISlstripr   _AUTHORIZE_DESCRIPTION_ENCRYPTION_DESCRIPTION_SERVICEACCOUNT_DESCRIPTION_DESCRIPTIONr   r   r   r   r   r   r"    rJ   rH   <module>r      s|   6 & %  '    1 , ! 2 ( , 2 .   . G W ! ( 6 ( 3 2    !#7#>#>t#DD%,,T2359:	 2( V $  77"#$  %Y= %&9&<> &';'>@ *+C+FH  &/, 23  +/, [H [HrJ   