Skip to content

Commit 3b2b41c

Browse files
committed
fix lint and address comments
1 parent 9a19f99 commit 3b2b41c

File tree

3 files changed

+57
-28
lines changed

3 files changed

+57
-28
lines changed

securitycenter/snippets_management_api/noxfile_config.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@
2323
TEST_CONFIG_OVERRIDE = {
2424
# You can opt out from the test for specific Python versions.
2525
"ignored_versions": ["2.7", "3.7", "3.9", "3.10", "3.11"],
26+
# Old samples are opted out of enforcing Python type hints
27+
# All new samples should feature them
28+
"enforce_type_hints": True,
2629
# An envvar key for determining the project id to use. Change it
2730
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
2831
# build specific Cloud project. You can also use your own string

securitycenter/snippets_management_api/security_health_analytics_custom_module_test.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,26 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616
import os
17-
import uuid
17+
1818
import backoff
19-
from google.api_core.exceptions import InternalServerError, ServiceUnavailable, NotFound
19+
20+
from google.api_core.exceptions import InternalServerError, NotFound, ServiceUnavailable
2021
from google.cloud import securitycentermanagement_v1
21-
import security_health_analytics_custom_modules
22-
import pytest
23-
import time
22+
2423
import random
24+
import time
25+
26+
import pytest
27+
28+
import security_health_analytics_custom_modules
2529

26-
#Replace these variables before running the sample.
30+
# Replace these variables before running the sample.
31+
# GCLOUD_ORGANIZATION: The organization ID.
2732
ORGANIZATION_ID = os.environ["GCLOUD_ORGANIZATION"]
2833
LOCATION = "global"
2934
PREFIX = "python_sample_sha_custom_module" # Prefix used for identifying test modules
3035

36+
3137
@pytest.fixture(scope="session", autouse=True)
3238
def setup_environment():
3339
"""Fixture to ensure a clean environment by removing test modules before running tests."""
@@ -37,6 +43,7 @@ def setup_environment():
3743
print(f"Cleaning up existing custom modules for organization: {ORGANIZATION_ID}")
3844
cleanup_existing_custom_modules(ORGANIZATION_ID)
3945

46+
4047
def cleanup_existing_custom_modules(org_id: str):
4148
"""
4249
Deletes all custom modules matching a specific naming pattern.
@@ -59,6 +66,7 @@ def cleanup_existing_custom_modules(org_id: str):
5966
except NotFound:
6067
print(f"Custom Module not found for deletion: {module.name}")
6168

69+
6270
def add_custom_module(org_id: str):
6371

6472
parent = f"organizations/{org_id}/locations/global"
@@ -99,17 +107,17 @@ def add_custom_module(org_id: str):
99107
}
100108

101109
request = securitycentermanagement_v1.CreateSecurityHealthAnalyticsCustomModuleRequest(
102-
parent= parent,
103-
security_health_analytics_custom_module= custom_module,
110+
parent=parent,
111+
security_health_analytics_custom_module=custom_module,
104112
)
105-
106113
response = client.create_security_health_analytics_custom_module(request=request)
107114
print(f"Created Security Health Analytics Custom Module: {response.name}")
108115
module_name = response.name
109116
module_id = module_name.split("/")[-1]
110117

111118
return module_name, module_id
112119

120+
113121
@backoff.on_exception(
114122
backoff.expo, (InternalServerError, ServiceUnavailable, NotFound), max_tries=3
115123
)
@@ -124,6 +132,7 @@ def test_create_security_health_analytics_custom_module():
124132
assert response.display_name.startswith(PREFIX)
125133
assert response.enablement_state == securitycentermanagement_v1.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED
126134

135+
127136
@backoff.on_exception(
128137
backoff.expo, (InternalServerError, ServiceUnavailable, NotFound), max_tries=3
129138
)
@@ -139,9 +148,9 @@ def test_get_security_health_analytics_custom_module():
139148
# Verify that the custom module was created
140149
assert response.display_name.startswith(PREFIX)
141150
assert response.enablement_state == securitycentermanagement_v1.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED
142-
143151
print(f"Retrieved Custom Module: {response.name}")
144152

153+
145154
@backoff.on_exception(
146155
backoff.expo, (InternalServerError, ServiceUnavailable, NotFound), max_tries=3
147156
)
@@ -160,6 +169,7 @@ def test_delete_security_health_analytics_custom_module():
160169

161170
print(f"Custom module was deleted successfully: {module_id}")
162171

172+
163173
@backoff.on_exception(
164174
backoff.expo, (InternalServerError, ServiceUnavailable, NotFound), max_tries=3
165175
)
@@ -184,6 +194,7 @@ def test_list_security_health_analytics_custom_module():
184194
== securitycentermanagement_v1.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED
185195
)
186196

197+
187198
@backoff.on_exception(
188199
backoff.expo, (InternalServerError, ServiceUnavailable, NotFound), max_tries=3
189200
)

securitycenter/snippets_management_api/security_health_analytics_custom_modules.py

Lines changed: 33 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,22 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616

17-
from typing import Dict
18-
import time
1917
import random
18+
import time
19+
from typing import Dict
20+
2021
from google.cloud import securitycentermanagement_v1
22+
from google.api_core.exceptions import NotFound
23+
2124

2225
# [START securitycenter_create_security_health_analytics_custom_module]
2326
def create_security_health_analytics_custom_module(parent: str) -> Dict:
2427
"""
2528
Creates a Security Health Analytics custom module.
29+
30+
This custom module evaluates Cloud KMS CryptoKeys to ensure their rotation period exceeds 30 days (2592000 seconds),
31+
as per security best practices. A shorter rotation period helps reduce the risk of exposure in the event of a compromise.
32+
2633
Args:
2734
parent: Use any one of the following options:
2835
- organizations/{organization_id}/locations/{location_id}
@@ -42,24 +49,33 @@ def create_security_health_analytics_custom_module(parent: str) -> Dict:
4249
"display_name": display_name,
4350
"enablement_state": "ENABLED",
4451
"custom_config": {
45-
"description": "Sample custom module for testing purpose. Please do not delete.",
52+
"description": (
53+
"Sample custom module for testing purposes. This custom module evaluates "
54+
"Cloud KMS CryptoKeys to ensure their rotation period exceeds 30 days (2592000 seconds)."
55+
),
4656
"predicate": {
4757
"expression": "has(resource.rotationPeriod) && (resource.rotationPeriod > duration('2592000s'))",
48-
"title": "GCE Instance High Severity",
49-
"description": "Custom module to detect high severity issues on GCE instances.",
58+
"title": "Cloud KMS CryptoKey Rotation Period",
59+
"description": (
60+
"Evaluates whether the rotation period of a Cloud KMS CryptoKey exceeds 30 days. "
61+
"A longer rotation period might increase the risk of exposure."
62+
),
5063
},
51-
"recommendation": "Ensure proper security configurations on GCE instances.",
64+
"recommendation": (
65+
"Review and adjust the rotation period for Cloud KMS CryptoKeys to align with your security policies. "
66+
"Consider setting a shorter rotation period if possible."
67+
),
5268
"resource_selector": {"resource_types": ["cloudkms.googleapis.com/CryptoKey"]},
5369
"severity": "CRITICAL",
5470
"custom_output": {
5571
"properties": [
5672
{
5773
"name": "example_property",
5874
"value_expression": {
59-
"description": "The name of the instance",
75+
"description": "The resource name of the CryptoKey being evaluated.",
6076
"expression": "resource.name",
6177
"location": "global",
62-
"title": "Instance Name",
78+
"title": "CryptoKey Resource Name",
6379
},
6480
}
6581
]
@@ -68,15 +84,16 @@ def create_security_health_analytics_custom_module(parent: str) -> Dict:
6884
}
6985

7086
request = securitycentermanagement_v1.CreateSecurityHealthAnalyticsCustomModuleRequest(
71-
parent= parent,
72-
security_health_analytics_custom_module= custom_module,
87+
parent=parent,
88+
security_health_analytics_custom_module=custom_module,
7389
)
7490

7591
response = client.create_security_health_analytics_custom_module(request=request)
7692
print(f"Created Security Health Analytics Custom Module: {response.name}")
7793
return response
7894
# [END securitycenter_create_security_health_analytics_custom_module]
7995

96+
8097
# [START securitycenter_get_security_health_analytics_custom_module]
8198
def get_security_health_analytics_custom_module(parent: str, module_id: str):
8299
"""
@@ -95,7 +112,7 @@ def get_security_health_analytics_custom_module(parent: str, module_id: str):
95112

96113
try:
97114
request = securitycentermanagement_v1.GetSecurityHealthAnalyticsCustomModuleRequest(
98-
name= f"{parent}/securityHealthAnalyticsCustomModules/{module_id}",
115+
name=f"{parent}/securityHealthAnalyticsCustomModules/{module_id}",
99116
)
100117

101118
response = client.get_security_health_analytics_custom_module(request=request)
@@ -107,7 +124,6 @@ def get_security_health_analytics_custom_module(parent: str, module_id: str):
107124
# [END securitycenter_get_security_health_analytics_custom_module]
108125

109126

110-
111127
# [START securitycenter_list_security_health_analytics_custom_module]
112128
def list_security_health_analytics_custom_module(parent: str):
113129
"""
@@ -122,22 +138,20 @@ def list_security_health_analytics_custom_module(parent: str):
122138
Raises:
123139
NotFound: If the specified custom module does not exist.
124140
"""
125-
from google.api_core.exceptions import NotFound
126141

127142
client = securitycentermanagement_v1.SecurityCenterManagementClient()
128143

129144
try:
130145
request = securitycentermanagement_v1.ListSecurityHealthAnalyticsCustomModulesRequest(
131-
parent= parent,
146+
parent=parent,
132147
)
133148

134149
response = client.list_security_health_analytics_custom_modules(request=request)
135150

136151
custom_modules = []
137152
for custom_module in response:
138153
print(f"Custom Module: {custom_module.name}")
139-
custom_modules.append(custom_module)
140-
154+
custom_modules.append(custom_module)
141155
return custom_modules
142156
except NotFound as e:
143157
print(f"Parent resource not found: {parent}")
@@ -147,6 +161,7 @@ def list_security_health_analytics_custom_module(parent: str):
147161
raise e
148162
# [END securitycenter_list_security_health_analytics_custom_module]
149163

164+
150165
# [START securitycenter_delete_security_health_analytics_custom_module]
151166
def delete_security_health_analytics_custom_module(parent: str, module_id: str):
152167
"""
@@ -165,7 +180,7 @@ def delete_security_health_analytics_custom_module(parent: str, module_id: str):
165180

166181
try:
167182
request = securitycentermanagement_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest(
168-
name= f"{parent}/securityHealthAnalyticsCustomModules/{module_id}",
183+
name=f"{parent}/securityHealthAnalyticsCustomModules/{module_id}",
169184
)
170185

171186
client.delete_security_health_analytics_custom_module(request=request)
@@ -175,6 +190,7 @@ def delete_security_health_analytics_custom_module(parent: str, module_id: str):
175190
raise e
176191
# [END securitycenter_delete_security_health_analytics_custom_module]
177192

193+
178194
# [START securitycenter_update_security_health_analytics_custom_module]
179195
def update_security_health_analytics_custom_module(parent: str, module_id: str):
180196
"""
@@ -190,7 +206,6 @@ def update_security_health_analytics_custom_module(parent: str, module_id: str):
190206
NotFound: If the specified custom module does not exist.
191207
"""
192208
from google.protobuf.field_mask_pb2 import FieldMask
193-
from google.api_core.exceptions import NotFound, InternalServerError, ServiceUnavailable
194209

195210
client = securitycentermanagement_v1.SecurityCenterManagementClient()
196211
try:

0 commit comments

Comments
 (0)