Skip to content

Commit 6b83ff4

Browse files
FrodoTheTruem-strzelczyk
authored andcommitted
docs(samples): add template/monitoring samples (#174)
1 parent b07eebb commit 6b83ff4

12 files changed

+605
-0
lines changed

privateca/snippets/conftest.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@
2020

2121
from create_ca_pool import create_ca_pool
2222
from create_certificate_authority import create_certificate_authority
23+
from create_certificate_template import create_certificate_template
2324
from delete_ca_pool import delete_ca_pool
2425
from delete_certificate_authority import delete_certificate_authority
26+
from delete_certificate_template import delete_certificate_template
2527

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

7173
yield ca_pool, CA_NAME
74+
75+
76+
@pytest.fixture
77+
def certificate_template():
78+
TEMPLATE_NAME = generate_name()
79+
80+
create_certificate_template(PROJECT, LOCATION, TEMPLATE_NAME)
81+
82+
yield TEMPLATE_NAME
83+
84+
delete_certificate_template(PROJECT, LOCATION, TEMPLATE_NAME)
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2022 Google LLC
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
# [START privateca_create_certificate_template]
18+
import google.cloud.security.privateca_v1 as privateca_v1
19+
from google.type import expr_pb2
20+
21+
22+
def create_certificate_template(
23+
project_id: str, location: str, certificate_template_id: str,
24+
) -> None:
25+
"""
26+
Create a Certificate template. These templates can be reused for common
27+
certificate issuance scenarios.
28+
29+
Args:
30+
project_id: project ID or project number of the Cloud project you want to use.
31+
location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
32+
certificate_template_id: set a unique name for the certificate template.
33+
"""
34+
35+
caServiceClient = privateca_v1.CertificateAuthorityServiceClient()
36+
37+
# Describes any predefined X.509 values set by this template.
38+
# The provided extensions are copied over to certificate requests that use this template.
39+
x509_parameters = privateca_v1.X509Parameters(
40+
key_usage=privateca_v1.KeyUsage(
41+
base_key_usage=privateca_v1.KeyUsage.KeyUsageOptions(
42+
digital_signature=True, key_encipherment=True,
43+
),
44+
extended_key_usage=privateca_v1.KeyUsage.ExtendedKeyUsageOptions(
45+
server_auth=True,
46+
),
47+
),
48+
ca_options=privateca_v1.X509Parameters.CaOptions(is_ca=False,),
49+
)
50+
51+
# CEL expression that is evaluated against the Subject and
52+
# Subject Alternative Name of the certificate before it is issued.
53+
expr = expr_pb2.Expr(expression="subject_alt_names.all(san, san.type == DNS)")
54+
55+
# Set the certificate issuance schema.
56+
certificate_template = privateca_v1.CertificateTemplate(
57+
predefined_values=x509_parameters,
58+
identity_constraints=privateca_v1.CertificateIdentityConstraints(
59+
cel_expression=expr,
60+
allow_subject_passthrough=False,
61+
allow_subject_alt_names_passthrough=False,
62+
),
63+
)
64+
65+
# Request to create a certificate template.
66+
request = privateca_v1.CreateCertificateTemplateRequest(
67+
parent=caServiceClient.common_location_path(project_id, location),
68+
certificate_template=certificate_template,
69+
certificate_template_id=certificate_template_id,
70+
)
71+
operation = caServiceClient.create_certificate_template(request=request)
72+
result = operation.result()
73+
74+
print("Operation result:", result)
75+
76+
77+
# [END privateca_create_certificate_template]
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2022 Google LLC
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
# [START privateca_delete_certificate_template]
18+
import google.cloud.security.privateca_v1 as privateca_v1
19+
20+
21+
def delete_certificate_template(
22+
project_id: str, location: str, certificate_template_id: str,
23+
) -> None:
24+
"""
25+
Delete the certificate template present in the given project and location.
26+
27+
Args:
28+
project_id: project ID or project number of the Cloud project you want to use.
29+
location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
30+
certificate_template_id: set a unique name for the certificate template.
31+
"""
32+
33+
caServiceClient = privateca_v1.CertificateAuthorityServiceClient()
34+
35+
# Request to delete a certificate template.
36+
request = privateca_v1.DeleteCertificateTemplateRequest(
37+
name=caServiceClient.certificate_template_path(
38+
project_id, location, certificate_template_id,
39+
)
40+
)
41+
operation = caServiceClient.delete_certificate_template(request=request)
42+
result = operation.result()
43+
44+
print("Operation result", result)
45+
print("Deleted certificate template:", certificate_template_id)
46+
47+
48+
# [END privateca_delete_certificate_template]
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2022 Google LLC
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
# [START privateca_list_certificate_template]
18+
import google.cloud.security.privateca_v1 as privateca_v1
19+
20+
21+
def list_certificate_templates(project_id: str, location: str) -> None:
22+
"""
23+
List the certificate templates present in the given project and location.
24+
25+
Args:
26+
project_id: project ID or project number of the Cloud project you want to use.
27+
location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
28+
"""
29+
30+
caServiceClient = privateca_v1.CertificateAuthorityServiceClient()
31+
32+
# List Templates Request.
33+
request = privateca_v1.ListCertificateTemplatesRequest(
34+
parent=caServiceClient.common_location_path(project_id, location),
35+
)
36+
37+
print("Available certificate templates:")
38+
for certificate_template in caServiceClient.list_certificate_templates(
39+
request=request
40+
):
41+
print(certificate_template.name)
42+
43+
44+
# [END privateca_list_certificate_template]
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2022 Google LLC
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
# [START privateca_monitor_ca_expiry]
18+
import google.cloud.monitoring_v3 as monitoring_v3
19+
20+
21+
def create_ca_monitor_policy(project_id: str) -> None:
22+
"""
23+
Create a monitoring policy that notifies you 30 days before a managed CA expires.
24+
25+
Args:
26+
project_id: project ID or project number of the Cloud project you want to use.
27+
"""
28+
29+
alertPolicyServiceClient = monitoring_v3.AlertPolicyServiceClient()
30+
notificationChannelServiceClient = monitoring_v3.NotificationChannelServiceClient()
31+
32+
# Query which indicates the resource to monitor and the constraints.
33+
# Here, the alert policy notifies you 30 days before a managed CA expires.
34+
# For more information on creating queries, see: https://cloud.google.com/monitoring/mql/alerts
35+
query = (
36+
"fetch privateca.googleapis.com/CertificateAuthority"
37+
"| metric 'privateca.googleapis.com/ca/cert_chain_expiration'"
38+
"| group_by 5m,"
39+
"[value_cert_chain_expiration_mean: mean(value.cert_chain_expiration)]"
40+
"| every 5m"
41+
"| condition val() < 2.592e+06 's'"
42+
)
43+
44+
# Create a notification channel.
45+
notification_channel = monitoring_v3.NotificationChannel(
46+
type_="email",
47+
labels={"email_address": "[email protected]"},
48+
)
49+
channel = notificationChannelServiceClient.create_notification_channel(
50+
name=notificationChannelServiceClient.common_project_path(project_id),
51+
notification_channel=notification_channel,
52+
)
53+
54+
# Set the query and notification channel.
55+
alert_policy = monitoring_v3.AlertPolicy(
56+
display_name="policy-name",
57+
conditions=[
58+
monitoring_v3.AlertPolicy.Condition(
59+
display_name="ca-cert-chain-expiration",
60+
condition_monitoring_query_language=monitoring_v3.AlertPolicy.Condition.MonitoringQueryLanguageCondition(
61+
query=query,
62+
),
63+
)
64+
],
65+
combiner=monitoring_v3.AlertPolicy.ConditionCombinerType.AND,
66+
notification_channels=[channel.name],
67+
)
68+
69+
policy = alertPolicyServiceClient.create_alert_policy(
70+
name=notificationChannelServiceClient.common_project_path(project_id),
71+
alert_policy=alert_policy,
72+
)
73+
74+
print("Monitoring policy successfully created!", policy.name)
75+
76+
77+
# [END privateca_monitor_ca_expiry]

privateca/snippets/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
google-cloud-private-ca==1.2.1
22
google-cloud-kms==2.10.1
3+
google-cloud-monitoring==2.8.0

privateca/snippets/test_ca_pools.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from create_ca_pool import create_ca_pool
2222
from delete_ca_pool import delete_ca_pool
2323
from list_ca_pools import list_ca_pools
24+
from update_ca_pool_issuance_policy import update_ca_pool_issuance_policy
2425

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

7475
assert re.search(f"Deleted CA Pool: {CA_POOL_NAME}", out)
76+
77+
78+
def test_update_ca_pool_issuance_policy(ca_pool, capsys: typing.Any) -> None:
79+
CA_POOL_NAME = ca_pool
80+
81+
update_ca_pool_issuance_policy(PROJECT, LOCATION, CA_POOL_NAME)
82+
83+
out, _ = capsys.readouterr()
84+
85+
assert "CA Pool Issuance policy has been updated successfully!" in out

privateca/snippets/test_certificate_authorities.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@
2424
from delete_certificate_authority import delete_certificate_authority
2525
from disable_certificate_authority import disable_certificate_authority
2626
from enable_certificate_authority import enable_certificate_authority
27+
from monitor_certificate_authority import create_ca_monitor_policy
2728
from undelete_certificate_authority import undelete_certificate_authority
29+
from update_certificate_authority import update_ca_label
2830

2931

3032
PROJECT = google.auth.default()[1]
@@ -84,3 +86,23 @@ def test_undelete_certificate_authority(
8486
out, _ = capsys.readouterr()
8587
assert re.search(f"Successfully undeleted Certificate Authority: {CA_NAME}", out,)
8688
assert re.search(f"Successfully deleted Certificate Authority: {CA_NAME}", out,)
89+
90+
91+
def test_update_certificate_authority(
92+
certificate_authority, capsys: typing.Any
93+
) -> None:
94+
CA_POOL_NAME, CA_NAME = certificate_authority
95+
96+
update_ca_label(PROJECT, LOCATION, CA_POOL_NAME, CA_NAME)
97+
98+
out, _ = capsys.readouterr()
99+
100+
assert "Successfully updated the labels !" in out
101+
102+
103+
def test_create_monitor_ca_policy(capsys: typing.Any) -> None:
104+
create_ca_monitor_policy(PROJECT)
105+
106+
out, _ = capsys.readouterr()
107+
108+
assert "Monitoring policy successfully created!" in out

0 commit comments

Comments
 (0)