Skip to content
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
91 changes: 75 additions & 16 deletions src/cfnlint/rules/resources/lmbd/EventsLogGroupName.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ class EventsLogGroupName(CloudFormationLintRule):
"The current limit for a CloudWatch Log Group is they can have 5 subscription"
" filters. We will look for duplicate LogGroupNames inside Subscription Filters"
" and make sure they are within 5. This doesn't account for any other"
" subscription filters getting set."
" subscription filters getting set. Filters gated by Conditions are counted"
" per condition scenario, so filters that can never exist at the same time"
" are not counted together."
)
source_url = "https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/cloudwatch_limits_cwl.html"
tags = ["resources", "lambda"]
Expand All @@ -39,17 +41,60 @@ def check_events_subscription_duplicated(self, cfn: Template) -> RuleMatches:
)

log_group_paths = self.__get_log_group_name_list(cfn)
for _, paths in log_group_paths.items():
if len(paths) > self.limit:
matches.append(RuleMatch(paths[2], message))
for _, entries in log_group_paths.items():
path = self.__get_limit_exceeding_path(cfn, entries)
if path is not None:
matches.append(RuleMatch(path, message))

return matches

def __get_limit_exceeding_path(
self,
cfn: Template,
entries: list[tuple[list[str | int], str | None]],
) -> list[str | int] | None:
"""Return the path of the first filter over the limit, if any.

Filters without a Condition exist in every scenario. Filters with a
Condition exist only in scenarios where that Condition is true, so
the count that matters is the largest count over all satisfiable
condition scenarios, not the flat total. When the Conditions cannot
be resolved (for example an undefined Condition name) fall back to
the flat total so the rule keeps reporting instead of going silent.
"""
conditions = {condition for _, condition in entries if condition}
if not conditions:
if len(entries) > self.limit:
return entries[self.limit][0]
return None

scenarios = list(
cfn.conditions.build_scenarios({name: {True, False} for name in conditions})
)
if not scenarios:
if len(entries) > self.limit:
return entries[self.limit][0]
return None

worst: list[list[str | int]] = []
for scenario in scenarios:
present = [
path
for path, condition in entries
if condition is None or scenario.get(condition, True)
]
if len(present) > len(worst):
worst = present

if len(worst) > self.limit:
return worst[self.limit]
return None

def __get_log_group_name_list(
self,
cfn: Template,
) -> dict[str, list[list[str | int]]]:
log_group_paths: dict[str, list[list[str | int]]] = {}
) -> dict[str, list[tuple[list[str | int], str | None]]]:
log_group_paths: dict[str, list[tuple[list[str | int], str | None]]] = {}

# Enumerate AWS::Logs::SubscriptionFilter resources
for resource_name, resource in cfn.get_resources(
Expand All @@ -64,7 +109,10 @@ def __get_log_group_name_list(
log_group_paths[log_group_name] = []

log_group_paths[log_group_name].append(
["Resources", resource_name, "Properties", "LogGroupName"],
(
["Resources", resource_name, "Properties", "LogGroupName"],
self.__get_condition(resource),
),
)

# Enumerate AWS::Serverless::Function CloudWatchLogs events
Expand Down Expand Up @@ -96,19 +144,30 @@ def __get_log_group_name_list(
log_group_paths[log_group_name] = []

log_group_paths[log_group_name].append(
[
"Resources",
resource_name,
"Properties",
"Events",
event_id,
"Properties",
"LogGroupName",
],
(
[
"Resources",
resource_name,
"Properties",
"Events",
event_id,
"Properties",
"LogGroupName",
],
# A SAM event inherits the Condition of its function
self.__get_condition(resource),
),
)

return log_group_paths

def __get_condition(self, resource: dict) -> str | None:
"""Return the resource Condition name, if it is a plain string."""
condition = resource.get("Condition")
if isinstance(condition, str):
return condition
return None

def match(self, cfn: Template) -> RuleMatches:
"""Check if Lambda Events Subscription is duplicated"""
matches = []
Expand Down
198 changes: 198 additions & 0 deletions test/unit/rules/resources/lmbd/test_events_log_group_name.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,204 @@ def test_explicit_filters_only_exceeds_limit(self, rule):
matches = rule.match(template)
assert len(matches) == 1

def test_mutually_exclusive_conditions_within_limit(self, rule):
"""Filters gated by mutually exclusive Conditions are not counted together"""
dest_arn = "arn:aws:lambda:us-east-1:123456789012:function:f"
resources = {
"Logs": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"RetentionInDays": 1},
},
}
for i in range(3):
resources[f"ProdFilter{i}"] = {
"Type": "AWS::Logs::SubscriptionFilter",
"Condition": "IsProd",
"Properties": {
"LogGroupName": {"Ref": "Logs"},
"FilterPattern": f"prod{i}",
"DestinationArn": dest_arn,
},
}
for i in range(3):
resources[f"DevFilter{i}"] = {
"Type": "AWS::Logs::SubscriptionFilter",
"Condition": "IsDev",
"Properties": {
"LogGroupName": {"Ref": "Logs"},
"FilterPattern": f"dev{i}",
"DestinationArn": dest_arn,
},
}
template = Template(
"",
{
"AWSTemplateFormatVersion": "2010-09-09",
"Parameters": {
"Stage": {
"Type": "String",
"AllowedValues": ["prod", "dev"],
"Default": "prod",
},
},
"Conditions": {
"IsProd": {"Fn::Equals": [{"Ref": "Stage"}, "prod"]},
"IsDev": {"Fn::Not": [{"Condition": "IsProd"}]},
},
"Resources": resources,
},
)
# 3 Prod + 3 Dev filters, but at most 3 coexist in any scenario
matches = rule.match(template)
assert len(matches) == 0

def test_same_condition_exceeds_limit(self, rule):
"""6 filters under one Condition still exceed the limit"""
dest_arn = "arn:aws:lambda:us-east-1:123456789012:function:f"
resources = {
"Logs": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"RetentionInDays": 1},
},
}
for i in range(6):
resources[f"ProdFilter{i}"] = {
"Type": "AWS::Logs::SubscriptionFilter",
"Condition": "IsProd",
"Properties": {
"LogGroupName": {"Ref": "Logs"},
"FilterPattern": f"prod{i}",
"DestinationArn": dest_arn,
},
}
template = Template(
"",
{
"AWSTemplateFormatVersion": "2010-09-09",
"Conditions": {
"IsProd": {"Fn::Equals": [{"Ref": "Stage"}, "prod"]},
},
"Parameters": {
"Stage": {
"Type": "String",
"AllowedValues": ["prod", "dev"],
"Default": "prod",
},
},
"Resources": resources,
},
)
matches = rule.match(template)
assert len(matches) == 1

def test_unconditional_plus_conditional_exceeds_limit(self, rule):
"""Unconditional filters count in every scenario"""
dest_arn = "arn:aws:lambda:us-east-1:123456789012:function:f"
resources = {
"Logs": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"RetentionInDays": 1},
},
}
for i in range(4):
resources[f"Filter{i}"] = {
"Type": "AWS::Logs::SubscriptionFilter",
"Properties": {
"LogGroupName": {"Ref": "Logs"},
"FilterPattern": f"f{i}",
"DestinationArn": dest_arn,
},
}
for i in range(2):
resources[f"ProdFilter{i}"] = {
"Type": "AWS::Logs::SubscriptionFilter",
"Condition": "IsProd",
"Properties": {
"LogGroupName": {"Ref": "Logs"},
"FilterPattern": f"prod{i}",
"DestinationArn": dest_arn,
},
}
template = Template(
"",
{
"AWSTemplateFormatVersion": "2010-09-09",
"Conditions": {
"IsProd": {"Fn::Equals": [{"Ref": "Stage"}, "prod"]},
},
"Parameters": {
"Stage": {
"Type": "String",
"AllowedValues": ["prod", "dev"],
"Default": "prod",
},
},
"Resources": resources,
},
)
# 4 unconditional + 2 IsProd filters coexist when IsProd is true
matches = rule.match(template)
assert len(matches) == 1

def test_sam_events_mutually_exclusive_conditions_within_limit(self, rule):
"""SAM events inherit their function's Condition for the count"""
events = {}
for i in range(4):
events[f"Event{i}"] = {
"Type": "CloudWatchLogs",
"Properties": {
"LogGroupName": {"Ref": "Logs"},
"FilterPattern": "",
},
}
template = Template(
"",
{
"AWSTemplateFormatVersion": "2010-09-09",
"Transform": "AWS::Serverless-2016-10-31",
"Conditions": {
"IsProd": {"Fn::Equals": [{"Ref": "Stage"}, "prod"]},
"IsDev": {"Fn::Not": [{"Condition": "IsProd"}]},
},
"Parameters": {
"Stage": {
"Type": "String",
"AllowedValues": ["prod", "dev"],
"Default": "prod",
},
},
"Resources": {
"Logs": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"RetentionInDays": 1},
},
"ProdFunction": {
"Type": "AWS::Serverless::Function",
"Condition": "IsProd",
"Properties": {
"CodeUri": "hello_world/",
"Handler": "app.lambda_handler",
"Runtime": "python3.9",
"Events": events,
},
},
"DevFunction": {
"Type": "AWS::Serverless::Function",
"Condition": "IsDev",
"Properties": {
"CodeUri": "hello_world/",
"Handler": "app.lambda_handler",
"Runtime": "python3.9",
"Events": events,
},
},
},
},
)
# 4 Prod + 4 Dev events, but at most 4 coexist in any scenario
matches = rule.match(template)
assert len(matches) == 0

def test_non_cloudwatchlogs_event_ignored(self, rule):
"""Test that non-CloudWatchLogs event types are ignored"""
template = Template(
Expand Down
Loading