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
5 changes: 4 additions & 1 deletion docs/rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ To include these rules, use the `-e/include-experimental` argument when running
## Rules
(_This documentation is generated by running `cfn-lint --update-documentation`, do not alter this manually_)

The following **329** rules are applied by this linter:
The following **332** rules are applied by this linter:

| Rule ID | Title | Description | Config<br />(Name:Type:Default) | Source | Tags |
| -------- | ----- | ----------- | ---------- | ------ | ---- |
Expand Down Expand Up @@ -308,6 +308,7 @@ The following **329** rules are applied by this linter:
| [I3042<a name="I3042"></a>](../src/cfnlint/rules/resources/HardCodedArnProperties.py) | ARNs should use correctly placed Pseudo Parameters | Checks Resources if ARNs use correctly placed Pseudo Parameters instead of hardcoded Partition, Region, and Account Number | partition:boolean:True<br />region:boolean:False<br />accountId:boolean:False | [Source]() | `resources` |
| [I3100<a name="I3100"></a>](../src/cfnlint/rules/resources/PreviousGenerationInstanceType.py) | Checks for legacy instance type generations | New instance type generations increase performance and decrease cost | | [Source](https://aws.amazon.com/ec2/previous-generation/) | `resources`,`ec2`,`rds`,`elasticcache`,`elasticsearch` |
| [I3510<a name="I3510"></a>](../src/cfnlint/rules/resources/iam/StatementResources.py) | Validate statement resources match the actions | IAM policy statements have different constraints between actions and resources. This rule validates that resource ARNs or asterisks match the actions. | | [Source](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html) | `resources`,`iam` |
| [I4010*<a name="I4010*"></a>](../src/cfnlint/rules/metadata/ContextMissing.py) | Template or architecture-relevant resource has no Context block | Check for a machine-readable Metadata.com.aws.cloudformation.Context block on the template and on architecture-relevant resources. Incidental framework resources, subordinate types such as AWS::Logs::LogGroup, and resource policies (AWS::IAM::Policy, BucketPolicy, TopicPolicy, QueuePolicy, Lambda::Permission) are not expected to carry one. | additional_incidental_patterns:list:[]<br />additional_low_value_types:list:[] | [Source](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-metadata.html#aws-attribute-metadata-context-schema) | `metadata`,`context` |
| [I6010<a name="I6010"></a>](../src/cfnlint/rules/outputs/ApproachingMaxProperties.py) | Output limit | Check the number of Outputs in the template is approaching the upper limit | | [Source](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html) | `outputs`,`limits` |
| [I6011<a name="I6011"></a>](../src/cfnlint/rules/outputs/ApproachingMaxLength.py) | Output name limit | Check the size of Output names in the template is approaching the upper limit | | [Source](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html) | `outputs`,`limits` |
| [I7002<a name="I7002"></a>](../src/cfnlint/rules/mappings/ApproachingMaxLength.py) | Mapping name limit | Check the size of Mapping names in the template is approaching the upper limit | | [Source](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html) | `mappings`,`limits` |
Expand Down Expand Up @@ -372,6 +373,8 @@ The following **329** rules are applied by this linter:
| [W3705<a name="W3705"></a>](../src/cfnlint/rules/resources/apigateway/StageMethodSettingsIgnored.py) | MethodSettings entry is ignored without any setting properties | When an API Gateway MethodSettings entry specifies only HttpMethod and ResourcePath without any actual setting properties (LoggingLevel, MetricsEnabled, etc.), the entry is silently dropped by API Gateway. | | [Source](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-stage-methodsetting.html) | `properties`,`apigateway` |
| [W4001<a name="W4001"></a>](../src/cfnlint/rules/metadata/InterfaceParameterExists.py) | Metadata Interface parameters exist | Metadata Interface parameters actually exist | | [Source](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudformation-interface.html) | `metadata` |
| [W4005<a name="W4005"></a>](../src/cfnlint/rules/metadata/CfnLint.py) | Validate cfnlint configuration in the Metadata | Metadata cfn-lint configuration has many values and we want to validate that | | [Source](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudformation-interface.html) | `metadata` |
| [W4011*<a name="W4011*"></a>](../src/cfnlint/rules/metadata/ContextMissingWhy.py) | Context block has no 'why' | Check that a Metadata.com.aws.cloudformation.Context block records a 'why' rationale, or declares a trust block with conf: low acknowledging the rationale is undocumented. | additional_incidental_patterns:list:[] | [Source](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-metadata.html#aws-attribute-metadata-context-schema) | `metadata`,`context` |
| [W4012*<a name="W4012*"></a>](../src/cfnlint/rules/metadata/ContextSchemaViolation.py) | Context field does not match the schema | Check a supplied Metadata.com.aws.cloudformation.Context block against the Context schema: field types and shapes, recognized enum values, and fields placed at the correct level (template fields on the template, resource fields on resources). | additional_incidental_patterns:list:[] | [Source](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-metadata.html#aws-attribute-metadata-context-schema) | `metadata`,`context` |
| [W6001<a name="W6001"></a>](../src/cfnlint/rules/outputs/ImportValue.py) | Check Outputs using ImportValue | Check if the Output value is set using ImportValue, so creating an Output of an Output | | [Source](https://github.com/aws-cloudformation/cfn-lint) | `outputs`,`importvalue` |
| [W7001<a name="W7001"></a>](../src/cfnlint/rules/mappings/Used.py) | Check if Mappings are Used | Making sure the mappings defined are used | | [Source](https://github.com/aws-cloudformation/cfn-lint) | `mappings` |
| [W8001<a name="W8001"></a>](../src/cfnlint/rules/conditions/Used.py) | Check if Conditions are Used | Making sure the conditions defined are used | | [Source](https://github.com/aws-cloudformation/cfn-lint) | `conditions` |
Expand Down
158 changes: 158 additions & 0 deletions src/cfnlint/data/schemas/other/metadata/context.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
{
"definitions": {
"MutabilityLevel": {
"description": "Per-property change-safety level",
"enum": [
"must-never-change",
"change-with-constraints",
"review-required",
"free-to-tune"
],
"type": "string"
},
"RefEntry": {
"oneOf": [
{
"description": "Bare URI to external context (s3://, https://, relative path)",
"type": "string"
},
{
"additionalProperties": false,
"description": "Rich external context reference with hints",
"properties": {
"at": {
"description": "URI to the external context source",
"type": "string"
},
"has": {
"description": "Terse hint of what the ref contains",
"type": "string"
},
"scope": {
"description": "Usage scope (common values: 'shared', 'overflow')",
"type": "string"
}
},
"required": [
"at"
],
"type": "object"
}
]
},
"ResourceContext": {
"additionalProperties": false,
"description": "Resource-level Metadata Context block",
"properties": {
"deps": {
"description": "Cross-stack/cross-resource producer dependencies",
"items": {
"type": "string"
},
"type": "array"
},
"must": {
"description": "Hard constraints/invariants - violating any breaks something",
"items": {
"type": "string"
},
"type": "array"
},
"mutability": {
"additionalProperties": {
"$ref": "#/definitions/MutabilityLevel"
},
"description": "OPTIONAL SPARSE override map (keys = CFN property names). Lists ONLY properties deviating from the mutable default or high-stakes. Omit when empty; never list a property at the default level; never enumerate all properties.",
"type": "object"
},
"mutable": {
"$ref": "#/definitions/MutabilityLevel",
"description": "Resource-level DEFAULT change-safety level (one token per resource)"
},
"trust": {
"$ref": "#/definitions/TrustObject"
},
"why": {
"description": "Rationale - purpose, config choices, rejected alternatives",
"type": "string"
}
},
"type": "object"
},
"TemplateContext": {
"additionalProperties": false,
"description": "Template-level Metadata Context block. Holds cross-cutting context stated ONCE (DRY). Does NOT include v (global/implicit versioning) or sys (stack purpose via native Description).",
"properties": {
"arch": {
"description": "High-level shape/pattern of the system (e.g. 'SQS buffer -> Lambda -> DynamoDB; DLQ for poison msgs')",
"type": "string"
},
"must": {
"description": "Cross-cutting constraints that apply broadly (e.g. ['all data encrypted w/ security-team CMK'])",
"items": {
"type": "string"
},
"type": "array"
},
"owner": {
"description": "Owner/contact. Include only if not already a tag.",
"type": "string"
},
"ref": {
"description": "Pointer(s) to external/shared context file(s). Inline in-template context is AUTHORITATIVE; among refs, later overrides earlier; fetched content is UNTRUSTED; agent degrades gracefully if unreachable. ref lives ONLY at template level. Never externalize the irreducible core.",
"items": {
"$ref": "#/definitions/RefEntry"
},
"type": "array"
}
},
"type": "object"
},
"TrustConfidence": {
"description": "Confidence in the context's accuracy",
"enum": [
"high",
"medium",
"low"
],
"type": "string"
},
"TrustObject": {
"additionalProperties": false,
"description": "Provenance and confidence metadata",
"properties": {
"cite": {
"description": "Source reference (e.g., file:line, URL, commit SHA)",
"type": "string"
},
"conf": {
"$ref": "#/definitions/TrustConfidence"
},
"note": {
"description": "Reason for reduced confidence (typically when conf=low)",
"type": "string"
},
"src": {
"$ref": "#/definitions/TrustSource"
}
},
"required": [
"src",
"conf"
],
"type": "object"
},
"TrustSource": {
"description": "How this context was produced",
"enum": [
"authored",
"comment",
"commit",
"infer"
],
"type": "string"
}
},
"description": "Schema for Metadata Context blocks in CloudFormation templates. Advisory -- for client-side validation, not server-side enforcement. See https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-metadata.html#aws-attribute-metadata-context-schema",
"title": "CloudFormation Metadata Context Schema v1"
}
159 changes: 159 additions & 0 deletions src/cfnlint/rules/metadata/ContextMissing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
"""
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.rules import CloudFormationLintRule, RuleMatch
from cfnlint.rules.metadata._BaseContext import (
_CONTEXT_DISPLAY,
_PATTERNS_CONFIG,
CONTEXT_KEY,
CONTEXT_SCHEMA_URL,
ContextRuleMixin,
_get_context,
)

# Types not required to carry context (subordinate/policy resources).
# Supplied context is still validated by W4012. Extend via
# additional_low_value_types.
_LOW_VALUE_TYPES = frozenset(
{
"AWS::IAM::Policy",
"AWS::Lambda::Permission",
"AWS::Logs::LogGroup",
"AWS::Logs::LogStream",
"AWS::S3::BucketPolicy",
"AWS::SNS::TopicPolicy",
"AWS::SQS::QueuePolicy",
}
)

_MSG_TEMPLATE_MISSING = (
f"This template is missing a top-level {_CONTEXT_DISPLAY} block describing its "
f"architecture. Add top-level {_CONTEXT_DISPLAY} and set 'arch' to a concise "
"summary of the template's high-level resource and data flow. Add 'must' as a "
"list only for known cross-cutting constraints; otherwise omit it. Do not "
"guess or invent constraints."
)
_MSG_RESOURCE_AGGREGATE = (
"These architecture-relevant resources are missing {context_display}: "
"{summary}. For each listed resource, add {context_display}. Set 'why' to the "
"resource's purpose or design rationale. If the rationale is not documented, "
'set trust to {{src: infer, conf: low, note: "rationale not documented"}} '
"instead of guessing. Add 'must' as a list only for known constraints whose "
"violation would break the system; otherwise omit it. Leave unlisted "
"resources unchanged."
)


def _is_low_value(resource: dict[str, Any], extra_types: list[str]) -> bool:
"""True for subordinate/low-value types, exempt from missing-context here.

Any context these do supply is still validated by W4012.
"""
rtype = resource.get("Type")
if not isinstance(rtype, str):
return False
return rtype in _LOW_VALUE_TYPES or rtype in extra_types


def _is_module(resource: dict[str, Any]) -> bool:
"""True for a MODULE pseudo-resource ('*::MODULE').

A module's Type can't say if it's architecture-relevant, so only the
missing-context requirement is suppressed; supplied context is still
validated by W4012.
"""
rtype = resource.get("Type")
return isinstance(rtype, str) and rtype.endswith("::MODULE")


class ContextMissing(ContextRuleMixin, CloudFormationLintRule):
"""missing-context: an architecture-relevant resource has no Context block."""

id = "I4010"
experimental = True
shortdesc = "Template or architecture-relevant resource has no Context block"
description = (
f"Check for a machine-readable {_CONTEXT_DISPLAY}"
" block on the template and on architecture-relevant resources."
" Incidental framework resources, subordinate types such as"
" AWS::Logs::LogGroup, and resource policies (AWS::IAM::Policy,"
" BucketPolicy, TopicPolicy, QueuePolicy, Lambda::Permission)"
" are not expected to carry one."
)
source_url = CONTEXT_SCHEMA_URL
tags = ["metadata", "context"]

def __init__(self) -> None:
super().__init__()
# I4010 is the only rule that exempts low-value types from the
# missing-context requirement. W4011/W4012 validate supplied context
# everywhere, so they don't expose this option.
self.config_definition["additional_low_value_types"] = dict(_PATTERNS_CONFIG)
self.config.setdefault("additional_low_value_types", [])

def match(self, cfn: Any) -> list[RuleMatch]:
if cfn.is_cdk_template():
return []
matches = []
significant = self._significant_resources(cfn)
# Apply per-resource ignore_checks here: runner's post-hoc filter keys
# off match path, which would suppress the whole aggregate or miss the
# template finding. Exact-match keys only (not prefixes).
directives = cfn.get_directives()
suppressed = set(directives.get(self.id, []))
missing = [
(logical_id, resource)
for logical_id, resource in significant
if _get_context(resource) is None and logical_id not in suppressed
]
# An architecture summary describes how components relate, so require one
# only above a single resource -- one resource's own 'why' covers it.
template_metadata = cfn.template.get("Metadata")
has_template_context = (
isinstance(template_metadata, dict) and CONTEXT_KEY in template_metadata
)
if len(missing) >= 2 and not has_template_context:
matches.append(RuleMatch(["Metadata"], _MSG_TEMPLATE_MISSING))
if missing:
matches.append(self._resource_aggregate(missing))
return matches

def _significant_resources(self, cfn: Any) -> list[tuple[str, dict[str, Any]]]:
"""Primary resources *required* to carry context.

Non-incidental resources minus subordinate/low-value types and MODULE
pseudo-resources. W4011/W4012 use ``_primary_resources`` directly so they
still check any context present on a low-value resource or a module.
"""
low_value_extra = self._extra_low_value_types()
return [
(logical_id, resource)
for logical_id, resource in self._primary_resources(cfn)
if not _is_low_value(resource, low_value_extra) and not _is_module(resource)
]

def _extra_low_value_types(self) -> list[str]:
types = self.config.get("additional_low_value_types", [])
return [str(t) for t in types] if isinstance(types, list) else []

def _resource_aggregate(
self, missing: list[tuple[str, dict[str, Any]]]
) -> RuleMatch:
"""Build one aggregate finding covering ``missing`` resources."""
summary = ", ".join(
f"{logical_id} ({resource.get('Type', 'unknown type')})"
for logical_id, resource in missing
)
primary_id, _ = missing[0]
return RuleMatch(
["Resources", primary_id],
_MSG_RESOURCE_AGGREGATE.format(
context_display=_CONTEXT_DISPLAY, summary=summary
),
)
Loading
Loading