Skip to content

Commit aa2d1fa

Browse files
committed
remove/update/eval/defer todos
1 parent f905c89 commit aa2d1fa

File tree

23 files changed

+453
-495
lines changed

23 files changed

+453
-495
lines changed

aws_sra_examples/solutions/genai/bedrock_org/lambda/rules/sra_bedrock_check_cloudwatch_endpoints/app.py

Lines changed: 37 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,11 @@
2121
LOGGER.info(f"boto3 version: {boto3.__version__}")
2222

2323
# Get AWS region from environment variable
24-
AWS_REGION = os.environ.get('AWS_REGION')
24+
AWS_REGION = os.environ.get("AWS_REGION")
2525

2626
# Initialize AWS clients
27-
ec2_client = boto3.client('ec2', region_name=AWS_REGION)
28-
config_client = boto3.client('config', region_name=AWS_REGION)
27+
ec2_client = boto3.client("ec2", region_name=AWS_REGION)
28+
config_client = boto3.client("config", region_name=AWS_REGION)
2929

3030

3131
def evaluate_compliance(vpc_id: str) -> tuple[str, str]:
@@ -39,22 +39,19 @@ def evaluate_compliance(vpc_id: str) -> tuple[str, str]:
3939
"""
4040
try:
4141
response = ec2_client.describe_vpc_endpoints(
42-
Filters=[
43-
{'Name': 'vpc-id', 'Values': [vpc_id]},
44-
{'Name': 'service-name', 'Values': [f'com.amazonaws.{AWS_REGION}.logs']}
45-
]
42+
Filters=[{"Name": "vpc-id", "Values": [vpc_id]}, {"Name": "service-name", "Values": [f"com.amazonaws.{AWS_REGION}.logs"]}]
4643
)
4744

48-
endpoints = response['VpcEndpoints']
45+
endpoints = response["VpcEndpoints"]
4946

5047
if endpoints:
51-
endpoint_id = endpoints[0]['VpcEndpointId']
52-
return 'COMPLIANT', f"CloudWatch gateway endpoint is in place for VPC {vpc_id}. Endpoint ID: {endpoint_id}"
53-
return 'NON_COMPLIANT', f"No CloudWatch gateway endpoint found for VPC {vpc_id}"
48+
endpoint_id = endpoints[0]["VpcEndpointId"]
49+
return "COMPLIANT", f"CloudWatch gateway endpoint is in place for VPC {vpc_id}. Endpoint ID: {endpoint_id}"
50+
return "NON_COMPLIANT", f"No CloudWatch gateway endpoint found for VPC {vpc_id}"
5451

5552
except Exception as e:
5653
LOGGER.error(f"Error evaluating CloudWatch gateway endpoint for VPC {vpc_id}: {str(e)}")
57-
return 'ERROR', f"Error evaluating compliance: {str(e)}"
54+
return "ERROR", f"Error evaluating compliance: {str(e)}"
5855

5956

6057
def lambda_handler(event: dict, context: Any) -> None: # noqa: U100
@@ -64,48 +61,49 @@ def lambda_handler(event: dict, context: Any) -> None: # noqa: U100
6461
event (dict): Lambda event object
6562
context (Any): Lambda context object
6663
"""
67-
LOGGER.info('Evaluating compliance for AWS Config rule')
64+
LOGGER.info("Evaluating compliance for AWS Config rule")
6865
LOGGER.info(f"Event: {json.dumps(event)}")
6966

70-
invoking_event = json.loads(event['invokingEvent'])
67+
invoking_event = json.loads(event["invokingEvent"])
7168

7269
evaluations = []
7370

74-
if invoking_event['messageType'] == 'ScheduledNotification':
71+
if invoking_event["messageType"] == "ScheduledNotification":
7572
# This is a scheduled run, evaluate all VPCs
7673
vpcs = ec2_client.describe_vpcs()
77-
for vpc in vpcs['Vpcs']:
78-
vpc_id = vpc['VpcId']
74+
for vpc in vpcs["Vpcs"]:
75+
vpc_id = vpc["VpcId"]
7976
compliance_type, annotation = evaluate_compliance(vpc_id)
80-
evaluations.append({
81-
'ComplianceResourceType': 'AWS::EC2::VPC',
82-
'ComplianceResourceId': vpc_id,
83-
'ComplianceType': compliance_type,
84-
'Annotation': annotation,
85-
'OrderingTimestamp': invoking_event['notificationCreationTime']
86-
})
77+
evaluations.append(
78+
{
79+
"ComplianceResourceType": "AWS::EC2::VPC",
80+
"ComplianceResourceId": vpc_id,
81+
"ComplianceType": compliance_type,
82+
"Annotation": annotation,
83+
"OrderingTimestamp": invoking_event["notificationCreationTime"],
84+
}
85+
)
8786
else:
8887
# This is a configuration change event
89-
configuration_item = invoking_event['configurationItem']
90-
if configuration_item['resourceType'] != 'AWS::EC2::VPC':
88+
configuration_item = invoking_event["configurationItem"]
89+
if configuration_item["resourceType"] != "AWS::EC2::VPC":
9190
LOGGER.info(f"Skipping non-VPC resource: {configuration_item['resourceType']}")
9291
return
9392

94-
vpc_id = configuration_item['resourceId']
93+
vpc_id = configuration_item["resourceId"]
9594
compliance_type, annotation = evaluate_compliance(vpc_id)
96-
evaluations.append({
97-
'ComplianceResourceType': configuration_item['resourceType'],
98-
'ComplianceResourceId': vpc_id,
99-
'ComplianceType': compliance_type,
100-
'Annotation': annotation,
101-
'OrderingTimestamp': configuration_item['configurationItemCaptureTime']
102-
})
95+
evaluations.append(
96+
{
97+
"ComplianceResourceType": configuration_item["resourceType"],
98+
"ComplianceResourceId": vpc_id,
99+
"ComplianceType": compliance_type,
100+
"Annotation": annotation,
101+
"OrderingTimestamp": configuration_item["configurationItemCaptureTime"],
102+
}
103+
)
103104

104105
# Submit compliance evaluations
105106
if evaluations:
106-
config_client.put_evaluations(
107-
Evaluations=evaluations,
108-
ResultToken=event['resultToken']
109-
)
107+
config_client.put_evaluations(Evaluations=evaluations, ResultToken=event["resultToken"])
110108

111-
LOGGER.info(f"Compliance evaluation complete. Processed {len(evaluations)} evaluations.")
109+
LOGGER.info(f"Compliance evaluation complete. Processed {len(evaluations)} evaluations.")

aws_sra_examples/solutions/genai/bedrock_org/lambda/rules/sra_bedrock_check_eval_job_bucket/app.py

Lines changed: 35 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -43,73 +43,73 @@ def evaluate_compliance(event: dict, context: Any) -> tuple[str, str]: # noqa:
4343
"""
4444
LOGGER.info(f"Evaluate Compliance Event: {event}")
4545
# Initialize AWS clients
46-
s3 = boto3.client('s3')
46+
s3 = boto3.client("s3")
4747

4848
# Get rule parameters
49-
params = ast.literal_eval(event['ruleParameters'])
49+
params = ast.literal_eval(event["ruleParameters"])
5050
LOGGER.info(f"Parameters: {params}")
51-
bucket_name = params.get('BucketName', '')
52-
check_retention = params.get('CheckRetention', 'true').lower() != 'false'
53-
check_encryption = params.get('CheckEncryption', 'true').lower() != 'false'
54-
check_logging = params.get('CheckLogging', 'true').lower() != 'false'
55-
check_object_locking = params.get('CheckObjectLocking', 'true').lower() != 'false'
56-
check_versioning = params.get('CheckVersioning', 'true').lower() != 'false'
51+
bucket_name = params.get("BucketName", "")
52+
check_retention = params.get("CheckRetention", "true").lower() != "false"
53+
check_encryption = params.get("CheckEncryption", "true").lower() != "false"
54+
check_logging = params.get("CheckLogging", "true").lower() != "false"
55+
check_object_locking = params.get("CheckObjectLocking", "true").lower() != "false"
56+
check_versioning = params.get("CheckVersioning", "true").lower() != "false"
5757

5858
# Check if the bucket exists
5959
if not check_bucket_exists(bucket_name):
60-
return build_evaluation('NOT_APPLICABLE', f"Bucket {bucket_name} does not exist or is not accessible")
60+
return build_evaluation("NOT_APPLICABLE", f"Bucket {bucket_name} does not exist or is not accessible")
6161

62-
compliance_type = 'COMPLIANT'
62+
compliance_type = "COMPLIANT"
6363
annotation = []
6464

6565
# Check retention
6666
if check_retention:
6767
try:
6868
retention = s3.get_bucket_lifecycle_configuration(Bucket=bucket_name)
69-
if not any(rule.get('Expiration') for rule in retention.get('Rules', [])):
70-
compliance_type = 'NON_COMPLIANT'
69+
if not any(rule.get("Expiration") for rule in retention.get("Rules", [])):
70+
compliance_type = "NON_COMPLIANT"
7171
annotation.append("Retention policy not set")
7272
except ClientError:
73-
compliance_type = 'NON_COMPLIANT'
73+
compliance_type = "NON_COMPLIANT"
7474
annotation.append("Retention policy not set")
7575

7676
# Check encryption
7777
if check_encryption:
7878
try:
7979
encryption = s3.get_bucket_encryption(Bucket=bucket_name)
80-
if 'ServerSideEncryptionConfiguration' not in encryption:
81-
compliance_type = 'NON_COMPLIANT'
80+
if "ServerSideEncryptionConfiguration" not in encryption:
81+
compliance_type = "NON_COMPLIANT"
8282
annotation.append("KMS CMK encryption not enabled")
8383
except ClientError:
84-
compliance_type = 'NON_COMPLIANT'
84+
compliance_type = "NON_COMPLIANT"
8585
annotation.append("KMS CMK encryption not enabled")
8686

8787
# Check logging
8888
if check_logging:
8989
logging = s3.get_bucket_logging(Bucket=bucket_name)
90-
if 'LoggingEnabled' not in logging:
91-
compliance_type = 'NON_COMPLIANT'
90+
if "LoggingEnabled" not in logging:
91+
compliance_type = "NON_COMPLIANT"
9292
annotation.append("Server access logging not enabled")
9393

9494
# Check object locking
9595
if check_object_locking:
9696
try:
9797
object_locking = s3.get_object_lock_configuration(Bucket=bucket_name)
98-
if 'ObjectLockConfiguration' not in object_locking:
99-
compliance_type = 'NON_COMPLIANT'
98+
if "ObjectLockConfiguration" not in object_locking:
99+
compliance_type = "NON_COMPLIANT"
100100
annotation.append("Object locking not enabled")
101101
except ClientError:
102-
compliance_type = 'NON_COMPLIANT'
102+
compliance_type = "NON_COMPLIANT"
103103
annotation.append("Object locking not enabled")
104104

105105
# Check versioning
106106
if check_versioning:
107107
versioning = s3.get_bucket_versioning(Bucket=bucket_name)
108-
if versioning.get('Status') != 'Enabled':
109-
compliance_type = 'NON_COMPLIANT'
108+
if versioning.get("Status") != "Enabled":
109+
compliance_type = "NON_COMPLIANT"
110110
annotation.append("Versioning not enabled")
111111

112-
annotation_str = '; '.join(annotation) if annotation else "All checked features are compliant"
112+
annotation_str = "; ".join(annotation) if annotation else "All checked features are compliant"
113113
return build_evaluation(compliance_type, annotation_str)
114114

115115

@@ -122,10 +122,10 @@ def check_bucket_exists(bucket_name: str) -> Any:
122122
Returns:
123123
Any: True if the bucket exists and is accessible, False otherwise
124124
"""
125-
s3 = boto3.client('s3')
125+
s3 = boto3.client("s3")
126126
try:
127127
response = s3.list_buckets()
128-
buckets = [bucket['Name'] for bucket in response['Buckets']]
128+
buckets = [bucket["Name"] for bucket in response["Buckets"]]
129129
return bucket_name in buckets
130130
except ClientError as e:
131131
LOGGER.info(f"An error occurred: {e}")
@@ -143,11 +143,7 @@ def build_evaluation(compliance_type: str, annotation: str) -> Any:
143143
Any: The evaluation compliance type and annotation
144144
"""
145145
LOGGER.info(f"Build Evaluation Compliance Type: {compliance_type} Annotation: {annotation}")
146-
return {
147-
'ComplianceType': compliance_type,
148-
'Annotation': annotation,
149-
'OrderingTimestamp': datetime.now().isoformat()
150-
}
146+
return {"ComplianceType": compliance_type, "Annotation": annotation, "OrderingTimestamp": datetime.now().isoformat()}
151147

152148

153149
def lambda_handler(event: dict, context: Any) -> None:
@@ -160,17 +156,17 @@ def lambda_handler(event: dict, context: Any) -> None:
160156
LOGGER.info(f"Lambda Handler Context: {context}")
161157
LOGGER.info(f"Lambda Handler Event: {event}")
162158
evaluation = evaluate_compliance(event, context)
163-
config = boto3.client('config')
164-
params = ast.literal_eval(event['ruleParameters'])
159+
config = boto3.client("config")
160+
params = ast.literal_eval(event["ruleParameters"])
165161
config.put_evaluations(
166162
Evaluations=[
167163
{
168-
'ComplianceResourceType': 'AWS::S3::Bucket',
169-
'ComplianceResourceId': params.get('BucketName'),
170-
'ComplianceType': evaluation['ComplianceType'], # type: ignore
171-
'Annotation': evaluation['Annotation'], # type: ignore
172-
'OrderingTimestamp': evaluation['OrderingTimestamp'] # type: ignore
164+
"ComplianceResourceType": "AWS::S3::Bucket",
165+
"ComplianceResourceId": params.get("BucketName"),
166+
"ComplianceType": evaluation["ComplianceType"], # type: ignore
167+
"Annotation": evaluation["Annotation"], # type: ignore
168+
"OrderingTimestamp": evaluation["OrderingTimestamp"], # type: ignore
173169
}
174170
],
175-
ResultToken=event['resultToken']
171+
ResultToken=event["resultToken"],
176172
)

aws_sra_examples/solutions/genai/bedrock_org/lambda/rules/sra_bedrock_check_guardrail_encryption/app.py

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,11 @@
2121
LOGGER.info(f"boto3 version: {boto3.__version__}")
2222

2323
# Get AWS region from environment variable
24-
AWS_REGION = os.environ.get('AWS_REGION')
24+
AWS_REGION = os.environ.get("AWS_REGION")
2525

2626
# Initialize AWS clients
27-
bedrock_client = boto3.client('bedrock', region_name=AWS_REGION)
28-
config_client = boto3.client('config', region_name=AWS_REGION)
27+
bedrock_client = boto3.client("bedrock", region_name=AWS_REGION)
28+
config_client = boto3.client("config", region_name=AWS_REGION)
2929

3030

3131
def evaluate_compliance(rule_parameters: dict) -> tuple[str, str]: # noqa: CFQ004
@@ -40,27 +40,27 @@ def evaluate_compliance(rule_parameters: dict) -> tuple[str, str]: # noqa: CFQ0
4040
LOGGER.info(f"Rule parameters: {json.dumps(rule_parameters)}")
4141
try:
4242
response = bedrock_client.list_guardrails()
43-
guardrails = response.get('guardrails', [])
43+
guardrails = response.get("guardrails", [])
4444

4545
if not guardrails:
46-
return 'NON_COMPLIANT', "No Bedrock guardrails found"
46+
return "NON_COMPLIANT", "No Bedrock guardrails found"
4747

4848
unencrypted_guardrails: list[str] = []
4949
for guardrail in guardrails:
50-
guardrail_id = guardrail['id']
51-
guardrail_name = guardrail['name']
50+
guardrail_id = guardrail["id"]
51+
guardrail_name = guardrail["name"]
5252
guardrail_detail = bedrock_client.get_guardrail(guardrailIdentifier=guardrail_id)
5353

54-
if 'kmsKeyArn' not in guardrail_detail:
54+
if "kmsKeyArn" not in guardrail_detail:
5555
unencrypted_guardrails.append(guardrail_name)
5656

5757
if unencrypted_guardrails:
58-
return 'NON_COMPLIANT', f"The following Bedrock guardrails are not encrypted with a KMS key: {', '.join(unencrypted_guardrails)}"
59-
return 'COMPLIANT', "All Bedrock guardrails are encrypted with a KMS key"
58+
return "NON_COMPLIANT", f"The following Bedrock guardrails are not encrypted with a KMS key: {', '.join(unencrypted_guardrails)}"
59+
return "COMPLIANT", "All Bedrock guardrails are encrypted with a KMS key"
6060

6161
except Exception as e:
6262
LOGGER.error(f"Error evaluating Bedrock guardrails encryption: {str(e)}")
63-
return 'ERROR', f"Error evaluating compliance: {str(e)}"
63+
return "ERROR", f"Error evaluating compliance: {str(e)}"
6464

6565

6666
def lambda_handler(event: dict, context: Any) -> None: # noqa: U100
@@ -70,28 +70,25 @@ def lambda_handler(event: dict, context: Any) -> None: # noqa: U100
7070
event (dict): Lambda event object
7171
context (Any): Lambda context object
7272
"""
73-
LOGGER.info('Evaluating compliance for AWS Config rule')
73+
LOGGER.info("Evaluating compliance for AWS Config rule")
7474
LOGGER.info(f"Event: {json.dumps(event)}")
7575

76-
invoking_event = json.loads(event['invokingEvent'])
77-
rule_parameters = json.loads(event['ruleParameters']) if 'ruleParameters' in event else {}
76+
invoking_event = json.loads(event["invokingEvent"])
77+
rule_parameters = json.loads(event["ruleParameters"]) if "ruleParameters" in event else {}
7878

7979
compliance_type, annotation = evaluate_compliance(rule_parameters)
8080

8181
evaluation = {
82-
'ComplianceResourceType': 'AWS::::Account',
83-
'ComplianceResourceId': event['accountId'],
84-
'ComplianceType': compliance_type,
85-
'Annotation': annotation,
86-
'OrderingTimestamp': invoking_event['notificationCreationTime']
82+
"ComplianceResourceType": "AWS::::Account",
83+
"ComplianceResourceId": event["accountId"],
84+
"ComplianceType": compliance_type,
85+
"Annotation": annotation,
86+
"OrderingTimestamp": invoking_event["notificationCreationTime"],
8787
}
8888

8989
LOGGER.info(f"Compliance evaluation result: {compliance_type}")
9090
LOGGER.info(f"Annotation: {annotation}")
9191

92-
config_client.put_evaluations(
93-
Evaluations=[evaluation],
94-
ResultToken=event['resultToken']
95-
)
92+
config_client.put_evaluations(Evaluations=[evaluation], ResultToken=event["resultToken"])
9693

97-
LOGGER.info("Compliance evaluation complete.")
94+
LOGGER.info("Compliance evaluation complete.")

0 commit comments

Comments
 (0)