Skip to content

Commit

Permalink
feat(samples): private CA python samples
Browse files Browse the repository at this point in the history
  • Loading branch information
FrodoTheTrue authored Jul 22, 2021
0 parents commit b2b59f0
Show file tree
Hide file tree
Showing 19 changed files with 1,346 additions and 0 deletions.
58 changes: 58 additions & 0 deletions privateca/snippets/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import uuid

import google.auth

import pytest

from create_ca_pool import create_ca_pool
from create_certificate_authority import create_certificate_authority
from delete_ca_pool import delete_ca_pool
from delete_certificate_authority import delete_certificate_authority

PROJECT = google.auth.default()[1]
LOCATION = "europe-west1"
COMMON_NAME = "COMMON_NAME"
ORGANIZATION = "ORGANIZATION"
CA_DURATION = 1000000


def generate_name() -> str:
return "test-" + uuid.uuid4().hex[:10]


@pytest.fixture
def ca_pool():
CA_POOL_NAME = generate_name()

create_ca_pool(PROJECT, LOCATION, CA_POOL_NAME)

yield CA_POOL_NAME

delete_ca_pool(PROJECT, LOCATION, CA_POOL_NAME)


@pytest.fixture
def certificate_authority(ca_pool):
CA_NAME = generate_name()

create_certificate_authority(
PROJECT, LOCATION, ca_pool, CA_NAME, COMMON_NAME, ORGANIZATION, CA_DURATION
)

yield ca_pool, CA_NAME

delete_certificate_authority(PROJECT, LOCATION, ca_pool, CA_NAME)
53 changes: 53 additions & 0 deletions privateca/snippets/create_ca_pool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#!/usr/bin/env python

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START privateca_create_ca_pool]
import google.cloud.security.privateca_v1 as privateca_v1


def create_ca_pool(project_id: str, location: str, ca_pool_name: str) -> None:
"""
Create a Certificate Authority pool. All certificates created under this CA pool will
follow the same issuance policy, IAM policies,etc.,
Args:
project_id: project ID or project number of the Cloud project you want to use.
location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
ca_pool_name: a unique name for the ca pool.
"""

caServiceClient = privateca_v1.CertificateAuthorityServiceClient()

ca_pool = privateca_v1.CaPool(
# Set the tier (see: https://cloud.google.com/certificate-authority-service/docs/tiers).
tier=privateca_v1.CaPool.Tier.ENTERPRISE,
)
location_path = caServiceClient.common_location_path(project_id, location)

# Create the pool request.
request = privateca_v1.CreateCaPoolRequest(
parent=location_path,
ca_pool_id=ca_pool_name,
ca_pool=ca_pool,
)

# Create the CA pool.
operation = caServiceClient.create_ca_pool(request=request)

print("Operation result:", operation.result())


# [END privateca_create_ca_pool]
115 changes: 115 additions & 0 deletions privateca/snippets/create_certificate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
#!/usr/bin/env python

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START privateca_create_certificate]
from google.cloud import kms
import google.cloud.security.privateca_v1 as privateca_v1
from google.protobuf import duration_pb2


def create_certificate(
project_id: str,
location: str,
ca_pool_name: str,
ca_name: str,
certificate_name: str,
kms_location: str,
key_ring_id: str,
key_id: str,
key_version_id: str,
common_name: str,
domain_name: str,
certificate_lifetime: int,
) -> None:
"""
Create a Certificate which is issued by the Certificate Authority present in the CA Pool.
The key used to sign the certificate is created by the Cloud KMS.
Args:
project_id: project ID or project number of the Cloud project you want to use.
location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
ca_pool_name: set a unique name for the CA pool.
ca_name: the name of the certificate authority which issues the certificate.
certificate_name: set a unique name for the certificate.
kms_location: Cloud KMS location.
key_ring_id: ID of the Cloud KMS key ring.
key_id: ID of the key to use.
key_version_id: verstion ID of the key to use.
common_name: a title for your certificate.
domain_name: fully qualified domain name for your certificate.
certificate_lifetime: the validity of the certificate in seconds.
"""

kmsClient = kms.KeyManagementServiceClient()
caServiceClient = privateca_v1.CertificateAuthorityServiceClient()

# To sign and issue a certificate, a public key is essential. Here, we are making use
# of Cloud KMS to retrieve an already created public key. For more info, see: https://cloud.google.com/kms/docs/retrieve-public-key.
# Generating keys locally is also possible.

key_version_name = kmsClient.crypto_key_version_path(
project_id, kms_location, key_ring_id, key_id, key_version_id
)
kms_public_key = kmsClient.get_public_key(name=key_version_name)

# Set the Public Key and its format as obtained from the Cloud KMS.
public_key = privateca_v1.PublicKey(
key=str.encode(kms_public_key.pem),
format_=privateca_v1.PublicKey.KeyFormat.PEM,
)

subject_config = privateca_v1.CertificateConfig.SubjectConfig(
subject=privateca_v1.Subject(common_name=common_name),
subject_alt_name=privateca_v1.SubjectAltNames(dns_names=[domain_name]),
)

# Set the X.509 fields required for the certificate.
x509_parameters = privateca_v1.X509Parameters(
key_usage=privateca_v1.KeyUsage(
base_key_usage=privateca_v1.KeyUsage.KeyUsageOptions(
digital_signature=True,
key_encipherment=True,
),
extended_key_usage=privateca_v1.KeyUsage.ExtendedKeyUsageOptions(
server_auth=True,
client_auth=True,
),
),
)

# Create certificate.
certificate = privateca_v1.Certificate(
config=privateca_v1.CertificateConfig(
public_key=public_key,
subject_config=subject_config,
x509_config=x509_parameters,
),
lifetime=duration_pb2.Duration(seconds=certificate_lifetime),
)

# Create the Certificate Request.
request = privateca_v1.CreateCertificateRequest(
parent=caServiceClient.ca_pool_path(project_id, location, ca_pool_name),
certificate_id=certificate_name,
certificate=certificate,
issuing_certificate_authority_id=ca_name,
)
result = caServiceClient.create_certificate(request=request)

print("Certificate creation result:", result)


# [END privateca_create_certificate]
97 changes: 97 additions & 0 deletions privateca/snippets/create_certificate_authority.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#!/usr/bin/env python

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START privateca_create_ca]
import google.cloud.security.privateca_v1 as privateca_v1
from google.protobuf import duration_pb2


def create_certificate_authority(
project_id: str,
location: str,
ca_pool_name: str,
ca_name: str,
common_name: str,
organization: str,
ca_duration: int,
) -> None:
"""
Create Certificate Authority which is the root CA in the given CA Pool. This CA will be
responsible for signing certificates within this pool.
Args:
project_id: project ID or project number of the Cloud project you want to use.
location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
ca_pool_name: set it to the CA Pool under which the CA should be created.
ca_name: unique name for the CA.
common_name: a title for your certificate authority.
organization: the name of your company for your certificate authority.
ca_duration: the validity of the certificate authority in seconds.
"""

caServiceClient = privateca_v1.CertificateAuthorityServiceClient()

# Set the types of Algorithm used to create a cloud KMS key.
key_version_spec = privateca_v1.CertificateAuthority.KeyVersionSpec(
algorithm=privateca_v1.CertificateAuthority.SignHashAlgorithm.RSA_PKCS1_4096_SHA256
)

# Set CA subject config.
subject_config = privateca_v1.CertificateConfig.SubjectConfig(
subject=privateca_v1.Subject(common_name=common_name, organization=organization)
)

# Set the key usage options for X.509 fields.
x509_parameters = privateca_v1.X509Parameters(
key_usage=privateca_v1.KeyUsage(
base_key_usage=privateca_v1.KeyUsage.KeyUsageOptions(
crl_sign=True,
cert_sign=True,
)
),
ca_options=privateca_v1.X509Parameters.CaOptions(
is_ca=True,
),
)

# Set certificate authority settings.
certificate_authority = privateca_v1.CertificateAuthority(
# CertificateAuthority.Type.SELF_SIGNED denotes that this CA is a root CA.
type_=privateca_v1.CertificateAuthority.Type.SELF_SIGNED,
key_spec=key_version_spec,
config=privateca_v1.CertificateConfig(
subject_config=subject_config,
x509_config=x509_parameters,
),
lifetime=duration_pb2.Duration(seconds=ca_duration),
)

ca_pool_path = caServiceClient.ca_pool_path(project_id, location, ca_pool_name)

# Create the CertificateAuthorityRequest.
request = privateca_v1.CreateCertificateAuthorityRequest(
parent=ca_pool_path,
certificate_authority_id=ca_name,
certificate_authority=certificate_authority,
)

operation = caServiceClient.create_certificate_authority(request=request)
result = operation.result()

print("Operation result:", result)


# [END privateca_create_ca]
45 changes: 45 additions & 0 deletions privateca/snippets/delete_ca_pool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#!/usr/bin/env python

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START privateca_delete_ca_pool]
import google.cloud.security.privateca_v1 as privateca_v1


def delete_ca_pool(project_id: str, location: str, ca_pool_name: str) -> None:
"""
Delete the CA pool as mentioned by the ca_pool_name.
Before deleting the pool, all CAs in the pool MUST BE deleted.
Args:
project_id: project ID or project number of the Cloud project you want to use.
location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
ca_pool_name: the name of the CA pool to be deleted.
"""

caServiceClient = privateca_v1.CertificateAuthorityServiceClient()

ca_pool_path = caServiceClient.ca_pool_path(project_id, location, ca_pool_name)

# Create the Delete request.
request = privateca_v1.DeleteCaPoolRequest(name=ca_pool_path)

# Delete the CA Pool.
caServiceClient.delete_ca_pool(request=request)

print("Deleted CA Pool:", ca_pool_name)


# [END privateca_delete_ca_pool]
Loading

0 comments on commit b2b59f0

Please sign in to comment.