
    8                        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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rSrS r S r!\RD                  " \RF                  RH                  5      \RJ                   " S S\RL                  5      5       5       r'g)zCreate a certificate.    )absolute_import)division)unicode_literals)cryptokeyversions)base)certificate_utils)request_utils)
exceptions)deps)flags)key_generation)	pem_utils)resource_args)labels_util)concept_parsers)presentation_specs)log)filesNa7  The path where the generated private key file should be written (in PEM format).

Note: possession of this key file could allow anybody to act as this certificate's
subject. Please make sure that you store this key file in a secure location at all
times, and ensure that only authorized users have access to it.c                      [         R                  " U 5      $ ! [         R                  [        [        4 a&    [
        R                  " SR                  U 5      5      ef = f)Nz&Could not read provided CSR file '{}'.)r   ReadFileContentsErrorOSErrorIOErrorr
   BadFileExceptionformat)csr_files    ,lib/surface/privateca/certificates/create.py_ReadCsrr   .   sS    !!(++
++w	( 

%
%077A s
    AAc                      U /U-   n[         R                  " U[        R                  " U5      5        g ! [         R                  [
        [        4 a&    [        R                  " SR                  U5      5      ef = f)Nz$Could not write certificate to '{}'.)
r   WriteFileContentsr   PemChainForOutputr   r   r   r
   r   r   )pem_certissuing_chain	cert_file	pem_chains       r   _WritePemChainr&   7   si    
]*I	Iy'B'B9'MN
++w	( 

%
%.55i@ s
   14 AA9c                   `    \ rS rSrSr\S 5       r\S 5       rS r	\S 5       r
S rS rS	 rS
rg)CreateA   aB  Create a new certificate.

## EXAMPLES

To create a certificate using a CSR:

    $ {command} frontend-server-tls \
      --issuer-pool=my-pool --issuer-location=us-west1 \
      --csr=./csr.pem \
      --cert-output-file=./cert.pem \
      --validity=P30D

To create a certificate using a client-generated key:

    $ {command} frontend-server-tls \
      --issuer-pool=my-pool --issuer-location=us-west1 \
      --generate-key \
      --key-output-file=./key \
      --cert-output-file=./cert.pem \
      --dns-san=www.example.com \
      --use-preset-profile=leaf_server_tls
c                    U R                  SSSS9n[        R                  " SSSS9R                  U5        [        R                  " SS	S
SSS9R                  U5        [        R
                  " U SSS5        [        R                  " U 5        U R                  SSSS9nUR                  SS9n[        R                  " SSSS9R                  U5        [        R                  " SSSS
S9R                  U5        UR                  SS9nUR                  SSSS9nUR                  SS9n[        R                  " SSSSSSS9R                  U5        [        R                  " S[        SS9R                  U5        [        R                  " SS SS9R                  U 5        UR                  S!SS9n[        R                  " U5        UR                  SS"S#9n[        R                  " USS$S%9  [        R                  " U5        [        R                  " U 5        S&n	[        R                  " [        R                   " U	["        R$                  " U	[&        R)                  5       /5      S'SS(9[        R                   " S)["        R*                  " S*5      S+SSS,9[        R                   " S-["        R,                  " 5       S.US/9/S0S1/0S29R                  U 5        U R.                  R1                  S35        g )4NTz Certificate persistence options.)mutexrequiredhelpz--cert-output-fileznThe path where the resulting PEM-encoded certificate chain file should be written (ordered from leaf to root).F)r-   r,   z--validate-onlyzIf this flag is set, the certificate resource will not be persisted and the returned certificate will not contain the pem_certificate field.
store_true)r-   actiondefaultr,   certificateP30Dz30 dayszCertificate generation method.z4To issue a certificate from a CSR use the following:)r-   --csrz4A PEM-encoded certificate signing request file path.z--rdn-sequence-subjectzyIf this value is set then the issued certificate will use the subject found in the CSR preserving the exact RDN sequence.)r-   hiddenr/   z?Alternatively, you may describe the certificate and key to use.z]To describe the key that will be used for this certificate, use one of the following options.z.To generate a new key pair, use the following:--generate-keyzTUse this flag to have a new RSA-2048 private key securely generated on your machine.store_const)r-   r/   constr0   r,   z--key-output-filez--cazThe name of an existing certificate authority to use for issuing the certificate. If omitted, a certificate authority will be will be chosen from the CA pool by the service on your behalf.z&The subject names for the certificate.z1The x509 configuration used for this certificate.)r+   r-   r   )is_ca_commanddefault_max_chain_lengthCERTIFICATEa5  The name of the certificate to issue. If the certificate ID is omitted, a random identifier will be generated according to the following format: {YYYYMMDD}-{3 random alphanumeric characters}-{3 random alphanumeric characters}. The certificate ID is not required when the issuing CA pool is in the DevOps tier.)r,   
--templatecertificate_templateaE  The name of a certificate template to use for issuing this certificate, if desired. A template may overwrite parts of the certificate request, and the use of certificate templates may be required and/or regulated by the issuing CA Pool's CA Manager. The specified template must be in the same location as the issuing CA Pool.)r,   prefixes--kms-key-versionz5An existing KMS key version backing this certificate.)groupz--template.locationzCERTIFICATE.issuer-location)command_level_fallthroughszyaml(certificateDescription))	add_groupr   ArgumentAddToParserr   AddValidityFlagr   AddCreateLabelsFlags_KEY_OUTPUT_HELPAddSubjectFlagsAddInlineX509ParametersFlagsAddUsePresetProfilesFlagAddSubjectKeyIdFlagr   ConceptParserr   ResourcePresentationSpecr   CreateCertResourceSpecr(   !_GenerateCertificateIdFallthrough%CreateCertificateTemplateResourceSpecCreateKmsKeyVersionResourceSpecdisplay_info	AddFormat)
parserpersistence_groupcert_generation_group	csr_groupnon_csr_group	key_groupkey_generation_groupsubject_groupx509_parameters_groupcert_args
             r   ArgsCreate.Args[   s?   ((T(J )  	MM>  k#$MM& 
 k#$	&-C$$V,",,T(H -  &//C 0 I 	MML k)MM J  k))33N 4 M '',	 ( I %..= /  	MM* 
 k&'MM"2Tk&'MMI  k&!++5 , M 
-()33L 4  
&&UQ 
""#89	f%H!!7744vGGIJ#  77CC**  77#==?G	9"	
H "$A#B$
I'N k& !!"@A    c                 L   ^  ST l         U 4S jn[        R                  " USSSS9$ )NFc                  <   > ST l         [        R                  " 5       $ )NT)id_fallthrough_was_usedr   GenerateCertId)clss   r   FallthroughFn?Create._GenerateCertificateIdFallthrough.<locals>.FallthroughFn   s    $(c!--//r_   z<certificate id will default to an automatically generated id)functionhintactiveplural)rb   r   Fallthrough)rd   re   s   ` r   rN   (Create._GenerateCertificateIdFallthrough   s1    "'C0 K	 r_   c                     UR                  S5      (       a/  UR                  S5      (       a  [        R                  " SS/S5      e[        R                  " US5        g)z Validates the command-line args.use_preset_profiletemplatez--use-preset-profiler;   zZTo create a certificate, please specify either a preset profile or a certificate template.kms_key_versionN)IsSpecifiedr
   OneOfArgumentsRequiredExceptionr   %ValidateResourceIsCompleteIfSpecified)selfargss     r   _ValidateArgsCreate._ValidateArgs   sW    ,--$2B2B:2N2N66!<
0+  77>OPr_   c                 8   / nU R                   (       d  UR                  S5        UR                  S5      (       a  UR                  S5        U(       aH  SR                  U5      n[	        U5      S:X  a  SOSn[
        R                  " SR                  X4S95        g	g	)
zNPrints warnings if certain command-line args are used for an unpersisted cert.zcertificate IDlabelsz,    waswerez{names} {verb} specified but will not be used since the issuing CA pool is in the DevOps tier, which does not expose certificate lifecycle.)namesverbN)rb   appendrq   joinlenr   warningr   )rd   ru   unused_argsr}   r~   s        r    _PrintWarningsForUnpersistedCert'Create._PrintWarningsForUnpersistedCert  s     K&&)*!!"ii$e+&!+Ud	kk##)66#A r_   c                    UR                   R                  R                  5       nUR                  (       a;  [        R
                  " S5      u  p4[        R                  " UR                  U5        U$ U(       aV  [        R                  " U5      n[        R                  (       a  [        UR                  5      $ [        UR                  S5      $ [        R                  " / SQS5      e)z]Fetches the public key associated with a non-CSR certificate request, as UTF-8 encoded bytes.i   zutf-8)r3   r5   r>   zTo create a certificate, please specify either a CSR, the --generate-key flag to create a new key, or the --kms-key-version flag to use an existing KMS key.)CONCEPTSrp   Parsegenerate_keyr   	RSAKeyGenExportPrivateKeykey_output_filer   GetPublicKeysixPY2bytespemr
   rr   )rt   ru   rp   private_key
public_keypublic_key_responses         r   _GetPublicKeyCreate._GetPublicKey  s    mm3399;O . 8 8 >k%%d&:&:KH	-::?K WW #''
( (,,g6 66
:D r_   c                    U R                  U5      nU R                  R                  5       nU R                  R                  5       Ul        X4R                  l        U R                  R                  R                  R                  UR                  l        [        R                  " U5      Ul        [        R                  " USS9Ul        [        R                  " X R                  5      Ul        U$ )NF)r8   )r   messagesCertificateConfig	PublicKey	publicKeykeyFormatValueValuesEnumPEMr   r   ParseSubjectFlagssubjectConfigParseX509Parameters
x509ConfigParseSubjectKeyIdsubjectKeyId)rt   requestru   r   configs        r   _GenerateCertificateConfig!Create._GenerateCertificateConfig5  s    ##D)J]],,.F}}..0F%"mm55KKOOF 2248F11$eLF11$FFMr_   c                 Z   [         R                  " SS9U l        [         R                  " SS9U l        U R                  U5        UR                  R                  R                  5       n[        R                  " XR                  R                  R                  5      nU R                  R                  5       nU R                  R                  5       Ul        UR                  5       Ul        [         R"                  " U5      UR                  l        X4R                  l        UR)                  5       R+                  5       Ul        [.        R0                  " 5       Ul        UR4                  Ul        UR9                  S5      (       a  UR:                  Ul        UR                  R>                  R                  5       nU(       aP  UR@                  UR@                  :w  a  [B        RD                  " SS5      eUR+                  5       UR                  l#        URH                  (       ao  [K        URH                  5      UR                  l&        URN                  (       a9  U R                  R                  RP                  RR                  UR                  l*        O U RW                  XA5      UR                  l,        U R                  RZ                  R]                  U5      nUR4                  (       a  U$ SnUR^                  (       a  USRa                  UR^                  5      -  nO[\        Rc                  U5        URd                  (       aI  USRa                  URf                  5      -  n[i        URd                  URj                  URf                  5        US	-  n[l        Rn                  Rq                  U5        g )
Nv1)api_versioncar;   zMThe certificate template must be in the same location as the issuing CA Pool.zCreated Certificatez [{}]z and saved it to [{}].)9privateca_baseGetClientInstanceclientGetMessagesModuler   rv   r   r1   r   r   ParseCreateArgsCertificateLabelsValue:PrivatecaProjectsLocationsCaPoolsCertificatesCreateRequestNamecertificateIdr   ParseValidityFlaglifetimery   ParentRelativeNameparentr	   GenerateRequestId	requestIdvalidate_onlyvalidateOnlyrq   r   issuingCertificateAuthorityIdro   locationsIdr
   InvalidArgumentExceptioncertificateTemplatecsrr   pemCsrrdn_sequence_subjectSubjectModeValueValuesEnumRDN_SEQUENCEsubjectModer   r   'projects_locations_caPools_certificatesr(   namer   r   pemCertificatecert_output_filer&   pemCertificateChainr   statusPrint)rt   ru   cert_refry   r   template_refr1   status_messages           r   Run
Create.RunA  s    22tDDK"44FDMt}}((..0H((mm''33F
 	PPR  --335G$MMOG#(#:#:4#@G !'__&335GN%779G--G.2ggg+==))//1L		!	!X%9%9	911
 	

 1=0I0I0Kg-xx#+DHH#5g 		"	"MM%%@@MM 	' $(#B#B
$g  ++EELLK
 *N{'7'788n--d3!!/66t7L7LMMn

$
$

)
)


 cNJJ^$r_   )r   r   N)__name__
__module____qualname____firstlineno____doc__staticmethodr]   classmethodrN   rv   r   r   r   r   __static_attributes__ r_   r   r(   r(   A   s^    . NB NB`  Q  "6
E%r_   r(   )(r   
__future__r   r   r   googlecloudsdk.api_lib.cloudkmsr    googlecloudsdk.api_lib.privatecar   r   r   r	   googlecloudsdk.callioper
    googlecloudsdk.calliope.conceptsr   $googlecloudsdk.command_lib.privatecar   r   r   r   $googlecloudsdk.command_lib.util.argsr   (googlecloudsdk.command_lib.util.conceptsr   r   googlecloudsdk.corer   googlecloudsdk.core.utilr   r   rF   r   r&   ReleaseTracksReleaseTrackGADefaultUniverseOnlyCreateCommandr(   r   r_   r   <module>r      s     &  ' = C > : ( . 1 6 ? : > < D G # * 
C  D%%(()C%T C%  *C%r_   