def Await(operation, progress_message): """Waits for operation to complete while displaying in-progress indicator. Args: operation: The Operation resource. progress_message: The message to display with the in-progress indicator. Returns: The resource that is the result of the operation. Raises: OperationError: if the operation did not complete successfully """ if operation.done: if operation.error: raise OperationError(operation.error.message) return operation.response operation_ref = GetOperationRef(operation) poller = waiter.CloudOperationPollerNoResources( base.GetClientInstance().projects_locations_operations) try: return waiter.WaitFor(poller, operation_ref, progress_message) except waiter.TimeoutError: raise OperationTimeoutError( 'Requested action timed out. Please run the describe command on your resource to see if changes were successful, or try again in a few minutes.' )
def SetUp(self): self.messages = base.GetMessagesModule() self.client = mock.Client( client_class=apis.GetClientClass('privateca', 'v1alpha1'), real_client=base.GetClientInstance()) self.client.Mock() self.addCleanup(self.client.Unmock)
def Run(self, args): cert_ref = Revoke.ParseCertificateResource(args) if not console_io.PromptContinue( message='You are about to revoke Certificate [{}]'.format( cert_ref.RelativeName()), default=True): log.status.Print('Aborted by user.') return reason = flags_v1.ParseRevocationChoiceToEnum(args.reason) client = privateca_base.GetClientInstance(api_version='v1') messages = privateca_base.GetMessagesModule(api_version='v1') certificate = client.projects_locations_caPools_certificates.Revoke( messages. PrivatecaProjectsLocationsCaPoolsCertificatesRevokeRequest( name=cert_ref.RelativeName(), revokeCertificateRequest=messages.RevokeCertificateRequest( reason=reason, requestId=request_utils.GenerateRequestId()))) revoke_time = times.ParseDateTime( certificate.revocationDetails.revocationTime) log.status.Print('Revoked certificate [{}] at {}.'.format( certificate.name, times.FormatDateTime(revoke_time, tzinfo=times.LOCAL)))
def SetUp(self): self.messages = base.GetMessagesModule() self.client = mock.Client( client_class=base.GetClientClass(), real_client=base.GetClientInstance()) self.client.Mock() self.addCleanup(self.client.Unmock)
def Run(self, args): client = privateca_base.GetClientInstance(api_version='v1') messages = privateca_base.GetMessagesModule(api_version='v1') template_ref = args.CONCEPTS.certificate_template.Parse() template_name = template_ref.RelativeName() if not console_io.PromptContinue( message='You are about to delete the certificate template [{}]' .format(template_ref.RelativeName()), default=True): log.status.Print('Aborted by user.') return operation = client.projects_locations_certificateTemplates.Delete( messages. PrivatecaProjectsLocationsCertificateTemplatesDeleteRequest( name=template_name, requestId=request_utils.GenerateRequestId())) operations.Await(operation, 'Deleting Certificate Template', api_version='v1') log.status.Print( 'Deleted Certificate Template [{}].'.format(template_name))
def Run(self, args): cert_ref = _ParseCertificateResource(args) reason = flags.ParseRevocationChoiceToEnum(args.reason) client = privateca_base.GetClientInstance() messages = privateca_base.GetMessagesModule() operation = client.projects_locations_certificateAuthorities_certificates.Revoke( messages. PrivatecaProjectsLocationsCertificateAuthoritiesCertificatesRevokeRequest( name=cert_ref.RelativeName(), revokeCertificateRequest=messages.RevokeCertificateRequest( reason=reason, requestId=request_utils.GenerateRequestId()))) response = operations.Await(operation, 'Revoking Certificate.') certificate = operations.GetMessageFromResponse( response, messages.Certificate) log.status.Print('Publishing a new Certificate Revocation List.') client.projects_locations_certificateAuthorities.PublishCrl( messages. PrivatecaProjectsLocationsCertificateAuthoritiesPublishCrlRequest( name=cert_ref.Parent().RelativeName(), publishCertificateRevocationListRequest=messages. PublishCertificateRevocationListRequest())) revoke_time = times.ParseDateTime( certificate.revocationDetails.revocationTime) log.status.Print('Revoked certificate [{}] at {}.'.format( certificate.name, times.FormatDateTime(revoke_time, tzinfo=times.LOCAL)))
def Run(self, args): client = privateca_base.GetClientInstance('v1') messages = privateca_base.GetMessagesModule('v1') ca_pool_ref = args.CONCEPTS.ca_pool.Parse() issuance_policy = flags_v1.ParseIssuancePolicy(args) publishing_options = flags_v1.ParsePublishingOptions(args) tier = flags_v1.ParseTierFlag(args) labels = labels_util.ParseCreateArgs(args, messages.CaPool.LabelsValue) new_ca_pool = messages.CaPool(issuancePolicy=issuance_policy, publishingOptions=publishing_options, tier=tier, labels=labels) operation = client.projects_locations_caPools.Create( messages.PrivatecaProjectsLocationsCaPoolsCreateRequest( caPool=new_ca_pool, caPoolId=ca_pool_ref.Name(), parent=ca_pool_ref.Parent().RelativeName(), requestId=request_utils.GenerateRequestId())) ca_pool_response = operations.Await(operation, 'Creating CA Pool.', api_version='v1') ca_pool = operations.GetMessageFromResponse(ca_pool_response, messages.CaPool) log.status.Print('Created CA Pool [{}].'.format(ca_pool.name))
def Run(self, args): client = privateca_base.GetClientInstance() messages = privateca_base.GetMessagesModule() ca_ref = args.CONCEPTS.certificate_authority.Parse() current_ca = client.projects_locations_certificateAuthorities.Get( messages. PrivatecaProjectsLocationsCertificateAuthoritiesGetRequest( name=ca_ref.RelativeName())) resource_args.CheckExpectedCAType( messages.CertificateAuthority.TypeValueValuesEnum.SUBORDINATE, current_ca) operation = client.projects_locations_certificateAuthorities.Restore( messages. PrivatecaProjectsLocationsCertificateAuthoritiesRestoreRequest( name=ca_ref.RelativeName(), restoreCertificateAuthorityRequest=messages. RestoreCertificateAuthorityRequest( requestId=request_utils.GenerateRequestId()))) operations.Await(operation, 'Restoring Subordinate CA') log.status.Print('Restored Subordinate CA [{}].'.format( ca_ref.RelativeName()))
def Run(self, args): client = privateca_base.GetClientInstance() messages = privateca_base.GetMessagesModule() ca_ref = args.CONCEPTS.issuer.Parse() if ca_ref: parent_resource = ca_ref.RelativeName() elif args.IsSpecified('issuer_location'): parent_resource = 'projects/{}/locations/{}/certificateAuthorities/-'.format( properties.VALUES.core.project.GetOrFail(), args.issuer_location) elif args.IsSpecified('issuer'): raise exceptions.InvalidArgumentException('--issuer-location', 'location must be specified.') else: parent_resource = 'projects/{}/locations/-/certificateAuthorities/-'.format( properties.VALUES.core.project.GetOrFail()) request = messages.PrivatecaProjectsLocationsCertificateAuthoritiesCertificatesListRequest( parent=parent_resource, orderBy=common_args.ParseSortByArg(args.sort_by), pageSize=args.page_size, filter=args.filter) return list_pager.YieldFromList( client.projects_locations_certificateAuthorities_certificates, request, field='certificates', limit=args.limit, batch_size_attribute='pageSize')
def Run(self, args): client = privateca_base.GetClientInstance(api_version='v1') messages = privateca_base.GetMessagesModule(api_version='v1') ca_ref = args.CONCEPTS.certificate_authority.Parse() current_ca = client.projects_locations_caPools_certificateAuthorities.Get( messages. PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesGetRequest( name=ca_ref.RelativeName())) resource_args.CheckExpectedCAType( messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED, current_ca, version='v1') operation = client.projects_locations_caPools_certificateAuthorities.Undelete( messages. PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesUndeleteRequest( name=ca_ref.RelativeName(), undeleteCertificateAuthorityRequest=messages. UndeleteCertificateAuthorityRequest( requestId=request_utils.GenerateRequestId()))) operations.Await(operation, 'Undeleting Root CA', api_version='v1') log.status.Print('Undeleted Root CA [{}].'.format( ca_ref.RelativeName()))
def SetUp(self): self.parser = util.ArgumentParser() properties.VALUES.core.project.Set(_DEFAULT_PROJECT) properties.VALUES.privateca.location.Set(_DEFAULT_LOCATION) # Child classes can set this to include irrelevant but required args. self.other_args = [] self.mock_client = api_mock.Client( privateca_base.GetClientClass(), real_client=privateca_base.GetClientInstance()) self.mock_client.Mock() self.addCleanup(self.mock_client.Unmock) self.messages = privateca_base.GetMessagesModule() self.source_ca = self.messages.CertificateAuthority( type=self.messages.CertificateAuthority.TypeValueValuesEnum. SELF_SIGNED, lifetime='10s', config=self.messages.CertificateConfig( reusableConfig=self.messages.ReusableConfigWrapper( reusableConfig='my-reusable-config'), subjectConfig=self.messages.SubjectConfig( commonName='foobar', subject=self.messages.Subject(organization='foo'))), issuingOptions=self.messages.IssuingOptions(), keySpec=self.messages.KeyVersionSpec( cloudKmsKeyVersion=_KmsKeyVersion()), gcsBucket='my-bucket', ) self.request = self.messages.PrivatecaProjectsLocationsCertificateAuthoritiesGetRequest( name=_CA_NAME)
def Run(self, args): client = privateca_base.GetClientInstance(api_version='v1') messages = privateca_base.GetMessagesModule(api_version='v1') location = args.location if args.IsSpecified('location') else '-' ca_pool_id = args.pool if args.IsSpecified('pool') else '-' if location == '-' and ca_pool_id != '-': raise exceptions.InvalidArgumentException( '--location', 'If a pool id is specified, you must also specify the location of that pool.' ) parent_resource = 'projects/{}/locations/{}/caPools/{}'.format( properties.VALUES.core.project.GetOrFail(), location, ca_pool_id) request = messages.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesListRequest( parent=parent_resource, filter='type:SELF_SIGNED', orderBy=common_args.ParseSortByArg(args.sort_by)) return list_pager.YieldFromList( client.projects_locations_caPools_certificateAuthorities, request, field='certificateAuthorities', limit=args.limit, batch_size_attribute='pageSize', batch_size=args.page_size, get_field_func=response_utils.GetFieldAndLogUnreachable)
def Run(self, args): client = privateca_base.GetClientInstance() messages = privateca_base.GetMessagesModule() ca_ref = args.CONCEPTS.certificate_authority.Parse() if not console_io.PromptContinue( message='You are about to delete Certificate Authority [{}]'. format(ca_ref.RelativeName()), default=True): log.status.Print('Aborted by user.') return current_ca = client.projects_locations_certificateAuthorities.Get( messages. PrivatecaProjectsLocationsCertificateAuthoritiesGetRequest( name=ca_ref.RelativeName())) resource_args.CheckExpectedCAType( messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED, current_ca) operation = client.projects_locations_certificateAuthorities.Delete( messages. PrivatecaProjectsLocationsCertificateAuthoritiesDeleteRequest( name=ca_ref.RelativeName(), requestId=request_utils.GenerateRequestId())) operations.Await(operation, 'Deleting Root CA') log.status.Print('Deleted Root CA [{}].'.format(ca_ref.RelativeName()))
def GetCertificateBySerialNum(ca_ref, serial_num): """Obtains a certificate by serial num by filtering all certs in a CA. Args: ca_ref: The resource reference to the certificate authority. serial_num: The serial number to lookup the certificate by. Returns: The certificate message of the corresponding serial number. Ignores duplicate certificates. Raises: exceptions.InvalidArgumentError if there were no certificates with the specified ca and serial number. """ cert_filter = 'certificate_description.subject_description.hex_serial_number:{}'.format( serial_num) client = base.GetClientInstance() messages = base.GetMessagesModule() response = client.projects_locations_certificateAuthorities_certificates.List( messages. PrivatecaProjectsLocationsCertificateAuthoritiesCertificatesListRequest( parent=ca_ref.RelativeName(), filter=cert_filter)) if not response.certificates: raise exceptions.InvalidArgumentException( 'serial number', 'The serial number specified does not exist under the certificate authority [{}]]' .format(ca_ref.RelativeName())) return response.certificates[0]
def ValidateIssuingCA(ca_name): """Checks that a CA is valid to be issuing Certificate Authority for a subordinate. Args: ca_name: The resource name of the issuing Certificate Authority. Raises: InvalidArgumentException if the CA does not exist or is not enabled. """ try: client = privateca_base.GetClientInstance() messages = privateca_base.GetMessagesModule() ca = client.projects_locations_certificateAuthorities.Get( messages.PrivatecaProjectsLocationsCertificateAuthoritiesGetRequest( name=ca_name)) if ca.state != messages.CertificateAuthority.StateValueValuesEnum.ENABLED: raise exceptions.InvalidArgumentException( '--issuer', 'The issuing Certificate Authority [{}] is not in ENABLED state. Please enable it and try again.' .format(ca_name)) except apitools_exceptions.HttpNotFoundError: raise exceptions.InvalidArgumentException( '--issuer', 'The issuing Certificate Authority [{}] was not found. Please verify this information is correct and try again.' .format(ca_name))
def Run(self, args): client = privateca_base.GetClientInstance() messages = privateca_base.GetMessagesModule() ca_ref = args.CONCEPTS.certificate_authority.Parse() current_ca = client.projects_locations_certificateAuthorities.Get( messages. PrivatecaProjectsLocationsCertificateAuthoritiesGetRequest( name=ca_ref.RelativeName())) resource_args.CheckExpectedCAType( messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED, current_ca) ca_to_update, update_mask = update_utils.UpdateCAFromArgs( args, current_ca.labels) operation = client.projects_locations_certificateAuthorities.Patch( messages. PrivatecaProjectsLocationsCertificateAuthoritiesPatchRequest( name=ca_ref.RelativeName(), certificateAuthority=ca_to_update, updateMask=','.join(update_mask), requestId=request_utils.GenerateRequestId())) return operations.Await(operation, 'Updating Root CA.')
def Run(self, args): client = privateca_base.GetClientInstance('v1') messages = privateca_base.GetMessagesModule('v1') cert_template_ref = args.CONCEPTS.certificate_template.Parse() flags_v1.ValidateIdentityConstraints(args) new_cert_template = messages.CertificateTemplate( predefinedValues=flags_v1.ParsePredefinedValues(args), identityConstraints=flags_v1.ParseIdentityConstraints(args), passthroughExtensions=flags_v1.ParseExtensionConstraints(args), description=args.description if args.IsSpecified('description') else None) operation = client.projects_locations_certificateTemplates.Create( messages. PrivatecaProjectsLocationsCertificateTemplatesCreateRequest( parent=cert_template_ref.Parent().RelativeName(), certificateTemplateId=cert_template_ref.Name(), certificateTemplate=new_cert_template, requestId=request_utils.GenerateRequestId())) cert_template_response = operations.Await( operation, 'Creating Certificate Template.', api_version='v1') cert_template = operations.GetMessageFromResponse( cert_template_response, messages.CertificateTemplate) log.status.Print('Created Certificate Template [{}].'.format( cert_template.name))
def Run(self, args): client = privateca_base.GetClientInstance(api_version='v1') messages = privateca_base.GetMessagesModule(api_version='v1') display_info = args.GetDisplayInfo() defaults = resource_projection_spec.ProjectionSpec( symbols=display_info.transforms, aliases=display_info.aliases) client_filter, server_filter = filter_rewrite.BackendFilterRewrite( ).Rewrite( args.filter, defaults=defaults) log.info('original_filter=%r, client_filter=%r, server_filter=%r', args.filter, client_filter, server_filter) # Overwrite client filter used by gcloud. args.filter = client_filter parent = args.CONCEPTS.issuer_pool.Parse() request = messages.PrivatecaProjectsLocationsCaPoolsCertificatesListRequest( parent=parent.RelativeName(), orderBy=common_args.ParseSortByArg(args.sort_by), filter=server_filter) return list_pager.YieldFromList( client.projects_locations_caPools_certificates, request, field='certificates', limit=args.limit, batch_size_attribute='pageSize', batch_size=args.page_size, get_field_func=response_utils.GetFieldAndLogUnreachable)
def Run(self, args): client = privateca_base.GetClientInstance(api_version='v1') messages = privateca_base.GetMessagesModule(api_version='v1') ca_ref = args.CONCEPTS.certificate_authority.Parse() ca_name = ca_ref.RelativeName() current_ca = client.projects_locations_caPools_certificateAuthorities.Get( messages. PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesGetRequest( name=ca_name)) resource_args.CheckExpectedCAType( messages.CertificateAuthority.TypeValueValuesEnum.SUBORDINATE, current_ca, version='v1') ca_to_update, update_mask = update_utils_v1.UpdateCAFromArgs( args, current_ca.labels) # Patch is the gcloud client lib method to update a CA. operation = client.projects_locations_caPools_certificateAuthorities.Patch( messages. PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesPatchRequest( name=ca_name, certificateAuthority=ca_to_update, updateMask=','.join(update_mask), requestId=request_utils.GenerateRequestId())) return operations.Await(operation, 'Updating Subordinate CA.', api_version='v1')
def Run(self, args): client = privateca_base.GetClientInstance() messages = privateca_base.GetMessagesModule() ca_ref = args.CONCEPTS.certificate_authority.Parse() pem_cert, pem_chain = self._ParsePemChainFromFile(args.pem_chain) operation = client.projects_locations_certificateAuthorities.Activate( messages. PrivatecaProjectsLocationsCertificateAuthoritiesActivateRequest( name=ca_ref.RelativeName(), activateCertificateAuthorityRequest=messages. ActivateCertificateAuthorityRequest( pemCaCertificate=pem_cert, pemCaCertificateChain=pem_chain))) operations.Await(operation, 'Activating Certificate Authority.') log.status.Print('Creating the initial Certificate Revocation List.') client.projects_locations_certificateAuthorities.PublishCrl( messages. PrivatecaProjectsLocationsCertificateAuthoritiesPublishCrlRequest( name=ca_ref.RelativeName(), publishCertificateRevocationListRequest=messages. PublishCertificateRevocationListRequest()))
def SetUp(self): properties.VALUES.core.project.Set('fake-project') self.messages = privateca_base.GetMessagesModule() self.mock_client = api_mock.Client( client_class=privateca_base.GetClientClass(), real_client=privateca_base.GetClientInstance()) self.mock_client.Mock() self.addCleanup(self.mock_client.Unmock)
def Run(self, args): client = privateca_base.GetClientInstance(api_version='v1') messages = privateca_base.GetMessagesModule(api_version='v1') ca_ref = args.CONCEPTS.certificate_authority.Parse() return client.projects_locations_caPools_certificateAuthorities.Fetch( messages. PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesFetchRequest( name=ca_ref.RelativeName()))
def _CheckRequestTypeHook(resource_ref, expected_type, version='v1beta1'): """Do a get on a CA resource and check its type against expected_type.""" client = base.GetClientInstance(api_version=version) messages = base.GetMessagesModule(api_version=version) certificate_authority = client.projects_locations_certificateAuthorities.Get( messages.PrivatecaProjectsLocationsCertificateAuthoritiesGetRequest( name=resource_ref.RelativeName())) resource_args.CheckExpectedCAType(expected_type, certificate_authority)
def Run(self, args): client = privateca_base.GetClientInstance() messages = privateca_base.GetMessagesModule() ca_ref = args.CONCEPTS.certificate_authority.Parse() return client.projects_locations_certificateAuthorities.GetCsr( messages. PrivatecaProjectsLocationsCertificateAuthoritiesGetCsrRequest( name=ca_ref.RelativeName()))
def Run(self, args): """Runs the command.""" self.client = privateca_base.GetClientInstance() self.messages = privateca_base.GetMessagesModule() project = constants.PREDEFINED_REUSABLE_CONFIG_PROJECT location = _GetLocation(args) # TODO(b/170409946): Revert to ListLatestReusableConfigs after IAM issue. return self.ListKnownReusableConfigs(project, location)
def Run(self, args): self.client = privateca_base.GetClientInstance() self.messages = privateca_base.GetMessagesModule() cert_ref = args.CONCEPTS.certificate.Parse() issuing_ca = self._GetIssuingCa(cert_ref.Parent().RelativeName()) if issuing_ca.tier == self.messages.CertificateAuthority.TierValueValuesEnum.DEVOPS: CreateBeta._ValidateArgsForDevOpsIssuer(args) labels = labels_util.ParseCreateArgs( args, self.messages.Certificate.LabelsValue) request = self.messages.PrivatecaProjectsLocationsCertificateAuthoritiesCertificatesCreateRequest( ) request.certificate = self.messages.Certificate() request.certificateId = cert_ref.Name() request.certificate.lifetime = flags.ParseValidityFlag(args) request.certificate.labels = labels request.parent = cert_ref.Parent().RelativeName() request.requestId = request_utils.GenerateRequestId() # TODO(b/12345): only show this for Enterprise certs. create_utils.PrintBetaResourceDeletionDisclaimer('certificates') if args.csr: request.certificate.pemCsr = _ReadCsr(args.csr) elif args.generate_key: request.certificate.config = self._GenerateCertificateConfig( request, args, cert_ref.locationsId) else: # This should not happen because of the required arg group, but protects # in case of future additions. raise exceptions.OneOfArgumentsRequiredException( ['--csr', '--generate-key'], ('To create a certificate, please specify either a CSR or the ' '--generate-key flag to create a new key.')) certificate = self.client.projects_locations_certificateAuthorities_certificates.Create( request) status_message = 'Created Certificate' # DevOps certs won't have a name. if certificate.name: status_message += ' [{}]'.format(certificate.name) if args.IsSpecified('cert_output_file'): status_message += ' and saved it to [{}]'.format( args.cert_output_file) _WritePemChain(certificate.pemCertificate, certificate.pemCertificateChain, args.cert_output_file) status_message += '.' log.status.Print(status_message)
def GetSupportedLocations(): """Gets a list of supported Private CA locations for the current project.""" client = base.GetClientInstance() messages = base.GetMessagesModule() project = properties.VALUES.core.project.GetOrFail() response = client.projects_locations.List( messages.PrivatecaProjectsLocationsListRequest( name='projects/{}'.format(project))) return map(lambda location: location.locationId, response.locations)
def Run(self, args): """Runs the command.""" reusable_config = args.CONCEPTS.reusable_config.Parse() client = privateca_base.GetClientInstance() messages = privateca_base.GetMessagesModule() return client.projects_locations_reusableConfigs.Get( messages.PrivatecaProjectsLocationsReusableConfigsGetRequest( name=reusable_config.RelativeName()))
def Run(self, args): client = privateca_base.GetClientInstance(api_version='v1') messages = privateca_base.GetMessagesModule(api_version='v1') certificate_ref = args.CONCEPTS.certificate.Parse() # Attempt to get the certificate certificate = client.projects_locations_caPools_certificates.Get( messages.PrivatecaProjectsLocationsCaPoolsCertificatesGetRequest( name=certificate_ref.RelativeName())) # The certificate exists, update it return self._RunUpdate(client, messages, certificate, args)
def SetUp(self): self.mock_client = api_mock.Client( privateca_base.GetClientClass(), real_client=privateca_base.GetClientInstance()) self.mock_client.Mock() self.addCleanup(self.mock_client.Unmock) self.messages = privateca_base.GetMessagesModule() self.test_cert = files.ReadFileContents( self.Resource('tests', 'unit', 'surface', 'privateca', 'test_data', 'test_cert.pem')) self.parent_cert = ('----BEGIN CERTIFICATE----\ntest\n----END ' 'CERTIFICATE----')