Skip to content

Commit

Permalink
docs(samples): add template/monitoring samples (#174)
Browse files Browse the repository at this point in the history
  • Loading branch information
FrodoTheTrue committed Feb 14, 2022
1 parent 2b643ea commit a945636
Show file tree
Hide file tree
Showing 12 changed files with 605 additions and 0 deletions.
13 changes: 13 additions & 0 deletions privateca/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 privateca/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.
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 privateca/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.
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 privateca/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.
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),
)

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 privateca/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.
"""

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": "python-docs-samples-testing@google.com"},
)
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 privateca/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 privateca/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 privateca/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

0 comments on commit a945636

Please sign in to comment.