Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rules for Rules section #3703

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
Empty file.
35 changes: 35 additions & 0 deletions src/cfnlint/data/schemas/other/rules/configuration.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"additionalProperties": false,
"definitions": {
"assertion": {
"properties": {
"Assert": {},
"AssertDescription": {
"type": "string"
}
},
"type": "object"
},
"rule": {
"properties": {
"Assertions": {
"items": {
"$ref": "#/definitions/assertion"
},
"type": "array"
},
"RuleCondition": {}
},
"required": [
"Assertions"
],
"type": "object"
}
},
"patternProperties": {
"^[A-Za-z0-9]+$": {
"$ref": "#/definitions/rule"
}
},
"type": "object"
}
21 changes: 21 additions & 0 deletions src/cfnlint/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,12 +185,33 @@
FUNCTION_NOT = "Fn::Not"
FUNCTION_EQUALS = "Fn::Equals"
FUNCTION_BASE64 = "Fn::Base64"
FUNCTION_CONTAINS = "Fn::Contains"
FUNCTION_EACH_MEMBER_EQUALS = "Fn::EachMemberEquals"
FUNCTION_EACH_MEMBER_IN = "Fn::EachMemberIn"
FUNCTION_REF_ALL = "Fn::RefAll"
FUNCTION_VALUE_OF = "Fn::ValueOf"
FUNCTION_VALUE_OF_ALL = "Fn::ValueOfAll"
FUNCTION_FOR_EACH = re.compile(r"^Fn::ForEach::[a-zA-Z0-9]+$")

FUNCTION_CONDITIONS = frozenset(
[FUNCTION_AND, FUNCTION_OR, FUNCTION_NOT, FUNCTION_EQUALS]
)

FUNCTION_RULES = frozenset(
[
FUNCTION_AND,
FUNCTION_OR,
FUNCTION_NOT,
FUNCTION_EQUALS,
FUNCTION_CONTAINS,
FUNCTION_EACH_MEMBER_EQUALS,
FUNCTION_EACH_MEMBER_IN,
FUNCTION_REF_ALL,
FUNCTION_VALUE_OF,
FUNCTION_VALUE_OF_ALL,
]
)

FUNCTIONS_ALL = frozenset.union(
*[FUNCTIONS, FUNCTION_CONDITIONS, frozenset(["Condition"])]
)
Expand Down
2 changes: 1 addition & 1 deletion src/cfnlint/rules/resources/ectwo/RouteTableAssociation.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def get_values(self, subnetid, resource_condition, property_condition):
if isinstance(subnetid, dict):
if len(subnetid) == 1:
for key, value in subnetid.items():
if key in cfnlint.helpers.CONDITION_FUNCTIONS:
if key == cfnlint.helpers.FUNCTION_IF:
if isinstance(value, list):
if len(value) == 3:
property_condition = value[0]
Expand Down
41 changes: 41 additions & 0 deletions src/cfnlint/rules/rules/Assert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""

from __future__ import annotations

from typing import Any

from cfnlint.helpers import FUNCTION_RULES
from cfnlint.jsonschema import ValidationResult, Validator
from cfnlint.rules.jsonschema.CfnLintJsonSchema import CfnLintJsonSchema


class Assert(CfnLintJsonSchema):
id = "E1701"
shortdesc = "Validate the configuration of Assertions"
description = "Make sure the Assert value in a Rule is properly configured"
source_url = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/rules-section-structure.html"
tags = ["rules"]

def __init__(self):
super().__init__(
keywords=["Rules/*/Assertions/*/Assert"],
all_matches=True,
)

def validate(
self, validator: Validator, keywords: Any, instance: Any, schema: dict[str, Any]
) -> ValidationResult:
validator = validator.evolve(
context=validator.context.evolve(
functions=list(FUNCTION_RULES) + ["Condition"],
),
function_filter=validator.function_filter.evolve(
add_cfn_lint_keyword=False,
),
schema={"type": "boolean"},
)

yield from self._iter_errors(validator, instance)
67 changes: 67 additions & 0 deletions src/cfnlint/rules/rules/Configuration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""

from __future__ import annotations

from typing import Any

import cfnlint.data.schemas.other.rules
from cfnlint.jsonschema import Validator
from cfnlint.jsonschema._keywords import patternProperties
from cfnlint.jsonschema._keywords_cfn import cfn_type
from cfnlint.rules.jsonschema.CfnLintJsonSchema import CfnLintJsonSchema, SchemaDetails


class Configuration(CfnLintJsonSchema):
id = "E1700"
shortdesc = "Rules have the appropriate configuration"
description = "Making sure the Rules section is properly configured"
source_url = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/rules-section-structure.html"
tags = ["rules"]

def __init__(self):
super().__init__(
keywords=["Rules"],
schema_details=SchemaDetails(
cfnlint.data.schemas.other.rules, "configuration.json"
),
all_matches=True,
)
self.validators = {
"type": cfn_type,
"patternProperties": self._pattern_properties,
}

def _pattern_properties(
self, validator: Validator, aP: Any, instance: Any, schema: Any
):
# We have to rework pattern properties
# to re-add the keyword or we will have an
# infinite loop
validator = validator.evolve(
function_filter=validator.function_filter.evolve(
add_cfn_lint_keyword=True,
)
)
yield from patternProperties(validator, aP, instance, schema)

def validate(
self, validator: Validator, conditions: Any, instance: Any, schema: Any
):
rule_validator = self.extend_validator(
validator=validator,
schema=self.schema,
context=validator.context.evolve(
resources={},
strict_types=False,
),
).evolve(
context=validator.context.evolve(strict_types=False),
function_filter=validator.function_filter.evolve(
add_cfn_lint_keyword=False,
),
)

yield from super()._iter_errors(rule_validator, instance)
41 changes: 41 additions & 0 deletions src/cfnlint/rules/rules/RuleCondition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""

from __future__ import annotations

from typing import Any

from cfnlint.helpers import FUNCTION_RULES
from cfnlint.jsonschema import ValidationResult, Validator
from cfnlint.rules.jsonschema.CfnLintJsonSchema import CfnLintJsonSchema


class RuleCondition(CfnLintJsonSchema):
id = "E1702"
shortdesc = "Validate the configuration of Rules RuleCondition"
description = "Make sure the RuleCondition in a Rule is properly configured"
source_url = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/rules-section-structure.html"
tags = ["rules"]

def __init__(self):
super().__init__(
keywords=["Rules/*/RuleCondition"],
all_matches=True,
)

def validate(
self, validator: Validator, keywords: Any, instance: Any, schema: dict[str, Any]
) -> ValidationResult:
validator = validator.evolve(
context=validator.context.evolve(
functions=list(FUNCTION_RULES) + ["Condition"],
),
function_filter=validator.function_filter.evolve(
add_cfn_lint_keyword=False,
),
schema={"type": "boolean"},
)

yield from self._iter_errors(validator, instance)
Empty file.
6 changes: 3 additions & 3 deletions src/cfnlint/template/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ def get_condition_values(self, template, path: Path | None) -> list[dict[str, An
# Checking for conditions inside of conditions
if isinstance(item, dict):
for sub_key, sub_value in item.items():
if sub_key in cfnlint.helpers.CONDITION_FUNCTIONS:
if sub_key == cfnlint.helpers.FUNCTION_IF:
results = self.get_condition_values(
sub_value, result["Path"] + [sub_key]
)
Expand Down Expand Up @@ -521,7 +521,7 @@ def get_values(self, obj, key, path: Path | None = None):
is_condition = False
is_no_value = False
for obj_key, obj_value in value.items():
if obj_key in cfnlint.helpers.CONDITION_FUNCTIONS:
if obj_key == cfnlint.helpers.FUNCTION_IF:
is_condition = True
results = self.get_condition_values(
obj_value, path[:] + [obj_key]
Expand Down Expand Up @@ -552,7 +552,7 @@ def get_values(self, obj, key, path: Path | None = None):
is_condition = False
is_no_value = False
for obj_key, obj_value in list_value.items():
if obj_key in cfnlint.helpers.CONDITION_FUNCTIONS:
if obj_key == cfnlint.helpers.FUNCTION_IF:
is_condition = True
results = self.get_condition_values(
obj_value, path[:] + [list_index, obj_key]
Expand Down
3 changes: 3 additions & 0 deletions test/integration/test_schema_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ class TestSchemaFiles(TestCase):
"Resources/*/Type",
"Resources/*/UpdatePolicy",
"Resources/*/UpdateReplacePolicy",
"Rules",
"Rules/*/Assertions/*/Assert",
"Rules/*/RuleCondition",
"Transform",
]

Expand Down
Empty file.
50 changes: 50 additions & 0 deletions test/unit/rules/rules/test_assert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""

from collections import deque

import pytest

from cfnlint.jsonschema import ValidationError
from cfnlint.rules.rules.Assert import Assert


@pytest.fixture(scope="module")
def rule():
rule = Assert()
yield rule


@pytest.mark.parametrize(
"name,instance,expected",
[
(
"boolean is okay",
True,
[],
),
(
"wrong type",
[],
[
ValidationError(
"[] is not of type 'boolean'",
validator="type",
schema_path=deque(["type"]),
rule=Assert(),
)
],
),
(
"functions are okay",
{"Fn::Equals": ["a", "b"]},
[],
),
],
)
def test_validate(name, instance, expected, rule, validator):
errs = list(rule.validate(validator, {}, instance, {}))

assert errs == expected, f"Test {name!r} got {errs!r}"
Loading
Loading