
    3                     z   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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	j&                   e	j(                  e	j*                  j,                  e	j*                  j.                  e	j*                  j0                         G d de	j2                                      Zy)zUpdate a key.    )absolute_import)division)unicode_literals)
exceptions)base)flags)maps)resource_args)labels_utilc                   >    e Zd ZdZed        Zd Zd Zd Zd Z	d Z
y)	Updatea  Update a key.

  1. Update the rotation schedule for the given key.

  Updates the rotation schedule for the given key. The schedule
  automatically creates a new primary version for the key
  according to `next-rotation-time` and `rotation-period` flags.

  Flag `next-rotation-time` must be in ISO 8601 or RFC3339 format,
  and `rotation-period` must be in the form INTEGER[UNIT], where units
  can be one of seconds (s), minutes (m), hours (h) or days (d).

  Key rotations performed manually via `update-primary-version` and the
  version `create` do not affect the stored `next-rotation-time`.

  2. Remove the rotation schedule for the given key with
  `remove-rotation-schedule` flag.

  3. Update/Remove the labels for the given key with `update-labels` and/or
  `remove-labels` flags.

  4. Update the primary version for the given key with `primary-version` flag.

  5. Update the Key Access Justifications policy for the given key with
  `allowed-access-reasons` flag to allow specified reasons. The key must be
  enrolled in Key Access Justifications to use this flag.

  6. Remove the Key Access Justifications policy for the given key with
  `remove-key-access-justifications-policy` flag. The key must be enrolled in
  Key Access Justifications to use this flag.

  7. Update the Key Access Justifications policy for the given key with
  `allowed_access_reasons` flag to allow zero access reasons. This effectively
  disables the key, because a policy is configured to reject all access reasons.
  The key must be enrolled in Key Access Justifications to use this flag.

  ## EXAMPLES

  The following command sets a 30 day rotation period for the key
  named `frodo` within the keyring `fellowship` and location `global`
  starting at the specified time:

    $ {command} frodo \
        --location=global \
        --keyring=fellowship \
        --rotation-period=30d \
        --next-rotation-time=2017-10-12T12:34:56.1234Z

  The following command removes the rotation schedule for the key
  named `frodo` within the keyring `fellowship` and location `global`:

    $ {command} frodo \
        --location=global \
        --keyring=fellowship \
        --remove-rotation-schedule

  The following command updates the labels value for the key
  named `frodo` within the keyring `fellowship` and location `global`. If the
  label key does not exist at the time, it will be added:

    $ {command} frodo \
        --location=global \
        --keyring=fellowship \
        --update-labels=k1=v1

  The following command removes labels k1 and k2 from the key
  named `frodo` within the keyring `fellowship` and location `global`:

    $ {command} frodo \
        --location=global \
        --keyring=fellowship \
        --remove-labels=k1,k2

  The following command updates the primary version for the key
  named `frodo` within the keyring `fellowship` and location `global`:

    $ {command} frodo \
        --location=global \
        --keyring=fellowship \
        --primary-version=1

  The following command updates the default algorithm for the key named `frodo`
  within the keyring `fellowship` and location `global`, assuming the key
  originally has purpose 'asymmetric-encryption' and algorithm
  'rsa-decrypt-oaep-2048-sha256':

    $ {command} frodo \
        --location=global \
        --keyring=fellowship \
        --default-algorithm=rsa-decrypt-oaep-4096-sha256

  The following command updates the Key Access Justifications policy for the key
  named `frodo` within the keyring ``fellowship'' and location ``global'' to
  allow only ``customer-initiated-access'' and
  ``google-initiated-system-operation'':

    $ {command} frodo \
        --location=global \
        --keyring=fellowship \
        --allowed-access-reasons=customer-initiated-access,google-initiated-system-operation

  The following command removes the Key Access Justifications policy for the key
  named `frodo` within the keyring ``fellowship'' and location ``global'', which
  results in all access reasons being allowed:

    $ {command} frodo \
        --location=global \
        --keyring=fellowship \
        --remove-key-access-justifications-policy

  The following command updates the Key Access Justifications policy for the key
  named `frodo` within the keyring ``fellowship'' and location ``global'' to
  allow only zero access reasons, effectively disabling the key:

    $ {command} frodo \
        --location=global \
        --keyring=fellowship \
        --allowed-access-reasons=
  c                    t        j                  | dd       t        j                  |        t        j                  |        t        j
                  |        t        j                  | d       t        j                  |        t        j                  |        t        j                  |        t        j                  |        y )NTkeyzto make primary)r
   AddKmsKeyResourceArgForKMSr   AddRotationPeriodFlagAddNextRotationTimeFlagAddRemoveRotationScheduleFlagAddCryptoKeyPrimaryVersionFlagr   AddUpdateLabelsFlagsAddDefaultAlgorithmFlagAddAllowedAccessReasonsFlag*AddRemoveKeyAccessJustificationsPolicyFlag)parsers    lib/surface/kms/keys/update.pyArgszUpdate.Args   s    ,,VT5A	'	!!&)	''/	((1BC$$V,	!!&)	%%f-	44V<    c                    g }t         j                  j                  |      }|j                         r|j	                  d       |j
                  rO|j                  s|j                  rt        j                  d      |j	                  d       |j	                  d       |j                  r|j	                  d       |j                  r|j	                  d       |j                  r|j	                  d       |j                  !|j                  rt        j                  d      |j                  |j                  r|j	                  d       |j                  s|st        j                  d      |S )	Nlabelsz=You cannot set and remove rotation schedule at the same time.rotationPeriodnextRotationTimezversionTemplate.algorithmzNYou cannot set and remove a Key Access Justifications policy at the same time.keyAccessJustificationsPolicya  At least one of --primary-version or --update-labels or --remove-labels or --clear-labels or --rotation-period or --next-rotation-time or --remove-rotation-schedule or --default-algorithm or --allowed-access-reasons or --remove-key-access-justifications-policy must be specified.)r   DiffFromUpdateArgsMayHaveUpdatesappendremove_rotation_schedulerotation_periodnext_rotation_timekms_exceptionsArgumentErrordefault_algorithmallowed_access_reasons'remove_key_access_justifications_policyprimary_versionUpdateError)selfargsfields_to_updatelabels_diffs       r   ProcessFlagszUpdate.ProcessFlags   sR   ""11$7K!!#h'$$			!8!8**KM 	M./01./019:##/88(( 
 	##/77=> (8&&I  r   c                 ~   t        j                         }t        j                         }|j                  j                  j                         }|j                  |j                         |j                  |j                              }	 |j                  j                  |      }|S # t        j                  $ r Y y w xY w)N)cryptoKeyVersionId)name$updateCryptoKeyPrimaryVersionRequest)cloudkms_baseGetClientInstanceGetMessagesModuleCONCEPTSr   ParseFCloudkmsProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersionRequestRelativeName$UpdateCryptoKeyPrimaryVersionRequestr.   &projects_locations_keyRings_cryptoKeysUpdatePrimaryVersionapitools_exceptions	HttpError)r0   r1   clientmessagescrypto_key_refreqresponses          r   rB   zUpdate.UpdatePrimaryVersion   s    ,,.F..0H]]&&,,.N

Y
Y((*99#'#7#7 : 9 Z ;C>>SS
h
 O (( s   	B& &B<;B<c           	         t        j                         }t        j                         }|j                  j                  j                         }t        j                  j                  |      j                  |j                  j                  |j                        }|j                  r|j                  }n|j                  }|j                  |j                         |j                  |            }	dj!                  |      |	_        t%        j&                  ||	j(                         t%        j*                  ||	j(                         |j,                  rt.        j0                  |j2                     }
|j,                  |
vrJt5        j6                  dj9                  |j,                  |j2                  dj!                  |
                  |j;                  t.        j<                  j?                  |j,                              |	j(                  _         |jB                  s t%        jD                  ||	j(                         	 |jF                  jI                  |	      }|S # tJ        jL                  $ r Y y w xY w)N)r   )r7   	cryptoKey,zzUpdate failed: Algorithm {algorithm} is not valid. Here are the valid algorithm(s) for purpose {purpose}: {all_algorithms}z, )	algorithmpurposeall_algorithms)rM   )'r9   r:   r;   r<   r   r=   r   r"   r#   Apply	CryptoKeyLabelsValuer   needs_update7CloudkmsProjectsLocationsKeyRingsCryptoKeysPatchRequestr?   join
updateMaskr   SetNextRotationTimerK   SetRotationPeriodr+   r	   VALID_ALGORITHMS_MAPrN   r)   r/   formatCryptoKeyVersionTemplateALGORITHM_MAPPERGetEnumForChoiceversionTemplater-    SetKeyAccessJustificationsPolicyrA   PatchrC   rD   )r0   r1   
crypto_keyr2   rE   rF   rG   labels_update
new_labelsrH   valid_algorithmsrI   s               r   UpdateOtherszUpdate.UpdateOthers   s   ,,.F..0H]]&&,,.N$$33D9??&&
(9(9;M !! ''j$$j

J
J((*$$ %  K  C XX./CN	dCMM2	D#--022:3E3EF			'7	7((IIO00"**#yy)9: JP J<= 	= '/&G&G))::$$& 'H ''cmm# 77,,T3==A>>DDSIh O (( s   <I I/.I/c                     d}|s|dz  }n|j                   r|dz  }|s$|dj                  dj                  |            z  }n%|r#|dj                  dj                  |            z  }t        j                  |      )a  Handles various errors that may occur during any update stage.

    Never returns without an exception.

    Args:
      args: Input arguments.
      set_primary_version_succeeds: True if the primary verion is updated
        successfully.
      other_updates_succeed: True if all other updates (besides primary verions)
        is updated successfully.
      fields_to_update: A list of fields to be updated.

    Raises:
      ToolException: An exception raised when there is error during any update
      stage.
    zAn Error occurred:z) Failed to update field 'primaryVersion'.z$ Field 'primaryVersion' was updated.z  Failed to update field(s) '{}'.z', 'z Field(s) '{}' were updated.)r.   rZ   rU   r)   r/   )r0   r1   set_primary_version_succeedsother_updates_succeedr2   errs         r   HandleErrorszUpdate.HandleErrors  s    $ C'	88c				33c 	/66
++&
') )c		+22
++&
') )c

$
$S
))r   c                    | j                  |      }t        j                         }t        j                         }|j                  j
                  j                         }|j                  j                  |j                  |j                                     }d}|j                  r| j                  |      }|r|}nd}d}	|r| j                  |||      }|r|}nd}	|r|	s| j                  |||	|       y|S )z<Updates the relevant fields (of a CryptoKey) from the flags.)r7   TFN)r4   r9   r:   r;   r<   r   r=   rA   Get5CloudkmsProjectsLocationsKeyRingsCryptoKeysGetRequestr?   r.   rB   re   rj   )
r0   r1   r2   rE   rF   rG   ra   rg   rI   rh   s
             r   Runz
Update.Run/  s    ((. ,,.F..0H]]&&,,.N>>BBFF,,. 	G 	01J
 $( **40h	
',$ !""45EFh	
 %'/D
:-/?A r   N)__name__
__module____qualname____doc__staticmethodr   r4   rB   re   rj   rn    r   r   r   r      s8    
vp 	= 	=*X$(T*>$r   r   N)rr   
__future__r   r   r   apitools.base.pyr   rC   googlecloudsdk.api_lib.cloudkmsr   r9   googlecloudsdk.calliopegooglecloudsdk.command_lib.kmsr)   r   r	   r
   $googlecloudsdk.command_lib.util.argsr   UniverseCompatibleReleaseTracksReleaseTrackALPHABETAGAUpdateCommandr   rt   r   r   <module>r      s     &  ' > A ( G 0 / 8 < T..33T5F5F5I5IpT p pr   