Skip to content
This repository was archived by the owner on Jul 6, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions samples/snippets/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@

from create_ca_pool import create_ca_pool
from create_certificate_authority import create_certificate_authority
from create_certificate_template import create_certificate_template
from delete_ca_pool import delete_ca_pool
from delete_certificate_authority import delete_certificate_authority
from delete_certificate_template import delete_certificate_template

PROJECT = google.auth.default()[1]
LOCATION = "europe-west1"
Expand Down Expand Up @@ -69,3 +71,14 @@ def deleted_certificate_authority(ca_pool):
delete_certificate_authority(PROJECT, LOCATION, ca_pool, CA_NAME)

yield ca_pool, CA_NAME


@pytest.fixture
def certificate_template():
TEMPLATE_NAME = generate_name()

create_certificate_template(PROJECT, LOCATION, TEMPLATE_NAME)

yield TEMPLATE_NAME

delete_certificate_template(PROJECT, LOCATION, TEMPLATE_NAME)
77 changes: 77 additions & 0 deletions samples/snippets/create_certificate_template.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#!/usr/bin/env python

# Copyright 2022 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_template]
import google.cloud.security.privateca_v1 as privateca_v1
from google.type import expr_pb2


def create_certificate_template(
project_id: str, location: str, certificate_template_id: str,
) -> None:
"""
Create a Certificate template. These templates can be reused for common
certificate issuance scenarios.

Args:
project_id: project ID or project number of the Cloud project you want to use.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, project ID and project number are different entities. Does this function accept either or these? If not, please specify the correct one, project ID OR project number.

location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
certificate_template_id: set a unique name for the certificate template.
"""

caServiceClient = privateca_v1.CertificateAuthorityServiceClient()

# Describes any predefined X.509 values set by this template.
# The provided extensions are copied over to certificate requests that use this template.
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,
),
),
ca_options=privateca_v1.X509Parameters.CaOptions(is_ca=False,),
)

# CEL expression that is evaluated against the Subject and
# Subject Alternative Name of the certificate before it is issued.
expr = expr_pb2.Expr(expression="subject_alt_names.all(san, san.type == DNS)")

# Set the certificate issuance schema.
certificate_template = privateca_v1.CertificateTemplate(
predefined_values=x509_parameters,
identity_constraints=privateca_v1.CertificateIdentityConstraints(
cel_expression=expr,
allow_subject_passthrough=False,
allow_subject_alt_names_passthrough=False,
),
)

# Request to create a certificate template.
request = privateca_v1.CreateCertificateTemplateRequest(
parent=caServiceClient.common_location_path(project_id, location),
certificate_template=certificate_template,
certificate_template_id=certificate_template_id,
)
operation = caServiceClient.create_certificate_template(request=request)
result = operation.result()

print("Operation result:", result)


# [END privateca_create_certificate_template]
48 changes: 48 additions & 0 deletions samples/snippets/delete_certificate_template.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#!/usr/bin/env python

# Copyright 2022 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_certificate_template]
import google.cloud.security.privateca_v1 as privateca_v1


def delete_certificate_template(
project_id: str, location: str, certificate_template_id: str,
) -> None:
"""
Delete the certificate template present in the given project and location.

Args:
project_id: project ID or project number of the Cloud project you want to use.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, project ID and project number are different entities. Does this function accept either or these? If not, please specify the correct one, project ID OR project number.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great catch - they are different entities

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have double checked with a gloud projects describe and it seems that both project ID and number work in API calls. See more here: https://cloud.google.com/resource-manager/docs/creating-managing-projects

To be on the safe side we should test this sample with ID and number as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed that this is a bit strange behavior
Makes sense to add a test.

location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
certificate_template_id: set a unique name for the certificate template.
"""

caServiceClient = privateca_v1.CertificateAuthorityServiceClient()

# Request to delete a certificate template.
request = privateca_v1.DeleteCertificateTemplateRequest(
name=caServiceClient.certificate_template_path(
project_id, location, certificate_template_id,
)
)
operation = caServiceClient.delete_certificate_template(request=request)
result = operation.result()

print("Operation result", result)
print("Deleted certificate template:", certificate_template_id)


# [END privateca_delete_certificate_template]
44 changes: 44 additions & 0 deletions samples/snippets/list_certificate_templates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/env python

# Copyright 2022 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_list_certificate_template]
import google.cloud.security.privateca_v1 as privateca_v1


def list_certificate_templates(project_id: str, location: str) -> None:
"""
List the certificate templates present in the given project and location.

Args:
project_id: project ID or project number of the Cloud project you want to use.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, project ID and project number are different entities. Does this function accept either or these? If not, please specify the correct one, project ID OR project number.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great catch - they are different entities

location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
"""

caServiceClient = privateca_v1.CertificateAuthorityServiceClient()

# List Templates Request.
request = privateca_v1.ListCertificateTemplatesRequest(
parent=caServiceClient.common_location_path(project_id, location),
)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aren't we supposed to print an error message, in case of an error?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess here we have either exception itself or printed list of templates

print("Available certificate templates:")
for certificate_template in caServiceClient.list_certificate_templates(
request=request
):
print(certificate_template.name)


# [END privateca_list_certificate_template]
77 changes: 77 additions & 0 deletions samples/snippets/monitor_certificate_authority.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#!/usr/bin/env python

# Copyright 2022 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_monitor_ca_expiry]
import google.cloud.monitoring_v3 as monitoring_v3


def create_ca_monitor_policy(project_id: str) -> None:
"""
Create a monitoring policy that notifies you 30 days before a managed CA expires.

Args:
project_id: project ID or project number of the Cloud project you want to use.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, project ID and project number are different entities. Does this function accept either or these? If not, please specify the correct one, project ID OR project number.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great catch - they are different entities

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For python-compute we use the same description: https://github.com/googleapis/python-compute/blob/main/samples/snippets/sample_create_vm.py#L167

Here we accept both entities as an input parameter: project ID and project number

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still think that they're different. The Project ID starts with a letter whereas Project number is all numeric. See https://cloud.google.com/resource-manager/docs/creating-managing-projects.
Does the code accept both?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, have just checked, the code accepts both

"""

alertPolicyServiceClient = monitoring_v3.AlertPolicyServiceClient()
notificationChannelServiceClient = monitoring_v3.NotificationChannelServiceClient()

# Query which indicates the resource to monitor and the constraints.
# Here, the alert policy notifies you 30 days before a managed CA expires.
# For more information on creating queries, see: https://cloud.google.com/monitoring/mql/alerts
query = (
"fetch privateca.googleapis.com/CertificateAuthority"
"| metric 'privateca.googleapis.com/ca/cert_chain_expiration'"
"| group_by 5m,"
"[value_cert_chain_expiration_mean: mean(value.cert_chain_expiration)]"
"| every 5m"
"| condition val() < 2.592e+06 's'"
)

# Create a notification channel.
notification_channel = monitoring_v3.NotificationChannel(
type_="email",
labels={"email_address": "[email protected]"},
)
channel = notificationChannelServiceClient.create_notification_channel(
name=notificationChannelServiceClient.common_project_path(project_id),
notification_channel=notification_channel,
)

# Set the query and notification channel.
alert_policy = monitoring_v3.AlertPolicy(
display_name="policy-name",
conditions=[
monitoring_v3.AlertPolicy.Condition(
display_name="ca-cert-chain-expiration",
condition_monitoring_query_language=monitoring_v3.AlertPolicy.Condition.MonitoringQueryLanguageCondition(
query=query,
),
)
],
combiner=monitoring_v3.AlertPolicy.ConditionCombinerType.AND,
notification_channels=[channel.name],
)

policy = alertPolicyServiceClient.create_alert_policy(
name=notificationChannelServiceClient.common_project_path(project_id),
alert_policy=alert_policy,
)

print("Monitoring policy successfully created!", policy.name)


# [END privateca_monitor_ca_expiry]
1 change: 1 addition & 0 deletions samples/snippets/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
google-cloud-private-ca==1.2.1
google-cloud-kms==2.10.1
google-cloud-monitoring==2.8.0
11 changes: 11 additions & 0 deletions samples/snippets/test_ca_pools.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from create_ca_pool import create_ca_pool
from delete_ca_pool import delete_ca_pool
from list_ca_pools import list_ca_pools
from update_ca_pool_issuance_policy import update_ca_pool_issuance_policy

PROJECT = google.auth.default()[1]
LOCATION = "europe-west1"
Expand Down Expand Up @@ -72,3 +73,13 @@ def test_delete_ca_pool(capsys: typing.Any) -> None:
out, _ = capsys.readouterr()

assert re.search(f"Deleted CA Pool: {CA_POOL_NAME}", out)


def test_update_ca_pool_issuance_policy(ca_pool, capsys: typing.Any) -> None:
CA_POOL_NAME = ca_pool

update_ca_pool_issuance_policy(PROJECT, LOCATION, CA_POOL_NAME)

out, _ = capsys.readouterr()

assert "CA Pool Issuance policy has been updated successfully!" in out
22 changes: 22 additions & 0 deletions samples/snippets/test_certificate_authorities.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@
from delete_certificate_authority import delete_certificate_authority
from disable_certificate_authority import disable_certificate_authority
from enable_certificate_authority import enable_certificate_authority
from monitor_certificate_authority import create_ca_monitor_policy
from undelete_certificate_authority import undelete_certificate_authority
from update_certificate_authority import update_ca_label


PROJECT = google.auth.default()[1]
Expand Down Expand Up @@ -84,3 +86,23 @@ def test_undelete_certificate_authority(
out, _ = capsys.readouterr()
assert re.search(f"Successfully undeleted Certificate Authority: {CA_NAME}", out,)
assert re.search(f"Successfully deleted Certificate Authority: {CA_NAME}", out,)


def test_update_certificate_authority(
certificate_authority, capsys: typing.Any
) -> None:
CA_POOL_NAME, CA_NAME = certificate_authority

update_ca_label(PROJECT, LOCATION, CA_POOL_NAME, CA_NAME)

out, _ = capsys.readouterr()

assert "Successfully updated the labels !" in out


def test_create_monitor_ca_policy(capsys: typing.Any) -> None:
create_ca_monitor_policy(PROJECT)

out, _ = capsys.readouterr()

assert "Monitoring policy successfully created!" in out
Loading