repo
stringclasses
358 values
pull_number
int64
6
67.9k
instance_id
stringlengths
12
49
issue_numbers
sequencelengths
1
7
base_commit
stringlengths
40
40
patch
stringlengths
87
101M
test_patch
stringlengths
72
22.3M
problem_statement
stringlengths
3
256k
hints_text
stringlengths
0
545k
created_at
stringlengths
20
20
PASS_TO_PASS
sequencelengths
0
0
FAIL_TO_PASS
sequencelengths
0
0
aws-cloudformation/cfn-lint
1,144
aws-cloudformation__cfn-lint-1144
[ "1141" ]
9a42be5007813de4a7d1742264f5a991193b8273
diff --git a/src/cfnlint/rules/functions/SubNeeded.py b/src/cfnlint/rules/functions/SubNeeded.py --- a/src/cfnlint/rules/functions/SubNeeded.py +++ b/src/cfnlint/rules/functions/SubNeeded.py @@ -18,6 +18,7 @@ from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch + class SubNeeded(CloudFormationLintRule): """Check if a substitution string exists without a substitution function""" id = 'E1029' @@ -28,7 +29,8 @@ class SubNeeded(CloudFormationLintRule): # Free-form text properties to exclude from this rule # content is part of AWS::CloudFormation::Init - excludes = ['UserData', 'ZipFile', 'Condition', 'AWS::CloudFormation::Init', 'CloudWatchAlarmDefinition', 'TopicRulePayload'] + excludes = ['UserData', 'ZipFile', 'Condition', 'AWS::CloudFormation::Init', + 'CloudWatchAlarmDefinition', 'TopicRulePayload'] api_excludes = ['Uri', 'Body'] # IAM Policy has special variables that don't require !Sub, Check for these @@ -37,13 +39,25 @@ class SubNeeded(CloudFormationLintRule): # https://docs.aws.amazon.com/iot/latest/developerguide/thing-policy-variables.html # https://docs.aws.amazon.com/transfer/latest/userguide/users.html#users-policies-scope-down # https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html - resource_excludes = ['${aws:CurrentTime}', '${aws:EpochTime}', '${aws:TokenIssueTime}', '${aws:principaltype}', - '${aws:SecureTransport}', '${aws:SourceIp}', '${aws:UserAgent}', '${aws:userid}', + resource_excludes = ['${aws:CurrentTime}', '${aws:EpochTime}', + '${aws:TokenIssueTime}', '${aws:principaltype}', + '${aws:SecureTransport}', '${aws:SourceIp}', + '${aws:UserAgent}', '${aws:userid}', '${aws:username}', '${ec2:SourceInstanceARN}', - '${iot:Connection.Thing.ThingName}', '${iot:Connection.Thing.ThingTypeName}', - '${iot:Connection.Thing.IsAttached}', '${iot:ClientId}', '${transfer:HomeBucket}', - '${transfer:HomeDirectory}', '${transfer:HomeFolder}', '${transfer:UserName}', - '${cognito-identity.amazonaws.com:aud}', '${cognito-identity.amazonaws.com:sub}', '${cognito-identity.amazonaws.com:amr}'] + '${iot:Connection.Thing.ThingName}', + '${iot:Connection.Thing.ThingTypeName}', + '${iot:Connection.Thing.IsAttached}', + '${iot:ClientId}', '${transfer:HomeBucket}', + '${transfer:HomeDirectory}', '${transfer:HomeFolder}', + '${transfer:UserName}', '${redshift:DbUser}', + '${cognito-identity.amazonaws.com:aud}', + '${cognito-identity.amazonaws.com:sub}', + '${cognito-identity.amazonaws.com:amr}'] + + # https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-access-control-identity-based.html + condition_excludes = [ + '${redshift:DbUser}', + ] def _match_values(self, searchRegex, cfnelem, path): """Recursively search for values matching the searchRegex""" @@ -96,13 +110,15 @@ def match(self, cfn): # We want to search all of the paths to check if each one contains an 'Fn::Sub' for parameter_string_path in parameter_string_paths: - # Exxclude the special IAM variables variable = parameter_string_path[-1] if 'Resource' in parameter_string_path: if variable in self.resource_excludes: continue + if 'Condition' in parameter_string_path: + if variable in self.condition_excludes: + continue # Exclude literals (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html) if variable.startswith('${!'): @@ -121,7 +137,8 @@ def match(self, cfn): if not found_sub: # Remove the last item (the variable) to prevent multiple errors on 1 line errors path = parameter_string_path[:-1] - message = 'Found an embedded parameter outside of an "Fn::Sub" at {}'.format('/'.join(map(str, path))) + message = 'Found an embedded parameter outside of an "Fn::Sub" at {}'.format( + '/'.join(map(str, path))) matches.append(RuleMatch(path, message)) return matches
diff --git a/test/fixtures/templates/good/functions/sub_needed.yaml b/test/fixtures/templates/good/functions/sub_needed.yaml --- a/test/fixtures/templates/good/functions/sub_needed.yaml +++ b/test/fixtures/templates/good/functions/sub_needed.yaml @@ -18,6 +18,60 @@ Resources: Action: - "iam:UploadSSHPublicKey" Resource: "arn:aws:iam::*:user/${aws:username}" + myPolicy2: + Type: AWS::IAM::Policy + Properties: + Roles: + - testRole + PolicyName: test2 + PolicyDocument: + { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "GetClusterCredsStatement", + "Effect": "Allow", + "Action": [ + "redshift:GetClusterCredentials" + ], + "Resource": [ + "arn:aws:redshift:us-west-2:123456789012:dbuser:examplecluster/${redshift:DbUser}", + "arn:aws:redshift:us-west-2:123456789012:dbname:examplecluster/testdb", + "arn:aws:redshift:us-west-2:123456789012:dbgroup:examplecluster/common_group" + ], + "Condition": { + "StringEquals": { + "aws:userid":"AIDIODR4TAW7CSEXAMPLE:${redshift:DbUser}@yourdomain.com" + } + } + }, + { + "Sid": "CreateClusterUserStatement", + "Effect": "Allow", + "Action": [ + "redshift:CreateClusterUser" + ], + "Resource": [ + "arn:aws:redshift:us-west-2:123456789012:dbuser:examplecluster/${redshift:DbUser}" + ], + "Condition": { + "StringEquals": { + "aws:userid":"AIDIODR4TAW7CSEXAMPLE:${redshift:DbUser}@yourdomain.com" + } + } + }, + { + "Sid": "RedshiftJoinGroupStatement", + "Effect": "Allow", + "Action": [ + "redshift:JoinGroup" + ], + "Resource": [ + "arn:aws:redshift:us-west-2:123456789012:dbgroup:examplecluster/common_group" + ] + } + ] + } Key: Type: AWS::ApiGateway::ApiKey Properties:
E1029 - False positive with IAM policy Redshift condition keys *cfn-lint version: (`cfn-lint --version`)* cfn-lint 0.24.1 *Description of issue.* ${redshift:DbUser} triggers: `E1029:Found an embedded parameter outside of an "Fn::Sub"` I'm defining a policy document similar to the one below. cfn-lint returns a E1029 on each line where the ${redshift:DbUser} condition key is used. Source: [https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-access-control-identity-based.html#redshift-policy-resources.getclustercredentials-resources](url) Sample: ```json { "Version": "2012-10-17", "Statement": [ { "Sid": "GetClusterCredsStatement", "Effect": "Allow", "Action": [ "redshift:GetClusterCredentials" ], "Resource": [ "arn:aws:redshift:us-west-2:123456789012:dbuser:examplecluster/${redshift:DbUser}", "arn:aws:redshift:us-west-2:123456789012:dbname:examplecluster/testdb", "arn:aws:redshift:us-west-2:123456789012:dbgroup:examplecluster/common_group" ], "Condition": { "StringEquals": { "aws:userid":"AIDIODR4TAW7CSEXAMPLE:${redshift:DbUser}@yourdomain.com" } } }, { "Sid": "CreateClusterUserStatement", "Effect": "Allow", "Action": [ "redshift:CreateClusterUser" ], "Resource": [ "arn:aws:redshift:us-west-2:123456789012:dbuser:examplecluster/${redshift:DbUser}" ], "Condition": { "StringEquals": { "aws:userid":"AIDIODR4TAW7CSEXAMPLE:${redshift:DbUser}@yourdomain.com" } } }, { "Sid": "RedshiftJoinGroupStatement", "Effect": "Allow", "Action": [ "redshift:JoinGroup" ], "Resource": [ "arn:aws:redshift:us-west-2:123456789012:dbgroup:examplecluster/common_group" ] } ] } ``` Resource string from actual template: `{ "Fn::Join" : [ "", [ "arn:aws:redshift:us-west-2:", { "Ref" : "AWS::AccountId" }, ":dbuser:", { "Fn::FindInMap" : [ "Environment", { "Ref" : "EnvironmentType" }, "RSClusterName" ] }, "/${redshift:DBUser}" ] ] }`
2019-09-28T12:22:09Z
[]
[]
aws-cloudformation/cfn-lint
1,151
aws-cloudformation__cfn-lint-1151
[ "1127" ]
32bc877d4eb556d8bdf3f7f40a171826de0f20d0
diff --git a/src/cfnlint/__init__.py b/src/cfnlint/__init__.py --- a/src/cfnlint/__init__.py +++ b/src/cfnlint/__init__.py @@ -229,16 +229,23 @@ def get_valid_getatts(self): results = {} resources = self.template.get('Resources', {}) - astrik_types = ( - 'Custom::', 'AWS::CloudFormation::Stack', + astrik_string_types = ( + 'AWS::CloudFormation::Stack', + ) + astrik_unknown_types = ( + 'Custom::', 'AWS::Serverless::', 'AWS::CloudFormation::CustomResource' ) + for name, value in resources.items(): if 'Type' in value: valtype = value['Type'] - if valtype.startswith(astrik_types): + if valtype.startswith(astrik_string_types): LOGGER.debug('Cant build an appropriate getatt list from %s', valtype) results[name] = {'*': {'PrimitiveItemType': 'String'}} + elif valtype.startswith(astrik_unknown_types): + LOGGER.debug('Cant build an appropriate getatt list from %s', valtype) + results[name] = {'*': {}} else: if value['Type'] in resourcetypes: if 'Attributes' in resourcetypes[valtype]: diff --git a/src/cfnlint/rules/functions/Join.py b/src/cfnlint/rules/functions/Join.py --- a/src/cfnlint/rules/functions/Join.py +++ b/src/cfnlint/rules/functions/Join.py @@ -78,18 +78,22 @@ def _is_ref_a_list(self, parameter, template_parameters): return True return False - def _is_getatt_a_list(self, parameter, get_atts): """ Is a GetAtt a List """ for resource, attributes in get_atts.items(): for attribute_name, attribute_values in attributes.items(): - if resource == parameter[0] and attribute_name in ['*', parameter[1]]: + if resource == parameter[0] and attribute_name == '*': + if attribute_values.get('PrimitiveItemType'): + return 'FALSE' if attribute_values.get('Type') == 'List': - return True - - return False + return 'TRUE' + return 'UNKNOWN' + if resource == parameter[0] and attribute_name == parameter[1]: + if attribute_values.get('Type') == 'List': + return 'TRUE' + return 'FALSE' def _match_string_objs(self, join_string_objs, cfn, path): """ Check join list """ @@ -112,7 +116,7 @@ def _match_string_objs(self, join_string_objs, cfn, path): matches.append(RuleMatch( path, message.format('/'.join(map(str, path))))) elif key in ['Fn::GetAtt']: - if not self._is_getatt_a_list(self._normalize_getatt(value), get_atts): + if self._is_getatt_a_list(self._normalize_getatt(value), get_atts) == 'FALSE': message = 'Fn::Join must use a list at {0}' matches.append(RuleMatch( path, message.format('/'.join(map(str, path))))) @@ -139,7 +143,7 @@ def _match_string_objs(self, join_string_objs, cfn, path): matches.append(RuleMatch( path, message.format('/'.join(map(str, path))))) elif key in ['Fn::GetAtt']: - if self._is_getatt_a_list(self._normalize_getatt(value), get_atts): + if self._is_getatt_a_list(self._normalize_getatt(value), get_atts) == 'TRUE': message = 'Fn::Join must not be a list at {0}' matches.append(RuleMatch( path, message.format('/'.join(map(str, path)))))
diff --git a/test/fixtures/templates/good/functions/join.yaml b/test/fixtures/templates/good/functions/join.yaml --- a/test/fixtures/templates/good/functions/join.yaml +++ b/test/fixtures/templates/good/functions/join.yaml @@ -45,4 +45,26 @@ Resources: - Fn::Join: - '' - !Ref AWS::NotificationARNs + CustomResourceFn: + Type: "AWS::Serverless::Function" + Properties: + Handler: index.handler + Runtime: python3.7 + InlineCode: | + import cfnresponse + def handler(event, context): + outputs = {'ListOutput': ['joe', 'jill', 'jane', 'jim']} + return cfnresponse.send(event, context, "SUCCESS", outputs) + + CustomResource: + Type: "Custom::Resource" + Properties: + ServiceToken: !GetAtt CustomResourceFn.Arn + + Bucket: + Type: "AWS::S3::Bucket" + Properties: + Tags: + - Key: BucketUsers + Value: !Join [":", !GetAtt CustomResource.ListOutput]
E1022 Fn::Join must use a list - fails with CloudFormation Custom Resource *cfn-lint version: 0.21.4* E1022 helpfully checks Fn::Join arguments for their type as a list; however, it is not able to recognize CloudFormation Custom Resource outputs as possible lists. The following template launches successfully: ``` AWSTemplateFormatVersion: "2010-09-09" Transform: AWS::Serverless-2016-10-31 Resources: CustomResourceFn: Type: "AWS::Serverless::Function" Properties: Handler: index.handler Runtime: python3.7 InlineCode: | import cfnresponse def handler(event, context): outputs = {'ListOutput': ['joe', 'jill', 'jane', 'jim']} return cfnresponse.send(event, context, "SUCCESS", outputs) CustomResource: Type: "Custom::Resource" Properties: ServiceToken: !GetAtt CustomResourceFn.Arn Bucket: Type: "AWS::S3::Bucket" Properties: Tags: - Key: BucketUsers Value: !Join [":", !GetAtt CustomResource.ListOutput] ``` However, it raises the following error: ``` E1022 Fn::Join must use a list at Resources/Bucket/Properties/Tags/0/Value/Fn::Join cfn/core/E1022.yml:25:11 ```
2019-09-30T01:55:19Z
[]
[]
aws-cloudformation/cfn-lint
1,212
aws-cloudformation__cfn-lint-1212
[ "1211" ]
71b6848fe0137f3492bb615284ac7541bfeb1596
diff --git a/src/cfnlint/rules/resources/properties/Properties.py b/src/cfnlint/rules/resources/properties/Properties.py --- a/src/cfnlint/rules/resources/properties/Properties.py +++ b/src/cfnlint/rules/resources/properties/Properties.py @@ -68,65 +68,79 @@ def primitivetypecheck(self, value, primtype, proppath): return matches - def check_list_for_condition(self, text, prop, parenttype, resourcename, propspec, path): - """Checks lists that are a dict for conditions""" + def _check_list_for_condition(self, text, prop, parenttype, resourcename, propspec, path): + """ Loop for conditions """ matches = [] - if len(text[prop]) == 1: # pylint: disable=R1702 - for sub_key, sub_value in text[prop].items(): - if sub_key in cfnlint.helpers.CONDITION_FUNCTIONS: - if len(sub_value) == 3: - for if_i, if_v in enumerate(sub_value[1:]): - condition_path = path[:] + [sub_key, if_i + 1] - if isinstance(if_v, list): - for index, item in enumerate(if_v): - arrproppath = condition_path[:] + if len(text) == 3: + for if_i, if_v in enumerate(text[1:]): + condition_path = path[:] + [if_i + 1] + if isinstance(if_v, list): + for index, item in enumerate(if_v): + arrproppath = condition_path[:] - arrproppath.append(index) - matches.extend(self.propertycheck( - item, propspec['ItemType'], - parenttype, resourcename, arrproppath, False)) - elif isinstance(if_v, dict): - if len(if_v) == 1: - for d_k, d_v in if_v.items(): - if d_k != 'Ref' or d_v != 'AWS::NoValue': - if d_k == 'Fn::GetAtt': - resource_name = None - if isinstance(d_v, list): - resource_name = d_v[0] - elif isinstance(d_v, six.string_types): - resource_name = d_v.split('.')[0] - if resource_name: - resource_type = self.cfn.template.get( - 'Resources', {}).get(resource_name, {}).get('Type') - if not (resource_type.startswith('Custom::')): - message = 'Property {0} should be of type List for resource {1} at {2}' - matches.append( - RuleMatch( - condition_path, - message.format(prop, resourcename, ('/'.join(str(x) for x in condition_path))))) - else: - message = 'Property {0} should be of type List for resource {1} at {2}' - matches.append( - RuleMatch( - condition_path, - message.format(prop, resourcename, ('/'.join(str(x) for x in condition_path))))) + arrproppath.append(index) + matches.extend(self.propertycheck( + item, propspec['ItemType'], + parenttype, resourcename, arrproppath, False)) + elif isinstance(if_v, dict): + if len(if_v) == 1: + for d_k, d_v in if_v.items(): + if d_k != 'Ref' or d_v != 'AWS::NoValue': + if d_k == 'Fn::GetAtt': + resource_name = None + if isinstance(d_v, list): + resource_name = d_v[0] + elif isinstance(d_v, six.string_types): + resource_name = d_v.split('.')[0] + if resource_name: + resource_type = self.cfn.template.get( + 'Resources', {}).get(resource_name, {}).get('Type') + if not (resource_type.startswith('Custom::')): + message = 'Property {0} should be of type List for resource {1} at {2}' + matches.append( + RuleMatch( + condition_path, + message.format(prop, resourcename, ('/'.join(str(x) for x in condition_path))))) + elif d_k == 'Fn::If': + matches.extend( + self._check_list_for_condition( + d_v, prop, parenttype, resourcename, propspec, condition_path) + ) else: message = 'Property {0} should be of type List for resource {1} at {2}' matches.append( RuleMatch( condition_path, message.format(prop, resourcename, ('/'.join(str(x) for x in condition_path))))) - else: - message = 'Property {0} should be of type List for resource {1} at {2}' - matches.append( - RuleMatch( - condition_path, - message.format(prop, resourcename, ('/'.join(str(x) for x in condition_path))))) - else: - message = 'Invalid !If condition specified at %s' % ( - '/'.join(map(str, path))) - matches.append(RuleMatch(path, message)) + message = 'Property {0} should be of type List for resource {1} at {2}' + matches.append( + RuleMatch( + condition_path, + message.format(prop, resourcename, ('/'.join(str(x) for x in condition_path))))) + else: + message = 'Property {0} should be of type List for resource {1} at {2}' + matches.append( + RuleMatch( + condition_path, + message.format(prop, resourcename, ('/'.join(str(x) for x in condition_path))))) + + else: + message = 'Invalid !If condition specified at %s' % ( + '/'.join(map(str, path))) + matches.append(RuleMatch(path, message)) + + return matches + + def check_list_for_condition(self, text, prop, parenttype, resourcename, propspec, path): + """Checks lists that are a dict for conditions""" + matches = [] + if len(text[prop]) == 1: # pylint: disable=R1702 + for sub_key, sub_value in text[prop].items(): + if sub_key in cfnlint.helpers.CONDITION_FUNCTIONS: + matches.extend(self._check_list_for_condition( + sub_value, prop, parenttype, resourcename, propspec, path + [sub_key] + )) else: # FindInMaps can be lists of objects so skip checking those if sub_key != 'Fn::FindInMap':
diff --git a/test/fixtures/templates/bad/object_should_be_list.yaml b/test/fixtures/templates/bad/object_should_be_list.yaml --- a/test/fixtures/templates/bad/object_should_be_list.yaml +++ b/test/fixtures/templates/bad/object_should_be_list.yaml @@ -668,6 +668,12 @@ Resources: KeyType: HASH - AttributeName: !Ref SortKeyName KeyType: RANGE - - - AttributeName: !Ref PartitionKeyName - KeyType: HASH - - "String2" + - !If + - HasSortKey + - - AttributeName: !Ref PartitionKeyName + KeyType: HASH + - AttributeName: !Ref SortKeyName + KeyType: RANGE + - - AttributeName: !Ref PartitionKeyName + KeyType: HASH + - "String2" diff --git a/test/fixtures/templates/good/resources/properties/properties_nested_if.yaml b/test/fixtures/templates/good/resources/properties/properties_nested_if.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/properties/properties_nested_if.yaml @@ -0,0 +1,20 @@ +AWSTemplateFormatVersion: "2010-09-09" +Resources: + R53ResolverInboundEndPoint: + Type: AWS::Route53Resolver::ResolverEndpoint + Condition: CreateR53Resolver + Properties: + Direction: INBOUND + IpAddresses: !If + - 3AZ + - - SubnetId: !Ref PrivateSubnet1 + - SubnetId: !Ref PrivateSubnet2 + - SubnetId: !Ref PrivateSubnet3 + - !If + - 2AZ + - - SubnetId: !Ref PrivateSubnet1 + - SubnetId: !Ref PrivateSubnet2 + - - "AWS::NoValue" + Name: !Sub "vpc-${VpcName}-inbound-endpoint" + SecurityGroupIds: + - !Ref R53ResolverSecurityGroup diff --git a/test/unit/rules/resources/properties/test_properties.py b/test/unit/rules/resources/properties/test_properties.py --- a/test/unit/rules/resources/properties/test_properties.py +++ b/test/unit/rules/resources/properties/test_properties.py @@ -18,6 +18,7 @@ def setUp(self): self.success_templates = [ 'test/fixtures/templates/good/resource_properties.yaml', 'test/fixtures/templates/good/resources/properties/templated_code.yaml', + 'test/fixtures/templates/good/resources/properties/properties_nested_if.yaml', ] def test_file_positive(self):
E3002: Property IpAddresses should be of type List for resource *cfn-lint version: cfn-lint 0.25.2* When I use "conditional !If" inside "IpAddresses" properties of "AWS::Route53Resolver::ResolverEndpoint" I get error E3002. ```bash cfn-lint --info -t vpc-k8s.template 2019-11-22 10:03:57,241 - cfnlint - INFO - Run scan of template vpc-k8s.template E3002 Property IpAddresses should be of type List for resource R53ResolverInboundEndPoint at Resources/R53ResolverInboundEndPoint/Properties/IpAddresses/Fn::If/2 vpc-k8s.template:824:11 ``` But the template work perfectly and `aws cloudformation validate-template --template-body file://vpc-k8s.template` works fine too ```yaml R53ResolverInboundEndPoint: Type: AWS::Route53Resolver::ResolverEndpoint Condition: CreateR53Resolver Properties: Direction: INBOUND IpAddresses: !If - 3AZ - - SubnetId: !Ref PrivateSubnet1 - SubnetId: !Ref PrivateSubnet2 - SubnetId: !Ref PrivateSubnet3 - !If - 2AZ - - SubnetId: !Ref PrivateSubnet1 - SubnetId: !Ref PrivateSubnet2 - - "AWS::NoValue" Name: !Sub "vpc-${VpcName}-inbound-endpoint" SecurityGroupIds: - !Ref R53ResolverSecurityGroup ``` ![Screenshot 2019-11-22 at 9 39 05 AM](https://user-images.githubusercontent.com/1197820/69412968-35b65100-0d10-11ea-97f3-d71423b63ef0.png) ![Screenshot 2019-11-22 at 9 39 15 AM](https://user-images.githubusercontent.com/1197820/69412981-39e26e80-0d10-11ea-9273-4377975c9d89.png)
Thanks for the details. Thought we had this covered but obviously not. I will take a look.
2019-11-22T16:51:59Z
[]
[]
aws-cloudformation/cfn-lint
1,226
aws-cloudformation__cfn-lint-1226
[ "1222" ]
6ff7d7693f6e5170a98a35a48495ad927d46695c
diff --git a/src/cfnlint/__init__.py b/src/cfnlint/__init__.py --- a/src/cfnlint/__init__.py +++ b/src/cfnlint/__init__.py @@ -799,6 +799,7 @@ def get_object_without_conditions(self, obj): ] """ results = [] + scenarios = self.get_conditions_scenarios_from_object([obj]) if not isinstance(obj, dict): @@ -856,9 +857,10 @@ def get_conditions_from_property(value): for k, v in value.items(): if k == 'Fn::If': if isinstance(v, list) and len(v) == 3: - results.add(v[0]) - results = results.union(get_conditions_from_property(v[1])) - results = results.union(get_conditions_from_property(v[2])) + if isinstance(v[0], six.string_types): + results.add(v[0]) + results = results.union(get_conditions_from_property(v[1])) + results = results.union(get_conditions_from_property(v[2])) elif isinstance(value, list): for v in value: results = results.union(get_conditions_from_property(v)) diff --git a/src/cfnlint/rules/conditions/Exists.py b/src/cfnlint/rules/conditions/Exists.py --- a/src/cfnlint/rules/conditions/Exists.py +++ b/src/cfnlint/rules/conditions/Exists.py @@ -28,9 +28,8 @@ def match(self, cfn): iftrees = cfn.search_deep_keys('Fn::If') for iftree in iftrees: if isinstance(iftree[-1], list): - ref_conditions[iftree[-1][0]] = iftree - else: - ref_conditions[iftree[-1]] = iftree + if isinstance(iftree[-1][0], six.string_types): + ref_conditions[iftree[-1][0]] = iftree # Get resource's Conditions for resource_name, resource_values in cfn.get_resources().items(): diff --git a/src/cfnlint/rules/functions/If.py b/src/cfnlint/rules/functions/If.py --- a/src/cfnlint/rules/functions/If.py +++ b/src/cfnlint/rules/functions/If.py @@ -25,16 +25,23 @@ def match(self, cfn): # Get the conditions used in the functions for iftree in iftrees: - if isinstance(iftree[-1], list): - if_condition = iftree[-1][0] + ifs = iftree[-1] + if isinstance(ifs, list): + if_condition = ifs[0] + if len(ifs) != 3: + message = 'Fn::If must be a list of 3 elements.' + matches.append(RuleMatch( + iftree[:-1], message + )) + if not isinstance(if_condition, six.string_types): + message = 'Fn::If first element must be a condition and a string.' + matches.append(RuleMatch( + iftree[:-1] + [0], message + )) else: - if_condition = iftree[-1] - - if not isinstance(if_condition, six.string_types): - message = 'Fn::If first elements must be a condition and a string.' + message = 'Fn::If must be a list of 3 elements.' matches.append(RuleMatch( - iftree[:-1] + [0], - message.format(if_condition) + iftree[:-1], message )) return matches
diff --git a/test/fixtures/templates/bad/functions/if.yaml b/test/fixtures/templates/bad/functions/if.yaml --- a/test/fixtures/templates/bad/functions/if.yaml +++ b/test/fixtures/templates/bad/functions/if.yaml @@ -8,10 +8,22 @@ Parameters: Type: String Default: isDevelopment Conditions: - isProduction: !Equals [!Ref myEnvironment, 'prd'] - isDevelopment: !Equals [!Ref myEnvironment, 'dev'] + isProduction: !Equals [!Ref myEnvironment, "prd"] + isDevelopment: !Equals [!Ref myEnvironment, "dev"] Resources: myInstance: Type: AWS::EC2::Instance Properties: - ImageId: !If [!Ref myCondition, 'ami-123456', 'ami-abcdef'] + ImageId: !If [!Ref myCondition, "ami-123456", "ami-abcdef"] + myInstance2: + Type: AWS::EC2::Instance + Properties: + ImageId: !If [myCondition, "ami-123456"] + myInstance3: + Type: AWS::EC2::Instance + Properties: + ImageId: + Fn::If: + myCondition: + - "ami-123456" + - "ami-abcdef" diff --git a/test/unit/rules/functions/test_if.py b/test/unit/rules/functions/test_if.py --- a/test/unit/rules/functions/test_if.py +++ b/test/unit/rules/functions/test_if.py @@ -20,4 +20,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/functions/if.yaml', 1) + self.helper_file_negative('test/fixtures/templates/bad/functions/if.yaml', 3)
Fn:If argument count not checked *cfn-lint version:* 0.25.3 *Description of issue.* cfn-lint does not currently appear to check the number of arguments passed to Fn::If, while there may be cases where this is not practical to check, eg where an existing list is passed. I believe it would probably be possible to detect the following case, where a list of two elements is passed explicitly. I would guess that this may also be true for various other intrinsic functions, but have not tested that. ```` Description: "Test - If argument count" Parameters: TestParam: Type: String Default: Value Conditions: HasParam: !Not [ !Equals [ !Ref TestParam, '' ] ] Resources: SSM: Type: AWS::SSM::Parameter Condition: HasParam Properties: Type: String Description: "Just a test" Name: "/This-Is-Just-A-Test" Value: !If - HasParam - ValueIfTrue ```
Agreed. Should be an easy thing to add.
2019-11-26T03:52:11Z
[]
[]
aws-cloudformation/cfn-lint
1,227
aws-cloudformation__cfn-lint-1227
[ "1223" ]
10fe59e3a78120c475b83056677cfd3140bc68a9
diff --git a/src/cfnlint/rules/parameters/Configuration.py b/src/cfnlint/rules/parameters/Configuration.py --- a/src/cfnlint/rules/parameters/Configuration.py +++ b/src/cfnlint/rules/parameters/Configuration.py @@ -28,6 +28,10 @@ class Configuration(CloudFormationLintRule): 'Type', ] + required_keys = [ + 'Type' + ] + def match(self, cfn): """Check CloudFormation Parameters""" @@ -41,5 +45,12 @@ def match(self, cfn): ['Parameters', paramname, propname], message.format(paramname, propname) )) + for reqname in self.required_keys: + if reqname not in paramvalue.keys(): + message = 'Parameter {0} is missing required property {1}' + matches.append(RuleMatch( + ['Parameters', paramname], + message.format(paramname, reqname) + )) return matches
diff --git a/test/unit/rules/parameters/test_configuration.py b/test/unit/rules/parameters/test_configuration.py --- a/test/unit/rules/parameters/test_configuration.py +++ b/test/unit/rules/parameters/test_configuration.py @@ -20,4 +20,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/parameters.yaml', 1) + self.helper_file_negative('test/fixtures/templates/bad/parameters.yaml', 2)
Warning Check on Unused Parameter hides Error Check about Missing Parameter Type *cfn-lint version: cfn-lint 0.25.3* Parameters defined in a template, but not directly used, are not validated for missing attributes like `Type`. For various reasons, we want to include parameters in our templates that are not used by resources in the templates and therefore disable `W2001` When this happens, the following template will not fail cfn-lint. If I uncomment the `Metadata` section, I will finally see the `E1012` failure. I should not have to resolve a Warning in order to unmask an Error. ```yaml Parameters: Foo: Description: "Foo?" Conditions: AlwaysFalse: !Equals [ true, false ] Resources: # Metadata: # Foo: !Ref Foo NullResource: Type: Custom::NullResource Condition: AlwaysFalse ```
2019-11-26T04:10:10Z
[]
[]
aws-cloudformation/cfn-lint
1,231
aws-cloudformation__cfn-lint-1231
[ "1230" ]
35e3108de2b5e0adb285eebd3301dfb5b8ed3534
diff --git a/src/cfnlint/rules/resources/updatepolicy/Configuration.py b/src/cfnlint/rules/resources/updatepolicy/Configuration.py --- a/src/cfnlint/rules/resources/updatepolicy/Configuration.py +++ b/src/cfnlint/rules/resources/updatepolicy/Configuration.py @@ -91,6 +91,12 @@ class Configuration(CloudFormationLintRule): 'AWS::Lambda::Alias' ] }, + 'EnableVersionUpgrade': { + 'PrimitiveType': 'Boolean', + 'ResourceTypes': [ + 'AWS::Elasticsearch::Domain' + ] + }, 'UseOnlineResharding': { 'PrimitiveType': 'Boolean', 'ResourceTypes': [
diff --git a/test/fixtures/templates/bad/resources/updatepolicy/config.yaml b/test/fixtures/templates/bad/resources/updatepolicy/config.yaml --- a/test/fixtures/templates/bad/resources/updatepolicy/config.yaml +++ b/test/fixtures/templates/bad/resources/updatepolicy/config.yaml @@ -25,7 +25,7 @@ Resources: MinSize: '1' UpdatePolicy: AutoScalingScheduledAction: - IgnoreUnmodifiedGroupSizeProperties: 'true' # invalide type + IgnoreUnmodifiedGroupSizeProperties: 'true' # invalid type AutoScalingRollingUpdate: MinInstancesInService: '1' # invalide type MaxBatchSize: '2' # invalide type @@ -130,3 +130,11 @@ Resources: Properties: MinSize: '1' MaxSize: '1' + ESD1: + Type: AWS::Elasticsearch::Domain + UpdatePolicy: + AutoScalingReplacingUpdate: true # wrong property name + ESD2: + Type: AWS::Elasticsearch::Domain + UpdatePolicy: + EnableVersionUpgrade: 'true' # invalid type diff --git a/test/fixtures/templates/good/resources/updatepolicy/config.yaml b/test/fixtures/templates/good/resources/updatepolicy/config.yaml --- a/test/fixtures/templates/good/resources/updatepolicy/config.yaml +++ b/test/fixtures/templates/good/resources/updatepolicy/config.yaml @@ -79,3 +79,11 @@ Resources: Properties: MinSize: '1' MaxSize: '1' + ESD1: + Type: AWS::Elasticsearch::Domain + UpdatePolicy: + EnableVersionUpgrade: false + ESD2: + Type: AWS::Elasticsearch::Domain + UpdatePolicy: + EnableVersionUpgrade: true diff --git a/test/unit/rules/resources/updatepolicy/test_configuration.py b/test/unit/rules/resources/updatepolicy/test_configuration.py --- a/test/unit/rules/resources/updatepolicy/test_configuration.py +++ b/test/unit/rules/resources/updatepolicy/test_configuration.py @@ -24,4 +24,4 @@ def test_file_positive(self): def test_file_negative_alias(self): """Test failure""" self.helper_file_negative( - 'test/fixtures/templates/bad/resources/updatepolicy/config.yaml', 11) + 'test/fixtures/templates/bad/resources/updatepolicy/config.yaml', 14)
`EnableVersionUpgrade` Update Policy Not Recognized *cfn-lint version: (`cfn-lint --version`)* 0.25.5 *Description of issue:* cfn-lint does not understand `AWS::Elasticsearch::Domain`'s new `UpdatePolicy` of `EnableVersionUpgrade`. This key accepts a Boolean value. > If `EnableVersionUpgrade` is set to true, you can update the `ElasticsearchVersion` property of the `AWS::Elasticsearch::Domain` resource, and CloudFormation will update that property without interruption. When `EnableVersionUpgrade` is set to `false`, or not specified, updating the `ElasticsearchVersion` property results in CloudFormation replacing the entire `AWS::Elasticsearch::Domain` resource. I have a patch for this ready to go, and the PR should be created in a couple of minutes.
2019-11-26T19:16:06Z
[]
[]
aws-cloudformation/cfn-lint
1,256
aws-cloudformation__cfn-lint-1256
[ "1252" ]
0ce9f8d207e6801f62802563fd668b28af92235d
diff --git a/src/cfnlint/rules/functions/SubNeeded.py b/src/cfnlint/rules/functions/SubNeeded.py --- a/src/cfnlint/rules/functions/SubNeeded.py +++ b/src/cfnlint/rules/functions/SubNeeded.py @@ -98,6 +98,8 @@ def match(self, cfn): # We want to search all of the paths to check if each one contains an 'Fn::Sub' for parameter_string_path in parameter_string_paths: + if parameter_string_path[0] in ['Parameters']: + continue # Exxclude the special IAM variables variable = parameter_string_path[-1]
diff --git a/test/fixtures/templates/good/functions/sub_needed.yaml b/test/fixtures/templates/good/functions/sub_needed.yaml --- a/test/fixtures/templates/good/functions/sub_needed.yaml +++ b/test/fixtures/templates/good/functions/sub_needed.yaml @@ -1,6 +1,9 @@ --- AWSTemplateFormatVersion: "2010-09-09" Parameters: + MyContentBucket: + Description: "Bucket name for content (usually ${VPCName}-my-content), use 'none' to disable creation" + Type: String AMIId: Type: 'String' Description: 'The AMI ID for the image to use.'
False positive: Sub is required if a variable is used in a string in parameter descriptions *cfn-lint version: 0.26.0* *Description of issue.* Parameter descriptions fail E1029 if they contain text which looks like variable substitution: e.g. ```yaml MyContentBucket: Description: "Bucket name for content (usually ${VPCName}-my-content), use 'none' to disable creation" Type: String ``` Gives an error: [E1029: Sub is required if a variable is used in a string] (Found an embedded parameter outside of an "Fn::Sub" at Parameters/MyContentBucket/Description)
2019-12-16T01:02:44Z
[]
[]
aws-cloudformation/cfn-lint
1,301
aws-cloudformation__cfn-lint-1301
[ "1295" ]
ffd22836781ac595be44a092d09699dbb18a0041
diff --git a/src/cfnlint/rules/parameters/Configuration.py b/src/cfnlint/rules/parameters/Configuration.py --- a/src/cfnlint/rules/parameters/Configuration.py +++ b/src/cfnlint/rules/parameters/Configuration.py @@ -14,37 +14,120 @@ class Configuration(CloudFormationLintRule): source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html' tags = ['parameters'] - valid_keys = [ - 'AllowedPattern', - 'AllowedValues', - 'ConstraintDescription', - 'Default', - 'Description', - 'MaxLength', - 'MaxValue', - 'MinLength', - 'MinValue', - 'NoEcho', - 'Type', - ] + valid_keys = { + 'AllowedPattern': { + 'Type': 'String' + }, + 'AllowedValues': { + 'Type': 'List', + 'ItemType': 'String', + }, + 'ConstraintDescription': { + 'Type': 'String' + }, + 'Default': { + 'Type': 'String' + }, + 'Description': { + 'Type': 'String' + }, + 'MaxLength': { + 'Type': 'Integer', + 'ValidForTypes': ['String'] + }, + 'MaxValue': { + 'Type': 'Integer', + 'ValidForTypes': ['Number'] + }, + 'MinLength': { + 'Type': 'Integer', + 'ValidForTypes': ['String'] + }, + 'MinValue': { + 'Type': 'Integer', + 'ValidForTypes': ['Number'] + }, + 'NoEcho': { + 'Type': 'Boolean' + }, + 'Type': { + 'Type': 'String' + } + } required_keys = [ 'Type' ] + def check_type(self, value, path, props): + """ Check the type and handle recursion with lists """ + results = [] + prop_type = props.get('Type') + try: + if prop_type in ['List']: + if isinstance(value, list): + for i, item in enumerate(value): + results.extend(self.check_type(item, path[:] + [i], { + 'Type': props.get('ItemType') + })) + else: + message = 'Property %s should be of type %s' % ( + '/'.join(map(str, path)), prop_type) + results.append(RuleMatch(path, message)) + if prop_type in ['String']: + if isinstance(value, (dict, list)): + message = 'Property %s should be of type %s' % ( + '/'.join(map(str, path)), prop_type) + results.append(RuleMatch(path, message)) + str(value) + elif prop_type in ['Boolean']: + if not isinstance(value, bool): + if value not in ['True', 'true', 'False', 'false']: + message = 'Property %s should be of type %s' % ( + '/'.join(map(str, path)), prop_type) + results.append(RuleMatch(path, message)) + elif prop_type in ['Integer']: + if isinstance(value, bool): + message = 'Property %s should be of type %s' % ( + '/'.join(map(str, path)), prop_type) + results.append(RuleMatch(path, message)) + else: # has to be a Double + int(value) + except Exception: # pylint: disable=W0703 + message = 'Property %s should be of type %s' % ( + '/'.join(map(str, path)), prop_type) + results.append(RuleMatch(path, message,)) + + return results + def match(self, cfn): """Check CloudFormation Parameters""" matches = [] for paramname, paramvalue in cfn.get_parameters().items(): - for propname, _ in paramvalue.items(): + for propname, propvalue in paramvalue.items(): if propname not in self.valid_keys: message = 'Parameter {0} has invalid property {1}' matches.append(RuleMatch( ['Parameters', paramname, propname], message.format(paramname, propname) )) + else: + props = self.valid_keys.get(propname) + prop_path = ['Parameters', paramname, propname] + matches.extend(self.check_type( + propvalue, prop_path, props)) + # Check that the property is needed for the current type + valid_for = props.get('ValidForTypes') + if valid_for is not None and paramvalue.get('Type'): + if paramvalue.get('Type') not in valid_for: + message = 'Parameter {0} has property {1} which is only valid for {2}' + matches.append(RuleMatch( + ['Parameters', paramname, propname], + message.format(paramname, propname, valid_for) + )) + for reqname in self.required_keys: if reqname not in paramvalue.keys(): message = 'Parameter {0} is missing required property {1}'
diff --git a/test/fixtures/templates/bad/parameters.yaml b/test/fixtures/templates/bad/parameters.yaml deleted file mode 100644 --- a/test/fixtures/templates/bad/parameters.yaml +++ /dev/null @@ -1,22 +0,0 @@ ---- -AWSTemplateFormatVersion: '2010-09-09' -Parameters: - myParameter: - # Type not string - Type: NotString - Default: Value - Description: Type not String - myInvalidParameter: - # invalid Property - NotType: String - mySsmParam: - Type: AWS::SSM::Parameter::Value<Test> -Resources: - # Helps tests map resource types - IamPipeline: - Type: "AWS::CloudFormation::Stack" - Properties: - TemplateURL: !Sub 'https://s3.${AWS::Region}.amazonaws.com/bucket-dne-${AWS::Region}/${AWS::AccountId}/pipeline.yaml' - Parameters: - DeploymentName: iam-pipeline - Deploy: 'auto' diff --git a/test/fixtures/templates/bad/parameters/configuration.yaml b/test/fixtures/templates/bad/parameters/configuration.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/parameters/configuration.yaml @@ -0,0 +1,38 @@ +--- +AWSTemplateFormatVersion: "2010-09-09" +Parameters: + allowedValuesNotAList: + Type: String + AllowedValues: vpc!@#$ + allowedValuesAListofBadTypes: + Type: String + AllowedValues: + - key: value + minValueIsNotNumber: + Type: Number + MinValue: a + maxLengthIsNotString: + Type: Number + MaxLength: 10 + notBooleanEcho: + Type: String + NoEcho: 123 + myParameter: + # Type not string + Type: NotString + Default: Value + Description: Type not String + myInvalidParameter: + # invalid Property + NotType: String + mySsmParam: + Type: AWS::SSM::Parameter::Value<Test> +Resources: + # Helps tests map resource types + IamPipeline: + Type: "AWS::CloudFormation::Stack" + Properties: + TemplateURL: !Sub "https://s3.${AWS::Region}.amazonaws.com/bucket-dne-${AWS::Region}/${AWS::AccountId}/pipeline.yaml" + Parameters: + DeploymentName: iam-pipeline + Deploy: "auto" diff --git a/test/unit/rules/parameters/test_configuration.py b/test/unit/rules/parameters/test_configuration.py --- a/test/unit/rules/parameters/test_configuration.py +++ b/test/unit/rules/parameters/test_configuration.py @@ -20,4 +20,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/parameters.yaml', 2) + self.helper_file_negative('test/fixtures/templates/bad/parameters/configuration.yaml', 7) diff --git a/test/unit/rules/parameters/test_types.py b/test/unit/rules/parameters/test_types.py --- a/test/unit/rules/parameters/test_types.py +++ b/test/unit/rules/parameters/test_types.py @@ -20,4 +20,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/parameters.yaml', 1) + self.helper_file_negative('test/fixtures/templates/bad/parameters/configuration.yaml', 1) diff --git a/test/unit/rules/parameters/test_used.py b/test/unit/rules/parameters/test_used.py --- a/test/unit/rules/parameters/test_used.py +++ b/test/unit/rules/parameters/test_used.py @@ -24,7 +24,7 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/parameters.yaml', 3) + self.helper_file_negative('test/fixtures/templates/bad/parameters/configuration.yaml', 8) def test_file_negative_removed(self): """Test failure"""
Template format error: Every AllowedValues member must be a list cfn-lint 0.26.2 Checking .yaml file, block ```yaml Parameters: Env: Type: "String" Description: "Environment" Default: "staging" AllowedValues: staging mock production DEVOPS ``` Lint says no errors, but when run aws cloudformation: An error occurred (ValidationError) when calling the CreateStack operation: Template format error: Every AllowedValues member must be a list.
Should be an easy one to do. Thanks for submitting this.
2020-01-11T13:20:28Z
[]
[]
aws-cloudformation/cfn-lint
1,305
aws-cloudformation__cfn-lint-1305
[ "1221" ]
0757dc4c7ba108f47c19eb0917b0e6e37ee62d83
diff --git a/src/cfnlint/helpers.py b/src/cfnlint/helpers.py --- a/src/cfnlint/helpers.py +++ b/src/cfnlint/helpers.py @@ -106,6 +106,11 @@ 'Fn::Join', 'Fn::Split', 'Fn::FindInMap', 'Fn::Select', 'Ref', 'Fn::If', 'Fn::Contains', 'Fn::Sub', 'Fn::Cidr'] +FUNCTIONS_MULTIPLE = ['Fn::GetAZs', 'Fn::Split'] + +# FindInMap can be singular or multiple. This needs to be acconted for individually +FUNCTIONS_SINGLE = list(set(FUNCTIONS) - set(FUNCTIONS_MULTIPLE) - set('Fn::FindInMap')) + FUNCTION_IF = 'Fn::If' FUNCTION_AND = 'Fn::And' FUNCTION_OR = 'Fn::Or' diff --git a/src/cfnlint/rules/outputs/Configuration.py b/src/cfnlint/rules/outputs/Configuration.py --- a/src/cfnlint/rules/outputs/Configuration.py +++ b/src/cfnlint/rules/outputs/Configuration.py @@ -4,6 +4,7 @@ """ from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch +from cfnlint.helpers import FUNCTIONS_SINGLE class Configuration(CloudFormationLintRule): @@ -21,6 +22,65 @@ class Configuration(CloudFormationLintRule): 'Condition' ] + # Map can be singular or multiple for this case we are going to skip + valid_funcs = FUNCTIONS_SINGLE + ['Fn::FindInMap'] + + def check_func(self, value, path): + """ Check that a value is using the correct functions """ + matches = [] + if isinstance(value, dict): + if len(value) == 1: + for k in value.keys(): + if k not in self.valid_funcs: + message = '{0} must use one of the functions {1}' + matches.append(RuleMatch( + path, + message.format('/'.join(path), self.valid_funcs) + )) + else: + message = '{0} must use one of the functions {1}' + matches.append(RuleMatch( + path, + message.format('/'.join(path), self.valid_funcs) + )) + elif isinstance(value, (list)): + message = '{0} must be a string or one of the functions {1}' + matches.append(RuleMatch( + path, + message.format('/'.join(path), self.valid_funcs) + )) + + return matches + + def check_export(self, value, path): + """ Check export structure""" + matches = [] + if isinstance(value, dict): + if len(value) == 1: + for k, v in value.items(): + if k != 'Name': + message = '{0} must be a an object of one with key "Name"' + matches.append(RuleMatch( + path, + message.format('/'.join(path)) + )) + else: + matches.extend(self.check_func(v, path[:] + ['Name'])) + else: + message = '{0} must be a an object of one with key "Name"' + matches.append(RuleMatch( + path, + message.format('/'.join(path)) + )) + else: + message = '{0} must be a an object of one with key "Name"' + matches.append(RuleMatch( + path, + message.format('/'.join(path)) + )) + + return matches + def match(self, cfn): """Check CloudFormation Outputs""" @@ -37,6 +97,13 @@ def match(self, cfn): ['Outputs', output_name, prop], message.format(output_name, prop) )) + value = output_value.get('Value') + if value: + matches.extend(self.check_func(value, ['Outputs', output_name, 'Value'])) + export = output_value.get('Export') + if export: + matches.extend(self.check_export( + export, ['Outputs', output_name, 'Export'])) else: matches.append(RuleMatch(['Outputs'], 'Outputs do not follow correct format.')) diff --git a/src/cfnlint/rules/outputs/Required.py b/src/cfnlint/rules/outputs/Required.py --- a/src/cfnlint/rules/outputs/Required.py +++ b/src/cfnlint/rules/outputs/Required.py @@ -28,12 +28,5 @@ def match(self, cfn): ['Outputs', output_name, 'Value'], message.format(output_name, 'Value') )) - if 'Export' in output_value: - if 'Name' not in output_value['Export']: - message = 'Output {0} is missing property {1}' - matches.append(RuleMatch( - ['Outputs', output_name, 'Export'], - message.format(output_name, 'Name') - )) return matches diff --git a/src/cfnlint/rules/outputs/Value.py b/src/cfnlint/rules/outputs/Value.py --- a/src/cfnlint/rules/outputs/Value.py +++ b/src/cfnlint/rules/outputs/Value.py @@ -72,17 +72,4 @@ def match(self, cfn): message.format(ref[1], obj) )) - # Check if the output values are not lists - outputs = cfn.template.get('Outputs', {}) - for output_name, output in outputs.items(): - - value_obj = output.get('Value') - if value_obj: - if isinstance(value_obj, list): - message = 'Output {0} value is of type list' - matches.append(RuleMatch( - output_name, - message.format(output_name) - )) - return matches
diff --git a/test/fixtures/templates/bad/outputs.yaml b/test/fixtures/templates/bad/outputs/configuration.yaml similarity index 61% rename from test/fixtures/templates/bad/outputs.yaml rename to test/fixtures/templates/bad/outputs/configuration.yaml --- a/test/fixtures/templates/bad/outputs.yaml +++ b/test/fixtures/templates/bad/outputs/configuration.yaml @@ -18,7 +18,7 @@ Outputs: Export: Name: instance myBadOutput: - BadValue: 'Test' + BadValue: "Test" myBadMissingOutput: Export: Name: Missing @@ -27,18 +27,37 @@ Outputs: Export: BadName: instance myBadGetAttArrayOutput: - Value: !GetAtt [ myVpc, CidrBlockAssociations ] + Value: !GetAtt [myVpc, CidrBlockAssociations] myBadArrayOutput: Value: - !Ref RouteTablePrivate1 - !Ref RouteTablePrivate2 myGoodArrayOutput: Value: - Fn::Join: [ ',', !GetAtt [ myVpc, CidrBlockAssociations ]] + Fn::Join: [",", !GetAtt [myVpc, CidrBlockAssociations]] myBadRefArrayOutput: Value: !Ref myNumbers myGoodRefArrayOutput: Value: - Fn::Join: [ ',', !Ref myNumbers] + Fn::Join: [",", !Ref myNumbers] myOutputImportValue: Value: !ImportValue "existing-output" + invalidFunction: + Value: !BadFunc value + invalidExportKey: + Export: + Bad: Value + invalidExportObject: + Export: + Ref: test + Bad: key + invalidExportList: + Export: + - Ref: test + - Bad: key + invalidValueObject: + Value: + Ref: test + Bad: key + invalidDescription: + Description: !Ref test diff --git a/test/unit/rules/outputs/test_configuration.py b/test/unit/rules/outputs/test_configuration.py --- a/test/unit/rules/outputs/test_configuration.py +++ b/test/unit/rules/outputs/test_configuration.py @@ -20,4 +20,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/outputs.yaml', 1) + self.helper_file_negative('test/fixtures/templates/bad/outputs/configuration.yaml', 8) diff --git a/test/unit/rules/outputs/test_importvalue.py b/test/unit/rules/outputs/test_importvalue.py --- a/test/unit/rules/outputs/test_importvalue.py +++ b/test/unit/rules/outputs/test_importvalue.py @@ -23,4 +23,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/outputs.yaml', 1) + self.helper_file_negative('test/fixtures/templates/bad/outputs/configuration.yaml', 1) diff --git a/test/unit/rules/outputs/test_required.py b/test/unit/rules/outputs/test_required.py --- a/test/unit/rules/outputs/test_required.py +++ b/test/unit/rules/outputs/test_required.py @@ -20,4 +20,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/outputs.yaml', 3) + self.helper_file_negative('test/fixtures/templates/bad/outputs/configuration.yaml', 6) diff --git a/test/unit/rules/outputs/test_value.py b/test/unit/rules/outputs/test_value.py --- a/test/unit/rules/outputs/test_value.py +++ b/test/unit/rules/outputs/test_value.py @@ -20,4 +20,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/outputs.yaml', 3) + self.helper_file_negative('test/fixtures/templates/bad/outputs/configuration.yaml', 2)
Intrinsic function names are not validated in Conditions or Outputs *cfn-lint version:* 0.25.3 *Description of issue.* It appears that cfn lint does not check the name of intrinsic functions used in either the Conditions or the Outputs section of the template. Using "Fn::Of": / !Of instead of "Fn::Or": / !Or in either the Conditions or Outputs section of the template is not detected as an error, while trying to use it in the Resources section correctly triggers an error (E3002 Property ... has an illegal function Fn::Of The following template generates E3002 for Resources/SSM/Properties/Value but does not detect / report any problems in either the Conditions or Outputs sections, both of which reference the non-existent intrinsic functions 'Of' and Offer ``` Description: "Test - unknown intrinsic" Parameters: TestParam1: Type: String Default: Value1 TestParam2: Type: String Default: Value2 Conditions: HasParam: "Fn::Of": - !Not [ !Equals [ !Ref TestParam1, '' ] ] - !Not [ !Equals [ !Ref TestParam2, '' ] ] Resources: SSM: Type: AWS::SSM::Parameter Condition: HasParam Properties: Type: String Description: "Just a test" Name: "/This-Is-Just-A-Test" Value: !Of TestParam1 Outputs: Suffix: Description: This is a test Value: !Offer TestParam1 ```
Agreed. Let me work on something for this. Thanks for reporting it. Half of this is done. Need to do this for outputs still.
2020-01-13T02:40:29Z
[]
[]
aws-cloudformation/cfn-lint
1,375
aws-cloudformation__cfn-lint-1375
[ "1373" ]
42c0cd89577a39e903e5ef8a337926cc7ff6822c
diff --git a/src/cfnlint/__init__.py b/src/cfnlint/__init__.py --- a/src/cfnlint/__init__.py +++ b/src/cfnlint/__init__.py @@ -24,11 +24,14 @@ from cfnlint.rules import ParseError as _ParseError from cfnlint.rules import TransformError as _TransformError from cfnlint.rules import RuleError as _RuleError +from cfnlint.decode.node import dict_node import cfnlint.rules LOGGER = logging.getLogger(__name__) # pylint: disable=too-many-lines + + def refactored(message): """ Decoreate for refactoring classes """ def cls_wrapper(cls): @@ -745,7 +748,7 @@ def get_value(value, scenario): # pylint: disable=R0911 return value - result = {} + result = dict_node({}, obj.start_mark, obj.end_mark) if isinstance(obj, dict): if len(obj) == 1: if obj.get('Fn::If'): @@ -753,13 +756,11 @@ def get_value(value, scenario): # pylint: disable=R0911 if new_value is not None: result = new_value else: - result = {} for key, value in obj.items(): new_value = get_value(value, scenario) if new_value is not None: result[key] = new_value else: - result = {} for key, value in obj.items(): new_value = get_value(value, scenario) if new_value is not None: diff --git a/src/cfnlint/decode/node.py b/src/cfnlint/decode/node.py --- a/src/cfnlint/decode/node.py +++ b/src/cfnlint/decode/node.py @@ -116,6 +116,9 @@ def get_safe(self, key, default=None, path=None, type_t=()): Get values in format """ path = path or [] + + if default == {}: + default = dict_node({}, self.start_mark, self.end_mark) value = self.get(key, default) if value is None and default is None: # if default is None and value is None return empty list diff --git a/src/cfnlint/rules/resources/rds/AuroraScalingConfiguration.py b/src/cfnlint/rules/resources/rds/AuroraScalingConfiguration.py --- a/src/cfnlint/rules/resources/rds/AuroraScalingConfiguration.py +++ b/src/cfnlint/rules/resources/rds/AuroraScalingConfiguration.py @@ -27,15 +27,20 @@ def check(self, properties, path, cfn): properties, ['EngineMode', 'ScalingConfiguration']) for property_set in property_sets: properties = property_set.get('Object') + scenario = property_set.get('Scenario') engine_sets = properties.get_safe('EngineMode', type_t=six.string_types) for engine, _ in engine_sets: if engine != 'serverless': if properties.get('ScalingConfiguration'): - message = 'You cannot specify ScalingConfiguration for non Aurora Serverless AWS::RDS::DBCluster: {}' - matches.append(RuleMatch( - path, - message.format('/'.join(map(str, path))) - )) + message = 'You cannot specify ScalingConfiguration for non Aurora Serverless AWS::RDS::DBCluster at {}' + if scenario is None: + matches.append( + RuleMatch(path, message.format('/'.join(map(str, path))))) + else: + scenario_text = ' and '.join( + ['when condition "%s" is %s' % (k, v) for (k, v) in scenario.items()]) + matches.append( + RuleMatch(path, message.format('/'.join(map(str, path)) + ' ' + scenario_text))) return matches def match_resource_properties(self, properties, _, path, cfn):
diff --git a/test/fixtures/templates/bad/resources/rds/aurora_autoscaling.yaml b/test/fixtures/templates/bad/resources/rds/aurora_autoscaling.yaml --- a/test/fixtures/templates/bad/resources/rds/aurora_autoscaling.yaml +++ b/test/fixtures/templates/bad/resources/rds/aurora_autoscaling.yaml @@ -1,6 +1,15 @@ --- AWSTemplateFormatVersion: 2010-09-09 +Parameters: + Serverless: + Description: Whether to use Aurora Serverless + Type: String + AllowedValues: ["false", "true"] + +Conditions: + UseServerless: !Equals [!Ref Serverless, "true"] + Resources: DatabaseCluster2: Type: AWS::RDS::DBCluster @@ -11,3 +20,19 @@ Resources: ScalingConfiguration: MinCapacity: 1 MaxCapacity: 3 + DatabaseCluster3: + Type: AWS::RDS::DBCluster + Properties: + Engine: aurora-postgresql + EngineMode: !If [UseServerless, "serverless", "provisioned"] + EngineVersion: "10.7" + ScalingConfiguration: !If + - UseServerless + - AutoPause: true + MaxCapacity: 192 + MinCapacity: 384 + SecondsUntilAutoPause: 1800 + - AutoPause: true + MaxCapacity: 192 + MinCapacity: 384 + SecondsUntilAutoPause: 1800 diff --git a/test/fixtures/templates/good/resources/rds/aurora_autoscaling.yaml b/test/fixtures/templates/good/resources/rds/aurora_autoscaling.yaml --- a/test/fixtures/templates/good/resources/rds/aurora_autoscaling.yaml +++ b/test/fixtures/templates/good/resources/rds/aurora_autoscaling.yaml @@ -1,6 +1,13 @@ --- AWSTemplateFormatVersion: 2010-09-09 +Parameters: + Serverless: + Description: Whether to use Aurora Serverless + Type: String + AllowedValues: ["false", "true"] +Conditions: + UseServerless: !Equals [!Ref Serverless, "true"] Resources: DatabaseCluster1: Type: AWS::RDS::DBCluster @@ -16,3 +23,16 @@ Resources: ScalingConfiguration: MinCapacity: 1 MaxCapacity: 3 + DatabaseCluster3: + Type: AWS::RDS::DBCluster + Properties: + Engine: aurora-postgresql + EngineMode: !If [UseServerless, "serverless", "provisioned"] + EngineVersion: "10.7" + ScalingConfiguration: !If + - UseServerless + - AutoPause: true + MaxCapacity: 192 + MinCapacity: 384 + SecondsUntilAutoPause: 1800 + - !Ref AWS::NoValue diff --git a/test/unit/module/test_template.py b/test/unit/module/test_template.py --- a/test/unit/module/test_template.py +++ b/test/unit/module/test_template.py @@ -449,7 +449,7 @@ def test_get_conditions_scenarios_from_object(self): def test_get_object_without_conditions(self): """ Test Getting condition names in an object/list """ - template = { + template = cfnlint.helpers.convert_dict({ 'Conditions': { 'useAmiId': {'Fn::Not': [{'Fn::Equals': [{'Ref': 'myAmiId'}, '']}]} }, @@ -462,7 +462,7 @@ def test_get_object_without_conditions(self): } } } - } + }) template = Template('test.yaml', template) results = template.get_object_without_conditions( @@ -545,7 +545,7 @@ def test_get_object_without_conditions_no_value(self): def test_get_object_without_conditions_for_list(self): """ Test Getting condition names in an object/list """ - template = { + template = cfnlint.helpers.convert_dict({ 'Conditions': { 'CreateAppVolume': {'Fn::Equals': [{'Ref': 'CreateVolums'}, 'true']} }, @@ -581,7 +581,7 @@ def test_get_object_without_conditions_for_list(self): } } } - } + }) template = Template('test.yaml', template) @@ -667,7 +667,7 @@ def test_get_object_without_conditions_for_bad_formats(self): def test_get_object_without_nested_conditions(self): """ Test Getting condition names in an object/list """ - template = { + template = cfnlint.helpers.convert_dict({ 'Conditions': { 'isProduction': {'Fn::Equals': [{'Ref': 'myEnvironment'}, 'prod']}, 'isDevelopment': {'Fn::Equals': [{'Ref': 'myEnvironment'}, 'dev']} @@ -692,7 +692,7 @@ def test_get_object_without_nested_conditions(self): } } } - } + }) template = Template('test.yaml', template) results = template.get_object_without_conditions( diff --git a/test/unit/rules/resources/rds/test_aurora_scaling_configuration.py b/test/unit/rules/resources/rds/test_aurora_scaling_configuration.py --- a/test/unit/rules/resources/rds/test_aurora_scaling_configuration.py +++ b/test/unit/rules/resources/rds/test_aurora_scaling_configuration.py @@ -24,4 +24,4 @@ def test_file_positive(self): def test_file_negative_alias(self): """Test failure""" self.helper_file_negative( - 'test/fixtures/templates/bad/resources/rds/aurora_autoscaling.yaml', 1) + 'test/fixtures/templates/bad/resources/rds/aurora_autoscaling.yaml', 2)
E0002 during E3028: 'dict' object has no attribute 'get_safe' *cfn-lint version: (0.28.1)* ``` > cfn-lint cloudformation_templates/lint_fail.yaml E0002 Unknown exception while processing rule E3028: 'dict' object has no attribute 'get_safe' cloudformation_templates/lint_fail.yaml:1:1 ``` This did not occur on 0.27.4, which is what I was running before. Here's the template: ```yaml --- AWSTemplateFormatVersion: '2010-09-09' Parameters: Serverless: Description: Whether to use Aurora Serverless Type: String AllowedValues: ["false", "true"] Conditions: UseServerless: !Equals [!Ref Serverless, "true"] Resources: AuroraCluster: Type: AWS::RDS::DBCluster Properties: Engine: aurora-postgresql EngineMode: !If [UseServerless, "serverless", "provisioned"] EngineVersion: "10.7" ScalingConfiguration: !If - UseServerless - AutoPause: true MaxCapacity: 192 MinCapacity: 384 SecondsUntilAutoPause: 1800 - !Ref AWS::NoValue ```
@iamed2 fix coming shortly
2020-02-20T00:12:46Z
[]
[]
aws-cloudformation/cfn-lint
1,381
aws-cloudformation__cfn-lint-1381
[ "800" ]
7cb12a5d9a24fd9a04ee2559d2011d9fb10ba7ac
diff --git a/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py b/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py --- a/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py +++ b/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py @@ -84,7 +84,6 @@ def _value_check(self, value, path, item_type, extra_args): def check_primitive_type(self, value, item_type, path): """Chec item type""" matches = [] - if isinstance(value, dict) and item_type == 'Json': return matches if item_type in ['String']: @@ -140,7 +139,7 @@ def check_value(self, value, path, **kwargs): return matches - def check(self, cfn, properties, specs, path): + def check(self, cfn, properties, specs, spec_type, path): """Check itself""" matches = [] @@ -154,14 +153,15 @@ def check(self, cfn, properties, specs, path): else: item_type = None if primitive_type: - matches.extend( - cfn.check_value( - properties, prop, path, - check_value=self.check_value, - primitive_type=primitive_type, - item_type=item_type + if not(spec_type == 'AWS::CloudFormation::Stack' and prop == 'Parameters'): + matches.extend( + cfn.check_value( + properties, prop, path, + check_value=self.check_value, + primitive_type=primitive_type, + item_type=item_type + ) ) - ) return matches @@ -171,7 +171,7 @@ def match_resource_sub_properties(self, properties, property_type, path, cfn): if self.property_specs.get(property_type, {}).get('Properties'): property_specs = self.property_specs.get(property_type, {}).get('Properties', {}) - matches.extend(self.check(cfn, properties, property_specs, path)) + matches.extend(self.check(cfn, properties, property_specs, property_type, path)) return matches @@ -179,6 +179,6 @@ def match_resource_properties(self, properties, resource_type, path, cfn): """Check CloudFormation Properties""" matches = [] resource_specs = self.resource_specs.get(resource_type, {}).get('Properties', {}) - matches.extend(self.check(cfn, properties, resource_specs, path)) + matches.extend(self.check(cfn, properties, resource_specs, resource_type, path)) return matches
diff --git a/test/fixtures/templates/good/resources/properties/primitive_types.yaml b/test/fixtures/templates/good/resources/properties/primitive_types.yaml --- a/test/fixtures/templates/good/resources/properties/primitive_types.yaml +++ b/test/fixtures/templates/good/resources/properties/primitive_types.yaml @@ -6,7 +6,7 @@ Resources: Properties: Name: Test Cutoff: 0 - Schedule: 'rate(1 days)' + Schedule: "rate(1 days)" AllowUnassociatedTargets: false Duration: 1 BaselinePatchDailySSMMaintenanceWindowTarget: @@ -17,7 +17,13 @@ Resources: WindowId: !Ref BaselinePatchDailySSMMaintenanceWindow ResourceType: INSTANCE Targets: - - Key: tag:Patch - Values: - - Daily - - daily + - Key: tag:Patch + Values: + - Daily + - daily + ManagerService: + Type: AWS::CloudFormation::Stack + Properties: + TemplateURL: ../../../common/service.yaml + Parameters: + DesiredCount: 1
E3012 "String" recommended for an external template parameter where type is "Number" *cfn-lint version: 0.18.0* I define some of my template with sub-templates and everything is packaged with that kind of command line ``` aws cloudformation package --template-file ./sources/template-source.yaml --s3-bucket my-bucket-build --output-template-file final-template.yaml ``` In `template-source` I have a resource which type is `AWS::CloudFormation::Stack`. It's definition looks like that : ``` yaml ManagerService: Type: AWS::CloudFormation::Stack Properties: TemplateURL: ../../../common/service.yaml Parameters: Cluster: !Ref Cluster DesiredCount: 1 ``` Here is the definition of the parameter in my `service` template : ```yaml Parameters: Cluster: Description: Please provide the ECS Cluster ID that this service should run on Type: String DesiredCount: Description: How many instances of this task should we run across our cluster? Type: Number Default: 1 ``` And cfn-lint return the following error : ``` cfn-lint source-template.yaml E3012 Property Resources/ManagerService/Properties/Parameters/DesiredCount should be of type String ``` It says that type should be a String, but the type in the template is define as Number. Am I missing something ? Thanks for your help
this is an interesting question. So we don't pull the nested stack templates to check their parameter types. We use the CloudFormation Spec to determine correctness for this. The trick here is the Map types are Strings. I am debating if we should just disable that check for this scenario. ``` "Parameters": { "Documentation": "http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stack.html#cfn-cloudformation-stack-parameters", "DuplicatesAllowed": false, "PrimitiveItemType": "String", "Required": false, "Type": "Map", "UpdateType": "Mutable" }, ``` Thanks for the quick answer ! It make sens if the documentation define it as String. But the problem is if we want to ensure the data to match a Number, it still a best practice to keep it as a Number. Otherwise we also could set it as string and use AllowedPattern but it's a bit complexe as the Number type exist. So yeah, maybe disable that check in the specific cas could be a solution. I agree with you on this. I would like @chuckmeyer and @fatbasstard to weigh in on this too. Going to mark it as a question for now and until we can get their opinions. Few more thoughts. - We won't know what the sub stack types are so we can't really test them. Basically, I won't know its a number so that is on you to validate (at least with the current features in cfn-lint) - Has anyone tested what List parameters look like here? @kddejong List parameters do not pass through to sub stacks successfully. If you have a CommaDelimitedList type in your main stack and you attempt pass it through to a CommaDelimitedList in the sub stack, you will get a failure. Only types that can be coerced to strings can be passed through to a substack, like numbers and booleans. The only way to pass a list through is to `!Join [',', !Ref MyList]` as you pass it through to the sub stack. I think configuring `E3012` with `strict: False` would do the trick here. Any progress on this? I'm using this in vscode-cfn-lint and the same scenario is tripping me up. For the moment, I've disabled the check with the follwing `.cfnlintrc` file : ``` include_checks: - I configure_rules: E3012: strict: False ```
2020-02-23T14:58:06Z
[]
[]
aws-cloudformation/cfn-lint
1,391
aws-cloudformation__cfn-lint-1391
[ "1386", "1386" ]
7099d54fcb17deca849fe1f8a6cdf75050d459f5
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -72,6 +72,8 @@ def get_version(filename): 'jsonschema~=3.0', 'pathlib2>=2.3.0;python_version<="3.4"', 'importlib_resources~=1.0.2;python_version<"3.7"', + 'networkx~=2.4;python_version>="3.5"', + 'networkx~=2.1;python_version<"3.5"' ], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', entry_points={ diff --git a/src/cfnlint/__init__.py b/src/cfnlint/__init__.py --- a/src/cfnlint/__init__.py +++ b/src/cfnlint/__init__.py @@ -349,7 +349,8 @@ def _search_deep_keys(self, searchText, cfndict, path): def search_deep_keys(self, searchText): """ - Search for keys in all parts of the templates + Search for a key in all parts of the template. + :return if searchText is "Ref", an array like ['Resources', 'myInstance', 'Properties', 'ImageId', 'Ref', 'Ec2ImageId'] """ LOGGER.debug('Search for key %s as far down as the template goes', searchText) results = [] diff --git a/src/cfnlint/graph.py b/src/cfnlint/graph.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/graph.py @@ -0,0 +1,117 @@ +""" +Helpers for loading resources, managing specs, constants, etc. + +Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +import re +import six +from networkx import networkx + + +class Graph(object): + """Models a template as a directed graph of resources""" + + def __init__(self, cfn): + """Builds a graph where resources are nodes and edges are explicit (DependsOn) or implicit (Fn::GetAtt, Fn::Sub, Ref) + relationships between resources""" + + # Directed graph that allows self loops and parallel edges + self.graph = networkx.MultiDiGraph() + + # add all resources in the template as nodes + for resourceId in cfn.template['Resources'].keys(): + self.graph.add_node(resourceId) + + # add edges for "Ref" tags. { "Ref" : "logicalNameOfResource" } + refs_paths = cfn.search_deep_keys('Ref') + for ref_path in refs_paths: + ref_type, source_id = ref_path[:2] + target_id = ref_path[-1] + if not ref_type == 'Resources': + continue + + if isinstance(target_id, (six.text_type, six.string_types, int)) and (self._is_resource(cfn, target_id)): + target_resource_id = target_id + self.graph.add_edge(source_id, target_resource_id, label='Ref') + + # add edges for "Fn::GetAtt" tags. + # { "Fn::GetAtt" : [ "logicalNameOfResource", "attributeName" ] } or { "!GetAtt" : "logicalNameOfResource.attributeName" } + getatt_paths = cfn.search_deep_keys('Fn::GetAtt') + for getatt_path in getatt_paths: + ref_type, source_id = getatt_path[:2] + value = getatt_path[-1] + if not ref_type == 'Resources': + continue + + if isinstance(value, list) and len(value) == 2 and (self._is_resource(cfn, value[0])): + target_resource_id = value[0] + self.graph.add_edge(source_id, target_resource_id, label='GetAtt') + + if isinstance(value, (six.string_types, six.text_type)) and '.' in value: + target_resource_id = value.split('.')[0] + if self._is_resource(cfn, target_resource_id): + self.graph.add_edge(source_id, target_resource_id, label='GetAtt') + + # add edges for "DependsOn" tags. { "DependsOn" : [ String, ... ] } + depends_on_paths = cfn.search_deep_keys('DependsOn') + for depend_on_path in depends_on_paths: + ref_type, source_id = depend_on_path[:2] + target_ids = depend_on_path[-1] + if not ref_type == 'Resources': + continue + + if isinstance(target_ids, (six.text_type, six.string_types)): + target_ids = [target_ids] + for target_id in target_ids: + if self._is_resource(cfn, target_id): + target_resource_id = target_id + self.graph.add_edge(source_id, target_resource_id, label='DependsOn') + + # add edges for "Fn::Sub" tags. E.g. { "Fn::Sub": "arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${vpc}" } + sub_objs = cfn.search_deep_keys('Fn::Sub') + for sub_obj in sub_objs: + sub_parameters = [] + sub_parameter_values = {} + value = sub_obj[-1] + ref_type, source_id = sub_obj[:2] + + if not ref_type == 'Resources': + continue + + if isinstance(value, list): + if not value: + continue + if len(value) == 2: + sub_parameter_values = value[1] + sub_parameters = self._find_parameter(value[0]) + elif isinstance(value, (six.text_type, six.string_types)): + sub_parameters = self._find_parameter(value) + + for sub_parameter in sub_parameters: + if sub_parameter not in sub_parameter_values: + if '.' in sub_parameter: + sub_parameter = sub_parameter.split('.')[0] + if self._is_resource(cfn, sub_parameter): + self.graph.add_edge(source_id, sub_parameter, label='Sub') + + def get_cycles(self, cfn): + """Return all resource pairs that have a cycle in them""" + result = [] + for starting_resource in cfn.template.get('Resources', {}): + try: + for edge in list(networkx.find_cycle(self.graph, starting_resource)): + if edge not in result: + result.append(edge) + except networkx.NetworkXNoCycle: + continue + return result + + def _is_resource(self, cfn, identifier): + """Check if the identifier is that of a Resource""" + return cfn.template.get('Resources', {}).get(identifier, {}) + + def _find_parameter(self, string): + """Search string for tokenized fields""" + regex = re.compile(r'\${([a-zA-Z0-9.]*)}') + return regex.findall(string) diff --git a/src/cfnlint/rules/resources/CircularDependency.py b/src/cfnlint/rules/resources/CircularDependency.py --- a/src/cfnlint/rules/resources/CircularDependency.py +++ b/src/cfnlint/rules/resources/CircularDependency.py @@ -2,134 +2,30 @@ Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ -import re -import six from cfnlint.rules import CloudFormationLintRule +from cfnlint.graph import Graph from cfnlint.rules import RuleMatch - class CircularDependency(CloudFormationLintRule): """Check if Resources have a circular dependency""" id = 'E3004' shortdesc = 'Resource dependencies are not circular' description = 'Check that Resources are not circularly dependent ' \ - 'by Ref, Sub, or GetAtt' + 'by DependsOn, Ref, Sub, or GetAtt' source_url = 'https://github.com/aws-cloudformation/cfn-python-lint' tags = ['resources', 'circularly'] - def searchstring(self, string): - """Search string for tokenized fields""" - regex = re.compile(r'\${([a-zA-Z0-9.]*)}') - return regex.findall(string) - - def _check_circular_dependency(self, resources, starting_resource, found_resources, association): - """Check resource association """ - result = [] - - # if association for evaluation is in found resources - # we are looping and its time to stop - if association in found_resources: - # Only respond with the list if it is directly related to the resource - # being analyzed. Sometimes loops can happen outside of the - # resource being analyzed. - if association == starting_resource: - return found_resources - - return [] - - association_resources = resources.get(association) - if association_resources: - for association_resource in association_resources: - result.extend(self._check_circular_dependency( - resources, starting_resource, found_resources[:] + [association], association_resource)) - - return result - - def check_circular_dependencies(self, resources): - """Check circular dependencies one item at a time""" - matches = [] - for resource_name, associations in resources.items(): - resource_results = [] - for association in associations: - results = set( - self._check_circular_dependency( - resources, resource_name, [resource_name], association)) - found = False - if results: - for resource_result in resource_results: - if resource_result == results: - found = True - if not found: - resource_results.append(results) - for resource_result in resource_results: - message = 'Circular Dependencies for resource {0}. Circular dependency with [{1}]' - resource_tree = [ - 'Resources', resource_name - ] - matches.append( - RuleMatch( - resource_tree, message.format( - resource_name, ', '.join(map(str, resource_result))))) - - return matches - def match(self, cfn): """Check CloudFormation Resources""" matches = [] - ref_objs = cfn.search_deep_keys('Ref') - resources = {} - for ref_obj in ref_objs: - value = ref_obj[-1] - if isinstance(value, (six.text_type, six.string_types, int)): - ref_type, ref_name = ref_obj[:2] - if ref_type == 'Resources': - if cfn.template.get('Resources', {}).get(value, {}): - if not resources.get(ref_name): - resources[ref_name] = [] - resources[ref_name].append(value) - - getatt_objs = cfn.search_deep_keys('Fn::GetAtt') - for getatt_obj in getatt_objs: - value = getatt_obj[-1] - if not isinstance(value, list): - continue - if not len(value) == 2: - continue - ref_name = value[0] - res_type, res_name = getatt_obj[:2] - if res_type == 'Resources': - if cfn.template.get('Resources', {}).get(ref_name, {}): - if not resources.get(res_name): - resources[res_name] = [] - resources[res_name].append(ref_name) - - sub_objs = cfn.search_deep_keys('Fn::Sub') - for sub_obj in sub_objs: - sub_parameters = [] - sub_parameter_values = {} - value = sub_obj[-1] - res_type, res_name = sub_obj[:2] - - if isinstance(value, list): - if not value: - continue - if len(value) == 2: - sub_parameter_values = value[1] - sub_parameters = self.searchstring(value[0]) - elif isinstance(value, (six.text_type, six.string_types)): - sub_parameters = self.searchstring(value) - - if res_type == 'Resources': - for sub_parameter in sub_parameters: - if sub_parameter not in sub_parameter_values: - if '.' in sub_parameter: - sub_parameter = sub_parameter.split('.')[0] - if cfn.template.get('Resources', {}).get(sub_parameter, {}): - if not resources.get(res_name): - resources[res_name] = [] - resources[res_name].append(sub_parameter) + graph = Graph(cfn) + for cycle in graph.get_cycles(cfn): + source, target = cycle[:2] + message = 'Circular Dependencies for resource {0}. Circular dependency with [{1}]'.format(source, + target) + path = ['Resources', source] + matches.append(RuleMatch(path, message)) - matches.extend(self.check_circular_dependencies(resources)) return matches
diff --git a/test/fixtures/templates/bad/resources_circulary_dependency.yaml b/test/fixtures/templates/bad/resources_circular_dependency.yaml similarity index 100% rename from test/fixtures/templates/bad/resources_circulary_dependency.yaml rename to test/fixtures/templates/bad/resources_circular_dependency.yaml diff --git a/test/fixtures/templates/bad/resources_circular_dependency_2.yaml b/test/fixtures/templates/bad/resources_circular_dependency_2.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources_circular_dependency_2.yaml @@ -0,0 +1,44 @@ +Resources: + Resource: + Type: AWS::SNS::Topic + Properties: + DisplayName: + !Sub ${Resource2} + Resource2: + Type: AWS::SNS::Topic + Properties: + DisplayName: + !GetAtt Resource3.TopicName + Resource3: + Type: AWS::SNS::Topic + Properties: + DisplayName: + !Ref Resource4 + Resource4: + Type: AWS::SNS::Topic + Properties: + DisplayName: + Fn::Sub: ${Resource5} + Resource5: + Type: AWS::SNS::Topic + Properties: + DisplayName: + Fn::GetAtt: Resource6.TopicName + Resource6: + Type: AWS::SNS::Topic + Properties: + DisplayName: + Ref: Resource7 + Resource7: + Type: AWS::SNS::Topic + Properties: + DisplayName: + !Sub ${Resource8.TopicName} + Resource8: + Type: AWS::SNS::Topic + Properties: + DisplayName: + Fn::Sub: ${Resource9.TopicName} + Resource9: + DependsOn: Resource + Type: AWS::SNS::Topic \ No newline at end of file diff --git a/test/fixtures/templates/bad/resources_circular_dependency_dependson.yaml b/test/fixtures/templates/bad/resources_circular_dependency_dependson.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources_circular_dependency_dependson.yaml @@ -0,0 +1,9 @@ +--- +AWSTemplateFormatVersion: "2010-09-09" +Resources: + Resource: + Type: AWS::SNS::Topic + DependsOn: Resource2 + Resource2: + Type: AWS::SNS::Topic + DependsOn: Resource \ No newline at end of file diff --git a/test/unit/rules/resources/test_circulary_dependency.py b/test/unit/rules/resources/test_circular_dependency.py similarity index 54% rename from test/unit/rules/resources/test_circulary_dependency.py rename to test/unit/rules/resources/test_circular_dependency.py --- a/test/unit/rules/resources/test_circulary_dependency.py +++ b/test/unit/rules/resources/test_circular_dependency.py @@ -20,5 +20,18 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" + err_count = 6 self.helper_file_negative( - 'test/fixtures/templates/bad/resources_circulary_dependency.yaml', 6) + 'test/fixtures/templates/bad/resources_circular_dependency.yaml', err_count) + + def test_file_negative_fngetatt(self): + """Test failure""" + err_count = 9 + self.helper_file_negative( + 'test/fixtures/templates/bad/resources_circular_dependency_2.yaml', err_count) + + def test_file_negative_dependson(self): + """Test failure with DependsOn""" + err_count = 2 + self.helper_file_negative( + 'test/fixtures/templates/bad/resources_circular_dependency_dependson.yaml', err_count)
Rule E3004 is not checking for DependsOn declarations *cfn-lint version*: 0.8.2 *Description of issue.* The following template has a circular dependency: ```yaml Resources: Resource: Type: AWS::SNS::Topic DependsOn: Resource2 Resource2: Type: AWS::SNS::Topic DependsOn: Resource ``` but `cfn-lint` doesn't report any problems with it. Rule E3004 is not checking for DependsOn declarations *cfn-lint version*: 0.8.2 *Description of issue.* The following template has a circular dependency: ```yaml Resources: Resource: Type: AWS::SNS::Topic DependsOn: Resource2 Resource2: Type: AWS::SNS::Topic DependsOn: Resource ``` but `cfn-lint` doesn't report any problems with it.
Yup, code and description in this file would need to be updated: https://github.com/aws-cloudformation/cfn-python-lint/blob/35a1fa54e828ce5497683551e9c43b4b210b4227/src/cfnlint/rules/resources/CircularDependency.py#L13-L16 Couple other rules have examples grabbing [`DependsOn`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html) attribute values: https://github.com/aws-cloudformation/cfn-python-lint/blob/b788cc9bd3d49ed20d5f2e58602755a0ef37f52c/src/cfnlint/rules/resources/DependsOn.py#L40 https://github.com/aws-cloudformation/cfn-python-lint/blob/4e210a2325ca225ff8483ec66f0ca9096cd4f73f/src/cfnlint/rules/resources/DependsOnObsolete.py#L64 Yup, code and description in this file would need to be updated: https://github.com/aws-cloudformation/cfn-python-lint/blob/35a1fa54e828ce5497683551e9c43b4b210b4227/src/cfnlint/rules/resources/CircularDependency.py#L13-L16 Couple other rules have examples grabbing [`DependsOn`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html) attribute values: https://github.com/aws-cloudformation/cfn-python-lint/blob/b788cc9bd3d49ed20d5f2e58602755a0ef37f52c/src/cfnlint/rules/resources/DependsOn.py#L40 https://github.com/aws-cloudformation/cfn-python-lint/blob/4e210a2325ca225ff8483ec66f0ca9096cd4f73f/src/cfnlint/rules/resources/DependsOnObsolete.py#L64
2020-02-29T07:21:00Z
[]
[]
aws-cloudformation/cfn-lint
1,402
aws-cloudformation__cfn-lint-1402
[ "1387" ]
c772bc0b1d7ace30e87097218d269fb6a9372ee1
diff --git a/src/cfnlint/decode/__init__.py b/src/cfnlint/decode/__init__.py --- a/src/cfnlint/decode/__init__.py +++ b/src/cfnlint/decode/__init__.py @@ -65,7 +65,16 @@ def decode(filename, ignore_bad_template): json_err.match.filename = filename matches = [json_err.match] except JSONDecodeError as json_err: - matches = [create_match_json_parser_error(json_err, filename)] + if hasattr(json_err, 'message'): + if json_err.message == 'No JSON object could be decoded': # pylint: disable=no-member + matches = [create_match_yaml_parser_error(err, filename)] + else: + matches = [create_match_json_parser_error(json_err, filename)] + if hasattr(json_err, 'msg'): + if json_err.msg == 'Expecting value': # pylint: disable=no-member + matches = [create_match_yaml_parser_error(err, filename)] + else: + matches = [create_match_json_parser_error(json_err, filename)] except Exception as json_err: # pylint: disable=W0703 if ignore_bad_template: LOGGER.info('Template %s is malformed: %s', diff --git a/src/cfnlint/rules/__init__.py b/src/cfnlint/rules/__init__.py --- a/src/cfnlint/rules/__init__.py +++ b/src/cfnlint/rules/__init__.py @@ -422,7 +422,7 @@ class ParseError(CloudFormationLintRule): """Parse Lint Rule""" id = 'E0000' shortdesc = 'Parsing error found when parsing the template' - description = 'Checks for Null values and Duplicate values in resources' + description = 'Checks for JSON/YAML formatting errors in your template' source_url = 'https://github.com/aws-cloudformation/cfn-python-lint' tags = ['base']
diff --git a/test/unit/module/maintenance/test_update_documentation.py b/test/unit/module/maintenance/test_update_documentation.py --- a/test/unit/module/maintenance/test_update_documentation.py +++ b/test/unit/module/maintenance/test_update_documentation.py @@ -74,7 +74,7 @@ class TestRuleWarning(CloudFormationLintRule): call('| Rule ID | Title | Description | Config<br />(Name:Type:Default) | Source | Tags |\n'), call('| -------- | ----- | ----------- | ---------- | ------ | ---- |\n'), call( - '| E0000<a name="E0000"></a> | Parsing error found when parsing the template | Checks for Null values and Duplicate values in resources | | [Source]() | `base` |\n'), + '| E0000<a name="E0000"></a> | Parsing error found when parsing the template | Checks for JSON/YAML formatting errors in your template | | [Source]() | `base` |\n'), call( '| E0001<a name="E0001"></a> | Error found when transforming the template | Errors found when performing transformation on the template | | [Source]() | `base`,`transform` |\n'), call(
Linter Errors in YAML Parsing should be in linter Message # Version cfn-lint 0.28.2 # Description of issue. YAML Parsing errors should be included in the `Message` field rather than the generic `Expecting Value` message for rule `E0000`. The error messages from the `ScannerError` is much more accurate and descriptive than `Expecting Value`. Currently, specifying an "invalid token" (by putting `\t` before a token) will trigger this error, and is difficult to find because the Linter error points to the error being with the first character of the YAML file. To find the error in my template file, I had to make use of the python debugger and step through the `cfn-lint` and `pyyaml` code to get to a place where I could see the output of the exception, and then grepped the `cfn-lint` code for the specific error type. # Example Template File In this example template file, the error is on line 6, column 14 `Default:\tprivate` AWSTemplateFormatVersion: '2010-09-09' Description: "CloudFormation Stack for the Networking components within an AZ" Parameters: vpcId: Type: String Default: private AvailabilityZone: Description: 'Zero-indexed integer representing the AZ. For example, for AZ 2 within a region this will be 1' Type: Integer Default: 0 PublicSubnetCIDR: Description: CIDR value for the public subnet within this AZ; must not overlap with any other subnets in this VPC Type: String Default: 10.192.0.0/20 AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$' PrivateSubnetCIDR: Description: CIDR value for the private subnet within this AZ; must not overlap with any other subnets in this VPC Type: String Default: 10.192.30.0/20 AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$' Resources: cfPublicSubnet: Type: 'AWS::EC2::Subnet' Properties: AvailabilityZone: !Select [ !Ref AvailabilityZone, !GetAZs '' ] CidrBlock: !Ref PublicSubnetCIDR MapPublicIpOnLaunch: true VpcId: !Ref vpcId Tags: - Key: Name Value: !Sub cf-poc-public-subnet-az${AvailabilityZone} cfPrivateSubnet: Type: 'AWS::EC2::Subnet' Properties: AvailabilityZone: !Select [ !Ref AvailabilityZone, !GetAZs '' ] CidrBlock: !Ref PrivateSubnetCIDR VpcId: !Ref vpcId Tags: - Key: Name Value: !Sub "cf-poc-private-subnet-az${AvailabilityZone}" # NAT Gateway for Public Subnet cfNatGateway: Type: 'AWS::EC2::NatGateway' Properties: AllocationId: !GetAtt cfNatElasticIp.AllocationId SubnetId: !Ref cfPublicSubnet Tags: - Key: Name Value: !Sub "cf-poc-nat-gateway-az${AvailabilityZone}" # Elastic IPs for the NAT Gateways cfNatElasticIp: Type: 'AWS::EC2::EIP' Properties: Domain: vpc Tags: - Key: Name Value: !Sub "cf-poc-nat-eip-az${AvailabilityZone}" Outputs: cfPublicSubnet: Value: !Ref cfPublicSubnet cfPrivateSubnet: Value: !Ref cfPrivateSubnet cfNatGateway: Value: !Ref cfNatGateway # Additional Info The `ScannerError`, when allowed to print, outputs the following: yaml.scanner.ScannerError: while scanning for the next token found character '\t' that cannot start any token in "<unicode string>", line 6, column 14: Default: private which is much more accurate and informative than: [ { "Filename": "/home/eurythmia/CloudFormation/PoC-cf-AzNetwork.yaml", "Level": "Error", "Location": { "End": { "ColumnNumber": 2, "LineNumber": 1 }, "Path": null, "Start": { "ColumnNumber": 1, "LineNumber": 1 } }, "Message": "Expecting value", "Rule": { "Description": "Checks for Null values and Duplicate values in resources", "Id": "E0000", "ShortDescription": "Parsing error found when parsing the template", "Source": "https://github.com/aws-cloudformation/cfn-python-lint" } } ] This occurs in the code [somewhere around here](https://github.com/aws-cloudformation/cfn-python-lint/blob/master/src/cfnlint/decode/__init__.py#L58), by catching the error for this specific error type. In principle, I'm not against catching the error to provide the user with information, but in this case we should be creating Linter warnings using the information _from_ the exception.
I also just encountered this issue. Makes finding the problem a real pain but thanks to your question I could just search for `\t`s. Thank you. Yea we do a few extra parsing tries when we run into the `\t` issue. The result currently is a masked error message. Making a few changes that should bring back the original YAML error message in this scenario. This work for you? ``` E0000 found character '\t' that cannot start any token template.yaml:6:14 ``` As long as the error wasn't related to `\t` this is what is shown today. ``` E0000 could not find expected ':' template.yaml:4:1 ``` > Yea we do a few extra parsing tries when we run into the `\t` issue. The result currently is a masked error message. Making a few changes that should bring back the original YAML error message in this scenario. This work for you? > > ``` > E0000 found character '\t' that cannot start any token > template.yaml:6:14 > ``` > > As long as the error wasn't related to `\t` this is what is shown today. > > ``` > E0000 could not find expected ':' > template.yaml:4:1 > ``` Yeah; that looks like a reasonable solution, thanks :-)
2020-03-06T18:36:59Z
[]
[]
aws-cloudformation/cfn-lint
1,405
aws-cloudformation__cfn-lint-1405
[ "1351" ]
c9d78f4e8a53e5357902734d9d00814da99ba7b9
diff --git a/src/cfnlint/rules/resources/events/RuleScheduleExpression.py b/src/cfnlint/rules/resources/events/RuleScheduleExpression.py --- a/src/cfnlint/rules/resources/events/RuleScheduleExpression.py +++ b/src/cfnlint/rules/resources/events/RuleScheduleExpression.py @@ -37,7 +37,8 @@ def check_rate(self, value, path): # Check the Value if not items[0].isdigit(): message = 'Rate Value ({}) should be of type Integer.' - extra_args = {'actual_type': type(items[0]).__name__, 'expected_type': int.__name__} + extra_args = {'actual_type': type( + items[0]).__name__, 'expected_type': int.__name__} matches.append(RuleMatch(path, message.format(items[0]), **extra_args)) return matches @@ -57,6 +58,12 @@ def check_cron(self, value, path): if len(items) != 6: message = 'Cron expression must contain 6 elements (Minutes Hours Day-of-month Month Day-of-week Year), cron contains {} elements' matches.append(RuleMatch(path, message.format(len(items)))) + return matches + + _, _, day_of_month, _, day_of_week, _ = cron_expression.split(' ') + if day_of_month != '?' and day_of_week != '?': + matches.append(RuleMatch( + path, 'Don\'t specify the Day-of-month and Day-of-week fields in the same cron expression')) return matches
diff --git a/test/fixtures/templates/bad/resources/events/rule_schedule_expression.yaml b/test/fixtures/templates/bad/resources/events/rule_schedule_expression.yaml --- a/test/fixtures/templates/bad/resources/events/rule_schedule_expression.yaml +++ b/test/fixtures/templates/bad/resources/events/rule_schedule_expression.yaml @@ -29,3 +29,7 @@ Resources: Type: AWS::Events::Rule Properties: ScheduleExpression: "cron(0 */1 * * WED)" # Not enough values + MyScheduledRule8: + Type: AWS::Events::Rule + Properties: + ScheduleExpression: "cron(* 1 * * * *)" # specify the Day-of-month and Day-of-week fields in the same cron expression diff --git a/test/unit/rules/resources/events/test_rule_schedule_expression.py b/test/unit/rules/resources/events/test_rule_schedule_expression.py --- a/test/unit/rules/resources/events/test_rule_schedule_expression.py +++ b/test/unit/rules/resources/events/test_rule_schedule_expression.py @@ -24,4 +24,4 @@ def test_file_positive(self): def test_file_negative_alias(self): """Test failure""" self.helper_file_negative( - 'test/fixtures/templates/bad/resources/events/rule_schedule_expression.yaml', 7) + 'test/fixtures/templates/bad/resources/events/rule_schedule_expression.yaml', 8)
AWS::Events::Rule ScheduleExpression: "cron(* 1 * * * *)" *cfn-lint version: (cfn-lint 0.27.5)* *Description of issue.* ``` EventRule: Type: "AWS::Events::Rule" Properties: ScheduleExpression: "cron(* 1 * * * *)" State: "ENABLED" Targets: - Arn: !Ref Foo Id: "Foo" RoleArn: !GetAtt FooArn.Arn ``` Check should be probably in: [src/cfnlint/rules/resources/events/RuleScheduleExpression.py](https://github.com/aws-cloudformation/cfn-python-lint/blob/master/src/cfnlint/rules/resources/events/RuleScheduleExpression.py) The above `ScheduleExpression` is invalid (need a value for minute if hour is set). For example `cron(0 1 * * ? *)` --- [Schedule Expressions for Rules documentation](https://docs.aws.amazon.com/eventbridge/latest/userguide/scheduled-events.html)
@jtheuer I can get `* 1 * * ? *` to work. Are you getting an error in this situation? I'm seeing this in the documentation. ``` You can't specify the Day-of-month and Day-of-week fields in the same cron expression. If you specify a value (or a *) in one of the fields, you must use a ? (question mark) in the other. ``` Which was also corrected in your example and seems like an easy rule we can write. Thoughts?
2020-03-07T14:36:54Z
[]
[]
aws-cloudformation/cfn-lint
1,409
aws-cloudformation__cfn-lint-1409
[ "1395" ]
ec366bb242efa668c6844c06a2b8bc08501a720b
diff --git a/src/cfnlint/rules/resources/rds/AuroraDBInstanceProperties.py b/src/cfnlint/rules/resources/rds/AuroraDBInstanceProperties.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/resources/rds/AuroraDBInstanceProperties.py @@ -0,0 +1,66 @@ +""" +Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +import six +from cfnlint.rules import CloudFormationLintRule +from cfnlint.rules import RuleMatch + + +class AuroraDBInstanceProperties(CloudFormationLintRule): + """Aurora DB instances have a lot properties that can't be set and vice and versa""" + id = 'E3029' + shortdesc = 'Aurora instances don\'t require certain properties' + description = 'Certain properties are not reuqired when using the Aurora engine for AWS::RDS::DBInstance' + source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html' + tags = ['resources', 'rds'] + aurora_not_required_props = [ + 'AllocatedStorage', + 'BackupRetentionPeriod', + 'CopyTagsToSnapshot', + 'DeletionProtection', + 'EnableIAMDatabaseAuthentication', + 'MasterUserPassword', + 'StorageEncrypted', + ] + aurora_engines = [ + 'aurora', + 'aurora-mysql', + 'aurora-postgresql', + ] + + def __init__(self): + """Init""" + super(AuroraDBInstanceProperties, self).__init__() + self.resource_property_types = ['AWS::RDS::DBInstance'] + + def check(self, properties, path, cfn): + """Check itself""" + matches = [] + property_sets = cfn.get_object_without_conditions( + properties, ['Engine'] + self.aurora_not_required_props) + for property_set in property_sets: + properties = property_set.get('Object') + scenario = property_set.get('Scenario') + engine_sets = properties.get_safe('Engine', type_t=six.string_types) + for engine, _ in engine_sets: + if engine in self.aurora_engines: + for prop in properties: + if prop in self.aurora_not_required_props: + path_prop = path[:] + [prop] + message = 'You cannot specify {} for Aurora AWS::RDS::DBInstance at {}' + if scenario is None: + matches.append( + RuleMatch(path_prop, message.format(prop, '/'.join(map(str, path_prop))))) + else: + scenario_text = ' and '.join( + ['when condition "%s" is %s' % (k, v) for (k, v) in scenario.items()]) + matches.append( + RuleMatch(path_prop, message.format(prop, '/'.join(map(str, path_prop)) + ' ' + scenario_text))) + return matches + + def match_resource_properties(self, properties, _, path, cfn): + """Match for sub properties""" + matches = [] + matches.extend(self.check(properties, path, cfn)) + return matches
diff --git a/test/fixtures/templates/bad/resources/rds/aurora_dbinstance_properties.yaml b/test/fixtures/templates/bad/resources/rds/aurora_dbinstance_properties.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources/rds/aurora_dbinstance_properties.yaml @@ -0,0 +1,40 @@ +--- +AWSTemplateFormatVersion: 2010-09-09 +Description: "RDS Storage Encrypted" +Parameters: + Engine: + Type: String + UseAurora: + Type: String + AllowedValues: + - "true" + - "false" +Conditions: + IsAurora: + Fn::Or: + - !Equals [!Ref Engine, "aurora"] + - !Equals [!Ref Engine, "aurora-mysql"] + - !Equals [!Ref Engine, "aurora-postgresql"] + IsAurora2: !Equals [!Ref UseAurora, "true"] +Resources: + MyDBSmall: + Type: "AWS::RDS::DBInstance" + Properties: + Engine: aurora + AllocatedStorage: "100" + DBInstanceClass: db.r3.2xlarge + StorageEncrypted: true + MyDbInstance2: + Type: "AWS::RDS::DBInstance" + Properties: + Engine: !Ref Engine + DBInstanceClass: db.r3.2xlarge + # While this is bad we can't determine the Engine so skipping + AllocatedStorage: !If [IsAurora, "100", !Ref "AWS::NoValue"] + MySqlInstance: + Type: "AWS::RDS::DBInstance" + Properties: + Engine: !If [IsAurora2, aurora-mysql, mysql] + DBInstanceClass: db.r3.2xlarge + # Since we can figure out the engine this one should fail + AllocatedStorage: !If [IsAurora2, "100", !Ref "AWS::NoValue"] diff --git a/test/fixtures/templates/good/resources/rds/aurora_dbinstance_properties.yaml b/test/fixtures/templates/good/resources/rds/aurora_dbinstance_properties.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/rds/aurora_dbinstance_properties.yaml @@ -0,0 +1,38 @@ +--- +AWSTemplateFormatVersion: 2010-09-09 +Description: "RDS Storage Encrypted" +Parameters: + Engine: + Type: String + UseAurora: + Type: String + AllowedValues: + - "true" + - "false" +Conditions: + IsAurora: + Fn::Or: + - !Equals [!Ref Engine, "aurora"] + - !Equals [!Ref Engine, "aurora-mysql"] + - !Equals [!Ref Engine, "aurora-postgresql"] + IsAurora2: !Equals [!Ref UseAurora, "true"] +Resources: + MyDbInstance1: + Type: "AWS::RDS::DBInstance" + Properties: + Engine: mysql + AllocatedStorage: "100" + DBInstanceClass: db.r3.2xlarge + StorageEncrypted: true + MyDbInstance2: + Type: "AWS::RDS::DBInstance" + Properties: + Engine: !Ref Engine + DBInstanceClass: db.r3.2xlarge + AllocatedStorage: !If [IsAurora, !Ref "AWS::NoValue", "100"] + MySqlInstance: + Type: "AWS::RDS::DBInstance" + Properties: + Engine: !If [IsAurora2, aurora-mysql, mysql] + DBInstanceClass: db.r3.2xlarge + AllocatedStorage: !If [IsAurora2, !Ref "AWS::NoValue", "100"] diff --git a/test/unit/rules/resources/rds/test_auroa_dbinstance_properties.py b/test/unit/rules/resources/rds/test_auroa_dbinstance_properties.py new file mode 100644 --- /dev/null +++ b/test/unit/rules/resources/rds/test_auroa_dbinstance_properties.py @@ -0,0 +1,27 @@ +""" +Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from test.unit.rules import BaseRuleTestCase +from cfnlint.rules.resources.rds.AuroraDBInstanceProperties import AuroraDBInstanceProperties # pylint: disable=E0401 + + +class TestAuroraDBInstanceProperties(BaseRuleTestCase): + """Test RDS Auror Auto Scaling Configurartion""" + + def setUp(self): + """Setup""" + super(TestAuroraDBInstanceProperties, self).setUp() + self.collection.register(AuroraDBInstanceProperties()) + self.success_templates = [ + 'test/fixtures/templates/good/resources/rds/aurora_dbinstance_properties.yaml' + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative_alias(self): + """Test failure""" + self.helper_file_negative( + 'test/fixtures/templates/bad/resources/rds/aurora_dbinstance_properties.yaml', 3)
Check for AllocatedStorage when DBInstance engine is not Aurora *cfn-lint version: (`cfn-lint --version`)* 0.28.2 *Using latest spec* *Description of issue.* `cfn-lint` does not currently warn/error when an `AWS::RDS::DBInstance` is missing the `AllocatedStorage` property. This property is required when using non-Aurora engines, and is not when using Aurora.
2020-03-09T14:14:09Z
[]
[]
aws-cloudformation/cfn-lint
1,419
aws-cloudformation__cfn-lint-1419
[ "1415" ]
be3867c6d45862a155b3c35ba6b0690ad5cab6bb
diff --git a/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py b/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py --- a/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py +++ b/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py @@ -18,6 +18,15 @@ class ValuePrimitiveType(CloudFormationLintRule): source_url = 'https://github.com/aws-cloudformation/cfn-python-lint/blob/master/docs/cfn-resource-specification.md#valueprimitivetype' tags = ['resources'] + strict_exceptions = { + 'AWS::CloudFormation::Stack': [ + 'Parameters' + ], + 'AWS::Lambda::Function.Environment': [ + 'Variables' + ] + } + def __init__(self): """Init""" super(ValuePrimitiveType, self).__init__() @@ -41,10 +50,10 @@ def initialize(self, cfn): for property_spec in self.property_specs: self.resource_sub_property_types.append(property_spec) - def _value_check(self, value, path, item_type, extra_args): + def _value_check(self, value, path, item_type, strict_check, extra_args): """ Checks non strict """ matches = [] - if not self.config['strict']: + if not strict_check: try: if item_type in ['String']: str(value) @@ -81,7 +90,7 @@ def _value_check(self, value, path, item_type, extra_args): return matches - def check_primitive_type(self, value, item_type, path): + def check_primitive_type(self, value, item_type, path, strict_check): """Chec item type""" matches = [] if isinstance(value, dict) and item_type == 'Json': @@ -89,20 +98,20 @@ def check_primitive_type(self, value, item_type, path): if item_type in ['String']: if not isinstance(value, (six.string_types)): extra_args = {'actual_type': type(value).__name__, 'expected_type': str.__name__} - matches.extend(self._value_check(value, path, item_type, extra_args)) + matches.extend(self._value_check(value, path, item_type, strict_check, extra_args)) elif item_type in ['Boolean']: if not isinstance(value, (bool)): extra_args = {'actual_type': type(value).__name__, 'expected_type': bool.__name__} - matches.extend(self._value_check(value, path, item_type, extra_args)) + matches.extend(self._value_check(value, path, item_type, strict_check, extra_args)) elif item_type in ['Double']: if not isinstance(value, (float, int)): extra_args = {'actual_type': type(value).__name__, 'expected_type': [ float.__name__, int.__name__]} - matches.extend(self._value_check(value, path, item_type, extra_args)) + matches.extend(self._value_check(value, path, item_type, strict_check, extra_args)) elif item_type in ['Integer']: if not isinstance(value, (int)): extra_args = {'actual_type': type(value).__name__, 'expected_type': int.__name__} - matches.extend(self._value_check(value, path, item_type, extra_args)) + matches.extend(self._value_check(value, path, item_type, strict_check, extra_args)) elif item_type in ['Long']: if sys.version_info < (3,): integer_types = (int, long,) # pylint: disable=undefined-variable @@ -111,7 +120,7 @@ def check_primitive_type(self, value, item_type, path): if not isinstance(value, integer_types): extra_args = {'actual_type': type(value).__name__, 'expected_type': ' or '.join([ x.__name__ for x in integer_types])} - matches.extend(self._value_check(value, path, item_type, extra_args)) + matches.extend(self._value_check(value, path, item_type, strict_check, extra_args)) elif isinstance(value, list): message = 'Property should be of type %s at %s' % (item_type, '/'.join(map(str, path))) extra_args = {'actual_type': type(value).__name__, 'expected_type': list.__name__} @@ -124,18 +133,19 @@ def check_value(self, value, path, **kwargs): matches = [] primitive_type = kwargs.get('primitive_type', {}) item_type = kwargs.get('item_type', {}) + strict_check = kwargs.get('non_strict', self.config['strict']) if item_type in ['Map']: if isinstance(value, dict): for map_key, map_value in value.items(): if not isinstance(map_value, dict): matches.extend(self.check_primitive_type( - map_value, primitive_type, path + [map_key])) + map_value, primitive_type, path + [map_key], strict_check)) else: # some properties support primitive types and objects # skip in the case it could be an object and the value is a object if (item_type or primitive_type) and isinstance(value, dict): return matches - matches.extend(self.check_primitive_type(value, primitive_type, path)) + matches.extend(self.check_primitive_type(value, primitive_type, path, strict_check)) return matches @@ -153,15 +163,19 @@ def check(self, cfn, properties, specs, spec_type, path): else: item_type = None if primitive_type: - if not(spec_type == 'AWS::CloudFormation::Stack' and prop == 'Parameters'): - matches.extend( - cfn.check_value( - properties, prop, path, - check_value=self.check_value, - primitive_type=primitive_type, - item_type=item_type - ) + strict_check = self.config['strict'] + if spec_type in self.strict_exceptions: + if prop in self.strict_exceptions[spec_type]: + strict_check = False + matches.extend( + cfn.check_value( + properties, prop, path, + check_value=self.check_value, + primitive_type=primitive_type, + item_type=item_type, + non_strict=strict_check, ) + ) return matches
diff --git a/test/unit/rules/resources/properties/test_value_primitive_type.py b/test/unit/rules/resources/properties/test_value_primitive_type.py --- a/test/unit/rules/resources/properties/test_value_primitive_type.py +++ b/test/unit/rules/resources/properties/test_value_primitive_type.py @@ -63,33 +63,34 @@ def setUp(self): def test_file_positive(self): """Test Positive""" # Test Booleans - self.assertEqual(len(self.rule._value_check('True', ['test'], 'Boolean', {})), 0) - self.assertEqual(len(self.rule._value_check('False', ['test'], 'Boolean', {})), 0) - self.assertEqual(len(self.rule._value_check(1, ['test'], 'Boolean', {})), 1) + self.assertEqual(len(self.rule._value_check('True', ['test'], 'Boolean', False, {})), 0) + self.assertEqual(len(self.rule._value_check('False', ['test'], 'Boolean', False, {})), 0) + self.assertEqual(len(self.rule._value_check(1, ['test'], 'Boolean', False, {})), 1) # Test Strings - self.assertEqual(len(self.rule._value_check(1, ['test'], 'String', {})), 0) - self.assertEqual(len(self.rule._value_check(2, ['test'], 'String', {})), 0) - self.assertEqual(len(self.rule._value_check(True, ['test'], 'String', {})), 0) + self.assertEqual(len(self.rule._value_check(1, ['test'], 'String', False, {})), 0) + self.assertEqual(len(self.rule._value_check(2, ['test'], 'String', False, {})), 0) + self.assertEqual(len(self.rule._value_check(True, ['test'], 'String', False, {})), 0) # Test Integer - self.assertEqual(len(self.rule._value_check('1', ['test'], 'Integer', {})), 0) - self.assertEqual(len(self.rule._value_check('1.2', ['test'], 'Integer', {})), 1) - self.assertEqual(len(self.rule._value_check(True, ['test'], 'Integer', {})), 1) - self.assertEqual(len(self.rule._value_check('test', ['test'], 'Integer', {})), 1) + self.assertEqual(len(self.rule._value_check('1', ['test'], 'Integer', False, {})), 0) + self.assertEqual(len(self.rule._value_check('1.2', ['test'], 'Integer', False, {})), 1) + self.assertEqual(len(self.rule._value_check(True, ['test'], 'Integer', False, {})), 1) + self.assertEqual(len(self.rule._value_check('test', ['test'], 'Integer', False, {})), 1) # Test Double - self.assertEqual(len(self.rule._value_check('1', ['test'], 'Double', {})), 0) - self.assertEqual(len(self.rule._value_check('1.2', ['test'], 'Double', {})), 0) - self.assertEqual(len(self.rule._value_check(1, ['test'], 'Double', {})), 0) - self.assertEqual(len(self.rule._value_check(True, ['test'], 'Double', {})), 1) - self.assertEqual(len(self.rule._value_check('test', ['test'], 'Double', {})), 1) + self.assertEqual(len(self.rule._value_check('1', ['test'], 'Double', False, {})), 0) + self.assertEqual(len(self.rule._value_check('1.2', ['test'], 'Double', False, {})), 0) + self.assertEqual(len(self.rule._value_check(1, ['test'], 'Double', False, {})), 0) + self.assertEqual(len(self.rule._value_check(True, ['test'], 'Double', False, {})), 1) + self.assertEqual(len(self.rule._value_check('test', ['test'], 'Double', False, {})), 1) # Test Long - self.assertEqual(len(self.rule._value_check(str(65536 * 65536), ['test'], 'Long', {})), 0) - self.assertEqual(len(self.rule._value_check('1', ['test'], 'Long', {})), 0) - self.assertEqual(len(self.rule._value_check('1.2', ['test'], 'Long', {})), 1) - self.assertEqual(len(self.rule._value_check(1.2, ['test'], 'Long', {})), 1) - self.assertEqual(len(self.rule._value_check(65536 * 65536, ['test'], 'Long', {})), 0) - self.assertEqual(len(self.rule._value_check(True, ['test'], 'Long', {})), 1) - self.assertEqual(len(self.rule._value_check('test', ['test'], 'Long', {})), 1) + self.assertEqual(len(self.rule._value_check( + str(65536 * 65536), ['test'], 'Long', False, {})), 0) + self.assertEqual(len(self.rule._value_check('1', ['test'], 'Long', False, {})), 0) + self.assertEqual(len(self.rule._value_check('1.2', ['test'], 'Long', False, {})), 1) + self.assertEqual(len(self.rule._value_check(1.2, ['test'], 'Long', False, {})), 1) + self.assertEqual(len(self.rule._value_check(65536 * 65536, ['test'], 'Long', False, {})), 0) + self.assertEqual(len(self.rule._value_check(True, ['test'], 'Long', False, {})), 1) + self.assertEqual(len(self.rule._value_check('test', ['test'], 'Long', False, {})), 1) # Test Unknown type doesn't return error - self.assertEqual(len(self.rule._value_check(1, ['test'], 'Unknown', {})), 0) - self.assertEqual(len(self.rule._value_check('1', ['test'], 'Unknown', {})), 0) - self.assertEqual(len(self.rule._value_check(True, ['test'], 'Unknown', {})), 0) + self.assertEqual(len(self.rule._value_check(1, ['test'], 'Unknown', False, {})), 0) + self.assertEqual(len(self.rule._value_check('1', ['test'], 'Unknown', False, {})), 0) + self.assertEqual(len(self.rule._value_check(True, ['test'], 'Unknown', False, {})), 0)
Environment Variables as Integer on AWS SAM template *cfn-lint version: 0.28.4* *Description of issue.* When using Integer as Envrironment Variable for Serverless (AWS SAM), we get an error saying it should be String. E3012 Property Resources/MyResource/Properties/Environment/Variables/MAIL_PORT should be of type String Please provide as much information as possible: * Template linting issues: * Please provide a CloudFormation sample that generated the issue. ``` Description: My Lambda Repository Transform: AWS::Serverless-2016-10-31 Globals: Function: Environment: Variables: MAIL_PORT: 587 Resources: MyLambda: Type: AWS::Serverless::Function Properties: FunctionName: my-lambda CodeUri: . Handler: pipeline.php Timeout: 300 MemorySize: 512 Environment: Variables: TENANT_QUEUE: !Ref TenantQueue Role: !GetAtt LambdaExecutionRole.Arn Layers: [!Sub "arn:aws:lambda:${AWS::Region}:209497400698:layer:php-73:18"] Runtime: provided VpcConfig: SecurityGroupIds: [!ImportValue AllowAllAddressesContainerSecurityGroup] SubnetIds: !Split [',', !ImportValue PrivateSubnets] ``` * If present, please add links to the (official) documentation for clarification. * Validate if the issue still exists with the latest version of `cfn-lint` and/or the latest Spec files * Feature request: * Please provide argumentation about the missing feature. Context is key! Cfn-lint uses the [CloudFormation Resource Specifications](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) as the base to do validation. These files are included as part of the application version. Please update to the latest version of `cfn-lint` or update the spec files manually (`cfn-lint -u`)
Translated Template. ``` { "Description": "My Lambda Repository", "Resources": { "MyLambda": { "Properties": { "Code": { "S3Bucket": "bucket", "S3Key": "value" }, "Environment": { "Variables": { "MAIL_PORT": 587, "TENANT_QUEUE": { "Ref": "TenantQueue" } } }, "FunctionName": "my-lambda", "Handler": "pipeline.php", "Layers": [ { "Fn::Sub": "arn:aws:lambda:${AWS::Region}:209497400698:layer:php-73:18" } ], "MemorySize": 512, "Role": { "Fn::GetAtt": [ "LambdaExecutionRole", "Arn" ] }, "Runtime": "provided", "Tags": [ { "Key": "lambda:createdBy", "Value": "SAM" } ], "Timeout": 300, "VpcConfig": { "SecurityGroupIds": [ { "Fn::ImportValue": "AllowAllAddressesContainerSecurityGroup" } ], "SubnetIds": { "Fn::Split": [ ",", { "Fn::ImportValue": "PrivateSubnets" } ] } } }, "Type": "AWS::Lambda::Function" } } } ``` As the spec has it. ``` "Variables": { "Documentation": "http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-environment.html#cfn-lambda-function-environment-variables", "DuplicatesAllowed": false, "PrimitiveItemType": "String", "Required": false, "Type": "Map", "UpdateType": "Mutable" } ``` This isn't really a spec bug. By default we do strict checking of the types based on the spec. Two options: 1. We make an exception like we did for `AWS::CloudFormation::Stack` `Parameters`. 2. You turn off strict checking in E3012. Documentation is here https://github.com/aws-cloudformation/cfn-python-lint#configure-rules I was hoping this could work similarly to how ECS Task Definition environment variable does: I can have number values there.
2020-03-14T15:32:01Z
[]
[]
aws-cloudformation/cfn-lint
1,441
aws-cloudformation__cfn-lint-1441
[ "1438" ]
7126c66a16228964afb7b0e34affe55499ce5613
diff --git a/src/cfnlint/rules/resources/rds/InstanceEngine.py b/src/cfnlint/rules/resources/rds/InstanceEngine.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/resources/rds/InstanceEngine.py @@ -0,0 +1,57 @@ +""" +Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +import json +from cfnlint.rules import CloudFormationLintRule +from cfnlint.rules import RuleMatch + + +class InstanceEngine(CloudFormationLintRule): + """Check if Resources RDS Instance Size is compatible with the RDS type""" + id = 'E3040' + shortdesc = 'RDS DB Instance Engine is valid' + description = 'Check the RDS DB Instance Engine is valid' + source_url = 'https: // docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateDBInstance.html' + tags = ['resources', 'rds'] + + valid_engines = [ + 'aurora', + 'aurora-mysql', + 'aurora-postgresql', + 'mariadb', + 'mysql', + 'oracle-ee', + 'oracle-se2', + 'oracle-se1', + 'oracle-se', + 'postgres', + 'sqlserver-ee', + 'sqlserver-se', + 'sqlserver-ex', + 'sqlserver-web' + ] + + def __init__(self): + """Init""" + super(InstanceEngine, self).__init__() + self.resource_property_types = ['AWS::RDS::DBInstance'] + + def check_value(self, value, path): + """Check engine""" + if value.lower() not in self.valid_engines: + message = 'RDS Engine "{0}" must be one of {1}' + return [RuleMatch(path, message.format(value, json.dumps(self.valid_engines)))] + + return [] + + def match_resource_properties(self, properties, _, path, cfn): + """Match for sub properties""" + matches = [] + matches.extend( + cfn.check_value( + obj=properties, key='Engine', + path=path[:], + check_value=self.check_value + )) + return matches
diff --git a/test/fixtures/templates/bad/resources/rds/instance_engine.yaml b/test/fixtures/templates/bad/resources/rds/instance_engine.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources/rds/instance_engine.yaml @@ -0,0 +1,20 @@ +--- +AWSTemplateFormatVersion: "2010-09-09" +Parameters: + snapshotid: + Type: String +Conditions: + snapshot: !Not [!Equals [!Ref snapshotid, ""]] +Resources: + # Doesnt check if conditions are used + DBInstance1: + Type: AWS::RDS::DBInstance + Properties: + DBInstanceClass: db.m4.xlarge + Engine: !If [snapshot, badengine, simple] + # Doesnt fail on valid instance type + DBInstance2: + Type: AWS::RDS::DBInstance + Properties: + DBInstanceClass: db.r4.xlarge + Engine: auroramysql diff --git a/test/fixtures/templates/good/resources/rds/instance_engine.yaml b/test/fixtures/templates/good/resources/rds/instance_engine.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/rds/instance_engine.yaml @@ -0,0 +1,20 @@ +--- +AWSTemplateFormatVersion: "2010-09-09" +Parameters: + snapshotid: + Type: String +Conditions: + snapshot: !Not [!Equals [!Ref snapshotid, ""]] +Resources: + # Doesnt check if conditions are used + DBInstance1: + Type: AWS::RDS::DBInstance + Properties: + DBInstanceClass: db.m4.xlarge + Engine: !If [snapshot, !Ref aurora-mysql, aurora] + # Doesnt fail on valid instance type + DBInstance2: + Type: AWS::RDS::DBInstance + Properties: + DBInstanceClass: db.r4.xlarge + Engine: oracle-se2 diff --git a/test/unit/rules/resources/rds/test_instance_engine.py b/test/unit/rules/resources/rds/test_instance_engine.py new file mode 100644 --- /dev/null +++ b/test/unit/rules/resources/rds/test_instance_engine.py @@ -0,0 +1,27 @@ +""" +Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from test.unit.rules import BaseRuleTestCase +from cfnlint.rules.resources.rds.InstanceEngine import InstanceEngine # pylint: disable=E0401 + + +class TestInstanceEngine(BaseRuleTestCase): + """Test RDS Instance Size Configuration""" + + def setUp(self): + """Setup""" + super(TestInstanceEngine, self).setUp() + self.collection.register(InstanceEngine()) + self.success_templates = [ + 'test/fixtures/templates/good/resources/rds/instance_engine.yaml' + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative_alias(self): + """Test failure""" + self.helper_file_negative( + 'test/fixtures/templates/bad/resources/rds/instance_engine.yaml', 3)
E3030 case sensitivity caused DB instance destruction! *cfn-lint version: (`cfn-lint --version`)* 0.29.0 *Description of issue.* E3030 told me that "Postgres" was not an allowed engine name, so I changed it to "postgres". This caused cloudformation to rebuild my database instance, aka complete data loss. Luckily only discovered this on staging environment. I think since CloudFormation / RDS seems to allow it, this check should be made case insensitive :)
I think this is also a CloudFormation bug, in that it compares the strings in a case-sensitive manner, when RDS underneath compares them in a case-insensitive manner. If you could file a bug there too that would be great. Doing some more testing now. For some reason we called out mysql with multiple spellings. ``` "AllowedValues": [ "aurora", "aurora-mysql", "aurora-postgresql", "mariadb", "mysql", "MySQL", "oracle-ee", "oracle-se2", "oracle-se1", "oracle-se", "postgres", "sqlserver-ee", "sqlserver-se", "sqlserver-ex", "sqlserver-web" ] ``` I tested a few other resources (e.g. Lambda) and they all aren't case insensitive. So this seems particular to RDS. So I think we should leave the check as is, remove the values from this location and create a new rule that deals with case insensitive comparison.
2020-03-25T16:07:52Z
[]
[]
aws-cloudformation/cfn-lint
1,444
aws-cloudformation__cfn-lint-1444
[ "1443" ]
ac097e59421b1e96657a76fb088406af97be5766
diff --git a/src/cfnlint/rules/functions/SubNeeded.py b/src/cfnlint/rules/functions/SubNeeded.py --- a/src/cfnlint/rules/functions/SubNeeded.py +++ b/src/cfnlint/rules/functions/SubNeeded.py @@ -19,7 +19,7 @@ class SubNeeded(CloudFormationLintRule): # Free-form text properties to exclude from this rule # content is part of AWS::CloudFormation::Init excludes = ['UserData', 'ZipFile', 'Condition', 'AWS::CloudFormation::Init', - 'CloudWatchAlarmDefinition', 'TopicRulePayload'] + 'CloudWatchAlarmDefinition', 'TopicRulePayload', 'BuildSpec'] api_excludes = ['Uri', 'Body'] # IAM Policy has special variables that don't require !Sub, Check for these @@ -150,8 +150,8 @@ def match(self, cfn): if not found_sub: # Remove the last item (the variable) to prevent multiple errors on 1 line errors path = parameter_string_path[:-1] - message = 'Found an embedded parameter outside of an "Fn::Sub" at {}'.format( - '/'.join(map(str, path))) + message = 'Found an embedded parameter "{}" outside of an "Fn::Sub" at {}'.format( + variable, '/'.join(map(str, path))) matches.append(RuleMatch(path, message)) return matches
diff --git a/test/unit/rules/functions/test_sub_needed.py b/test/unit/rules/functions/test_sub_needed.py --- a/test/unit/rules/functions/test_sub_needed.py +++ b/test/unit/rules/functions/test_sub_needed.py @@ -31,9 +31,9 @@ def test_template_config(self): ) self.helper_file_rule_config( 'test/fixtures/templates/good/functions/sub_needed_custom_excludes.yaml', - {}, 3 - ) + {}, 4 + ) def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/functions/sub_needed.yaml', 4) + self.helper_file_negative('test/fixtures/templates/bad/functions/sub_needed.yaml', 6)
Unexpected E1029 error *cfn-lint version: (0.29.1)* *Description of issue.* After this version was released, I started getting an error when linting a template. This error specific to `BuildSpec` attributes for a `AWS::CodeBuild::Project` project. E1029 Found an embedded parameter outside of an "Fn::Sub" at Resources/MyCodeBuild/Properties/Source/BuildSpec cloudformation.json:151:11 I mocked up a JSON template that showcases the problem and [attached](https://github.com/aws-cloudformation/cfn-python-lint/files/4383494/cloudformation.txt) it.
2020-03-25T22:55:00Z
[]
[]
aws-cloudformation/cfn-lint
1,462
aws-cloudformation__cfn-lint-1462
[ "1170" ]
23c7fb5618bbb9a85c89cc6dda23765254e9cbfe
diff --git a/src/cfnlint/config.py b/src/cfnlint/config.py --- a/src/cfnlint/config.py +++ b/src/cfnlint/config.py @@ -48,17 +48,25 @@ class ConfigFileArgs(object): Parses .cfnlintrc in the Home and Project folder. """ file_args = {} + __user_config_file = None + __project_config_file = None + __custom_config_file = None - def __init__(self, schema=None): + def __init__(self, schema=None, config_file=None): # self.file_args = self.get_config_file_defaults() - self.__user_config_file = None - self.__project_config_file = None self.file_args = {} self.default_schema_file = Path(__file__).parent.joinpath( 'data/CfnLintCli/config/schema.json') with self.default_schema_file.open() as f: self.default_schema = json.load(f) self.schema = self.default_schema if not schema else schema + + if config_file: + self.__custom_config_file = config_file + else: + LOGGER.debug('Looking for CFLINTRC before attempting to load') + self.__user_config_file, self.__project_config_file = self._find_config() + self.load() def _find_config(self): @@ -113,24 +121,30 @@ def load(self): CFLINTRC configuration """ - LOGGER.debug('Looking for CFLINTRC before attempting to load') - user_config, project_config = self._find_config() + if self.__custom_config_file: + custom_config = self._read_config(self.__custom_config_file) + LOGGER.debug('Validating Custom CFNLINTRC') + self.validate_config(custom_config, self.schema) + LOGGER.debug('Custom configuration loaded as') + LOGGER.debug('%s', custom_config) - user_config = self._read_config(user_config) - LOGGER.debug('Validating User CFNLINTRC') - self.validate_config(user_config, self.schema) + self.file_args = custom_config + else: + user_config = self._read_config(self.__user_config_file) + LOGGER.debug('Validating User CFNLINTRC') + self.validate_config(user_config, self.schema) - project_config = self._read_config(project_config) - LOGGER.debug('Validating Project CFNLINTRC') - self.validate_config(project_config, self.schema) + project_config = self._read_config(self.__project_config_file) + LOGGER.debug('Validating Project CFNLINTRC') + self.validate_config(project_config, self.schema) - LOGGER.debug('User configuration loaded as') - LOGGER.debug('%s', user_config) - LOGGER.debug('Project configuration loaded as') - LOGGER.debug('%s', project_config) + LOGGER.debug('User configuration loaded as') + LOGGER.debug('%s', user_config) + LOGGER.debug('Project configuration loaded as') + LOGGER.debug('%s', project_config) - LOGGER.debug('Merging configurations...') - self.file_args = self.merge_config(user_config, project_config) + LOGGER.debug('Merging configurations...') + self.file_args = self.merge_config(user_config, project_config) def validate_config(self, config, schema): """Validate configuration against schema @@ -378,6 +392,9 @@ def __call__(self, parser, namespace, values, option_string=None): help='Provide configuration for a rule. Format RuleId:key=value. Example: E3012:strict=false' ) + standard.add_argument('--config-file', dest='config_file', + help='Specify the cfnlintrc file to use') + advanced.add_argument( '-o', '--override-spec', dest='override_spec', help='A CloudFormation Spec override file that allows customization' @@ -459,8 +476,9 @@ def __init__(self, cli_args): CliArgs.__init__(self, cli_args) # configure debug as soon as we can configure_logging(self.cli_args.debug, self.cli_args.info) - ConfigFileArgs.__init__(self) TemplateArgs.__init__(self, {}) + ConfigFileArgs.__init__( + self, config_file=self._get_argument_value('config_file', False, False)) def _get_argument_value(self, arg_name, is_template, is_config_file): """ Get Argument value """ @@ -623,6 +641,11 @@ def configure_rules(self): """ Configure rules """ return self._get_argument_value('configure_rules', True, True) + @property + def config_file(self): + """ Config file """ + return self._get_argument_value('config_file', False, False) + @property def build_graph(self): """ build_graph """
diff --git a/test/unit/module/config/test_config_file_args.py b/test/unit/module/config/test_config_file_args.py --- a/test/unit/module/config/test_config_file_args.py +++ b/test/unit/module/config/test_config_file_args.py @@ -26,22 +26,34 @@ def tearDown(self): def test_config_parser_read_config(self): """ Testing one file successful """ - # cfnlintrc_mock.return_value.side_effect = [Mock(return_value=True), Mock(return_value=False)] - config = cfnlint.config.ConfigFileArgs() - config_file = Path('test/fixtures/configs/cfnlintrc_read.yaml') - config_template = config._read_config(config_file) + config = cfnlint.config.ConfigFileArgs( + config_file=Path('test/fixtures/configs/cfnlintrc_read.yaml') + ) self.assertEqual( - config_template, + config.file_args, { 'templates': ['test/fixtures/templates/good/**/*.yaml'], 'include_checks': ['I'] } ) + @patch('cfnlint.config.ConfigFileArgs._read_config', create=True) + def test_config_parser_read_config_only_one_read(self, yaml_mock): + """ Testing one file successful """ + # Should only have one read here + # We aren't going to search and find the possible locations of + # cfnlintrc + yaml_mock.side_effect = [ + {"regions": ["us-west-1"]}, + ] + config = cfnlint.config.ConfigFileArgs( + config_file=Path('test/fixtures/configs/cfnlintrc_read.yaml') + ) + self.assertEqual(config.file_args, {'regions': ['us-west-1']}) + @patch('cfnlint.config.ConfigFileArgs._read_config', create=True) def test_config_parser_read(self, yaml_mock): """ Testing one file successful """ - # cfnlintrc_mock.return_value.side_effect = [Mock(return_value=True), Mock(return_value=False)] yaml_mock.side_effect = [ {"regions": ["us-west-1"]}, {}
Parameter to pick the location of .cfnlintrc Requesting to add a parameter that allows a user to specify a path to a `.cfnlintrc` file. Right now those are only a few locations we look for a `.cfnlintrc` file. We would like to allow a user to specify that location.
Hello! What's the status of this task? Is someone working on this? Sorry @Jhonatangiraldo. I missed this. I was going to pick this up this week unless you would like to take it. So digging this into today. The question I have is if a path is specified do we not look into any other .cfnlintrc files? Right now we look at a users config file a "projects" config file and we merge them together. we have 2 options here. 1. Merge the custom config file with the other 2 2. Not load the other 2 at all and only use the one specified. thoughts? > 2. Not load the other 2 at all and only use the one specified.
2020-04-08T01:56:20Z
[]
[]
aws-cloudformation/cfn-lint
1,483
aws-cloudformation__cfn-lint-1483
[ "1400" ]
495da386b658627aefda9d49a252e24a8244ba4d
diff --git a/src/cfnlint/rules/resources/route53/RecordSetName.py b/src/cfnlint/rules/resources/route53/RecordSetName.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/resources/route53/RecordSetName.py @@ -0,0 +1,59 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +import six +from cfnlint.rules import CloudFormationLintRule +from cfnlint.rules import RuleMatch + + +class RecordSetName(CloudFormationLintRule): + """Check if a Route53 Resoruce Records Name is valid with a HostedZoneName""" + id = 'E3041' + shortdesc = 'RecordSet HostedZoneName is a superdomain of Name' + description = 'In a RecordSet, the HostedZoneName must be a superdomain of the Name being validated' + source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-name' + tags = ['resource', 'properties', 'route53'] + + def __init__(self): + """ Init """ + super(RecordSetName, self).__init__() + self.resource_property_types = ['AWS::Route53::RecordSet'] + + def match_resource_properties(self, properties, _, path, cfn): + """ Check Load Balancers """ + matches = [] + + property_sets = cfn.get_object_without_conditions(properties, ['Name', 'HostedZoneName']) + for property_set in property_sets: + props = property_set.get('Object') + scenario = property_set.get('Scenario') + name = props.get('Name', None) + hz_name = props.get('HostedZoneName', None) + if isinstance(name, six.string_types) and isinstance(hz_name, six.string_types): + if hz_name[-1] != '.': + message = 'HostedZoneName must end in a dot at {}' + if scenario is None: + matches.append( + RuleMatch(path[:] + ['HostedZoneName'], message.format('/'.join(map(str, path))))) + else: + scenario_text = ' and '.join( + ['when condition "%s" is %s' % (k, v) for (k, v) in scenario.items()]) + matches.append( + RuleMatch(path[:] + ['HostedZoneName'], message.format('/'.join(map(str, path)) + ' ' + scenario_text))) + if hz_name[-1] == '.': + hz_name = hz_name[:-1] + if name[-1] == '.': + name = name[:-1] + if not name.endswith('.' + hz_name): + message = 'Name must be a superdomain of HostedZoneName at {}' + if scenario is None: + matches.append( + RuleMatch(path[:] + ['Name'], message.format('/'.join(map(str, path))))) + else: + scenario_text = ' and '.join( + ['when condition "%s" is %s' % (k, v) for (k, v) in scenario.items()]) + matches.append( + RuleMatch(path[:] + ['Name'], message.format('/'.join(map(str, path)) + ' ' + scenario_text))) + + return matches
diff --git a/test/fixtures/templates/bad/resources/route53/recordset_name.yaml b/test/fixtures/templates/bad/resources/route53/recordset_name.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources/route53/recordset_name.yaml @@ -0,0 +1,43 @@ +AWSTemplateFormatVersion: 2010-09-09 +Conditions: + isPrimaryRegion: + Fn::Equals: + - !Ref AWS::Region + - "us-east-1" +Resources: + RecordSet1: + Type: AWS::Route53::RecordSet + Properties: + HostedZoneName: notexample.com + Name: test.example.com + ResourceRecords: + - 192.0.2.99 + TTL: 900 + Type: A + RecordSet2: + Type: AWS::Route53::RecordSet + Properties: + HostedZoneName: example.com. + Name: testexample.com + ResourceRecords: + - 192.0.2.99 + TTL: 900 + Type: A + RecordSet3: + Type: AWS::Route53::RecordSet + Properties: + HostedZoneName: !If [isPrimaryRegion, notexample.com, example.com.] + Name: test.example.com + ResourceRecords: + - 192.0.2.99 + TTL: 900 + Type: A + RecordSet4: + Type: AWS::Route53::RecordSet + Properties: + HostedZoneName: example.com. + Name: !If [isPrimaryRegion, testexample.com, test.example.com] + ResourceRecords: + - 192.0.2.99 + TTL: 900 + Type: A diff --git a/test/fixtures/templates/good/resources/route53/recordset_name.yaml b/test/fixtures/templates/good/resources/route53/recordset_name.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/route53/recordset_name.yaml @@ -0,0 +1,20 @@ +AWSTemplateFormatVersion: 2010-09-09 +Resources: + RecordSet1: + Type: AWS::Route53::RecordSet + Properties: + HostedZoneName: example.com. + Name: rs1.example.com + ResourceRecords: + - 192.0.2.99 + TTL: 900 + Type: A + RecordSet2: + Type: AWS::Route53::RecordSet + Properties: + HostedZoneName: example.com. + Name: rs2.example.com. + ResourceRecords: + - 192.0.2.99 + TTL: 900 + Type: A diff --git a/test/fixtures/templates/good/transform/list_transform.yaml b/test/fixtures/templates/good/transform/list_transform.yaml --- a/test/fixtures/templates/good/transform/list_transform.yaml +++ b/test/fixtures/templates/good/transform/list_transform.yaml @@ -1,5 +1,5 @@ --- -AWSTemplateFormatVersion: '2010-09-09' +AWSTemplateFormatVersion: "2010-09-09" Transform: - AWS::Serverless-2016-10-31 @@ -15,7 +15,7 @@ Resources: SkillFunction: Type: AWS::Serverless::Function Properties: - CodeUri: '.' + CodeUri: "." Handler: main.handler Runtime: python3.7 Timeout: 30 diff --git a/test/unit/rules/resources/route53/test_recordset_name.py b/test/unit/rules/resources/route53/test_recordset_name.py new file mode 100644 --- /dev/null +++ b/test/unit/rules/resources/route53/test_recordset_name.py @@ -0,0 +1,27 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from test.unit.rules import BaseRuleTestCase +from cfnlint.rules.resources.route53.RecordSetName import RecordSetName # pylint: disable=E0401 + + +class TestRoute53RecordSetName(BaseRuleTestCase): + """Test CloudFront Aliases Configuration""" + + def setUp(self): + """Setup""" + super(TestRoute53RecordSetName, self).setUp() + self.collection.register(RecordSetName()) + self.success_templates = [ + 'test/fixtures/templates/good/resources/route53/recordset_name.yaml' + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative(self): + """Test failure""" + self.helper_file_negative( + 'test/fixtures/templates/bad/resources/route53/recordset_name.yaml', 6)
Check whether RecordSet name is valid *cfn-lint version: 0.28.2* *Description of issue.* cfn-lint could check whether the name is valid for a given hosted zone. Specifically: ``` + "FooBarDelegation": { + "Type": "AWS::Route53::RecordSet", + "Properties": { + "HostedZoneName": "bar.example.com.", + "Name": "foo", + "TTL": "86400", + "Type": "NS", + "ResourceRecords": [ ... + ] + } ``` could be attempted, which results in a not very clear error: ``` RRSet with DNS name foo. is not permitted in zone bar.example.com. ``` The solution is to have name `foo.bar.example.com` instead. This came up in a highly upvoted SO question as well: https://stackoverflow.com/questions/11420063/rrset-with-dns-name-foo-is-not-permitted-in-zone-bar It would be great if (when the values are available), cfn-lint raised an error "Name has to end with HostedZoneName"
@viraptor few other things I'm curious on. 1. Looks like `HostedZoneName` needs to end with a trailing `.` 2. Name can end or not with a trailing dot. They are treated equally Do I have that correct?
2020-04-21T16:24:07Z
[]
[]
aws-cloudformation/cfn-lint
1,506
aws-cloudformation__cfn-lint-1506
[ "1368" ]
77be715e16585f04c0743b0a831c4d2ebdb85b5b
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -53,7 +53,8 @@ def get_version(filename): 'importlib_resources~=1.0.2;python_version=="3.4"', 'importlib_resources~=1.4;python_version<"3.7" and python_version!="3.4"', 'networkx~=2.4;python_version>="3.5"', - 'networkx<=2.2;python_version<"3.5"' + 'networkx<=2.2;python_version<"3.5"', + 'junit-xml~=1.9', ], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', entry_points={ diff --git a/src/cfnlint/__main__.py b/src/cfnlint/__main__.py --- a/src/cfnlint/__main__.py +++ b/src/cfnlint/__main__.py @@ -15,6 +15,7 @@ def main(): try: (args, filenames, formatter) = cfnlint.core.get_args_filenames(sys.argv[1:]) matches = [] + rules = None for filename in filenames: LOGGER.debug('Begin linting of file: %s', str(filename)) (template, rules, template_matches) = cfnlint.core.get_template_rules(filename, args) @@ -27,7 +28,7 @@ def main(): matches.extend(template_matches) LOGGER.debug('Completed linting of file: %s', str(filename)) - matches_output = formatter.print_matches(matches) + matches_output = formatter.print_matches(matches, rules) if matches_output: print(matches_output) return cfnlint.core.get_exit_code(matches) diff --git a/src/cfnlint/config.py b/src/cfnlint/config.py --- a/src/cfnlint/config.py +++ b/src/cfnlint/config.py @@ -349,7 +349,7 @@ def __call__(self, parser, namespace, values, option_string=None): '-I', '--info', help='Enable information logging', action='store_true' ) standard.add_argument( - '-f', '--format', help='Output Format', choices=['quiet', 'parseable', 'json'] + '-f', '--format', help='Output Format', choices=['quiet', 'parseable', 'json', 'junit'] ) standard.add_argument( diff --git a/src/cfnlint/core.py b/src/cfnlint/core.py --- a/src/cfnlint/core.py +++ b/src/cfnlint/core.py @@ -76,6 +76,8 @@ def get_formatter(fmt): formatter = cfnlint.formatters.ParseableFormatter() elif fmt == 'json': formatter = cfnlint.formatters.JsonFormatter() + elif fmt == 'junit': + formatter = cfnlint.formatters.JUnitFormatter() else: formatter = cfnlint.formatters.Formatter() diff --git a/src/cfnlint/formatters/__init__.py b/src/cfnlint/formatters/__init__.py --- a/src/cfnlint/formatters/__init__.py +++ b/src/cfnlint/formatters/__init__.py @@ -3,17 +3,20 @@ SPDX-License-Identifier: MIT-0 """ import json +from junit_xml import TestSuite, TestCase, to_xml_report_string from cfnlint.rules import Match - class BaseFormatter(object): """Base Formatter class""" def _format(self, match): """Format the specific match""" - def print_matches(self, matches): + def print_matches(self, matches, rules=None): """Output all the matches""" + # Unused argument http://pylint-messages.wikidot.com/messages:w0613 + del rules + if not matches: return None @@ -40,6 +43,56 @@ def _format(self, match): ) +class JUnitFormatter(BaseFormatter): + """JUnit-style Reports""" + + def _failure_format(self, match): + """Format output of a failure""" + formatstr = u'{0} at {1}:{2}:{3}' + return formatstr.format( + match.message, + match.filename, + match.linenumber, + match.columnnumber + ) + + def print_matches(self, matches, rules=None): + """Output all the matches""" + + if not rules: + return None + + test_cases = [] + for rule in rules.all_rules: + if not rules.is_rule_enabled(rule.id, rule.experimental): + if not rule.id: + continue + test_case = TestCase(name='{0} {1}'.format(rule.id, rule.shortdesc)) + + if rule.experimental: + test_case.add_skipped_info(message='Experimental rule - not enabled') + else: + test_case.add_skipped_info(message='Ignored rule') + test_cases.append(test_case) + else: + test_case = TestCase( + name='{0} {1}'.format(rule.id, rule.shortdesc), + allow_multiple_subelements=True, + url=rule.source_url + ) + for match in matches: + if match.rule.id == rule.id: + test_case.add_failure_info( + message=self._failure_format(match), + failure_type=match.message + ) + test_cases.append(test_case) + + test_suite = TestSuite('CloudFormation Lint', test_cases) + + return to_xml_report_string([test_suite], prettyprint=True) + + class JsonFormatter(BaseFormatter): """Json Formatter""" @@ -80,8 +133,11 @@ def default(self, o): } return {'__{}__'.format(o.__class__.__name__): o.__dict__} - def print_matches(self, matches): + def print_matches(self, matches, rules=None): # JSON formatter outputs a single JSON object + # Unused argument http://pylint-messages.wikidot.com/messages:w0613 + del rules + return json.dumps( matches, indent=4, cls=self.CustomEncoder, sort_keys=True, separators=(',', ': ')) diff --git a/src/cfnlint/rules/__init__.py b/src/cfnlint/rules/__init__.py --- a/src/cfnlint/rules/__init__.py +++ b/src/cfnlint/rules/__init__.py @@ -133,6 +133,7 @@ class RulesCollection(object): def __init__(self, ignore_rules=None, include_rules=None, configure_rules=None, include_experimental=False, mandatory_rules=None): self.rules = [] + self.all_rules = [] # Whether "experimental" rules should be added self.include_experimental = include_experimental @@ -148,6 +149,7 @@ def __init__(self, ignore_rules=None, include_rules=None, configure_rules=None, def register(self, rule): """Register rules""" + self.all_rules.append(rule) if self.is_rule_enabled(rule.id, rule.experimental): self.rules.append(rule) if rule.id in self.configure_rules: @@ -162,6 +164,7 @@ def __len__(self): def extend(self, more): """Extend rules""" for rule in more: + self.all_rules.append(rule) if self.is_rule_enabled(rule.id, rule.experimental): self.rules.append(rule) if rule.id in self.configure_rules:
diff --git a/test/unit/module/formatters/test_formatters.py b/test/unit/module/formatters/test_formatters.py --- a/test/unit/module/formatters/test_formatters.py +++ b/test/unit/module/formatters/test_formatters.py @@ -3,6 +3,7 @@ SPDX-License-Identifier: MIT-0 """ import json +import xml.etree.ElementTree as ET from test.testlib.testcase import BaseTestCase import cfnlint.formatters @@ -44,3 +45,85 @@ def test_json_formatter(self): self.assertEqual(json_results[0]['Level'], 'Informational') self.assertEqual(json_results[1]['Level'], 'Warning') self.assertEqual(json_results[2]['Level'], 'Error') + + def test_junit_returns_none(self): + """Test JUnut Formatter returns None if no rules are passed in""" + + # Test setup + filename = 'test/fixtures/templates/bad/formatters.yaml' + (args, filenames, formatter) = cfnlint.core.get_args_filenames([ + '--template', filename, '--format', 'junit', '--include-checks', 'I', '--ignore-checks', 'E1029']) + + results = [] + rules = None + for filename in filenames: + (template, rules, _) = cfnlint.core.get_template_rules(filename, args) + results.extend( + cfnlint.core.run_checks( + filename, template, rules, ['us-east-1'])) + + # Validate Formatter class initiated + self.assertEqual('JUnitFormatter', formatter.__class__.__name__) + + # The actual test + self.assertIsNone(formatter.print_matches([], [])) + + + def test_junit_formatter(self): + """Test JUnit Formatter""" + + # Run a broken template + filename = 'test/fixtures/templates/bad/formatters.yaml' + (args, filenames, formatter) = cfnlint.core.get_args_filenames([ + '--template', filename, '--format', 'junit', '--include-checks', 'I', '--ignore-checks', 'E1029']) + + results = [] + rules = None + for filename in filenames: + (template, rules, _) = cfnlint.core.get_template_rules(filename, args) + results.extend( + cfnlint.core.run_checks( + filename, template, rules, ['us-east-1'])) + + # Validate Formatter class initiated + self.assertEqual('JUnitFormatter', formatter.__class__.__name__) + + # We need 3 errors (Information, Warning, Error) + self.assertEqual(len(results), 3) + # Check the errors + self.assertEqual(results[0].rule.id, 'I3011') + self.assertEqual(results[1].rule.id, 'W1020') + self.assertEqual(results[2].rule.id, 'E3012') + + root = ET.fromstring(formatter.print_matches(results, rules)) + + self.assertEqual(root.tag, 'testsuites') + self.assertEqual(root[0].tag, 'testsuite') + + found_i3011 = False + found_w1020 = False + found_e3012 = False + name_i3011 = '{0} {1}'.format(results[0].rule.id, results[0].rule.shortdesc) + name_w1020 = '{0} {1}'.format(results[1].rule.id, results[1].rule.shortdesc) + name_e3012 = '{0} {1}'.format(results[2].rule.id, results[2].rule.shortdesc) + name_e1029 = 'E1029 Sub is required if a variable is used in a string' + for child in root[0]: + self.assertEqual(child.tag, 'testcase') + + if child.attrib['name'] in [name_i3011, name_w1020, name_e3012]: + self.assertEqual(child[0].tag, 'failure') + + if child.attrib['name'] == name_i3011: + found_i3011 = True + if child.attrib['name'] == name_w1020: + found_w1020 = True + if child.attrib['name'] == name_e3012: + found_e3012 = True + + if child.attrib['name'] == name_e1029: + self.assertEqual(child[0].tag, 'skipped') + self.assertEqual(child[0].attrib['type'], 'skipped') + + self.assertTrue(found_i3011) + self.assertTrue(found_w1020) + self.assertTrue(found_e3012)
--format JUnit XML reporting file format **Feature request** Would be really handle if we can get some more formatting options for popular test frameworks, for example JUnit XML. These frameworks integrate into many build pipeline technologies for an integrated test reporting. As it stands cfn-python-lint runs as a scripted step and will exit with errors if there are any structural issues with the templates. ideally i would like the output to be formatted into JUnit XML with results of each tested resources. this file is picked up by our build framework and the pipline will pass or fail based on the results of the test run, the same way we do for code tests.
I second this. Being able to ingest the linting results for display in a tool like Jenkins would be very useful, especially for review by non-developer cloud architects. Ant's JUnit XML schema is here for reference: https://github.com/windyroad/JUnit-Schema/blob/master/JUnit.xsd
2020-05-01T07:56:56Z
[]
[]
aws-cloudformation/cfn-lint
1,562
aws-cloudformation__cfn-lint-1562
[ "1561" ]
ebc7cfb3d77548b94066028509a5bcaa27892645
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -45,7 +45,7 @@ def get_version(filename): 'pyyaml<=5.2;python_version=="3.4"', 'pyyaml;python_version!="3.4"', 'six~=1.11', - 'aws-sam-translator>=1.23.0', + 'aws-sam-translator>=1.24.0', 'jsonpatch;python_version!="3.4"', 'jsonpatch<=1.24;python_version=="3.4"', 'jsonschema~=3.0', diff --git a/src/cfnlint/transform.py b/src/cfnlint/transform.py --- a/src/cfnlint/transform.py +++ b/src/cfnlint/transform.py @@ -85,6 +85,8 @@ def _replace_local_codeuri(self): Transform._update_to_s3_uri('DefinitionUri', resource_dict) else: resource_dict['DefinitionBody'] = '' + if resource_type == 'AWS::Serverless::StateMachine': + Transform._update_to_s3_uri('DefinitionUri', resource_dict) def transform_template(self): """
diff --git a/test/fixtures/templates/good/transform/step_function_local_definition.yaml b/test/fixtures/templates/good/transform/step_function_local_definition.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/transform/step_function_local_definition.yaml @@ -0,0 +1,12 @@ +Transform: AWS::Serverless-2016-10-31 +Resources: + StateMachine: + Type: AWS::Serverless::StateMachine + Properties: + DefinitionUri: ./test.json + Policies: + - Version: "2012-10-17" + Statement: + - Effect: Deny + Action: "*" + Resource: "*" diff --git a/test/unit/module/transform/test_transform.py b/test/unit/module/transform/test_transform.py --- a/test/unit/module/transform/test_transform.py +++ b/test/unit/module/transform/test_transform.py @@ -28,6 +28,21 @@ def test_parameter_for_autopublish_version(self): 'FunctionVersion': {'Fn::GetAtt': ['SkillFunctionVersion55ff35af87', 'Version']} }) + def test_conversion_of_step_function_definition_uri(self): + """ Tests that the a serverless step function can convert a local path to a s3 path """ + filename = 'test/fixtures/templates/good/transform/step_function_local_definition.yaml' + region = 'us-east-1' + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + transformed_template.transform_template() + self.assertDictEqual( + transformed_template._template.get('Resources').get( + 'StateMachine').get('Properties').get('DefinitionS3Location'), + { + 'Bucket': 'bucket', + 'Key': 'value' + }) + def test_parameter_for_autopublish_version_bad(self): """Test Parameter is created for autopublish version run""" filename = 'test/fixtures/templates/bad/transform/auto_publish_alias.yaml'
AWS::Serverless::StateMachine.DefinitionUri support for local files *cfn-lint version: 0.32.1* *Description of issue.* The recent release of SAM support for Step Functions has added the ability to use a non-S3 URL for the [`DefinitionUri`](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-statemachine.html#sam-statemachine-definitionuri) in order to reference local files that get included during a deploy. The linter is currently throwing an error for all non-S3 values, though. ``` [cfn-lint] E0001: Error transforming template: Resource with id [StateMachine] is invalid. 'DefinitionUri' is not a valid S3 Uri of the form 's3://bucket/key' with optional versionId query parameter. ```
2020-06-02T15:22:33Z
[]
[]
aws-cloudformation/cfn-lint
1,580
aws-cloudformation__cfn-lint-1580
[ "1133" ]
05db6949c9b43599f1b5e398a35f05046f9cf857
diff --git a/src/cfnlint/__main__.py b/src/cfnlint/__main__.py --- a/src/cfnlint/__main__.py +++ b/src/cfnlint/__main__.py @@ -26,14 +26,16 @@ def main(): rules = None for filename in filenames: LOGGER.debug('Begin linting of file: %s', str(filename)) - (template, rules, template_matches) = cfnlint.core.get_template_rules(filename, args) - if not template_matches: + (template, rules, errors) = cfnlint.core.get_template_rules(filename, args) + # template matches may be empty but the template is still None + # this happens when ignoring bad templates + if not errors and template: matches.extend( cfnlint.core.run_cli( filename, template, rules, args.regions, args.override_spec, args.build_graph, args.mandatory_checks)) else: - matches.extend(template_matches) + matches.extend(errors) LOGGER.debug('Completed linting of file: %s', str(filename)) matches_output = formatter.print_matches(matches, rules) diff --git a/src/cfnlint/config.py b/src/cfnlint/config.py --- a/src/cfnlint/config.py +++ b/src/cfnlint/config.py @@ -511,7 +511,8 @@ def ignore_checks(self): @property def include_checks(self): """ include_checks """ - return self._get_argument_value('include_checks', True, True) + results = self._get_argument_value('include_checks', True, True) + return ['W', 'E'] + results @property def mandatory_checks(self): diff --git a/src/cfnlint/core.py b/src/cfnlint/core.py --- a/src/cfnlint/core.py +++ b/src/cfnlint/core.py @@ -10,7 +10,7 @@ import cfnlint.runner from cfnlint.template import Template -from cfnlint.rules import RulesCollection +from cfnlint.rules import RulesCollection, ParseError, TransformError import cfnlint.config import cfnlint.formatters import cfnlint.decode @@ -157,10 +157,26 @@ def get_args_filenames(cli_args): def get_template_rules(filename, args): """ Get Template Configuration items and set them as default values""" - (template, matches) = cfnlint.decode.decode(filename, args.ignore_bad_template) - - if matches: - return(template, [], matches) + ignore_bad_template = False + if args.ignore_bad_template: + ignore_bad_template = True + else: + # There is no collection at this point so we need to handle this + # check directly + if not ParseError().is_enabled( + include_experimental=False, + ignore_rules=args.ignore_checks, + include_rules=args.include_checks, + mandatory_rules=args.mandatory_checks, + ): + ignore_bad_template = True + + (template, errors) = cfnlint.decode.decode(filename) + + if errors: + if len(errors) == 1 and ignore_bad_template and errors[0].rule.id == 'E0000': + return(template, [], []) + return(template, [], errors) args.template_args = template @@ -185,17 +201,30 @@ def run_checks(filename, template, rules, regions, mandatory_rules=None): unsupported_regions, REGIONS) raise InvalidRegionException(msg, 32) - matches = [] + errors = [] + + runner = cfnlint.runner.Runner(rules, filename, template, regions, + mandatory_rules=mandatory_rules) + + # Transform logic helps with handling serverless templates + ignore_transform_error = False + if not rules.is_rule_enabled(TransformError()): + ignore_transform_error = True + + errors.extend(runner.transform()) + + if errors: + if ignore_transform_error: + return([]) # if there is a transform error we can't continue + + return(errors) - runner = cfnlint.runner.Runner(rules, filename, template, regions, mandatory_rules=mandatory_rules) - matches.extend(runner.transform()) # Only do rule analysis if Transform was successful - if not matches: - try: - matches.extend(runner.run()) - except Exception as err: # pylint: disable=W0703 - msg = 'Tried to process rules on file %s but got an error: %s' % (filename, str(err)) - UnexpectedRuleException(msg, 1) - matches.sort(key=lambda x: (x.filename, x.linenumber, x.rule.id)) - - return(matches) + try: + errors.extend(runner.run()) + except Exception as err: # pylint: disable=W0703 + msg = 'Tried to process rules on file %s but got an error: %s' % (filename, str(err)) + UnexpectedRuleException(msg, 1) + errors.sort(key=lambda x: (x.filename, x.linenumber, x.rule.id)) + + return(errors) diff --git a/src/cfnlint/decode/__init__.py b/src/cfnlint/decode/__init__.py --- a/src/cfnlint/decode/__init__.py +++ b/src/cfnlint/decode/__init__.py @@ -18,7 +18,7 @@ LOGGER = logging.getLogger(__name__) -def decode(filename, ignore_bad_template): +def decode(filename): """ Decode filename into an object """ @@ -77,20 +77,14 @@ def decode(filename, ignore_bad_template): else: matches = [create_match_json_parser_error(json_err, filename)] except Exception as json_err: # pylint: disable=W0703 - if ignore_bad_template: - LOGGER.info('Template %s is malformed: %s', - filename, err.problem) - LOGGER.info('Tried to parse %s as JSON but got error: %s', - filename, str(json_err)) - else: - LOGGER.error( - 'Template %s is malformed: %s', filename, err.problem) - LOGGER.error('Tried to parse %s as JSON but got error: %s', - filename, str(json_err)) - return (None, [create_match_file_error( - filename, - 'Tried to parse %s as JSON but got error: %s' % ( - filename, str(json_err)))]) + LOGGER.error( + 'Template %s is malformed: %s', filename, err.problem) + LOGGER.error('Tried to parse %s as JSON but got error: %s', + filename, str(json_err)) + return (None, [create_match_file_error( + filename, + 'Tried to parse %s as JSON but got error: %s' % ( + filename, str(json_err)))]) else: matches = [create_match_yaml_parser_error(err, filename)] except YAMLError as err: diff --git a/src/cfnlint/formatters/__init__.py b/src/cfnlint/formatters/__init__.py --- a/src/cfnlint/formatters/__init__.py +++ b/src/cfnlint/formatters/__init__.py @@ -6,6 +6,7 @@ from junit_xml import TestSuite, TestCase, to_xml_report_string from cfnlint.rules import Match + class BaseFormatter(object): """Base Formatter class""" @@ -64,7 +65,7 @@ def print_matches(self, matches, rules=None): test_cases = [] for rule in rules.all_rules: - if not rules.is_rule_enabled(rule.id, rule.experimental): + if not rules.is_rule_enabled(rule): if not rule.id: continue test_case = TestCase(name='{0} {1}'.format(rule.id, rule.shortdesc)) diff --git a/src/cfnlint/rules/__init__.py b/src/cfnlint/rules/__init__.py --- a/src/cfnlint/rules/__init__.py +++ b/src/cfnlint/rules/__init__.py @@ -42,6 +42,37 @@ def verbose(self): def initialize(self, cfn): """Initialize the rule""" + def is_enabled(self, include_experimental=False, ignore_rules=None, include_rules=None, + mandatory_rules=None): + """ Is the rule enabled based on the configuration """ + ignore_rules = ignore_rules or [] + include_rules = include_rules or [] + mandatory_rules = mandatory_rules or [] + + # Evaluate experimental rules + if self.experimental and not include_experimental: + return False + + # Evaluate includes first: + include_filter = False + for include_rule in include_rules: + if self.id.startswith(include_rule): + include_filter = True + if not include_filter: + return False + + # Enable mandatory rules without checking for if they are ignored + for mandatory_rule in mandatory_rules: + if self.id.startswith(mandatory_rule): + return True + + # Allowing ignoring of rules based on prefix to ignore checks + for ignore_rule in ignore_rules: + if self.id.startswith(ignore_rule) and ignore_rule: + return False + + return True + def configure(self, configs=None): """ Set the configuration """ @@ -146,12 +177,15 @@ def __init__(self, ignore_rules=None, include_rules=None, configure_rules=None, self.configure_rules = configure_rules or [] # by default include 'W' and 'E' # 'I' has to be included manually for backwards compabitility - self.include_rules.extend(['W', 'E']) + # Have to add W, E here because integrations don't use config + for default_rule in ['W', 'E']: + if default_rule not in self.include_rules: + self.include_rules.extend([default_rule]) def register(self, rule): """Register rules""" self.all_rules.append(rule) - if self.is_rule_enabled(rule.id, rule.experimental): + if self.is_rule_enabled(rule): self.rules.append(rule) if rule.id in self.configure_rules: rule.configure(self.configure_rules[rule.id]) @@ -165,41 +199,16 @@ def __len__(self): def extend(self, more): """Extend rules""" for rule in more: - self.all_rules.append(rule) - if self.is_rule_enabled(rule.id, rule.experimental): - self.rules.append(rule) - if rule.id in self.configure_rules: - rule.configure(self.configure_rules[rule.id]) + self.register(rule) def __repr__(self): return '\n'.join([rule.verbose() for rule in sorted(self.rules, key=lambda x: x.id)]) - def is_rule_enabled(self, rule_id, experimental): + def is_rule_enabled(self, rule): """ Checks if an individual rule is valid """ - # Evaluate experimental rules - if experimental and not self.include_experimental: - return False - - # Evaluate includes first: - include_filter = False - for include_rule in self.include_rules: - if rule_id.startswith(include_rule): - include_filter = True - if not include_filter: - return False - - # Enable mandatory rules without checking for if they are ignored - for mandatory_rule in self.mandatory_rules: - if rule_id.startswith(mandatory_rule): - return True - - # Allowing ignoring of rules based on prefix to ignore checks - for ignore_rule in self.ignore_rules: - if rule_id.startswith(ignore_rule) and ignore_rule: - return False - - return True + return rule.is_enabled(self.include_experimental, self.ignore_rules, + self.include_rules, self.mandatory_rules) def run_check(self, check, filename, rule_id, *args): """ Run a check """ @@ -209,7 +218,7 @@ def run_check(self, check, filename, rule_id, *args): LOGGER.debug(str(err)) return [] except Exception as err: # pylint: disable=W0703 - if self.is_rule_enabled('E0002', False): + if self.is_rule_enabled(RuleError()): # In debug mode, print the error include complete stack trace if LOGGER.getEffectiveLevel() == logging.DEBUG: error_message = traceback.format_exc()
diff --git a/test/integration/test_transform_ignore.py b/test/integration/test_transform_ignore.py new file mode 100644 --- /dev/null +++ b/test/integration/test_transform_ignore.py @@ -0,0 +1,23 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from test.integration import BaseCliTestCase +import cfnlint.core + + +class TestTransformIgnore(BaseCliTestCase): + """Test Ignoring Transform Failure """ + + scenarios = [ + { + 'filename': 'test/fixtures/templates/bad/transform_serverless_template.yaml', + 'exit_code': 0, + }, + ] + + def test_templates(self): + """ Test same templates using integration approach""" + rules = cfnlint.core.get_rules( + [], ['E0001'], ['I', 'E', 'W'], {}, True) + self.run_module_integration_scenarios(rules) diff --git a/test/unit/module/config/test_config_mixin.py b/test/unit/module/config/test_config_mixin.py --- a/test/unit/module/config/test_config_mixin.py +++ b/test/unit/module/config/test_config_mixin.py @@ -31,7 +31,7 @@ def test_config_mix_in(self, yaml_mock): config = cfnlint.config.ConfigMixIn(['--regions', 'us-west-1']) self.assertEqual(config.regions, ['us-west-1']) - self.assertEqual(config.include_checks, ['I', 'I1111']) + self.assertEqual(config.include_checks, ['W', 'E', 'I', 'I1111']) @patch('cfnlint.config.ConfigFileArgs._read_config', create=True) def test_config_precedence(self, yaml_mock): @@ -55,7 +55,7 @@ def test_config_precedence(self, yaml_mock): # config files wins self.assertEqual(config.regions, ['us-west-2']) # CLI should win - self.assertEqual(config.include_checks, ['I1234', 'I4321']) + self.assertEqual(config.include_checks, ['W', 'E', 'I1234', 'I4321']) # template file wins over config file self.assertEqual(config.ignore_checks, ['W3001']) diff --git a/test/unit/module/core/test_run_cli.py b/test/unit/module/core/test_run_cli.py --- a/test/unit/module/core/test_run_cli.py +++ b/test/unit/module/core/test_run_cli.py @@ -37,7 +37,7 @@ def test_template_not_found(self): ['--template', filename, '--ignore-bad-template']) (_, _, matches) = cfnlint.core.get_template_rules(filenames[0], args) - self.assertEqual(len(matches), 1) + self.assertEqual(len(matches), 0) def test_template_not_found_directory(self): """Test template not found""" @@ -48,7 +48,7 @@ def test_template_not_found_directory(self): ['--template', filename, '--ignore-bad-template']) (_, _, matches) = cfnlint.core.get_template_rules(filenames[0], args) - self.assertEqual(len(matches), 1) + self.assertEqual(len(matches), 0) def test_template_invalid_yaml(self): """Test template not found""" @@ -78,7 +78,17 @@ def test_template_invalid_yaml_ignore(self): ['--template', filename, '--ignore-bad-template']) (_, _, matches) = cfnlint.core.get_template_rules(filenames[0], args) - self.assertEqual(len(matches), 1) + self.assertEqual(len(matches), 0) + + def test_template_invalid_yaml_ignore_by_rule_id(self): + """Test template not found""" + filename = 'test/fixtures/templates/bad/core/config_invalid_yaml.yaml' + + (args, filenames, _) = cfnlint.core.get_args_filenames( + ['--template', filename, '--ignore-checks', 'E0000']) + (_, _, matches) = cfnlint.core.get_template_rules(filenames[0], args) + + self.assertEqual(len(matches), 0) def test_template_invalid_json_ignore(self): """Test template not found""" @@ -88,7 +98,7 @@ def test_template_invalid_json_ignore(self): ['--template', filename, '--ignore-bad-template']) (_, _, matches) = cfnlint.core.get_template_rules(filenames[0], args) - self.assertEqual(len(matches), 1) + self.assertEqual(len(matches), 0) def test_template_via_stdin(self): """Test getting the template from stdin doesn't crash""" @@ -121,7 +131,7 @@ def test_template_config(self, yaml_mock): self.assertEqual(args.format, None) self.assertEqual(args.ignore_bad_template, True) self.assertEqual(args.ignore_checks, []) - self.assertEqual(args.include_checks, []) + self.assertEqual(args.include_checks, ['W', 'E']) self.assertEqual(args.listrules, False) self.assertEqual(args.debug, False) self.assertEqual(args.override_spec, None) @@ -156,7 +166,7 @@ def test_positional_template_parameters(self, yaml_mock): self.assertEqual(args.format, None) self.assertEqual(args.ignore_bad_template, True) self.assertEqual(args.ignore_checks, ['E0000']) - self.assertEqual(args.include_checks, []) + self.assertEqual(args.include_checks, ['W', 'E']) self.assertEqual(args.listrules, False) self.assertEqual(args.debug, False) self.assertEqual(args.override_spec, None) @@ -183,7 +193,7 @@ def test_override_parameters(self, yaml_mock): self.assertEqual(args.format, None) self.assertEqual(args.ignore_bad_template, True) self.assertEqual(args.ignore_checks, ['E0000']) - self.assertEqual(args.include_checks, []) + self.assertEqual(args.include_checks, ['W', 'E']) self.assertEqual(args.listrules, False) self.assertEqual(args.debug, False) self.assertEqual(args.override_spec, None) @@ -209,7 +219,7 @@ def test_bad_config(self, yaml_mock): self.assertEqual(args.format, None) self.assertEqual(args.ignore_bad_template, True) self.assertEqual(args.ignore_checks, []) - self.assertEqual(args.include_checks, []) + self.assertEqual(args.include_checks, ['W', 'E']) self.assertEqual(args.listrules, False) self.assertEqual(args.debug, False) self.assertEqual(args.override_spec, None) diff --git a/test/unit/module/test_rules_collections.py b/test/unit/module/test_rules_collections.py --- a/test/unit/module/test_rules_collections.py +++ b/test/unit/module/test_rules_collections.py @@ -9,7 +9,7 @@ import cfnlint.decode.cfn_yaml # pylint: disable=E0401 -class TestTemplate(BaseTestCase): +class TestRulesCollection(BaseTestCase): """Test Template RulesCollection in cfnlint """ def setUp(self): @@ -79,7 +79,7 @@ class rule_i0000(CloudFormationLintRule): """Info Rule""" id = 'I0000' - rules_to_add = [rule_e0000, rule_w0000, rule_i0000] + rules_to_add = [rule_e0000(), rule_w0000(), rule_i0000()] rules = RulesCollection(ignore_rules=None, include_rules=None) rules.extend(rules_to_add) self.assertEqual(len(rules), 2) @@ -100,7 +100,7 @@ class rule_i0000(CloudFormationLintRule): """Info Rule""" id = 'I0000' - rules_to_add = [rule_e0000, rule_w0000, rule_i0000] + rules_to_add = [rule_e0000(), rule_w0000(), rule_i0000()] rules = RulesCollection(ignore_rules=None, include_rules=['I']) rules.extend(rules_to_add) self.assertEqual(len(rules), 3) @@ -121,7 +121,7 @@ class rule_i0000(CloudFormationLintRule): """Info Rule""" id = 'I0000' - rules_to_add = [rule_e0000, rule_w0000, rule_i0000] + rules_to_add = [rule_e0000(), rule_w0000(), rule_i0000()] rules = RulesCollection(ignore_rules=['E']) rules.extend(rules_to_add) self.assertEqual(len(rules), 1) @@ -142,7 +142,7 @@ class rule_e0002(CloudFormationLintRule): """Error Rule""" id = 'E0002' - rules_to_add = [rule_e0000, rule_e0010, rule_e0002] + rules_to_add = [rule_e0000(), rule_e0010(), rule_e0002()] rules = RulesCollection(ignore_rules=['E000']) rules.extend(rules_to_add) self.assertEqual(len(rules), 1) @@ -163,7 +163,7 @@ class rule_e0002(CloudFormationLintRule): """Error Rule""" id = 'E0002' - rules_to_add = [rule_e0000, rule_e0010, rule_e0002] + rules_to_add = [rule_e0000(), rule_e0010(), rule_e0002()] rules = RulesCollection(ignore_rules=['E0002']) rules.extend(rules_to_add) self.assertEqual(len(rules), 2) @@ -184,7 +184,7 @@ class rule_i0000(CloudFormationLintRule): """Info Rule""" id = 'I0000' - rules_to_add = [rule_e0000, rule_w0000, rule_i0000] + rules_to_add = [rule_e0000(), rule_w0000(), rule_i0000()] rules = RulesCollection(ignore_rules=['E'], mandatory_rules=['E']) rules.extend(rules_to_add) self.assertEqual(len(rules), 2) @@ -209,7 +209,7 @@ class rule_w0000(CloudFormationLintRule): """Warning Rule""" id = 'W0000' - rules_to_add = [rule_e0000, rule_e0010, rule_e0002, rule_w0000] + rules_to_add = [rule_e0000(), rule_e0010(), rule_e0002(), rule_w0000()] rules = RulesCollection(ignore_rules=['E'], mandatory_rules=['E000']) rules.extend(rules_to_add) self.assertEqual(len(rules), 3) diff --git a/test/unit/module/test_string_template.py b/test/unit/module/test_string_template.py --- a/test/unit/module/test_string_template.py +++ b/test/unit/module/test_string_template.py @@ -18,5 +18,5 @@ def test_fail_yaml_run(self): filename = 'test/fixtures/templates/bad/string.yaml' - _, matches = cfnlint.decode.decode(filename, True) + _, matches = cfnlint.decode.decode(filename) assert len(matches) == 1
Ignore-checks doesn't work for E000* *cfn-lint version: 0.22.3 *Ignore Checks isn't working* Template: https://gist.github.com/jeffmacdonald/cbbdd8cc3a049f89dfb4a17991ca1afa I am getting the following error: ``` E0000 Expecting value templates/ssh-jump-host.yaml:1:1 ``` When I run `pipenv run cfn-lint --ignore-checks=E0000 templates/ssh-jump-host.yaml` The fun part is, I have I have errors in other templates (E2521) and I am able to ignore those just fine... it seems it's specifically E0000 that doesn't get ignored.
Agreed some of the E0000-E0005 checks may not be properly skipped when being configured to ignore them. We'll have to add some logic in for some of these generic rules. Is this still an issue? I'm trying to ignore a check on a specific resource which uses a Transform function. But it is not getting ignore when i use the following; ``` Metadata: cfn-lint: config: ignore_checks: - E3001 - E0001 ``` Seeing the same issue with `E0000`. Idem here. `E0001` won't be ignored. Tried ignoring in Metadata on Resource, top-level node, and in .cfnlintrc file. > Agreed some of the E0000-E0005 checks may not be properly skipped when being configured to ignore them. We'll have to add some logic in for some of these generic rules. @kddejong can you expand a bit on why it's failing for that particular subset of rules? They aren't standard rules. The are errors throw when a rule has an exception, or when the template is malformed, or has a null value, or the template can't be found, etc. I don't think there is any reason they can't be ignored. I think we would need to build in a little bit better logic for those types of errors. Additional I think there may be a few exceptions we have to figure out how to handle. - `Metadata` based exceptions may not work as expected. For instance, I'm not sure we can put an exception in Metadata to ignore the E0000 code for a null value in the template because we are doing that rule at template parsing time. In which case I never have the Metadata to read to apply the exception. - Another one will be if the serverless transform fails. We may be able to ignore the error but we can't really check the rest of the rules with a non transformed template. I'm not sure what our expectation would be in this case. https://github.com/aws-cloudformation/cfn-python-lint/blob/fe0af928a4ab26a6cedfd76564a26c9a4120b14f/src/cfnlint/rules/__init__.py#L424-L448 `E0000` could be ignorable. In the early stages we also had a parameter called `--ignore-bad-template` which was supposed to help there. Given the feature changes since this parameter was put in we would have probably done this differently. @miparnisari let me take a swing at this one. I'll want your opinions on some of this as we go but I think I have an idea or two.
2020-06-11T01:36:51Z
[]
[]
aws-cloudformation/cfn-lint
1,620
aws-cloudformation__cfn-lint-1620
[ "1619" ]
6f8d7d4e1664a6f6e56ae99593066fc593b11b66
diff --git a/src/cfnlint/rules/resources/certificatemanager/DomainValidationOptions.py b/src/cfnlint/rules/resources/certificatemanager/DomainValidationOptions.py --- a/src/cfnlint/rules/resources/certificatemanager/DomainValidationOptions.py +++ b/src/cfnlint/rules/resources/certificatemanager/DomainValidationOptions.py @@ -29,8 +29,8 @@ def check_value(self, value, path, **kwargs): for property_set in property_sets: properties = property_set.get('Object') scenario = property_set.get('Scenario') - domain_name = properties.get('DomainName', '') - validation_domain = properties.get('ValidationDomain', '') + domain_name = properties.get('DomainName', None) + validation_domain = properties.get('ValidationDomain', None) if isinstance(domain_name, six.string_types) and isinstance(validation_domain, six.string_types): if domain_name == validation_domain: continue
diff --git a/test/fixtures/templates/good/resources/certificatemanager/domain_validation_options.yaml b/test/fixtures/templates/good/resources/certificatemanager/domain_validation_options.yaml --- a/test/fixtures/templates/good/resources/certificatemanager/domain_validation_options.yaml +++ b/test/fixtures/templates/good/resources/certificatemanager/domain_validation_options.yaml @@ -14,3 +14,12 @@ Resources: DomainValidationOptions: - DomainName: "example.com" ValidationDomain: "example.com" + Certificate3: + Type: AWS::CertificateManager::Certificate + Properties: + DomainName: "*.aws.domain.com" + ValidationMethod: DNS + DomainValidationOptions: + # Don't fail when one of the values don't exist + - DomainName: aws.domain.com + HostedZoneId: !ImportValue SubdomainHostedZoneId
E3503 does not match CloudFormation - requires ValidationDomain when CF does not want it *cfn-lint version: (`cfn-lint --version`)* cfn-lint 0.33.2 *Description of issue.* I created an ACM certificate resource, and there were problems configuring the `DomainValidationOptions` block. If using DNS validation, the only properties needed are `DomainName` and `HostedZoneId`. However, cfn-lint was demanding a third property named `ValidationDomain`. When submitting the stack for deployment to CF, it triggered an immediate rollback because CF views `HostedZoneId` and `ValidationDomain` as mutually exclusive. Adding an ignore rule to skip the E3503 error allowed me to proceed without issues. This rule should be adjusted to match what CF enforces. **Sample:** ```yaml Resources: Certificate: Type: AWS::CertificateManager::Certificate Metadata: cfn-lint: config: ignore_checks: - E3503 Properties: DomainName: "*.aws.domain.com" ValidationMethod: DNS DomainValidationOptions: - DomainName: aws.domain.com HostedZoneId: !ImportValue SubdomainHostedZoneId ```
Agreed. Thanks for reporting. We will work on getting this fixed.
2020-07-09T17:23:13Z
[]
[]
aws-cloudformation/cfn-lint
1,627
aws-cloudformation__cfn-lint-1627
[ "1625" ]
170fe0c05cd38e6a20dc3fce2b78cd02291aca79
diff --git a/src/cfnlint/rules/resources/NoEcho.py b/src/cfnlint/rules/resources/NoEcho.py --- a/src/cfnlint/rules/resources/NoEcho.py +++ b/src/cfnlint/rules/resources/NoEcho.py @@ -2,6 +2,7 @@ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ +import six from cfnlint.helpers import bool_compare from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch @@ -14,34 +15,58 @@ class NoEcho(CloudFormationLintRule): source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html#parameters-section-structure-properties' tags = ['resources', 'NoEcho'] - def match(self, cfn): - matches = [] + def _get_no_echo_params(self, cfn): + """ Get no Echo Params""" no_echo_params = [] - parameters = cfn.get_parameters() - for parameter_name, parameter_value in parameters.items(): + for parameter_name, parameter_value in cfn.get_parameters().items(): noecho = parameter_value.get('NoEcho', default=False) if bool_compare(noecho, True): no_echo_params.append(parameter_name) + return no_echo_params + + def _check_ref(self, cfn, no_echo_params): + """ Check Refs """ + matches = [] + refs = cfn.search_deep_keys('Ref') + for ref in refs: + if ref[-1] in no_echo_params: + if len(ref) > 3: + if ref[0] == 'Resources' and ref[2] == 'Metadata': + matches.append(RuleMatch(ref, 'As the resource "metadata" section contains ' + + 'reference to a "NoEcho" parameter ' + + str(ref[-1]) + + ', CloudFormation will display the parameter value in ' + + 'plaintext')) + + return matches + + def _check_sub(self, cfn, no_echo_params): + """ Check Subs """ + matches = [] + subs = cfn.search_deep_keys('Fn::Sub') + for sub in subs: + if isinstance(sub[-1], six.string_types): + params = cfn.get_sub_parameters(sub[-1]) + for param in params: + if param in no_echo_params: + if len(sub) > 2: + if sub[0] == 'Resources' and sub[2] == 'Metadata': + + matches.append(RuleMatch(sub[:-1], 'As the resource "metadata" section contains ' + + 'reference to a "NoEcho" parameter ' + + str(param) + + ', CloudFormation will display the parameter value in ' + + 'plaintext')) + + return matches + + def match(self, cfn): + matches = [] + no_echo_params = self._get_no_echo_params(cfn) if not no_echo_params: - return no_echo_params - - resource_properties = cfn.get_resources() - resource_dict = {key: resource_properties[key] for key in resource_properties if - isinstance(resource_properties[key], dict)} - for resource_name, resource_values in resource_dict.items(): - resource_values = {key: resource_values[key] for key in resource_values if - isinstance(resource_values[key], dict)} - metadata = resource_values.get('Metadata', {}) - if metadata is not None: - for prop_name, properties in metadata.items(): - if isinstance(properties, dict): - for property_value in properties.values(): - for param in no_echo_params and no_echo_params: - if str(property_value).find(str(param)) > -1: - path = ['Resources', resource_name, 'Metadata', prop_name] - matches.append(RuleMatch(path, 'As the resource "metadata" section contains ' - 'reference to a "NoEcho" parameter ' + str(param) - + ', CloudFormation will display the parameter value in ' - 'plaintext')) + return matches + matches.extend(self._check_ref(cfn, no_echo_params)) + matches.extend(self._check_sub(cfn, no_echo_params)) + return matches
diff --git a/test/fixtures/results/quickstart/nist_application.json b/test/fixtures/results/quickstart/nist_application.json --- a/test/fixtures/results/quickstart/nist_application.json +++ b/test/fixtures/results/quickstart/nist_application.json @@ -179,33 +179,6 @@ "Source": "https://aws.amazon.com/blogs/devops/optimize-aws-cloudformation-templates/" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 32, - "LineNumber": 221 - }, - "Path": [ - "Resources", - "rAutoScalingConfigApp", - "Metadata", - "AWS::CloudFormation::Init" - ], - "Start": { - "ColumnNumber": 7, - "LineNumber": 221 - } - }, - "Message": "As the resource \"metadata\" section contains reference to a \"NoEcho\" parameter pDBPassword, CloudFormation will display the parameter value in plaintext", - "Rule": { - "Description": "Check if there is a NoEcho enabled parameter referenced within a resources Metadata section", - "Id": "W4002", - "ShortDescription": "Check for NoEcho References", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html#parameters-section-structure-properties" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", "Level": "Informational", @@ -397,6 +370,42 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, + { + "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", + "Level": "Warning", + "Location": { + "End": { + "ColumnNumber": 24, + "LineNumber": 343 + }, + "Path": [ + "Resources", + "rAutoScalingConfigApp", + "Metadata", + "AWS::CloudFormation::Init", + "install_wordpress", + "files", + "/tmp/create-wp-config", + "content", + "Fn::Join", + 1, + 9, + "Ref", + "pDBPassword" + ], + "Start": { + "ColumnNumber": 21, + "LineNumber": 343 + } + }, + "Message": "As the resource \"metadata\" section contains reference to a \"NoEcho\" parameter pDBPassword, CloudFormation will display the parameter value in plaintext", + "Rule": { + "Description": "Check if there is a NoEcho enabled parameter referenced within a resources Metadata section", + "Id": "W4002", + "ShortDescription": "Check for NoEcho References", + "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html#parameters-section-structure-properties" + } + }, { "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", "Level": "Informational", diff --git a/test/fixtures/results/quickstart/non_strict/nist_application.json b/test/fixtures/results/quickstart/non_strict/nist_application.json --- a/test/fixtures/results/quickstart/non_strict/nist_application.json +++ b/test/fixtures/results/quickstart/non_strict/nist_application.json @@ -179,33 +179,6 @@ "Source": "https://aws.amazon.com/blogs/devops/optimize-aws-cloudformation-templates/" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 32, - "LineNumber": 221 - }, - "Path": [ - "Resources", - "rAutoScalingConfigApp", - "Metadata", - "AWS::CloudFormation::Init" - ], - "Start": { - "ColumnNumber": 7, - "LineNumber": 221 - } - }, - "Message": "As the resource \"metadata\" section contains reference to a \"NoEcho\" parameter pDBPassword, CloudFormation will display the parameter value in plaintext", - "Rule": { - "Description": "Check if there is a NoEcho enabled parameter referenced within a resources Metadata section", - "Id": "W4002", - "ShortDescription": "Check for NoEcho References", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html#parameters-section-structure-properties" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", "Level": "Informational", @@ -397,6 +370,42 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, + { + "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", + "Level": "Warning", + "Location": { + "End": { + "ColumnNumber": 24, + "LineNumber": 343 + }, + "Path": [ + "Resources", + "rAutoScalingConfigApp", + "Metadata", + "AWS::CloudFormation::Init", + "install_wordpress", + "files", + "/tmp/create-wp-config", + "content", + "Fn::Join", + 1, + 9, + "Ref", + "pDBPassword" + ], + "Start": { + "ColumnNumber": 21, + "LineNumber": 343 + } + }, + "Message": "As the resource \"metadata\" section contains reference to a \"NoEcho\" parameter pDBPassword, CloudFormation will display the parameter value in plaintext", + "Rule": { + "Description": "Check if there is a NoEcho enabled parameter referenced within a resources Metadata section", + "Id": "W4002", + "ShortDescription": "Check for NoEcho References", + "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html#parameters-section-structure-properties" + } + }, { "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", "Level": "Informational", diff --git a/test/fixtures/templates/bad/noecho.yaml b/test/fixtures/templates/bad/noecho.yaml --- a/test/fixtures/templates/bad/noecho.yaml +++ b/test/fixtures/templates/bad/noecho.yaml @@ -1,13 +1,19 @@ -AWSTemplateFormatVersion: '2010-09-09' +AWSTemplateFormatVersion: "2010-09-09" Parameters: NoEchoParam: Type: String Default: NoEchoWasEchoed NoEcho: true Resources: - SNSTopicWithSecretName: + SNSTopicWithSecretNameInRef: Type: AWS::SNS::Topic Properties: DisplayName: testname Metadata: NoEchoParamInMetadata: !Ref NoEchoParam + SNSTopicWithSecretNameInSub: + Type: AWS::SNS::Topic + Properties: + DisplayName: testname + Metadata: + NoEchoParamInMetadata: !Sub "${NoEchoParam}" diff --git a/test/unit/rules/resources/test_noecho.py b/test/unit/rules/resources/test_noecho.py --- a/test/unit/rules/resources/test_noecho.py +++ b/test/unit/rules/resources/test_noecho.py @@ -19,4 +19,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/noecho.yaml', 1) + self.helper_file_negative('test/fixtures/templates/bad/noecho.yaml', 2)
False alarm from new W4002 *cfn-lint version: 0.34.0* [Here](https://gist.github.com/schmiddy/44a779032a930995d22ee2722a18f163) is an example template which causes a false alarm like this: ``` $ cfn-lint /tmp/example.yml W4002 As the resource "metadata" section contains reference to a "NoEcho" parameter DBUser, CloudFormation will display the parameter value in plaintext /tmp/example.yml:21:7 W4002 As the resource "metadata" section contains reference to a "NoEcho" parameter DBPass, CloudFormation will display the parameter value in plaintext /tmp/example.yml:21:7 ``` The problem seems to be that the rule is looking for any mention of the parameter name, even as a text description that is not actually referencing the parameter.
2020-07-16T19:05:37Z
[]
[]
aws-cloudformation/cfn-lint
1,631
aws-cloudformation__cfn-lint-1631
[ "1630" ]
961ec8f026c6b7774e83e6ca73ca5336f5c1c03a
diff --git a/src/cfnlint/rules/__init__.py b/src/cfnlint/rules/__init__.py --- a/src/cfnlint/rules/__init__.py +++ b/src/cfnlint/rules/__init__.py @@ -7,6 +7,7 @@ from datetime import datetime import importlib import traceback +import six import cfnlint.helpers from cfnlint.decode.node import TemplateAttributeError @@ -337,18 +338,19 @@ def run(self, filename, cfn): for resource_name, resource_attributes in cfn.get_resources().items(): resource_type = resource_attributes.get('Type') resource_properties = resource_attributes.get('Properties', {}) - path = ['Resources', resource_name, 'Properties'] - for rule in self.rules: - matches.extend( - self.run_check( - rule.matchall_resource_properties, filename, rule.id, - filename, cfn, resource_properties, resource_type, path + if isinstance(resource_type, six.string_types) and isinstance(resource_properties, dict): + path = ['Resources', resource_name, 'Properties'] + for rule in self.rules: + matches.extend( + self.run_check( + rule.matchall_resource_properties, filename, rule.id, + filename, cfn, resource_properties, resource_type, path + ) ) - ) - matches.extend( - self.run_resource( - filename, cfn, resource_type, resource_properties, path)) + matches.extend( + self.run_resource( + filename, cfn, resource_type, resource_properties, path)) return matches diff --git a/src/cfnlint/rules/resources/Configuration.py b/src/cfnlint/rules/resources/Configuration.py --- a/src/cfnlint/rules/resources/Configuration.py +++ b/src/cfnlint/rules/resources/Configuration.py @@ -16,8 +16,9 @@ class Configuration(CloudFormationLintRule): source_url = 'https://github.com/aws-cloudformation/cfn-python-lint' tags = ['resources'] - def match(self, cfn): - matches = [] + + def _check_resource(self, cfn, resource_name, resource_values): + """ Check Resource """ valid_attributes = [ 'Condition', @@ -42,6 +43,97 @@ def match(self, cfn): 'Version', ] + matches = [] + if not isinstance(resource_values, dict): + message = 'Resource not properly configured at {0}' + matches.append(RuleMatch( + ['Resources', resource_name], + message.format(resource_name) + )) + return matches + + # validate condition is a string + condition = resource_values.get('Condition', '') + if not isinstance(condition, six.string_types): + message = 'Condition for resource {0} should be a string' + matches.append(RuleMatch( + ['Resources', resource_name, 'Condition'], + message.format(resource_name) + )) + + resource_type = resource_values.get('Type', '') + check_attributes = [] + if not isinstance(resource_type, six.string_types): + message = 'Type has to be a string at {0}' + matches.append(RuleMatch( + ['Resources', resource_name], + message.format('/'.join(['Resources', resource_name])) + )) + return matches + + # Type is valid continue analysis + if resource_type.startswith('Custom::') or resource_type == 'AWS::CloudFormation::CustomResource': + check_attributes = valid_custom_attributes + else: + check_attributes = valid_attributes + + for property_key, _ in resource_values.items(): + if property_key not in check_attributes: + message = 'Invalid resource attribute {0} for resource {1}' + matches.append(RuleMatch( + ['Resources', resource_name, property_key], + message.format(property_key, resource_name))) + + if not resource_type: + message = 'Type not defined for resource {0}' + matches.append(RuleMatch( + ['Resources', resource_name], + message.format(resource_name) + )) + elif not isinstance(resource_type, six.string_types): + message = 'Type has to be a string at {0}' + matches.append(RuleMatch( + ['Resources', resource_name], + message.format('/'.join(['Resources', resource_name])) + )) + else: + self.logger.debug('Check resource types by region...') + for region, specs in cfnlint.helpers.RESOURCE_SPECS.items(): + if region in cfn.regions: + if resource_type not in specs['ResourceTypes']: + if not resource_type.startswith(('Custom::', 'AWS::Serverless::')): + message = 'Invalid or unsupported Type {0} for resource {1} in {2}' + matches.append(RuleMatch( + ['Resources', resource_name, 'Type'], + message.format(resource_type, resource_name, region) + )) + + if 'Properties' not in resource_values: + resource_spec = cfnlint.helpers.RESOURCE_SPECS[cfn.regions[0]] + if resource_type in resource_spec['ResourceTypes']: + properties_spec = resource_spec['ResourceTypes'][resource_type]['Properties'] + # pylint: disable=len-as-condition + if len(properties_spec) > 0: + required = 0 + for _, property_spec in properties_spec.items(): + if property_spec.get('Required', False): + required += 1 + if required > 0: + if resource_type == 'AWS::CloudFormation::WaitCondition' and 'CreationPolicy' in resource_values.keys(): + self.logger.debug('Exception to required properties section as CreationPolicy is defined.') + else: + message = 'Properties not defined for resource {0}' + matches.append(RuleMatch( + ['Resources', resource_name], + message.format(resource_name) + )) + + return matches + + + def match(self, cfn): + matches = [] + resources = cfn.template.get('Resources', {}) if not isinstance(resources, dict): message = 'Resource not properly configured' @@ -49,73 +141,6 @@ def match(self, cfn): else: for resource_name, resource_values in cfn.template.get('Resources', {}).items(): self.logger.debug('Validating resource %s base configuration', resource_name) - if not isinstance(resource_values, dict): - message = 'Resource not properly configured at {0}' - matches.append(RuleMatch( - ['Resources', resource_name], - message.format(resource_name) - )) - continue - resource_type = resource_values.get('Type', '') - check_attributes = [] - if resource_type.startswith('Custom::') or resource_type == 'AWS::CloudFormation::CustomResource': - check_attributes = valid_custom_attributes - else: - check_attributes = valid_attributes - - for property_key, _ in resource_values.items(): - if property_key not in check_attributes: - message = 'Invalid resource attribute {0} for resource {1}' - matches.append(RuleMatch( - ['Resources', resource_name, property_key], - message.format(property_key, resource_name))) - - # validate condition is a string - condition = resource_values.get('Condition', '') - if not isinstance(condition, six.string_types): - message = 'Condition for resource {0} should be a string' - matches.append(RuleMatch( - ['Resources', resource_name, 'Condition'], - message.format(resource_name) - )) - - resource_type = resource_values.get('Type', '') - if not resource_type: - message = 'Type not defined for resource {0}' - matches.append(RuleMatch( - ['Resources', resource_name], - message.format(resource_name) - )) - else: - self.logger.debug('Check resource types by region...') - for region, specs in cfnlint.helpers.RESOURCE_SPECS.items(): - if region in cfn.regions: - if resource_type not in specs['ResourceTypes']: - if not resource_type.startswith(('Custom::', 'AWS::Serverless::')): - message = 'Invalid or unsupported Type {0} for resource {1} in {2}' - matches.append(RuleMatch( - ['Resources', resource_name, 'Type'], - message.format(resource_type, resource_name, region) - )) - - if 'Properties' not in resource_values: - resource_spec = cfnlint.helpers.RESOURCE_SPECS[cfn.regions[0]] - if resource_type in resource_spec['ResourceTypes']: - properties_spec = resource_spec['ResourceTypes'][resource_type]['Properties'] - # pylint: disable=len-as-condition - if len(properties_spec) > 0: - required = 0 - for _, property_spec in properties_spec.items(): - if property_spec.get('Required', False): - required += 1 - if required > 0: - if resource_type == 'AWS::CloudFormation::WaitCondition' and 'CreationPolicy' in resource_values.keys(): - self.logger.debug('Exception to required properties section as CreationPolicy is defined.') - else: - message = 'Properties not defined for resource {0}' - matches.append(RuleMatch( - ['Resources', resource_name], - message.format(resource_name) - )) + matches.extend(self._check_resource(cfn, resource_name, resource_values)) return matches diff --git a/src/cfnlint/runner.py b/src/cfnlint/runner.py --- a/src/cfnlint/runner.py +++ b/src/cfnlint/runner.py @@ -68,4 +68,5 @@ def run(self): break else: return_matches.append(match) + return return_matches
diff --git a/test/fixtures/templates/bad/generic.yaml b/test/fixtures/templates/bad/generic.yaml --- a/test/fixtures/templates/bad/generic.yaml +++ b/test/fixtures/templates/bad/generic.yaml @@ -7,10 +7,10 @@ Mappings: runtime: us-east-1: production: - - CidrIp: 0.0.0.0/0 - IpProtocol: tcp - ToPort: 80 - FromPort: 80 + - CidrIp: 0.0.0.0/0 + IpProtocol: tcp + ToPort: 80 + FromPort: 80 Parameters: myParam: Type: String @@ -35,8 +35,7 @@ Resources: FakeKey: MadeYouLook IamInstanceProfile: !GetAtt RootInstanceProfile.Arn BlockDeviceMappings: - - - DeviceName: /dev/sda + - DeviceName: /dev/sda Ebs: VolumeType: io1 Iops: !Ref pIops @@ -45,7 +44,7 @@ Resources: BadSubX2Key: Not valid NetworkInterfaces: - DeviceIndex: - - "1" + - "1" BadKey: true MyEC2Instance3: Type: "AWS::EC2::Instance" @@ -62,8 +61,7 @@ Resources: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - - - Effect: "Allow" + - Effect: "Allow" Principal: Service: - "ec2.amazonaws.com" @@ -71,13 +69,11 @@ Resources: - "sts:AssumeRole" Path: "/" Policies: - - - PolicyName: "root" + - PolicyName: "root" PolicyDocument1: Version: "2012-10-17" Statement: - - - Effect: "Allow" + - Effect: "Allow" Action: "*" Resource: "*" RolePolicies: @@ -87,48 +83,45 @@ Resources: PolicyDocument: Version: "2012-10-17" Statement: - - - Effect: "Allow" + - Effect: "Allow" Action: "*" Resource: "*" Roles: - - - Ref: "RootRole" + - Ref: "RootRole" RootInstanceProfile: Type: "AWS::IAM::InstanceProfile" Properties: Path: "/" Roles: - - - Ref: "RootRole" + - Ref: "RootRole" # Bad Key under HealthCheck ElasticLoadBalancer: Type: AWS::ElasticLoadBalancing::LoadBalancer Properties: AvailabilityZones: - Fn::GetAZs: '' + Fn::GetAZs: "" Instances: - - Ref: MyEC2Instance + - Ref: MyEC2Instance Listeners: - - LoadBalancerPort: '80' - InstancePort: - Ref: WebServerPort - Protocol: HTTP + - LoadBalancerPort: "80" + InstancePort: + Ref: WebServerPort + Protocol: HTTP HealthCheck: FakeKey: Another fake key Target: Fn::Join: - - '' - - - 'HTTP:' - - Ref: WebServerPort - - "/" - HealthyThreshold: '3' + - "" + - - "HTTP:" + - Ref: WebServerPort + - "/" + HealthyThreshold: "3" # Int which should be string. (No Error) UnhealthyThreshold: 5 # Should be int (Error) Interval: Test - Timeout: '5' + Timeout: "5" SecurityGroup: Type: AWS::EC2::SecurityGroupIngress Properties: @@ -145,46 +138,46 @@ Resources: Type: AWS::ElasticLoadBalancing::LoadBalancer Properties: Tags: - - Fn::If: - - IsProduction - - Key: Production - Value: True - - Key: Production - Value: False - Fn::If: - - IsProduction - - AvailabilityZones: - Fn::GetAZs: '' - Listeners: - Fn::If: - - IsProduction - - LoadBalancerPort: '443' - InstancePort: '443' - Protocol: HTTP - - LoadBalancerPort: '443' - InstancePort: '443' - Protocol: HTTP - HealthCheck: - Target: HTTP:80/ - HealthyThreshold: '3' - UnhealthyThreshold: '5' - Interval: '30' - Timeout: '5' - ConnectionDrainingPolicy: - Enabled: 'true' - Timeout: '60' - - AvailabilityZones: - Fn::GetAZs: '' - Listeners: - - LoadBalancerPort: '80' - InstancePort: '80' - Protocol: HTTP - HealthCheck: - Target: HTTP:80/ - HealthyThreshold: '3' - UnhealthyThreshold: '5' - Interval: '30' - Timeout: '5' + - IsProduction + - Key: Production + Value: True + - Key: Production + Value: False + Fn::If: + - IsProduction + - AvailabilityZones: + Fn::GetAZs: "" + Listeners: + - Fn::If: + - IsProduction + - LoadBalancerPort: "443" + InstancePort: "443" + Protocol: HTTP + - LoadBalancerPort: "443" + InstancePort: "443" + Protocol: HTTP + HealthCheck: + Target: HTTP:80/ + HealthyThreshold: "3" + UnhealthyThreshold: "5" + Interval: "30" + Timeout: "5" + ConnectionDrainingPolicy: + Enabled: "true" + Timeout: "60" + - AvailabilityZones: + Fn::GetAZs: "" + Listeners: + - LoadBalancerPort: "80" + InstancePort: "80" + Protocol: HTTP + HealthCheck: + Target: HTTP:80/ + HealthyThreshold: "3" + UnhealthyThreshold: "5" + Interval: "30" + Timeout: "5" # Fail when not using FindInMap lambdaMap1: Type: AWS::EC2::SecurityGroup @@ -199,13 +192,13 @@ Resources: Properties: GroupDescription: test SecurityGroupIngress: - - Fn::FindInMap: [ runtime, !Ref 'AWS::Region', production ] + - Fn::FindInMap: [runtime, !Ref "AWS::Region", production] PermitAllInbound: Type: AWS::EC2::NetworkAclEntry Properties: CidrBlock: 10.0.0.0/16 Icmp: !Ref AWS::NoValue - NetworkAclId: '1' + NetworkAclId: "1" RuleNumber: 1 Protocol: 1 RuleAction: allow @@ -215,7 +208,7 @@ Resources: ImageId: "ami-2f726546" InstanceType: t1.micro KeyName: testkey - BlockDeviceMappings: !Ref 'AWS::NoValue' + BlockDeviceMappings: !Ref "AWS::NoValue" NetworkInterfaces: - DeviceIndex: "1" Outputs: diff --git a/test/fixtures/templates/bad/resources/configuration.yaml b/test/fixtures/templates/bad/resources/configuration.yaml --- a/test/fixtures/templates/bad/resources/configuration.yaml +++ b/test/fixtures/templates/bad/resources/configuration.yaml @@ -1,12 +1,19 @@ --- AWSTemplateFormatVersion: "2010-09-09" Conditions: - isUsEast1: !Equals [!Ref 'AWS::Region', 'us-east-1'] + isUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"] +Parameters: + CloudformationType: + Type: String + Default: AWS::EC2::Instance + AllowedValues: + - AWS::EC2::Instance + - AWS::AutoScaling::LaunchConfiguration Resources: AWSIAMRole1: Type: AWS::IAM::Role Condition: - - isUsEast1 + - isUsEast1 Properties: AssumeRolePolicyDocument: {} AWSIAMRole2: @@ -14,3 +21,8 @@ Resources: Condition: False Properties: AssumeRolePolicyDocument: {} + EC2InstanceOrLaunchConfig: + Type: !Ref CloudformationType + Properties: + InstanceType: t3.nano + ImageId: ami-0b90a8636b6f955c1 diff --git a/test/unit/rules/resources/test_configurations.py b/test/unit/rules/resources/test_configurations.py --- a/test/unit/rules/resources/test_configurations.py +++ b/test/unit/rules/resources/test_configurations.py @@ -21,4 +21,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" self.helper_file_negative('test/fixtures/templates/bad/generic.yaml', 2) - self.helper_file_negative('test/fixtures/templates/bad/resources/configuration.yaml', 2) + self.helper_file_negative('test/fixtures/templates/bad/resources/configuration.yaml', 3)
cfn-lint cannot catch "Every Type member must be a string" *cfn-lint version: (`cfn-lint --version`)* ``` cfn-lint 0.34.0 ``` *aws-cli version: (`aws --version`)* ``` aws-cli/1.18.97 Python/3.8.3 Linux/4.15.0-111-generic botocore/1.16.26 ``` *Description of issue.* ``` $ cat template.yml AWSTemplateFormatVersion: 2010-09-09 Parameters: CloudformationType: Type: String Default: AWS::EC2::Instance AllowedValues: - AWS::EC2::Instance - AWS::AutoScaling::LaunchConfiguration Resources: EC2InstanceOrLaunchConfig: Type: !Ref CloudformationType Properties: InstanceType: t3.nano ImageId: ami-0b90a8636b6f955c1 $ aws cloudformation deploy --stack-name test --template-file template.yml An error occurred (ValidationError) when calling the CreateChangeSet operation: Template format error: [/Resources/EC2InstanceOrLaunchConfig] Every Type member must be a string. $ aws cloudformation validate-template --template-body file://template.yml An error occurred (ValidationError) when calling the ValidateTemplate operation: Template format error: [/Resources/EC2InstanceOrLaunchConfig] Every Type member must be a string. $ cfn-lint template.yml $ echo $? 0 ```
Agreed we should have this covered. I'll get that fixed.
2020-07-22T18:31:48Z
[]
[]
aws-cloudformation/cfn-lint
1,640
aws-cloudformation__cfn-lint-1640
[ "1639" ]
879c1cef00f6aa63b74177ea6809f8721f57351c
diff --git a/src/cfnlint/helpers.py b/src/cfnlint/helpers.py --- a/src/cfnlint/helpers.py +++ b/src/cfnlint/helpers.py @@ -171,6 +171,64 @@ 'AWS::Redshift::Cluster' ] +VALID_PARAMETER_TYPES_SINGLE = [ + 'AWS::EC2::AvailabilityZone::Name', + 'AWS::EC2::Image::Id', + 'AWS::EC2::Instance::Id', + 'AWS::EC2::KeyPair::KeyName', + 'AWS::EC2::SecurityGroup::GroupName', + 'AWS::EC2::SecurityGroup::Id', + 'AWS::EC2::Subnet::Id', + 'AWS::EC2::VPC::Id', + 'AWS::EC2::Volume::Id', + 'AWS::Route53::HostedZone::Id', + 'AWS::SSM::Parameter::Name', + 'Number', + 'String', + 'AWS::SSM::Parameter::Value<AWS::EC2::AvailabilityZone::Name>', + 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>', + 'AWS::SSM::Parameter::Value<AWS::EC2::Instance::Id>', + 'AWS::SSM::Parameter::Value<AWS::EC2::KeyPair::KeyName>', + 'AWS::SSM::Parameter::Value<AWS::EC2::SecurityGroup::GroupName>', + 'AWS::SSM::Parameter::Value<AWS::EC2::SecurityGroup::Id>', + 'AWS::SSM::Parameter::Value<AWS::EC2::Subnet::Id>', + 'AWS::SSM::Parameter::Value<AWS::EC2::VPC::Id>', + 'AWS::SSM::Parameter::Value<AWS::EC2::Volume::Id>', + 'AWS::SSM::Parameter::Value<AWS::Route53::HostedZone::Id>', + 'AWS::SSM::Parameter::Value<AWS::SSM::Parameter::Name>', + 'AWS::SSM::Parameter::Value<Number>', + 'AWS::SSM::Parameter::Value<String>', +] + +VALID_PARAMETER_TYPES_LIST = [ + 'CommaDelimitedList', + 'List<AWS::EC2::AvailabilityZone::Name>', + 'List<AWS::EC2::Image::Id>', + 'List<AWS::EC2::Instance::Id>', + 'List<AWS::EC2::SecurityGroup::GroupName>', + 'List<AWS::EC2::SecurityGroup::Id>', + 'List<AWS::EC2::Subnet::Id>', + 'List<AWS::EC2::VPC::Id>', + 'List<AWS::EC2::Volume::Id>', + 'List<AWS::Route53::HostedZone::Id>', + 'List<Number>', + 'List<String>', + 'AWS::SSM::Parameter::Value<CommaDelimitedList>', + 'AWS::SSM::Parameter::Value<List<AWS::EC2::AvailabilityZone::Name>>', + 'AWS::SSM::Parameter::Value<List<AWS::EC2::Image::Id>>', + 'AWS::SSM::Parameter::Value<List<AWS::EC2::Instance::Id>>', + 'AWS::SSM::Parameter::Value<List<AWS::EC2::SecurityGroup::GroupName>>', + 'AWS::SSM::Parameter::Value<List<AWS::EC2::SecurityGroup::Id>>', + 'AWS::SSM::Parameter::Value<List<AWS::EC2::Subnet::Id>>', + 'AWS::SSM::Parameter::Value<List<AWS::EC2::VPC::Id>>', + 'AWS::SSM::Parameter::Value<List<AWS::EC2::Volume::Id>>', + 'AWS::SSM::Parameter::Value<List<AWS::Route53::HostedZone::Id>>', + 'AWS::SSM::Parameter::Value<List<Number>>', + 'AWS::SSM::Parameter::Value<List<String>>', +] + +VALID_PARAMETER_TYPES = VALID_PARAMETER_TYPES_SINGLE + VALID_PARAMETER_TYPES_LIST + def get_metadata_filename(url): """Returns the filename for a metadata file associated with a remote resource""" caching_dir = os.path.join(os.path.dirname(__file__), 'data', 'DownloadsMetadata') diff --git a/src/cfnlint/rules/conditions/Equals.py b/src/cfnlint/rules/conditions/Equals.py --- a/src/cfnlint/rules/conditions/Equals.py +++ b/src/cfnlint/rules/conditions/Equals.py @@ -3,6 +3,7 @@ SPDX-License-Identifier: MIT-0 """ import six +from cfnlint.helpers import VALID_PARAMETER_TYPES_LIST from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch @@ -15,27 +16,55 @@ class Equals(CloudFormationLintRule): source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-equals' tags = ['functions', 'equals'] + allowed_functions = ['Ref', 'Fn::FindInMap', + 'Fn::Sub', 'Fn::Join', 'Fn::Select', 'Fn::Split'] + function = 'Fn::Equals' + + def _check_equal_values(self, cfn, element, path): + matches = [] + + if len(element) == 1: + for element_key, element_value in element.items(): + if element_key not in self.allowed_functions: + message = self.function + \ + ' element must be a supported function ({0})' + matches.append(RuleMatch( + path[:] + [element_key], + message.format(', '.join(self.allowed_functions)) + )) + elif element_key == 'Ref': + valid_refs = cfn.get_valid_refs() + if element_value in valid_refs: + if valid_refs[element_value].get('From') == 'Parameters': + if valid_refs[element_value].get('Type') in VALID_PARAMETER_TYPES_LIST: + message = 'Every Fn::Equals object requires a list of 2 string parameters' + matches.append(RuleMatch( + path, message)) + else: + message = self.function + ' element must be a supported function ({0})' + matches.append(RuleMatch( + path, + message.format(', '.join(self.allowed_functions)) + )) + return matches + def match(self, cfn): - function = 'Fn::Equals' matches = [] # Build the list of functions - trees = cfn.search_deep_keys(function) - - allowed_functions = ['Ref', 'Fn::FindInMap', - 'Fn::Sub', 'Fn::Join', 'Fn::Select', 'Fn::Split'] + trees = cfn.search_deep_keys(self.function) for tree in trees: # Test when in Conditions if tree[0] == 'Conditions': value = tree[-1] if not isinstance(value, list): - message = function + ' must be a list of two elements' + message = self.function + ' must be a list of two elements' matches.append(RuleMatch( tree[:-1], message.format() )) elif len(value) != 2: - message = function + ' must be a list of two elements' + message = self.function + ' must be a list of two elements' matches.append(RuleMatch( tree[:-1], message.format() @@ -43,25 +72,14 @@ def match(self, cfn): else: for index, element in enumerate(value): if isinstance(element, dict): - if len(element) == 1: - for element_key in element.keys(): - if element_key not in allowed_functions: - message = function + ' element must be a supported function ({0})' - matches.append(RuleMatch( - tree[:-1] + [index, element_key], - message.format(', '.join(allowed_functions)) - )) - else: - message = function + ' element must be a supported function ({0})' - matches.append(RuleMatch( - tree[:-1] + [index], - message.format(', '.join(allowed_functions)) - )) + matches.extend(self._check_equal_values( + cfn, element, tree[:-1] + [index])) elif not isinstance(element, (six.string_types, bool, six.integer_types, float)): - message = function + ' element must be a String, Boolean, Number, or supported function ({0})' + message = self.function + \ + ' element must be a String, Boolean, Number, or supported function ({0})' matches.append(RuleMatch( tree[:-1] + [index], - message.format(', '.join(allowed_functions)) + message.format(', '.join(self.allowed_functions)) )) return matches diff --git a/src/cfnlint/rules/functions/Join.py b/src/cfnlint/rules/functions/Join.py --- a/src/cfnlint/rules/functions/Join.py +++ b/src/cfnlint/rules/functions/Join.py @@ -5,7 +5,7 @@ import six from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch -from cfnlint.helpers import RESOURCE_SPECS +from cfnlint.helpers import RESOURCE_SPECS, VALID_PARAMETER_TYPES_LIST class Join(CloudFormationLintRule): @@ -51,16 +51,8 @@ def _is_ref_a_list(self, parameter, template_parameters): 'AWS::NotificationARNs', ] - odd_list_params = [ - 'CommaDelimitedList', - 'AWS::SSM::Parameter::Value<CommaDelimitedList>', - ] - if parameter in template_parameters: - if ( - template_parameters.get(parameter) in odd_list_params or - template_parameters.get(parameter).startswith('AWS::SSM::Parameter::Value<List') or - template_parameters.get(parameter).startswith('List')): + if template_parameters.get(parameter) in VALID_PARAMETER_TYPES_LIST: return True if parameter in list_params: return True diff --git a/src/cfnlint/rules/functions/Sub.py b/src/cfnlint/rules/functions/Sub.py --- a/src/cfnlint/rules/functions/Sub.py +++ b/src/cfnlint/rules/functions/Sub.py @@ -3,7 +3,7 @@ SPDX-License-Identifier: MIT-0 """ import six -from cfnlint.helpers import PSEUDOPARAMS +from cfnlint.helpers import PSEUDOPARAMS, VALID_PARAMETER_TYPES_LIST from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch @@ -98,11 +98,6 @@ def _test_parameter(self, parameter, cfn, parameters, tree): matches = [] get_atts = cfn.get_valid_getatts() - odd_list_params = [ - 'CommaDelimitedList', - 'AWS::SSM::Parameter::Value<CommaDelimitedList>', - ] - valid_params = list(PSEUDOPARAMS) valid_params.extend(cfn.get_resource_names()) template_parameters = self._get_parameters(cfn) @@ -114,10 +109,7 @@ def _test_parameter(self, parameter, cfn, parameters, tree): found = False if parameter in template_parameters: found = True - if ( - template_parameters.get(parameter) in odd_list_params or - template_parameters.get(parameter).startswith('AWS::SSM::Parameter::Value<List') or - template_parameters.get(parameter).startswith('List')): + if template_parameters.get(parameter) in VALID_PARAMETER_TYPES_LIST: message = 'Fn::Sub cannot use list {0} at {1}' matches.append(RuleMatch( tree, message.format(parameter, '/'.join(map(str, tree))))) diff --git a/src/cfnlint/rules/parameters/Types.py b/src/cfnlint/rules/parameters/Types.py --- a/src/cfnlint/rules/parameters/Types.py +++ b/src/cfnlint/rules/parameters/Types.py @@ -2,6 +2,7 @@ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ +from cfnlint.helpers import VALID_PARAMETER_TYPES from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch @@ -14,34 +15,6 @@ class Types(CloudFormationLintRule): source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html#parmtypes' tags = ['parameters'] - valid_types = [ - 'AWS::EC2::AvailabilityZone::Name', - 'AWS::EC2::Image::Id', - 'AWS::EC2::Instance::Id', - 'AWS::EC2::KeyPair::KeyName', - 'AWS::EC2::SecurityGroup::GroupName', - 'AWS::EC2::SecurityGroup::Id', - 'AWS::EC2::Subnet::Id', - 'AWS::EC2::VPC::Id', - 'AWS::EC2::Volume::Id', - 'AWS::Route53::HostedZone::Id', - 'AWS::SSM::Parameter::Name', - 'CommaDelimitedList', - 'List<AWS::EC2::AvailabilityZone::Name>', - 'List<AWS::EC2::Image::Id>', - 'List<AWS::EC2::Instance::Id>', - 'List<AWS::EC2::SecurityGroup::GroupName>', - 'List<AWS::EC2::SecurityGroup::Id>', - 'List<AWS::EC2::Subnet::Id>', - 'List<AWS::EC2::VPC::Id>', - 'List<AWS::EC2::Volume::Id>', - 'List<AWS::Route53::HostedZone::Id>', - 'List<Number>', - 'List<String>', - 'Number', - 'String', - ] - def match(self, cfn): matches = [] @@ -50,12 +23,11 @@ def match(self, cfn): # this test isn't about missing required properties for a # parameter. paramtype = paramvalue.get('Type', 'String') - if paramtype not in self.valid_types: - if not paramtype.startswith('AWS::SSM::Parameter::Value'): - message = 'Parameter {0} has invalid type {1}' - matches.append(RuleMatch( - ['Parameters', paramname, 'Type'], - message.format(paramname, paramtype) - )) + if paramtype not in VALID_PARAMETER_TYPES: + message = 'Parameter {0} has invalid type {1}' + matches.append(RuleMatch( + ['Parameters', paramname, 'Type'], + message.format(paramname, paramtype) + )) return matches
diff --git a/test/fixtures/templates/bad/conditions/equals.yaml b/test/fixtures/templates/bad/conditions/equals.yaml --- a/test/fixtures/templates/bad/conditions/equals.yaml +++ b/test/fixtures/templates/bad/conditions/equals.yaml @@ -1,9 +1,23 @@ --- AWSTemplateFormatVersion: "2010-09-09" +Parameters: + Environments: + Type: CommaDelimitedList + Default: dev,test Conditions: TestEqual: !Equals 'Value' TestEqualToShort: !Equals ['1'] TestEqualToLong: !Equals ['1', '2', '3'] Test: !Equals [[{'Ref': 'AWS::Region'}], {'Bad': 'Value'}] TestWrongType: !Equals [1.234, ['Not a List']] + TagEnvironments: !Not + - !Equals + - !Ref Environments # missed !Join + - '' + ToManyFunctions: + Fn::Equals: + - Ref: AWS::Region + Fn::Select: [Environments, 0] + - "dev" + Resources: {} diff --git a/test/fixtures/templates/bad/parameters/configuration.yaml b/test/fixtures/templates/bad/parameters/configuration.yaml --- a/test/fixtures/templates/bad/parameters/configuration.yaml +++ b/test/fixtures/templates/bad/parameters/configuration.yaml @@ -26,6 +26,7 @@ Parameters: # invalid Property NotType: String mySsmParam: + # Invalid SSM Parameter type Type: AWS::SSM::Parameter::Value<Test> Resources: # Helps tests map resource types diff --git a/test/unit/rules/conditions/test_equals.py b/test/unit/rules/conditions/test_equals.py --- a/test/unit/rules/conditions/test_equals.py +++ b/test/unit/rules/conditions/test_equals.py @@ -23,4 +23,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/conditions/equals.yaml', 6) + self.helper_file_negative('test/fixtures/templates/bad/conditions/equals.yaml', 8) diff --git a/test/unit/rules/parameters/test_types.py b/test/unit/rules/parameters/test_types.py --- a/test/unit/rules/parameters/test_types.py +++ b/test/unit/rules/parameters/test_types.py @@ -20,4 +20,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/parameters/configuration.yaml', 1) + self.helper_file_negative('test/fixtures/templates/bad/parameters/configuration.yaml', 2)
Cannot catch "Fn::Equals object requires a list of 2 string parameters" *cfn-lint version: (`cfn-lint --version`)* ``` cfn-lint 0.34.1 ``` *aws-cli version: (`aws --version`)* ``` aws-cli/1.18.97 Python/3.8.3 Linux/4.15.0-111-generic botocore/1.16.26 ``` *Description of issue.* ``` $ cat template.yml AWSTemplateFormatVersion: 2010-09-09 Parameters: Environments: Type: CommaDelimitedList Default: dev,test Conditions: TagEnvironments: !Not - !Equals - !Ref Environments # missed !Join - '' Resources: VPC: Type: AWS::EC2::VPC Properties: CidrBlock: 172.16.0.0/24 Tags: !If - TagEnvironments - - Key: Environments Value: !Join - ',' - !Ref Environments - [] $ aws cloudformation deploy --stack-name test --template-file template.yml An error occurred (ValidationError) when calling the CreateChangeSet operation: Template error: every Fn::Equals object requires a list of 2 string parameters. $ aws cloudformation validate-template --template-body file://template.yml An error occurred (ValidationError) when calling the ValidateTemplate operation: Template error: every Fn::Equals object requires a list of 2 string parameters. $ cfn-lint template.yml $ echo $? 0 ```
2020-08-04T17:42:46Z
[]
[]
aws-cloudformation/cfn-lint
1,659
aws-cloudformation__cfn-lint-1659
[ "1658" ]
f440351e4c1b5daca4388216e162a190fe1d6da9
diff --git a/src/cfnlint/rules/functions/GetAtt.py b/src/cfnlint/rules/functions/GetAtt.py --- a/src/cfnlint/rules/functions/GetAtt.py +++ b/src/cfnlint/rules/functions/GetAtt.py @@ -80,6 +80,15 @@ def match(self, cfn): if resname: if resname in valid_getatts: if restype is not None: + # Check for maps + restypeparts = restype.split('.') + if restypeparts[0] in valid_getatts[resname] and len(restypeparts) >= 2: + if valid_getatts[resname][restypeparts[0]].get('Type') != 'Map': + message = 'Invalid GetAtt {0}.{1} for resource {2}' + matches.append(RuleMatch( + getatt[:-1], message.format(resname, restype, getatt[1]))) + else: + continue if restype not in valid_getatts[resname] and '*' not in valid_getatts[resname]: message = 'Invalid GetAtt {0}.{1} for resource {2}' matches.append(RuleMatch( diff --git a/src/cfnlint/rules/functions/Sub.py b/src/cfnlint/rules/functions/Sub.py --- a/src/cfnlint/rules/functions/Sub.py +++ b/src/cfnlint/rules/functions/Sub.py @@ -115,19 +115,19 @@ def _test_parameter(self, parameter, cfn, parameters, tree): tree, message.format(parameter, '/'.join(map(str, tree))))) for resource, attributes in get_atts.items(): for attribute_name, attribute_values in attributes.items(): - if resource == parameter.split('.')[0] and attribute_name == '*': - if attribute_values.get('Type') == 'List': - message = 'Fn::Sub cannot use list {0} at {1}' - matches.append(RuleMatch( - tree, message.format(parameter, '/'.join(map(str, tree))))) - found = True - elif (resource == parameter.split('.')[0] and - attribute_name == '.'.join(parameter.split('.')[1:])): - if attribute_values.get('Type') == 'List': - message = 'Fn::Sub cannot use list {0} at {1}' - matches.append(RuleMatch( - tree, message.format(parameter, '/'.join(map(str, tree))))) - found = True + if resource == parameter.split('.')[0]: + if attribute_name == '*': + found = True + elif attribute_name == '.'.join(parameter.split('.')[1:]): + if attribute_values.get('Type') == 'List': + message = 'Fn::Sub cannot use list {0} at {1}' + matches.append(RuleMatch( + tree, message.format(parameter, '/'.join(map(str, tree))))) + found = True + else: + if attribute_name == parameter.split('.')[1] and attribute_values.get('Type') == 'Map': + found = True + if not found: message = 'Parameter {0} for Fn::Sub not found at {1}' matches.append(RuleMatch(
diff --git a/test/fixtures/templates/bad/functions/getatt.yaml b/test/fixtures/templates/bad/functions/getatt.yaml --- a/test/fixtures/templates/bad/functions/getatt.yaml +++ b/test/fixtures/templates/bad/functions/getatt.yaml @@ -45,7 +45,16 @@ Resources: # Shouldn't raise an error when using a Ref for the attribute RdsMasterUsername: !If [ UseSSM, "Fn::GetAtt": [ RDSCredentials, !Select [0, !Ref SSMMasterDBUsernameKeyFullName] ], !Ref PGMasterUser ] RdsMasterPassword: !If [ UseSSM, "Fn::GetAtt": [ RDSCredentials, [!Ref SSMMasterDBPasswordKeyFullName] ], !Ref PGMasterPassword ] + ProvisionedProduct: + Type: AWS::ServiceCatalog::CloudFormationProvisionedProduct + Properties: + ProductName: example + ProvisioningArtifactName: v1 Outputs: ElasticSearchHostname: Value: Fn::GetAtt: ElasticSearchDomain.DomainEndpoint + OutputBadOutput: + Value: !GetAtt ProvisionedProduct.Output.Example + OutputBadName: + Value: !GetAtt myElasticSearch.DomainEndpoint.Example diff --git a/test/fixtures/templates/good/functions/getatt.yaml b/test/fixtures/templates/good/functions/getatt.yaml --- a/test/fixtures/templates/good/functions/getatt.yaml +++ b/test/fixtures/templates/good/functions/getatt.yaml @@ -57,6 +57,11 @@ Resources: Tags: - Key: foo Value: bar + ProvisionedProduct: + Type: AWS::ServiceCatalog::CloudFormationProvisionedProduct + Properties: + ProductName: example + ProvisioningArtifactName: v1 Outputs: ElasticSearchHostname: Value: @@ -65,3 +70,5 @@ Outputs: Description: Endpoint address for Redshift cluster. Value: Fn::GetAtt: myCluster.Endpoint.Address + OutputValue: + Value: !GetAtt ProvisionedProduct.Outputs.Example diff --git a/test/fixtures/templates/good/functions/sub.yaml b/test/fixtures/templates/good/functions/sub.yaml --- a/test/fixtures/templates/good/functions/sub.yaml +++ b/test/fixtures/templates/good/functions/sub.yaml @@ -59,3 +59,11 @@ Resources: 'Fn::Sub': 'Fn::Transform': # Doesn't fail on Transform Name: DynamicUserData + ProvisionedProduct: + Type: AWS::ServiceCatalog::CloudFormationProvisionedProduct + Properties: + ProductName: example + ProvisioningArtifactName: v1 +Outputs: + OutputSub: + Value: !Sub '${ProvisionedProduct.Outputs.Example}-example' diff --git a/test/unit/rules/functions/test_get_att.py b/test/unit/rules/functions/test_get_att.py --- a/test/unit/rules/functions/test_get_att.py +++ b/test/unit/rules/functions/test_get_att.py @@ -27,4 +27,4 @@ def test_file_negative(self): def test_file_negative_getatt(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/functions/getatt.yaml', 3) + self.helper_file_negative('test/fixtures/templates/bad/functions/getatt.yaml', 5)
AWS::ServiceCatalog::CloudFormationProvisionedProduct.Outputs In July 2020, support for retrieving the outputs of provisioned Service Catalog products [was added to CloudFormation](https://aws.amazon.com/blogs/mt/how-to-launch-secure-and-governed-aws-resources-with-aws-cloudformation-and-aws-service-catalog/). Given the following example template: ```yaml AWSTemplateFormatVersion: '2010-09-09' Resources: ProvisionedProduct: Type: AWS::ServiceCatalog::CloudFormationProvisionedProduct Properties: ProductName: example ProvisioningArtifactName: v1 Outputs: OutputValue: Value: !GetAtt ProvisionedProduct.Outputs.Example OutputSub: Value: !Sub '${ProvisionedProduct.Outputs.Example}-example' ``` The following linting errors are output when using cfn-lint 0.35.0: ``` E1010 Invalid GetAtt ProvisionedProduct.Outputs.Example for resource OutputValue example.yml:12:5 E1019 Parameter ProvisionedProduct.Outputs.Example for Fn::Sub not found at Outputs/OutputSub/Value/Fn::Sub example.yml:15:5 ``` Access to these outputs using `!GetAtt` is documented in the announcement of this functionality (e.g. `!GetAtt ApacheALB.Outputs.ALBTarget`). Additionally the example template given above works correctly when deployed. `Output` is documented in the [AWS::ServiceCatalog::CloudFormationProvisionedProduct return values](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-cloudformationprovisionedproduct.html#aws-resource-servicecatalog-cloudformationprovisionedproduct-return-values) and appears to already be defined within cfn-lint CloudSpecs as a `Map` type. I believe that this a false positive and am not aware of any alternative syntax to access these outputs (e.g. `!FindInMap` doesn't appear to be usable in this instance).
Submitted this to the wrong issue. I'm looking into this now.
2020-08-18T00:00:22Z
[]
[]
aws-cloudformation/cfn-lint
1,690
aws-cloudformation__cfn-lint-1690
[ "1688" ]
cf0f5b55bf471fc1e9021e28cbac54aef5bf8821
diff --git a/src/cfnlint/rules/resources/codepipeline/CodepipelineStageActions.py b/src/cfnlint/rules/resources/codepipeline/CodepipelineStageActions.py --- a/src/cfnlint/rules/resources/codepipeline/CodepipelineStageActions.py +++ b/src/cfnlint/rules/resources/codepipeline/CodepipelineStageActions.py @@ -220,6 +220,35 @@ def check_names_unique(self, action, path, action_names): return matches + def check_artifact_names(self, action, path, artifact_names): + """Check that output artifact names are unique and inputs are from previous stage outputs.""" + matches = [] + + input_artifacts = action.get('InputArtifacts') + if isinstance(input_artifacts, list): + for input_artifact in input_artifacts: + artifact_name = input_artifact.get('Name') + if isinstance(artifact_name, six.string_types): + if not artifact_name in artifact_names: + message = 'Every input artifact for an action must match the output artifact of an action earlier in the pipeline. ({name})'.format( + name=artifact_name + ) + matches.append(RuleMatch(path + ['InputArtifacts', 'Name'], message)) + + output_artifacts = action.get('OutputArtifacts') + if isinstance(output_artifacts, list): + for output_artifact in output_artifacts: + artifact_name = output_artifact.get('Name') + if isinstance(artifact_name, six.string_types): + if artifact_name in artifact_names: + message = 'Every output artifact in the pipeline must have a unique name. ({name})'.format( + name=artifact_name + ) + matches.append(RuleMatch(path + ['OutputArtifacts', 'Name'], message)) + artifact_names.add(artifact_name) + + return matches + def match(self, cfn): """Check that stage actions are set up properly.""" matches = [] @@ -228,6 +257,7 @@ def match(self, cfn): for resource in resources: path = resource['Path'] properties = resource['Value'] + artifact_names = set() s_stages = properties.get_safe('Stages', path) for s_stage_v, s_stage_p in s_stages: @@ -255,6 +285,8 @@ def match(self, cfn): l_i_a_action, 'InputArtifacts', full_path)) matches.extend(self.check_artifact_counts( l_i_a_action, 'OutputArtifacts', full_path)) + matches.extend(self.check_artifact_names( + l_i_a_action, full_path, artifact_names)) except AttributeError as err: self.logger.debug('Got AttributeError. Should have been caught by generic linting. ' 'Ignoring the error here: %s', str(err))
diff --git a/test/fixtures/templates/bad/resources/codepipeline/action_artifact_counts.yaml b/test/fixtures/templates/bad/resources/codepipeline/action_artifact_counts.yaml --- a/test/fixtures/templates/bad/resources/codepipeline/action_artifact_counts.yaml +++ b/test/fixtures/templates/bad/resources/codepipeline/action_artifact_counts.yaml @@ -5,7 +5,7 @@ Resources: Properties: Name: Test-pipeline ArtifactStore: - Location: 'pipeline-bucket' + Location: "pipeline-bucket" Type: S3 RoleArn: arn:aws:iam:::role/AWSCodePipelineRole Stages: @@ -24,7 +24,21 @@ Resources: Repo: cfn-python-lint PollForSourceChanges: true Branch: master - OAuthToken: 'secret-token' + OAuthToken: "secret-token" + - Name: Github2 + ActionTypeId: + Category: Source + Owner: ThirdParty + Provider: GitHub + Version: "1" + OutputArtifacts: + - Name: MyApp2 + Configuration: + Owner: aws-cloudformation + Repo: cfn-python-lint + PollForSourceChanges: true + Branch: master + OAuthToken: "secret-token" - Name: ECR ActionTypeId: Category: Source @@ -46,11 +60,11 @@ Resources: Configuration: ProjectName: cfn-python-lint InputArtifacts: - - Name: MyApp - - Name: MyApp2 # No Longer an error + - Name: MyApp + - Name: MyApp2 # No Longer an error OutputArtifacts: - - Name: MyOutput1 - - Name: MyOutput2 # No Longer an error + - Name: MyOutput2 + - Name: MyOutput3 # No Longer an error - Name: JenkinsBuild ActionTypeId: Category: Build @@ -60,17 +74,17 @@ Resources: Configuration: ProjectName: cfn-python-lint InputArtifacts: - - Name: MyInput1 - - Name: MyInput2 - - Name: MyInput3 - - Name: MyInput4 - - Name: MyInput5 - OutputArtifacts: + - Name: MyApp + - Name: MyApp2 - Name: MyOutput1 - Name: MyOutput2 - Name: MyOutput3 + OutputArtifacts: - Name: MyOutput4 - Name: MyOutput5 + - Name: MyOutput6 + - Name: MyOutput7 + - Name: MyOutput8 - Name: Test Actions: - Name: Validate @@ -89,12 +103,12 @@ Resources: - Name: MyOutput5 - Name: MyOutput6 # Error OutputArtifacts: - - Name: MyOutput1 - - Name: MyOutput2 - - Name: MyOutput3 - - Name: MyOutput4 - - Name: MyOutput5 - - Name: MyOutput6 # Error + - Name: MyOutput9 + - Name: MyOutput10 + - Name: MyOutput11 + - Name: MyOutput12 + - Name: MyOutput13 + - Name: MyOutput14 # Error - Name: ValidateDeviceFarm ActionTypeId: Category: Test @@ -113,7 +127,7 @@ Resources: InputArtifacts: - Name: MyOutput1 OutputArtifacts: - - Name: MyOutput1 + - Name: MyOutput15 - Name: ValidateJenkins ActionTypeId: Category: Test @@ -123,17 +137,17 @@ Resources: Configuration: ProjectName: cfn-python-lint InputArtifacts: - - Name: MyInput1 - - Name: MyInput2 - - Name: MyInput3 - - Name: MyInput4 - - Name: MyInput5 - OutputArtifacts: - Name: MyOutput1 - Name: MyOutput2 - Name: MyOutput3 - Name: MyOutput4 - Name: MyOutput5 + OutputArtifacts: + - Name: MyOutput16 + - Name: MyOutput17 + - Name: MyOutput18 + - Name: MyOutput19 + - Name: MyOutput20 - Name: Deploy Actions: - Name: MyDeploy @@ -159,7 +173,7 @@ Resources: ProductType: CLOUD_FORMATION_TEMPLATE ProductId: port-99slboidonpew InputArtifacts: - - Name: MyInput1 + - Name: MyOutput1 - Name: MyDeployAlexaSkillsKit ActionTypeId: Category: Deploy @@ -172,8 +186,8 @@ Resources: RefreshToken: 1234 SkillId: amzn1.ask.skill.22649d8f-0451-4b4b-9ed9-bfb6cEXAMPLE InputArtifacts: - - Name: MyInput1 - - Name: MyInput2 + - Name: MyOutput1 + - Name: MyOutput2 - Name: MyApprovalStage Actions: - Name: MyApprovalAction @@ -183,9 +197,9 @@ Resources: Version: "1" Provider: Manual InputArtifacts: - - Name: MyApp # Error + - Name: MyApp # Error OutputArtifacts: - - Name: MyOutput1 # Error + - Name: MyOutput21 # Error Configuration: NotificationArn: arn:aws:sns:us-east-2:80398EXAMPLE:MyApprovalTopic ExternalEntityLink: http://example.com diff --git a/test/fixtures/templates/bad/resources/codepipeline/input_artifact_not_exists.yaml b/test/fixtures/templates/bad/resources/codepipeline/input_artifact_not_exists.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources/codepipeline/input_artifact_not_exists.yaml @@ -0,0 +1,71 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: The AWS CloudFormation template for this Serverless application +Resources: + ServerlessDeploymentPipeline: + Type: AWS::CodePipeline::Pipeline + Properties: + ArtifactStores: + - Region: ca-central-1 + ArtifactStore: + Type: S3 + Location: my-artifact-bucket + Name: my-code-pipeline + RestartExecutionOnUpdate: false + RoleArn: arn:aws:iam::000000000000:role/root + Stages: + - Name: Source + Actions: + - Name: SourceAction + ActionTypeId: + Category: Source + Owner: AWS + Version: "1" + Provider: S3 + OutputArtifacts: + - Name: SourceArtifact + Configuration: + S3Bucket: my-source-bucket + S3ObjectKey: source-item.zip + RunOrder: 1 + - Name: DeployToEnvA + Actions: + - Name: CreateChangeSetEnvA + Region: us-east-1 + ActionTypeId: + Category: Deploy + Owner: AWS + Version: "1" + Provider: CloudFormation + InputArtifacts: + - Name: SourceArtifactNonExistent + OutputArtifacts: + - Name: CreateOutput + Configuration: + ActionMode: CHANGE_SET_REPLACE + StackName: my-service-env-a + Capabilities: CAPABILITY_NAMED_IAM + RoleArn: arn:aws:iam::000000000000:role/root + TemplatePath: SourceArtifact::env-a-us-east-1.json + ChangeSetName: ChangeSet + RunOrder: 1 + RoleArn: arn:aws:iam::000000000000:role/root + - Name: CreateChangeSetEnvB + Region: us-east-1 + ActionTypeId: + Category: Deploy + Owner: AWS + Version: "1" + Provider: CloudFormation + InputArtifacts: + - Name: SourceArtifact + OutputArtifacts: + - Name: CreateOutput2 + Configuration: + ActionMode: CHANGE_SET_REPLACE + StackName: my-service-env-b + Capabilities: CAPABILITY_NAMED_IAM + RoleArn: arn:aws:iam::000000000000:role/root + TemplatePath: SourceArtifact::env-b-us-east-1.json + ChangeSetName: ChangeSet + RunOrder: 1 + RoleArn: arn:aws:iam::000000000000:role/root diff --git a/test/fixtures/templates/bad/resources/codepipeline/output_artifact_non_unique.yaml b/test/fixtures/templates/bad/resources/codepipeline/output_artifact_non_unique.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources/codepipeline/output_artifact_non_unique.yaml @@ -0,0 +1,71 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: The AWS CloudFormation template for this Serverless application +Resources: + ServerlessDeploymentPipeline: + Type: AWS::CodePipeline::Pipeline + Properties: + ArtifactStores: + - Region: ca-central-1 + ArtifactStore: + Type: S3 + Location: my-artifact-bucket + Name: my-code-pipeline + RestartExecutionOnUpdate: false + RoleArn: arn:aws:iam::000000000000:role/root + Stages: + - Name: Source + Actions: + - Name: SourceAction + ActionTypeId: + Category: Source + Owner: AWS + Version: "1" + Provider: S3 + OutputArtifacts: + - Name: SourceArtifact + Configuration: + S3Bucket: my-source-bucket + S3ObjectKey: source-item.zip + RunOrder: 1 + - Name: DeployToEnvA + Actions: + - Name: CreateChangeSetEnvA + Region: us-east-1 + ActionTypeId: + Category: Deploy + Owner: AWS + Version: "1" + Provider: CloudFormation + InputArtifacts: + - Name: SourceArtifact + OutputArtifacts: + - Name: CreateOutput + Configuration: + ActionMode: CHANGE_SET_REPLACE + StackName: my-service-env-a + Capabilities: CAPABILITY_NAMED_IAM + RoleArn: arn:aws:iam::000000000000:role/root + TemplatePath: SourceArtifact::env-a-us-east-1.json + ChangeSetName: ChangeSet + RunOrder: 1 + RoleArn: arn:aws:iam::000000000000:role/root + - Name: CreateChangeSetEnvB + Region: us-east-1 + ActionTypeId: + Category: Deploy + Owner: AWS + Version: "1" + Provider: CloudFormation + InputArtifacts: + - Name: SourceArtifact + OutputArtifacts: + - Name: CreateOutput + Configuration: + ActionMode: CHANGE_SET_REPLACE + StackName: my-service-env-b + Capabilities: CAPABILITY_NAMED_IAM + RoleArn: arn:aws:iam::000000000000:role/root + TemplatePath: SourceArtifact::env-b-us-east-1.json + ChangeSetName: ChangeSet + RunOrder: 1 + RoleArn: arn:aws:iam::000000000000:role/root diff --git a/test/unit/rules/resources/codepipeline/test_stageactions.py b/test/unit/rules/resources/codepipeline/test_stageactions.py --- a/test/unit/rules/resources/codepipeline/test_stageactions.py +++ b/test/unit/rules/resources/codepipeline/test_stageactions.py @@ -35,3 +35,13 @@ def test_file_non_unique(self): """Test failure""" self.helper_file_negative( 'test/fixtures/templates/bad/resources/codepipeline/action_non_unique.yaml', 1) + + def test_output_artifact_names_unique(self): + """Test failure""" + self.helper_file_negative( + 'test/fixtures/templates/bad/resources/codepipeline/output_artifact_non_unique.yaml', 1) + + def test_input_artifact_names_exist(self): + """Test failure""" + self.helper_file_negative( + 'test/fixtures/templates/bad/resources/codepipeline/input_artifact_not_exists.yaml', 1) \ No newline at end of file
Doesn't catch CodePipeline OutputArtifacts need to be uniquely named cfn-lint 0.35.1 *Description of issue.* The linter doesn't catch that CodePipeline `OutputArtifacts` need to be uniquely named. Please provide as much information as possible: * Template linting issues: * Please provide a CloudFormation sample that generated the issue. This template generates the error `UPDATE_FAILED | Output Artifact Bundle name must be unique within the pipeline. CreateOutput has been used more than once.` <details> ```yaml AWSTemplateFormatVersion: "2010-09-09" Description: The AWS CloudFormation template for this Serverless application Resources: ServerlessDeploymentPipeline: Type: AWS::CodePipeline::Pipeline Properties: ArtifactStores: - Region: ca-central-1 ArtifactStore: Type: S3 Location: my-artifact-bucket Name: my-code-pipeline RestartExecutionOnUpdate: false RoleArn: arn:aws:iam::000000000000:role/root Stages: - Name: Source Actions: - Name: SourceAction ActionTypeId: Category: Source Owner: AWS Version: "1" Provider: S3 OutputArtifacts: - Name: SourceArtifact Configuration: S3Bucket: my-source-bucket S3ObjectKey: source-item.zip RunOrder: 1 - Name: DeployToEnvA Actions: - Name: CreateChangeSetEnvA Region: us-east-1 ActionTypeId: Category: Deploy Owner: AWS Version: "1" Provider: CloudFormation InputArtifacts: - Name: SourceArtifact OutputArtifacts: - Name: CreateOutput Configuration: ActionMode: CHANGE_SET_REPLACE StackName: my-service-env-a Capabilities: CAPABILITY_NAMED_IAM RoleArn: arn:aws:iam::000000000000:role/root TemplatePath: SourceArtifact::env-a-us-east-1.json ChangeSetName: ChangeSet RunOrder: 1 RoleArn: arn:aws:iam::000000000000:role/root - Name: CreateChangeSetEnvB Region: us-east-1 ActionTypeId: Category: Deploy Owner: AWS Version: "1" Provider: CloudFormation InputArtifacts: - Name: SourceArtifact OutputArtifacts: - Name: CreateOutput Configuration: ActionMode: CHANGE_SET_REPLACE StackName: my-service-env-b Capabilities: CAPABILITY_NAMED_IAM RoleArn: arn:aws:iam::000000000000:role/root TemplatePath: SourceArtifact::env-b-us-east-1.json ChangeSetName: ChangeSet RunOrder: 1 RoleArn: arn:aws:iam::000000000000:role/root ``` </details> * If present, please add links to the (official) documentation for clarification. - > Every output artifact in the pipeline must have a unique name. [Source](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome-introducing-artifacts.html) * Validate if the issue still exists with the latest version of `cfn-lint` and/or the latest Spec files: :heavy_check_mark: `0.35.1` is the latest version Cfn-lint uses the [CloudFormation Resource Specifications](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) as the base to do validation. These files are included as part of the application version. Please update to the latest version of `cfn-lint` or update the spec files manually (`cfn-lint -u`) :heavy_check_mark: I have also tried after running `cfn-lint -u`
2020-09-11T15:16:38Z
[]
[]
aws-cloudformation/cfn-lint
1,714
aws-cloudformation__cfn-lint-1714
[ "1713" ]
ad22c9a1c6cd20853ec91db4bcd1808ebbaad4e3
diff --git a/src/cfnlint/rules/__init__.py b/src/cfnlint/rules/__init__.py --- a/src/cfnlint/rules/__init__.py +++ b/src/cfnlint/rules/__init__.py @@ -232,12 +232,30 @@ def resource_property(self, filename, cfn, path, properties, resource_type, prop if property_spec_name in property_spec: for rule in self.rules: - matches.extend( - self.run_check( - rule.matchall_resource_sub_properties, filename, rule.id, - filename, cfn, properties, property_spec_name, path + if isinstance(properties, dict): + if len(properties) == 1: + for k, _ in properties.items(): + if k != 'Fn::If': + matches.extend( + self.run_check( + rule.matchall_resource_sub_properties, filename, rule.id, + filename, cfn, properties, property_spec_name, path + ) + ) + else: + matches.extend( + self.run_check( + rule.matchall_resource_sub_properties, filename, rule.id, + filename, cfn, properties, property_spec_name, path + ) + ) + else: + matches.extend( + self.run_check( + rule.matchall_resource_sub_properties, filename, rule.id, + filename, cfn, properties, property_spec_name, path + ) ) - ) resource_spec_properties = property_spec.get(property_spec_name, {}).get('Properties') if not resource_spec_properties: @@ -259,10 +277,17 @@ def resource_property(self, filename, cfn, path, properties, resource_type, prop if isinstance(resource_property_value, list): if len(resource_property_value) == 3: for index, c_value in enumerate(resource_property_value[1:]): - matches.extend(self.resource_property( - filename, cfn, - property_path[:] + [index + 1], - c_value, resource_type, property_type)) + if isinstance(c_value, list): + for s_i, c_l_value in enumerate(c_value): + matches.extend(self.resource_property( + filename, cfn, + property_path[:] + [index + 1] + [s_i], + c_l_value, resource_type, property_type)) + else: + matches.extend(self.resource_property( + filename, cfn, + property_path[:] + [index + 1], + c_value, resource_type, property_type)) continue if (resource_spec_property.get('Type') == 'List' and not resource_spec_properties.get('PrimitiveItemType')): diff --git a/src/cfnlint/rules/resources/properties/Properties.py b/src/cfnlint/rules/resources/properties/Properties.py --- a/src/cfnlint/rules/resources/properties/Properties.py +++ b/src/cfnlint/rules/resources/properties/Properties.py @@ -245,9 +245,17 @@ def propertycheck(self, text, proptype, parenttype, resourcename, path, root): if prop in cfnlint.helpers.CONDITION_FUNCTIONS and len_of_text == 1: cond_values = self.cfn.get_condition_values(text[prop]) for cond_value in cond_values: - matches.extend(self.propertycheck( - cond_value['Value'], proptype, parenttype, resourcename, - proppath + cond_value['Path'], root)) + if isinstance(cond_value['Value'], dict): + matches.extend(self.propertycheck( + cond_value['Value'], proptype, parenttype, resourcename, + proppath + cond_value['Path'], root)) + elif isinstance(cond_value['Value'], list): + for index, item in enumerate(cond_value['Value']): + matches.extend( + self.propertycheck( + item, proptype, parenttype, resourcename, + proppath + cond_value['Path'] + [index], root) + ) elif text.is_function_returning_object(): self.logger.debug('Ran into function "%s". Skipping remaining checks', prop) elif len(text) == 1 and prop in 'Ref' and text.get(prop) == 'AWS::NoValue':
diff --git a/test/fixtures/templates/good/resource_properties.yaml b/test/fixtures/templates/good/resource_properties.yaml --- a/test/fixtures/templates/good/resource_properties.yaml +++ b/test/fixtures/templates/good/resource_properties.yaml @@ -312,6 +312,7 @@ Parameters: Type: "CommaDelimitedList" Default: "foo.com, bar.com" Conditions: + S3ReplicationEnabled: !Equals [!Ref 'AWS::Region', 'us-east'] HasSingleClusterInstance: !Equals [!Ref 'AWS::Region', 'us-east-1'] Conditions: ConditionTrue: @@ -727,3 +728,15 @@ Resources: - Type: BASE_REF Pattern: ^refs/heads/master$ ExcludeMatchedPattern: false + CloudAvailS3Bucket: + Type: AWS::S3::Bucket + Properties: + ReplicationConfiguration: !If + - S3ReplicationEnabled + - - Role: !GetAtt CloudAvailReplicationRole.Arn + Rules: + - Destination: + Bucket: arn:aws:s3:::cloudavail.replication.bucket + Status: Enabled + + - - !Ref "AWS::NoValue"
Using If Condition for AWS::S3::Bucket ReplicationConfiguration property *cfn-lint version: (`cfn-lint --version`)* cfn-lint 0.34.0 ``` E3002 Expecting an object at Resources/CloudAvailS3Bucket/Properties/ReplicationConfiguration/Fn::If/1 devops/infra/cloudavail.yaml:146:11 E3002 Expecting an object at Resources/CloudAvailS3Bucket/Properties/ReplicationConfiguration/Fn::If/2 ``` ``` CloudAvailS3Bucket: Type: AWS::S3::Bucket ReplicationConfiguration: !If - S3ReplicationEnabled - - Role: !GetAtt CloudAvailReplicationRole.Arn Rules: - Destination: Bucket: arn:aws:s3:::cloudavail.replication.bucket Status: Enabled - - !Ref "AWS::NoValue" ```
2020-09-24T16:52:24Z
[]
[]
aws-cloudformation/cfn-lint
1,750
aws-cloudformation__cfn-lint-1750
[ "1084" ]
b7815fed1bc6ffc255bff816d8b884fec67b5f11
diff --git a/src/cfnlint/helpers.py b/src/cfnlint/helpers.py --- a/src/cfnlint/helpers.py +++ b/src/cfnlint/helpers.py @@ -79,34 +79,6 @@ REGEX_DYN_REF_SSM_SECURE = re.compile(r'^.*{{resolve:ssm-secure:[a-zA-Z0-9_\.\-/]+:\d+}}.*$') -AVAILABILITY_ZONES = [ - 'af-south-1a', 'af-south-1b', 'af-south-1c', - 'ap-east-1a', 'ap-east-1b', 'ap-east-1c', - 'ap-northeast-1a', 'ap-northeast-1b', 'ap-northeast-1c', 'ap-northeast-1d', - 'ap-northeast-2a', 'ap-northeast-2b', 'ap-northeast-2c', 'ap-northeast-2d', - 'ap-northeast-3a', - 'ap-south-1a', 'ap-south-1b', 'ap-south-1c', - 'ap-southeast-1a', 'ap-southeast-1b', 'ap-southeast-1c', - 'ap-southeast-2a', 'ap-southeast-2b', 'ap-southeast-2c', - 'ca-central-1a', 'ca-central-1b', 'ca-central-1d', - 'cn-north-1a', 'cn-north-1b', - 'cn-northwest-1a', 'cn-northwest-1b', 'cn-northwest-1c', - 'eu-central-1a', 'eu-central-1b', 'eu-central-1c', - 'eu-north-1a', 'eu-north-1b', 'eu-north-1c', - 'eu-south-1a', 'eu-south-1b', 'eu-south-1c', - 'eu-west-1a', 'eu-west-1b', 'eu-west-1c', - 'eu-west-2a', 'eu-west-2b', 'eu-west-2c', - 'eu-west-3a', 'eu-west-3b', 'eu-west-3c', - 'me-south-1a', 'me-south-1b', 'me-south-1c', - 'sa-east-1a', 'sa-east-1b', 'sa-east-1c', - 'us-east-1a', 'us-east-1b', 'us-east-1c', 'us-east-1d', 'us-east-1e', 'us-east-1f', - 'us-east-2a', 'us-east-2b', 'us-east-2c', - 'us-gov-east-1a', 'us-gov-east-1b', 'us-gov-east-1c', - 'us-gov-west-1a', 'us-gov-west-1b', 'us-gov-west-1c', - 'us-west-1a', 'us-west-1b', 'us-west-1c', - 'us-west-2a', 'us-west-2b', 'us-west-2c', 'us-west-2d', 'us-west-2-lax-1a', 'us-west-2-lax-1b', -] - FUNCTIONS = [ 'Fn::Base64', 'Fn::GetAtt', 'Fn::GetAZs', 'Fn::ImportValue', 'Fn::Join', 'Fn::Split', 'Fn::FindInMap', 'Fn::Select', 'Ref', diff --git a/src/cfnlint/rules/parameters/AllowedPattern.py b/src/cfnlint/rules/parameters/AllowedPattern.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/parameters/AllowedPattern.py @@ -0,0 +1,120 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +import re +import six +from cfnlint.rules import CloudFormationLintRule +from cfnlint.rules import RuleMatch + +from cfnlint.helpers import RESOURCE_SPECS + + +class AllowedPattern(CloudFormationLintRule): + """Check if parameters have a valid value""" + id = 'W2031' + shortdesc = 'Check if parameters have a valid value based on an allowed pattern' + description = 'Check if parameters have a valid value in a pattern. The Parameter\'s allowed pattern is based on the usages in property (Ref)' + source_url = 'https://github.com/aws-cloudformation/cfn-python-lint/blob/master/docs/cfn-resource-specification.md#allowedpattern' + tags = ['parameters', 'resources', 'property', 'allowed pattern'] + + def initialize(self, cfn): + """Initialize the rule""" + for resource_type_spec in RESOURCE_SPECS.get(cfn.regions[0]).get('ResourceTypes'): + self.resource_property_types.append(resource_type_spec) + for property_type_spec in RESOURCE_SPECS.get(cfn.regions[0]).get('PropertyTypes'): + self.resource_sub_property_types.append(property_type_spec) + + def check_value_ref(self, value, path, **kwargs): + """Check Ref""" + matches = [] + + cfn = kwargs.get('cfn') + if 'Fn::If' in path: + self.logger.debug( + 'Not able to guarentee that the default value hasn\'t been conditioned out') + return matches + if path[0] == 'Resources' and 'Condition' in cfn.template.get( + path[0], {}).get(path[1]): + self.logger.debug( + 'Not able to guarentee that the default value ' + 'hasn\'t been conditioned out') + return matches + + allowed_pattern = kwargs.get('value_specs', {}).get('AllowedPattern', {}) + allowed_pattern_regex = kwargs.get('value_specs', {}).get('AllowedPatternRegex', {}) + allowed_pattern_description = kwargs.get('value_specs', {}).get('AllowedPatternDescription', {}) + + if allowed_pattern_regex: + if value in cfn.template.get('Parameters', {}): + param = cfn.template.get('Parameters').get(value, {}) + parameter_values = param.get('AllowedValues') + default_value = param.get('Default') + parameter_type = param.get('Type') + if isinstance(parameter_type, six.string_types): + if ((not parameter_type.startswith('List<')) and + (not parameter_type.startswith('AWS::SSM::Parameter::Value<')) and + parameter_type not in ['CommaDelimitedList', 'List<String>']): + # Check Allowed Values + if parameter_values: + for index, allowed_value in enumerate(parameter_values): + if not re.match(allowed_pattern_regex, str(allowed_value)): + param_path = ['Parameters', value, 'AllowedValues', index] + description = allowed_pattern_description or 'Valid values must match pattern {0}'.format(allowed_pattern) + message = 'You must specify a valid allowed value for {0} ({1}).\n{2}' + matches.append(RuleMatch(param_path, message.format( + value, allowed_value, description))) + if default_value: + # Check Default, only if no allowed Values are specified in the parameter (that's covered by E2015) + if not re.match(allowed_pattern_regex, str(default_value)): + param_path = ['Parameters', value, 'Default'] + description = allowed_pattern_description or 'Valid values must match pattern {0}'.format(allowed_pattern) + message = 'You must specify a valid Default value for {0} ({1}).\n{2}' + matches.append(RuleMatch(param_path, message.format( + value, default_value, description))) + + return matches + + def check(self, cfn, properties, value_specs, property_specs, path): + """Check itself""" + matches = list() + for p_value, p_path in properties.items_safe(path[:]): + for prop in p_value: + if prop in value_specs: + value = value_specs.get(prop).get('Value', {}) + if value: + value_type = value.get('ValueType', '') + property_type = property_specs.get('Properties').get(prop).get('Type') + matches.extend( + cfn.check_value( + p_value, prop, p_path, + check_ref=self.check_value_ref, + value_specs=RESOURCE_SPECS.get(cfn.regions[0]).get( + 'ValueTypes').get(value_type, {}), + cfn=cfn, property_type=property_type, property_name=prop + ) + ) + + return matches + + def match_resource_sub_properties(self, properties, property_type, path, cfn): + """Match for sub properties""" + matches = list() + + specs = RESOURCE_SPECS.get(cfn.regions[0]).get( + 'PropertyTypes').get(property_type, {}).get('Properties', {}) + property_specs = RESOURCE_SPECS.get(cfn.regions[0]).get('PropertyTypes').get(property_type) + matches.extend(self.check(cfn, properties, specs, property_specs, path)) + + return matches + + def match_resource_properties(self, properties, resource_type, path, cfn): + """Check CloudFormation Properties""" + matches = list() + + specs = RESOURCE_SPECS.get(cfn.regions[0]).get( + 'ResourceTypes').get(resource_type, {}).get('Properties', {}) + resource_specs = RESOURCE_SPECS.get(cfn.regions[0]).get('ResourceTypes').get(resource_type) + matches.extend(self.check(cfn, properties, specs, resource_specs, path)) + + return matches diff --git a/src/cfnlint/rules/parameters/Cidr.py b/src/cfnlint/rules/parameters/Cidr.py deleted file mode 100644 --- a/src/cfnlint/rules/parameters/Cidr.py +++ /dev/null @@ -1,112 +0,0 @@ -""" -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: MIT-0 -""" -from cfnlint.rules import CloudFormationLintRule -from cfnlint.rules import RuleMatch - -from cfnlint.helpers import REGEX_CIDR - - -class Cidr(CloudFormationLintRule): - """CIDR checks""" - id = 'W2509' - shortdesc = 'CIDR Parameters have allowed values' - description = 'Check if a parameter is being used as a CIDR. ' \ - 'If it is make sure it has allowed values regex comparisons' - source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html' - tags = ['parameters', 'cidr'] - - def __init__(self): - """Init""" - super(Cidr, self).__init__() - resource_type_specs = [ - 'AWS::EC2::ClientVpnAuthorizationRule', - 'AWS::EC2::ClientVpnEndpoint', - 'AWS::EC2::ClientVpnRoute', - 'AWS::EC2::NetworkAclEntry', - 'AWS::EC2::Route', - 'AWS::EC2::SecurityGroupEgress', - 'AWS::EC2::SecurityGroupIngress', - 'AWS::EC2::Subnet', - 'AWS::EC2::TransitGatewayRoute', - 'AWS::EC2::VPC', - 'AWS::EC2::VPCCidrBlock', - 'AWS::EC2::VPNConnectionRoute', - 'AWS::RDS::DBSecurityGroupIngress', - 'AWS::Redshift::ClusterSecurityGroupIngress', - ] - - property_type_specs = [ - 'AWS::EC2::SecurityGroup.Egress', - 'AWS::EC2::SecurityGroup.Ingress', - 'AWS::EC2::VPNConnection.VpnTunnelOptionsSpecification', - 'AWS::MediaLive::InputSecurityGroup.InputWhitelistRuleCidr', - 'AWS::RDS::DBSecurityGroup.Ingress', - 'AWS::SES::ReceiptFilter.IpFilter', - ] - - for resource_type_spec in resource_type_specs: - self.resource_property_types.append(resource_type_spec) - for property_type_spec in property_type_specs: - self.resource_sub_property_types.append(property_type_spec) - - # pylint: disable=W0613 - def check_cidr_ref(self, value, path, parameters, resources): - matches = [] - - if value in parameters: - parameter = parameters.get(value, {}) - parameter_type = parameter.get('Type') - allowed_pattern = parameter.get('AllowedPattern', None) - allowed_values = parameter.get('AllowedValues', None) - if parameter_type not in ['AWS::SSM::Parameter::Value<String>']: - if not allowed_pattern and not allowed_values: - param_path = ['Parameters', value] - full_param_path = '/'.join(param_path) - message = 'AllowedPattern and/or AllowedValues for Parameter should be specified at {1}. ' \ - 'Example for AllowedPattern: \'{0}\'' - matches.append(RuleMatch(param_path, message.format( - REGEX_CIDR.pattern, full_param_path))) - - return matches - - def check(self, properties, resource_type, path, cfn): - """Check itself""" - matches = [] - - for cidrString in [ - 'CIDRIP', - 'Cidr', - 'CidrBlock', - 'CidrIp', - 'ClientCidrBlock', - 'DestinationCidrBlock', - 'TargetNetworkCidr', - 'TunnelInsideCidr', - ]: - matches.extend( - cfn.check_value( - properties, cidrString, path, - check_value=None, check_ref=self.check_cidr_ref, - check_find_in_map=None, check_split=None, check_join=None - ) - ) - - return matches - - def match_resource_sub_properties(self, properties, property_type, path, cfn): - """Match for sub properties""" - matches = [] - - matches.extend(self.check(properties, property_type, path, cfn)) - - return matches - - def match_resource_properties(self, properties, resource_type, path, cfn): - """Check CloudFormation Properties""" - matches = [] - - matches.extend(self.check(properties, resource_type, path, cfn)) - - return matches diff --git a/src/cfnlint/rules/parameters/CidrAllowedValues.py b/src/cfnlint/rules/parameters/CidrAllowedValues.py deleted file mode 100644 --- a/src/cfnlint/rules/parameters/CidrAllowedValues.py +++ /dev/null @@ -1,114 +0,0 @@ -""" -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: MIT-0 -""" -import re -from cfnlint.rules import CloudFormationLintRule -from cfnlint.rules import RuleMatch - -from cfnlint.helpers import REGEX_CIDR - - -class CidrAllowedValues(CloudFormationLintRule): - """CIDR checks""" - id = 'E2004' - shortdesc = 'CIDR Allowed Values should be a Cidr Range' - description = 'Check if a parameter is being used as a CIDR. ' \ - 'If it is make sure allowed values are proper CIDRs' - source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html' - tags = ['parameters', 'cidr'] - - def __init__(self): - """Init""" - super(CidrAllowedValues, self).__init__() - resource_type_specs = [ - 'AWS::EC2::ClientVpnAuthorizationRule', - 'AWS::EC2::ClientVpnEndpoint', - 'AWS::EC2::ClientVpnRoute', - 'AWS::EC2::NetworkAclEntry', - 'AWS::EC2::Route', - 'AWS::EC2::SecurityGroupEgress', - 'AWS::EC2::SecurityGroupIngress', - 'AWS::EC2::Subnet', - 'AWS::EC2::TransitGatewayRoute', - 'AWS::EC2::VPC', - 'AWS::EC2::VPCCidrBlock', - 'AWS::EC2::VPNConnectionRoute', - 'AWS::RDS::DBSecurityGroupIngress', - 'AWS::Redshift::ClusterSecurityGroupIngress', - ] - - property_type_specs = [ - 'AWS::EC2::SecurityGroup.Egress', - 'AWS::EC2::SecurityGroup.Ingress', - 'AWS::EC2::VPNConnection.VpnTunnelOptionsSpecification', - 'AWS::MediaLive::InputSecurityGroup.InputWhitelistRuleCidr', - 'AWS::RDS::DBSecurityGroup.Ingress', - 'AWS::SES::ReceiptFilter.IpFilter', - ] - - for resource_type_spec in resource_type_specs: - self.resource_property_types.append(resource_type_spec) - for property_type_spec in property_type_specs: - self.resource_sub_property_types.append(property_type_spec) - - # pylint: disable=W0613 - def check_cidr_ref(self, value, path, parameters, resources): - matches = [] - - if value in parameters: - parameter = parameters.get(value, {}) - parameter_type = parameters.get(value, {}).get('Type', '') - if parameter_type == 'AWS::SSM::Parameter::Value<String>': - # If we are reading from the Parameter store we can no longer - # check the value of the allowed values - return matches - allowed_values = parameter.get('AllowedValues', None) - if allowed_values: - for cidr in allowed_values: - if not re.match(REGEX_CIDR, cidr): - cidr_path = ['Parameters', value] - message = 'Cidr should be a Cidr Range based string for {0}' - matches.append(RuleMatch(cidr_path, message.format(cidr))) - - return matches - - def check(self, properties, resource_type, path, cfn): - """Check itself""" - matches = [] - - for cidrString in [ - 'CIDRIP', - 'Cidr', - 'CidrBlock', - 'CidrIp', - 'ClientCidrBlock', - 'DestinationCidrBlock', - 'TargetNetworkCidr', - 'TunnelInsideCidr', - ]: - matches.extend( - cfn.check_value( - properties, cidrString, path, - check_value=None, check_ref=self.check_cidr_ref, - check_find_in_map=None, check_split=None, check_join=None - ) - ) - - return matches - - def match_resource_sub_properties(self, properties, property_type, path, cfn): - """Match for sub properties""" - matches = [] - - matches.extend(self.check(properties, property_type, path, cfn)) - - return matches - - def match_resource_properties(self, properties, resource_type, path, cfn): - """Check CloudFormation Properties""" - matches = [] - - matches.extend(self.check(properties, resource_type, path, cfn)) - - return matches diff --git a/src/cfnlint/rules/resources/ectwo/Subnet.py b/src/cfnlint/rules/resources/ectwo/Subnet.py deleted file mode 100644 --- a/src/cfnlint/rules/resources/ectwo/Subnet.py +++ /dev/null @@ -1,137 +0,0 @@ -""" -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: MIT-0 -""" -import re -from cfnlint.rules import CloudFormationLintRule -from cfnlint.rules import RuleMatch -from cfnlint.helpers import AVAILABILITY_ZONES, REGEX_CIDR - - -class Subnet(CloudFormationLintRule): - """Check if EC2 Subnet Resource Properties""" - id = 'E2510' - shortdesc = 'Resource EC2 PropertiesEc2Subnet Properties' - description = 'See if EC2 Subnet Properties are set correctly' - source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html' - tags = ['properties', 'ec2', 'subnet'] - - def check_az_value(self, value, path): - """Check AZ Values""" - matches = [] - - if value not in AVAILABILITY_ZONES: - message = 'Not a valid Availbility Zone {0} at {1}' - matches.append(RuleMatch(path, message.format(value, ('/'.join(map(str, path)))))) - return matches - - def check_az_ref(self, value, path, parameters, resources): - """Check ref for AZ""" - matches = [] - allowed_types = [ - 'AWS::EC2::AvailabilityZone::Name', - 'String', - 'AWS::SSM::Parameter::Value<AWS::EC2::AvailabilityZone::Name>' - ] - if value in resources: - message = 'AvailabilityZone can\'t use a Ref to a resource for {0}' - matches.append(RuleMatch(path, message.format(('/'.join(map(str, path)))))) - elif value in parameters: - parameter = parameters.get(value, {}) - param_type = parameter.get('Type', '') - if param_type not in allowed_types: - param_path = ['Parameters', value, 'Type'] - message = 'Availability Zone should be of type [{0}] for {1}' - matches.append( - RuleMatch( - param_path, - message.format( - ', '.join(map(str, allowed_types)), - '/'.join(map(str, param_path))))) - return matches - - def check_cidr_value(self, value, path): - """Check CIDR Strings""" - matches = [] - - if not re.match(REGEX_CIDR, value): - message = 'CidrBlock needs to be of x.x.x.x/y at {0}' - matches.append(RuleMatch(path, message.format(('/'.join(['Parameters', value]))))) - return matches - - def check_cidr_ref(self, value, path, parameters, resources): - """Check CidrBlock for VPC""" - matches = [] - - allowed_types = [ - 'String', - 'AWS::SSM::Parameter::Value<String>' - ] - - if value in resources: - resource_obj = resources.get(value, {}) - if resource_obj: - resource_type = resource_obj.get('Type', '') - if not resource_type.startswith('Custom::'): - message = 'CidrBlock needs to be a valid Cidr Range at {0}' - matches.append(RuleMatch(path, message.format( - ('/'.join(['Parameters', value]))))) - if value in parameters: - parameter = parameters.get(value, {}) - parameter_type = parameter.get('Type', None) - if parameter_type not in allowed_types: - param_path = ['Parameters', value] - message = 'CidrBlock Parameter should be of type [{0}] for {1}' - matches.append( - RuleMatch( - param_path, - message.format( - ', '.join(map(str, allowed_types)), - '/'.join(map(str, param_path))))) - return matches - - def check_vpc_value(self, value, path): - """Check VPC Values""" - matches = [] - - if not value.startswith('vpc-'): - message = 'VpcId needs to be of format vpc-xxxxxxxx at {1}' - matches.append(RuleMatch(path, message.format(value, ('/'.join(map(str, path)))))) - return matches - - def check_vpc_ref(self, value, path, parameters, resources): - """Check ref for VPC""" - matches = [] - if value in resources: - # Check if resource is a VPC - message = 'VpcId can\'t use a Ref to a resource for {0}' - matches.append(RuleMatch(path, message.format(('/'.join(map(str, path)))))) - elif value in parameters: - parameter = parameters.get(value, {}) - param_type = parameter.get('Type', '') - if param_type != 'AWS::EC2::AvailabilityZone::Name': - param_path = ['Parameters', value, 'Type'] - message = 'Type for Parameter should be AWS::EC2::AvailabilityZone::Name for {0}' - matches.append(RuleMatch(param_path, message.format(('/'.join(param_path))))) - return matches - - def match(self, cfn): - """Check EC2 VPC Resource Parameters""" - - matches = [] - matches.extend( - cfn.check_resource_property( - 'AWS::EC2::Subnet', 'AvailabilityZone', - check_value=self.check_az_value, - check_ref=self.check_az_ref, - ) - ) - matches.extend( - cfn.check_resource_property( - 'AWS::EC2::Subnet', 'CidrBlock', - check_value=self.check_cidr_value, - check_ref=self.check_cidr_ref, - ) - ) - - return matches diff --git a/src/cfnlint/rules/resources/ectwo/Vpc.py b/src/cfnlint/rules/resources/ectwo/Vpc.py deleted file mode 100644 --- a/src/cfnlint/rules/resources/ectwo/Vpc.py +++ /dev/null @@ -1,79 +0,0 @@ -""" -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: MIT-0 -""" -import re -from cfnlint.rules import CloudFormationLintRule -from cfnlint.rules import RuleMatch - -import cfnlint.helpers - - -class Vpc(CloudFormationLintRule): - """Check if EC2 VPC Resource Properties""" - id = 'E2505' - shortdesc = 'Resource EC2 VPC Properties' - description = 'Check if the default tenancy is default or dedicated and that CidrBlock is a valid CIDR range.' - source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html' - tags = ['properties', 'ec2', 'vpc'] - - def check_cidr_value(self, value, path): - """Check CIDR Strings""" - matches = [] - - if not re.match(cfnlint.helpers.REGEX_CIDR, value): - message = 'CidrBlock needs to be of x.x.x.x/y at {0}' - matches.append(RuleMatch(path, message.format(('/'.join(['Parameters', value]))))) - else: - # CHeck the netmask block, has to be between /16 and /28 - netmask = int(value.split('/')[1]) - - if netmask < 16 or netmask > 28: - message = 'VPC Cidrblock netmask ({}) must be between /16 and /28' - matches.append(RuleMatch(path, message.format(value))) - - return matches - - def check_cidr_ref(self, value, path, parameters, resources): - """Check CidrBlock for VPC""" - matches = [] - - allowed_types = [ - 'String', - 'AWS::SSM::Parameter::Value<String>', - ] - if value in resources: - resource_obj = resources.get(value, {}) - if resource_obj: - resource_type = resource_obj.get('Type', '') - if not cfnlint.helpers.is_custom_resource(resource_type): - message = 'CidrBlock needs to be a valid Cidr Range at {0}' - matches.append(RuleMatch(path, message.format( - ('/'.join(['Parameters', value]))))) - if value in parameters: - parameter = parameters.get(value, {}) - parameter_type = parameter.get('Type', None) - if parameter_type not in allowed_types: - path_error = ['Parameters', value, 'Type'] - message = 'CidrBlock parameter should be of type [{0}] for {1}' - matches.append( - RuleMatch( - path_error, - message.format( - ', '.join(map(str, allowed_types)), - '/'.join(map(str, path_error))))) - return matches - - def match(self, cfn): - """Check EC2 VPC Resource Parameters""" - - matches = [] - matches.extend( - cfn.check_resource_property( - 'AWS::EC2::VPC', 'CidrBlock', - check_value=self.check_cidr_value, - check_ref=self.check_cidr_ref, - ) - ) - - return matches
diff --git a/test/fixtures/results/quickstart/nist_application.json b/test/fixtures/results/quickstart/nist_application.json --- a/test/fixtures/results/quickstart/nist_application.json +++ b/test/fixtures/results/quickstart/nist_application.json @@ -78,56 +78,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html#parmtypes" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 18, - "LineNumber": 182 - }, - "Path": [ - "Parameters", - "pManagementCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 182 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pManagementCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 18, - "LineNumber": 185 - }, - "Path": [ - "Parameters", - "pProductionCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 185 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pProductionCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", "Level": "Warning", diff --git a/test/fixtures/results/quickstart/nist_vpc_management.json b/test/fixtures/results/quickstart/nist_vpc_management.json --- a/test/fixtures/results/quickstart/nist_vpc_management.json +++ b/test/fixtures/results/quickstart/nist_vpc_management.json @@ -74,181 +74,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html#parmtypes" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_management.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 18, - "LineNumber": 200 - }, - "Path": [ - "Parameters", - "pBastionSSHCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 200 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pBastionSSHCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_management.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 18, - "LineNumber": 232 - }, - "Path": [ - "Parameters", - "pManagementCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 232 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pManagementCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_management.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 28, - "LineNumber": 236 - }, - "Path": [ - "Parameters", - "pManagementDMZSubnetACIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 236 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pManagementDMZSubnetACIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_management.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 28, - "LineNumber": 240 - }, - "Path": [ - "Parameters", - "pManagementDMZSubnetBCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 240 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pManagementDMZSubnetBCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_management.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 32, - "LineNumber": 244 - }, - "Path": [ - "Parameters", - "pManagementPrivateSubnetACIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 244 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pManagementPrivateSubnetACIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_management.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 32, - "LineNumber": 248 - }, - "Path": [ - "Parameters", - "pManagementPrivateSubnetBCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 248 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pManagementPrivateSubnetBCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_management.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 18, - "LineNumber": 267 - }, - "Path": [ - "Parameters", - "pProductionCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 267 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pProductionCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_vpc_management.yaml", "Level": "Informational", diff --git a/test/fixtures/results/quickstart/nist_vpc_production.json b/test/fixtures/results/quickstart/nist_vpc_production.json --- a/test/fixtures/results/quickstart/nist_vpc_production.json +++ b/test/fixtures/results/quickstart/nist_vpc_production.json @@ -1,229 +1,4 @@ [ - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_production.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 25, - "LineNumber": 99 - }, - "Path": [ - "Parameters", - "pAppPrivateSubnetACIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 99 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pAppPrivateSubnetACIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_production.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 25, - "LineNumber": 103 - }, - "Path": [ - "Parameters", - "pAppPrivateSubnetBCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 103 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pAppPrivateSubnetBCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_production.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 18, - "LineNumber": 107 - }, - "Path": [ - "Parameters", - "pBastionSSHCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 107 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pBastionSSHCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_production.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 24, - "LineNumber": 111 - }, - "Path": [ - "Parameters", - "pDBPrivateSubnetACIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 111 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pDBPrivateSubnetACIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_production.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 24, - "LineNumber": 115 - }, - "Path": [ - "Parameters", - "pDBPrivateSubnetBCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 115 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pDBPrivateSubnetBCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_production.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 18, - "LineNumber": 119 - }, - "Path": [ - "Parameters", - "pDMZSubnetACIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 119 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pDMZSubnetACIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_production.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 18, - "LineNumber": 123 - }, - "Path": [ - "Parameters", - "pDMZSubnetBCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 123 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pDMZSubnetBCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_production.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 18, - "LineNumber": 135 - }, - "Path": [ - "Parameters", - "pManagementCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 135 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pManagementCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_vpc_production.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 18, - "LineNumber": 149 - }, - "Path": [ - "Parameters", - "pProductionCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 149 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pProductionCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_vpc_production.yaml", "Level": "Warning", diff --git a/test/fixtures/results/quickstart/non_strict/nist_application.json b/test/fixtures/results/quickstart/non_strict/nist_application.json --- a/test/fixtures/results/quickstart/non_strict/nist_application.json +++ b/test/fixtures/results/quickstart/non_strict/nist_application.json @@ -78,56 +78,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html#parmtypes" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 18, - "LineNumber": 182 - }, - "Path": [ - "Parameters", - "pManagementCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 182 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pManagementCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Warning", - "Location": { - "End": { - "ColumnNumber": 18, - "LineNumber": 185 - }, - "Path": [ - "Parameters", - "pProductionCIDR" - ], - "Start": { - "ColumnNumber": 3, - "LineNumber": 185 - } - }, - "Message": "AllowedPattern and/or AllowedValues for Parameter should be specified at Parameters/pProductionCIDR. Example for AllowedPattern: '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$'", - "Rule": { - "Description": "Check if a parameter is being used as a CIDR. If it is make sure it has allowed values regex comparisons", - "Id": "W2509", - "ShortDescription": "CIDR Parameters have allowed values", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", "Level": "Warning", diff --git a/test/fixtures/templates/bad/properties_ec2_network.yaml b/test/fixtures/templates/bad/properties_ec2_network.yaml deleted file mode 100644 --- a/test/fixtures/templates/bad/properties_ec2_network.yaml +++ /dev/null @@ -1,54 +0,0 @@ ---- -AWSTemplateFormatVersion: "2010-09-09" -Description: > - AWS EC2 Good Template -Parameters: - cidrBlock: - Type: Number - cidrBlockAllowedValues: - Type: String - AllowedValues: - - '127.0.0.1' - - '8.8.8.8' - - 'notacidr' - vpcTenancy: - Type: String - AllowedValues: - - default2 - - dedicated - myAz: - Type: Number -Resources: - myVpc1: - Type: AWS::EC2::VPC - Properties: - CidrBlock: !Ref cidrBlock - InstanceTenancy: bad - myVpc2: - Type: AWS::EC2::VPC - Properties: - InstanceTenancy: !Ref myVpc1 - CidrBlock: 10.0.0.3 - myVpc3: - Type: AWS::EC2::VPC - Properties: - InstanceTenancy: !Ref vpcTenancy - CidrBlock: !Ref cidrBlockAllowedValues - myVpc4: - Type: AWS::EC2::VPC - Properties: - InstanceTenancy: !Ref vpcTenancy - CidrBlock: "10.0.0.8/8" - mySubnet2-1: - Type: AWS::EC2::Subnet - Properties: - CidrBlock: 10.0.1.0/64 - mySubnet2-2: - Type: AWS::EC2::Subnet - Properties: - AvailabilityZone: us-east-3a - CidrBlock: !Ref cidrBlock - mySubnet3-1: - Type: AWS::EC2::Subnet - Properties: - AvailabilityZone: !Ref myAz diff --git a/test/unit/module/cfn_json/test_cfn_json.py b/test/unit/module/cfn_json/test_cfn_json.py --- a/test/unit/module/cfn_json/test_cfn_json.py +++ b/test/unit/module/cfn_json/test_cfn_json.py @@ -36,7 +36,7 @@ def setUp(self): }, "vpc_management": { "filename": 'test/fixtures/templates/quickstart/vpc-management.json', - "failures": 36 + "failures": 23 }, "vpc": { "filename": 'test/fixtures/templates/quickstart/vpc.json', diff --git a/test/unit/rules/parameters/test_cidr.py b/test/unit/rules/parameters/test_cidr.py deleted file mode 100644 --- a/test/unit/rules/parameters/test_cidr.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: MIT-0 -""" -from test.unit.rules import BaseRuleTestCase -from cfnlint.rules.parameters.Cidr import Cidr # pylint: disable=E0401 - - -class TestParameterCidr(BaseRuleTestCase): - """Test template parameter configurations""" - - def setUp(self): - """Setup""" - super(TestParameterCidr, self).setUp() - self.collection.register(Cidr()) - - success_templates = [ - 'test/fixtures/templates/good/functions_cidr.yaml', - 'test/fixtures/templates/good/properties_ec2_vpc.yaml', - ] - - def test_file_positive(self): - """Test Positive""" - self.helper_file_positive() - - def test_file_negative_nist_app(self): - """Failure test""" - self.helper_file_negative('test/fixtures/templates/quickstart/nist_application.yaml', 2) - - def test_file_negative_nist_mgmt(self): - """Failure test""" - self.helper_file_negative('test/fixtures/templates/quickstart/nist_vpc_management.yaml', 7) - - def test_file_negative_nist_prod(self): - """Failure test""" - self.helper_file_negative('test/fixtures/templates/quickstart/nist_vpc_production.yaml', 9) - - def test_file_negative(self): - """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/properties_ec2_network.yaml', 1) diff --git a/test/unit/rules/parameters/test_cidr_allowed_values.py b/test/unit/rules/parameters/test_cidr_allowed_values.py deleted file mode 100644 --- a/test/unit/rules/parameters/test_cidr_allowed_values.py +++ /dev/null @@ -1,27 +0,0 @@ -""" -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: MIT-0 -""" -from test.unit.rules import BaseRuleTestCase -from cfnlint.rules.parameters.CidrAllowedValues import CidrAllowedValues # pylint: disable=E0401 - - -class TestParameterCidrAllowedValues(BaseRuleTestCase): - """Test template parameter configurations""" - - def setUp(self): - """Setup""" - super(TestParameterCidrAllowedValues, self).setUp() - self.collection.register(CidrAllowedValues()) - - success_templates = [ - 'test/fixtures/templates/good/properties_ec2_vpc.yaml', - ] - - def test_file_positive(self): - """Test Positive""" - self.helper_file_positive() - - def test_file_negative(self): - """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/properties_ec2_network.yaml', 3) diff --git a/test/unit/rules/resources/ec2/test_ec2_subnet.py b/test/unit/rules/resources/ec2/test_ec2_subnet.py deleted file mode 100644 --- a/test/unit/rules/resources/ec2/test_ec2_subnet.py +++ /dev/null @@ -1,26 +0,0 @@ -""" -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: MIT-0 -""" -from test.unit.rules import BaseRuleTestCase -from cfnlint.rules.resources.ectwo.Subnet import Subnet # pylint: disable=E0401 - - -class TestPropertyEc2Subnet(BaseRuleTestCase): - """Test Ec2 Subnet Resources""" - - def setUp(self): - """Setup""" - super(TestPropertyEc2Subnet, self).setUp() - self.collection.register(Subnet()) - self.success_templates = [ - 'test/fixtures/templates/good/properties_ec2_vpc.yaml', - ] - - def test_file_positive(self): - """Test Positive""" - self.helper_file_positive() - - def test_file_negative(self): - """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/properties_ec2_network.yaml', 4) diff --git a/test/unit/rules/resources/ec2/test_ec2_vpc.py b/test/unit/rules/resources/ec2/test_ec2_vpc.py deleted file mode 100644 --- a/test/unit/rules/resources/ec2/test_ec2_vpc.py +++ /dev/null @@ -1,26 +0,0 @@ -""" -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: MIT-0 -""" -from test.unit.rules import BaseRuleTestCase -from cfnlint.rules.resources.ectwo.Vpc import Vpc # pylint: disable=E0401 - - -class TestPropertyEc2Vpc(BaseRuleTestCase): - """Test Ec2 VPC Resources""" - - def setUp(self): - """Setup""" - super(TestPropertyEc2Vpc, self).setUp() - self.collection.register(Vpc()) - self.success_templates = [ - 'test/fixtures/templates/good/properties_ec2_vpc.yaml', - ] - - def test_file_positive(self): - """Test Positive""" - self.helper_file_positive() - - def test_file_negative(self): - """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/properties_ec2_network.yaml', 3)
extend CIDR regex validation Rules [`W2509`](https://github.com/aws-cloudformation/cfn-python-lint/blob/master/src/cfnlint/rules/parameters/Cidr.py) and [`E2004`](https://github.com/aws-cloudformation/cfn-python-lint/blob/master/src/cfnlint/rules/parameters/CidrAllowedValues.py) check CIDR parameters have `AllowedPattern` and `AllowedValues` are CIDRs respectively ```yaml Resources: ReceiptFilter: Type: AWS::SES::ReceiptFilter Properties: Filter: IpFilter: Policy: Block Cidr: 0.0.0.0/999 ``` `Invalid CIDR block: 0.0.0.0/999 (Service: AmazonSimpleEmailService; Status Code: 400; Error Code: InvalidParameterValue; Request ID: )` * Inline values * Mappings * Parameter Defaults * evaluate AllowedPatterns
2020-10-22T23:13:28Z
[]
[]
aws-cloudformation/cfn-lint
1,767
aws-cloudformation__cfn-lint-1767
[ "1743" ]
3c2165a65b8deba5731067a060636913f2784540
diff --git a/src/cfnlint/rules/resources/lmbd/EventsLogGroupName.py b/src/cfnlint/rules/resources/lmbd/EventsLogGroupName.py --- a/src/cfnlint/rules/resources/lmbd/EventsLogGroupName.py +++ b/src/cfnlint/rules/resources/lmbd/EventsLogGroupName.py @@ -2,6 +2,7 @@ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ +import json from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch @@ -9,45 +10,41 @@ class EventsLogGroupName(CloudFormationLintRule): """Check if the settings of multiple subscriptions are included for one LogGroup""" id = 'E2529' - shortdesc = 'Check for duplicate Lambda events' - description = 'Check if there are any duplicate log groups in the Lambda event trigger element.' + shortdesc = 'Check for SubscriptionFilters have beyond 2 attachments to a CloudWatch Log Group' + description = 'The current limit for a CloudWatch Log Group is they can have 2 subscription filters. ' \ + 'We will look for duplicate LogGroupNames inside Subscription Filters and make sure they are within 2. ' \ + 'This doesn\'t account for any other subscription filters getting set.' source_url = 'https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#user-content-cloudwatchlogs' tags = ['resources', 'lambda'] + limit = 2 def check_events_subscription_duplicated(self, cfn): """Check if Lambda Events Subscription is duplicated""" matches = [] - message = 'You must specify the AWS::Serverless::Function event correctly. ' \ - 'LogGroups are duplicated. ' - - log_group_name_list = self.__get_log_group_name_list(cfn) - - if self.__is_duplicated(log_group_name_list): - matches.append( - RuleMatch( - 'path', message.format() + message = 'You can only have {} Subscription Filters per CloudWatch Log Group'.format(self.limit) + + log_group_paths = self.__get_log_group_name_list(cfn) + for _, c in log_group_paths.items(): + if len(c) > self.limit: + matches.append( + RuleMatch( + ['Resources', c[2]], message.format() + ) ) - ) return matches - def __is_duplicated(self, duplicate_list): - unique_list = self.__remove(duplicate_list) - return len(unique_list) != len(duplicate_list) - - def __remove(self, duplicate): - final_list = [] - for ele in duplicate: - if ele not in final_list: - final_list.append(ele) - return final_list - def __get_log_group_name_list(self, cfn): - log_group_name_list = [] + log_group_paths = {} for value in cfn.get_resources('AWS::Logs::SubscriptionFilter').items(): prop = value[1].get('Properties') - log_group_name_list.append(prop.get('LogGroupName')) - return log_group_name_list + log_group_name = json.dumps(prop.get('LogGroupName')) + + if log_group_name not in log_group_paths: + log_group_paths[log_group_name] = [] + + log_group_paths[log_group_name].append(value[0]) + return log_group_paths def match(self, cfn): """Check if Lambda Events Subscription is duplicated"""
diff --git a/test/fixtures/templates/bad/some_logs_stream_lambda.yaml b/test/fixtures/templates/bad/some_logs_stream_lambda.yaml --- a/test/fixtures/templates/bad/some_logs_stream_lambda.yaml +++ b/test/fixtures/templates/bad/some_logs_stream_lambda.yaml @@ -70,6 +70,11 @@ Resources: Properties: LogGroupName: !Ref FunctionALogGroup FilterPattern: "" + FunctionDLogGroup: + Type: CloudWatchLogs + Properties: + LogGroupName: !Ref FunctionALogGroup + FilterPattern: "" LogSubscriptionFunctionLogGroup: Type: AWS::Logs::LogGroup Properties:
E2529 error with multiple `AWS::Logs::SubscriptionFilter` resources. *cfn-lint version: 0.38.0* *[`E2529`](https://github.com/aws-cloudformation/cfn-python-lint/blob/master/docs/rules.md#E2529) error with multiple [`AWS::Logs::SubscriptionFilter`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-subscriptionfilter.html) resources.* I have a CloudFormation template (using AWS SAM) that has multiple SubscriptionFilters. These SubscriptionFilters have the same `LogGroupName`, which causes an `E2529` error despite these filters having separate FilterPatterns. The template passes the [`aws cloudformation validate-template`](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/validate-template.html) command. [`src/cfnlint/rules/resources/lmbd/EventsLogGroupName.py`](https://github.com/aws-cloudformation/cfn-python-lint/blob/master/src/cfnlint/rules/resources/lmbd/EventsLogGroupName.py) ``` MainFunctionLogGroup: Type: AWS::Logs::LogGroup Properties: RetentionInDays: 14 LogGroupName: !Join ["", [/aws/lambda/, !Ref MainFunction]] MainFunctionLogFilter: Type: AWS::Logs::SubscriptionFilter Properties: DestinationArn: !Ref LogIngestionARN FilterPattern: "FilterPattern1" LogGroupName: !Ref MainFunctionLogGroup SecondaryLogFilter: Type: AWS::Logs::SubscriptionFilter Properties: DestinationArn: !Ref LogIngestionARN FilterPattern: "FilterPattern2" LogGroupName: !Ref MainFunctionLogGroup ```
Few things here. - `aws cloudformation validate-template` isn't detailed enough to catch this error. I'm assuming this template deploys correctly? That is the most important thing. - It looks like the limit for Subscription Filters has increased to 2 from 1. See [current docs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/cloudwatch_limits_cwl.html) and what is in the [docs repo](https://github.com/awsdocs/amazon-cloudwatch-logs-user-guide/blob/master/doc_source/cloudwatch_limits_cwl.md). The error message for this rule isn't well written. It has to do with Serverless but also applies to any SubscriptionFilter so it should be cleaned up. Additionally I believe this rule is testing the limits of SubscriptionFilters which has been changed so we need to change this rule to the new standard..
2020-11-05T14:59:58Z
[]
[]
aws-cloudformation/cfn-lint
1,773
aws-cloudformation__cfn-lint-1773
[ "1766" ]
4ef277bb637c533582c2b10d3589b4aa3623f3bf
diff --git a/src/cfnlint/rules/resources/properties/Properties.py b/src/cfnlint/rules/resources/properties/Properties.py --- a/src/cfnlint/rules/resources/properties/Properties.py +++ b/src/cfnlint/rules/resources/properties/Properties.py @@ -23,6 +23,7 @@ def __init__(self): self.resourcetypes = {} self.propertytypes = {} self.parameternames = {} + self.intrinsictypes = {} def primitivetypecheck(self, value, primtype, proppath): """ @@ -238,6 +239,7 @@ def propertycheck(self, text, proptype, parenttype, resourcename, path, root): # return objects. FindInMap cannot directly return an object. len_of_text = len(text) + #pylint: disable=too-many-nested-blocks for prop in text: proppath = path[:] proppath.append(prop) @@ -315,6 +317,17 @@ def propertycheck(self, text, proptype, parenttype, resourcename, path, root): RuleMatch( proppath, message.format(prop, resourcename))) + else: + if len(text[prop]) == 1: + for k in text[prop].keys(): + def_intrinsic_type = self.intrinsictypes.get(k, {}) + if def_intrinsic_type: + if len(def_intrinsic_type.get('ReturnTypes')) == 1 and def_intrinsic_type.get('ReturnTypes')[0] == 'Singular': + message = 'Property {0} is using {1} when a List is needed for resource {2}' + matches.append( + RuleMatch( + proppath, + message.format(prop, k, resourcename))) else: message = 'Property {0} should be of type List for resource {1}' matches.append( @@ -340,6 +353,7 @@ def match(self, cfn): resourcespecs = cfnlint.helpers.RESOURCE_SPECS[cfn.regions[0]] self.resourcetypes = resourcespecs['ResourceTypes'] self.propertytypes = resourcespecs['PropertyTypes'] + self.intrinsictypes = resourcespecs['IntrinsicTypes'] self.parameternames = self.cfn.get_parameter_names() for resourcename, resourcevalue in cfn.get_resources().items(): if 'Properties' in resourcevalue and 'Type' in resourcevalue:
diff --git a/test/fixtures/templates/bad/resource_properties.yaml b/test/fixtures/templates/bad/resource_properties.yaml --- a/test/fixtures/templates/bad/resource_properties.yaml +++ b/test/fixtures/templates/bad/resource_properties.yaml @@ -35,3 +35,16 @@ Resources: UserData: !Ref AWS::NotificationARNs Tags: - Key: Test + LambdaFunction: + Type: 'AWS::Lambda::Function' + Properties: + Runtime: java8 + Code: + S3Bucket: 'foo-bar' + S3Key: 'foo-bar' + S3ObjectVersion: 'foo-bar' + Handler: 'com.foo.bar::handleRequest' + Role: 'arn:aws:iam::123456789101:role/foo-bar' + VpcConfig: + SubnetIds: !ImportValue foobar1 + SecurityGroupIds: !ImportValue foobar2 diff --git a/test/unit/rules/resources/properties/test_properties.py b/test/unit/rules/resources/properties/test_properties.py --- a/test/unit/rules/resources/properties/test_properties.py +++ b/test/unit/rules/resources/properties/test_properties.py @@ -35,7 +35,7 @@ def test_file_negative_2(self): def test_file_negative_3(self): """Failure test""" - self.helper_file_negative('test/fixtures/templates/bad/resource_properties.yaml', 5) + self.helper_file_negative('test/fixtures/templates/bad/resource_properties.yaml', 7) def test_E3012_in_bad_template(self): """Test E3012 in known-bad template"""
Using ImportValue skips List type resource validation *cfn-lint version: (`cfn-lint --version`)* cfn-lint 0.40.0 *Description of issue.* When we use [`Fn::ImportValue`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) for a resource key that needs type List, it accepts a scalar value and cfn-lint doesn't fail. But when we use scalar value directly it works as expected and fails. Following template needs `SubnetIds` and `SecurityGroupIds` as list of Strings (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-vpcconfig.html), but using ImportValue masks the error and linting does not fail as expected Template that should fail but succeeds ```yaml Resources: LambdaFunction: Type: 'AWS::Lambda::Function' Properties: Runtime: java8 Code: S3Bucket: 'foo-bar' S3Key: 'foo-bar' S3ObjectVersion: 'foo-bar' Handler: 'com.foo.bar::handleRequest' Role: 'arn:aws:iam::123456789101:role/foo-bar' VpcConfig: SubnetIds: !ImportValue foobar1 SecurityGroupIds: !ImportValue foobar2 ``` Template that fails correctly ```yaml Resources: LambdaFunction: Type: 'AWS::Lambda::Function' Properties: Runtime: java8 Code: S3Bucket: 'foo-bar' S3Key: 'foo-bar' S3ObjectVersion: 'foo-bar' Handler: 'com.foo.bar::handleRequest' Role: 'arn:aws:iam::123456789101:role/foo-bar' VpcConfig: SubnetIds: 'foobar1' SecurityGroupIds: 'foobar2' E3002 Property SubnetIds should be of type List for resource LambdaFunction lambda-function.yaml:14:9 E3002 Property SecurityGroupIds should be of type List for resource LambdaFunction lambda-function.yaml:15:9 ```
2020-11-06T00:15:22Z
[]
[]
aws-cloudformation/cfn-lint
1,774
aws-cloudformation__cfn-lint-1774
[ "1772" ]
34f34e4d9a565be5c68abeefc42fcf9505f5c30c
diff --git a/src/cfnlint/rules/functions/Sub.py b/src/cfnlint/rules/functions/Sub.py --- a/src/cfnlint/rules/functions/Sub.py +++ b/src/cfnlint/rules/functions/Sub.py @@ -85,8 +85,8 @@ def _test_parameters(self, parameters, cfn, tree): message = 'Sub parameter should be an object of 1 for {0}' matches.append(RuleMatch( param_tree, message.format('/'.join(map(str, tree))))) - elif not isinstance(parameter_value_obj, six.string_types): - message = 'Sub parameter should be an object of 1 or string for {0}' + elif isinstance(parameter_value_obj, list): + message = 'Sub parameter value should be a string for {0}' matches.append(RuleMatch( param_tree, message.format('/'.join(map(str, tree)))))
diff --git a/test/fixtures/templates/bad/functions/sub.yaml b/test/fixtures/templates/bad/functions/sub.yaml --- a/test/fixtures/templates/bad/functions/sub.yaml +++ b/test/fixtures/templates/bad/functions/sub.yaml @@ -54,8 +54,10 @@ Resources: Properties: CidrBlock: Fn::Sub: - - "${myCidr}" + - "${myCidr}${number}" - myCidr: !Ref CidrBlock + number: + - bad LaunchConfiguration: Type: AWS::AutoScaling::LaunchConfiguration Properties: diff --git a/test/fixtures/templates/good/functions/sub.yaml b/test/fixtures/templates/good/functions/sub.yaml --- a/test/fixtures/templates/good/functions/sub.yaml +++ b/test/fixtures/templates/good/functions/sub.yaml @@ -13,6 +13,8 @@ Parameters: Description: App Package mySubnets: Type: List<AWS::EC2::Subnet::Id> + CidrBlock: + Type: String Resources: myInstance: Type: AWS::EC2::Instance @@ -64,6 +66,14 @@ Resources: Properties: ProductName: example ProvisioningArtifactName: v1 + myVPc2: + Type: AWS::EC2::VPC + Properties: + CidrBlock: + Fn::Sub: + - "${myCidr}${number}" + - myCidr: !Ref CidrBlock + number: 1 Outputs: OutputSub: Value: !Sub '${ProvisionedProduct.Outputs.Example}-example' diff --git a/test/unit/rules/functions/test_sub.py b/test/unit/rules/functions/test_sub.py --- a/test/unit/rules/functions/test_sub.py +++ b/test/unit/rules/functions/test_sub.py @@ -23,4 +23,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/functions/sub.yaml', 15) + self.helper_file_negative('test/fixtures/templates/bad/functions/sub.yaml', 16)
Incorrect rule: "E1019: Sub parameter should be an object of 1 or string for..." *cfn-lint version: 0.40.0* I am getting an incorrect error that [`E1019`](https://github.com/aws-cloudformation/cfn-python-lint/blob/master/docs/rules.md#E1019)` Sub parameter should be an object of 1 or string for...` when using YAML: ``` - Fn::Sub: - 'example-${Var}-${Var2}' - Var: 123 Var2: 456 ``` Official docs: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html Official docs sample: ``` Fn::Sub: - String - Var1Name: Var1Value Var2Name: Var2Value ```
Haven't looked into this yet, but getting thrown here: https://github.com/aws-cloudformation/cfn-python-lint/blob/4ef277bb637c533582c2b10d3589b4aa3623f3bf/src/cfnlint/rules/functions/Sub.py#L88-L91
2020-11-06T16:51:48Z
[]
[]
aws-cloudformation/cfn-lint
1,788
aws-cloudformation__cfn-lint-1788
[ "1662", "1662" ]
ac5627f267393d573d2b130f1607fbac1f7f1c7d
diff --git a/src/cfnlint/rules/functions/SubNeeded.py b/src/cfnlint/rules/functions/SubNeeded.py --- a/src/cfnlint/rules/functions/SubNeeded.py +++ b/src/cfnlint/rules/functions/SubNeeded.py @@ -2,57 +2,36 @@ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ -from functools import reduce # pylint: disable=redefined-builtin import re import six +import cfnlint.helpers from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch +from cfnlint.data import AdditionalSpecs class SubNeeded(CloudFormationLintRule): - """Check if a substitution string exists without a substitution function""" + """ + Check if a substitution string exists without a substitution function + + Found a false-positive or false-negative? All configuration for this rule + is contained in `src/cfnlint/data/AdditionalSpecs/SubNeededExcludes.json` + so you can add new entries to fix false-positives or amend existing + entries for false-negatives. + """ id = 'E1029' shortdesc = 'Sub is required if a variable is used in a string' description = 'If a substitution variable exists in a string but isn\'t wrapped with the Fn::Sub function the deployment will fail.' source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html' tags = ['functions', 'sub'] - # Free-form text properties to exclude from this rule - excludes = ['UserData', 'ZipFile', 'Condition', 'AWS::CloudFormation::Init', - 'CloudWatchAlarmDefinition', 'TopicRulePayload', 'BuildSpec', - 'RequestMappingTemplate', 'LogFormat', 'TemplateBody', 'ResponseMappingTemplate'] - api_excludes = ['Uri', 'Body', 'ConnectionId'] - - - # IAM Policy has special variables that don't require !Sub, Check for these - # https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html - # https://docs.aws.amazon.com/iot/latest/developerguide/basic-policy-variables.html - # https://docs.aws.amazon.com/iot/latest/developerguide/thing-policy-variables.html - # https://docs.aws.amazon.com/transfer/latest/userguide/users.html#users-policies-scope-down - # https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html - resource_excludes = ['${aws:CurrentTime}', '${aws:EpochTime}', - '${aws:TokenIssueTime}', '${aws:principaltype}', - '${aws:SecureTransport}', '${aws:SourceIp}', - '${aws:UserAgent}', '${aws:userid}', - '${aws:username}', '${ec2:SourceInstanceARN}', - '${iot:Connection.Thing.ThingName}', - '${iot:Connection.Thing.ThingTypeName}', - '${iot:Connection.Thing.IsAttached}', - '${iot:ClientId}', '${transfer:HomeBucket}', - '${transfer:HomeDirectory}', '${transfer:HomeFolder}', - '${transfer:UserName}', '${redshift:DbUser}', - '${cognito-identity.amazonaws.com:aud}', - '${cognito-identity.amazonaws.com:sub}', - '${cognito-identity.amazonaws.com:amr}'] - - # https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-access-control-identity-based.html - condition_excludes = [ - '${redshift:DbUser}', - ] - def __init__(self): """Init""" super(SubNeeded, self).__init__() + excludes_config = cfnlint.helpers.load_resource(AdditionalSpecs, 'SubNeededExcludes.json') + + self.excludes = excludes_config + self.config_definition = { 'custom_excludes': { 'default': '', @@ -62,19 +41,20 @@ def __init__(self): self.configure() self.subParameterRegex = re.compile(r'(\$\{[A-Za-z0-9_:\.]+\})') - def _match_values(self, cfnelem, path): + + def _match_values_recursive(self, cfnelem, path): """Recursively search for values matching the searchRegex""" values = [] if isinstance(cfnelem, dict): for key in cfnelem: pathprop = path[:] pathprop.append(key) - values.extend(self._match_values(cfnelem[key], pathprop)) + values.extend(self._match_values_recursive(cfnelem[key], pathprop)) elif isinstance(cfnelem, list): for index, item in enumerate(cfnelem): pathprop = path[:] pathprop.append(index) - values.extend(self._match_values(item, pathprop)) + values.extend(self._match_values_recursive(item, pathprop)) else: # Leaf node if isinstance(cfnelem, six.string_types): # and re.match(searchRegex, cfnelem): @@ -83,20 +63,17 @@ def _match_values(self, cfnelem, path): return values - def match_values(self, cfn): + + def _match_values(self, cfn): """ Search for values in all parts of the templates that match the searchRegex """ results = [] - results.extend(self._match_values(cfn.template, [])) + results.extend(self._match_values_recursive(cfn.template, [])) # Globals are removed during a transform. They need to be checked manually - results.extend(self._match_values(cfn.template.get('Globals', {}), [])) + results.extend(self._match_values_recursive(cfn.template.get('Globals', {}), [])) return results - def _api_exceptions(self, value): - """ Key value exceptions """ - parameter_search = re.compile(r'^\$\{stageVariables\..*\}$') - return re.match(parameter_search, value) def _variable_custom_excluded(self, value): """ User-defined exceptions for variables, anywhere in the file """ @@ -106,56 +83,125 @@ def _variable_custom_excluded(self, value): return re.match(custom_search, value) return False + + def _excluded_by_additional_resource_specs(self, variable, path, cfn): + """ + Should the variable be excluded due to the resource + configuration in the AdditionalSpecs file + 'SubNeededExcludes.json'? + """ + resource_name = path[0] + resource_type = cfn.template.get('Resources').get(resource_name).get('Type') + + if resource_type in self.excludes['ResourceTypes']: + return self._excluded_by_additional_resource_specs_recursive(variable, path, path[2:], self.excludes['ResourceTypes'][resource_type], cfn) + + return False + + + def _excluded_by_criteria(self, variable, full_path, exclusions, cfn): + """ + Run the exclusion logic, and because pylint too-many-return-statements complains + """ + # Have we excluded all variables for this resource? + if 'ExcludeAll' in exclusions and exclusions['ExcludeAll']: + return True + + # Have we excluded the specific variable + if 'ExcludeValues' in exclusions: + if variable in exclusions['ExcludeValues']: + return True + + if 'ExcludeRegex' in exclusions: + exclude_regex = re.compile(r'^{}$'.format(exclusions['ExcludeRegex'])) + if re.match(exclude_regex, variable): + return True + + if 'ExcludeBasedOnProperties' in exclusions: + for exclude_based_on_property in exclusions['ExcludeBasedOnProperties']: + exclude_based_on_property_path = exclude_based_on_property.split('.')[1:] + + current_property = cfn.template.get('Resources').get(full_path[0]).get('Properties') + + while exclude_based_on_property_path and current_property: + current_property = current_property.get(exclude_based_on_property_path[0]) + exclude_based_on_property_path = exclude_based_on_property_path[1:] + + if current_property and variable in current_property: + return True + + return False + + + def _excluded_by_additional_resource_specs_recursive(self, variable, full_path, path, exclusions, cfn): + """ + Should the variable be excluded due to the resource + configuration in the AdditionalSpecs file + 'SubNeededExcludes.json'? + """ + # Make sure the path is well-defined + if not path: + return False + + # Should we exclude the variable based on the current criteria defined in the specs? + if self._excluded_by_criteria(variable, full_path, exclusions, cfn): + return True + + # Recursively check the exclusion critera based on the property tree + sub_fields = ['Metadata', 'Properties'] + + for sub_field in sub_fields: + if sub_field in exclusions: + + # Traverse over any arrays, path should never end with an integer + while isinstance(path[0], int): + path = path[1:] + + # Recurse + if path[0] in exclusions[sub_field]: + if self._excluded_by_additional_resource_specs_recursive(variable, full_path, path[1:], exclusions[sub_field][path[0]], cfn): + return True + + return False + + + def _excluded_by_additional_specs(self, variable, path, cfn): + """ + Should the variable be excluded due to the configuration + in the AdditionalSpecs file 'SubNeededExcludes.json'? + """ + if path[0] == 'Resources': + # Check exclusion at the resource level first + return self._excluded_by_additional_resource_specs(variable[2:-1], path[1:], cfn) + + return False + + def match(self, cfn): matches = [] # Get a list of paths to every leaf node string containing at least one ${parameter} - parameter_string_paths = self.match_values(cfn) + parameter_string_paths = self._match_values(cfn) # We want to search all of the paths to check if each one contains an 'Fn::Sub' for parameter_string_path in parameter_string_paths: if parameter_string_path[0] in ['Parameters']: continue - # Exclude the special IAM variables - variable = parameter_string_path[-1] - if 'Resource' in parameter_string_path: - if variable in self.resource_excludes: - continue - if 'NotResource' in parameter_string_path: - if variable in self.resource_excludes: - continue - if 'Condition' in parameter_string_path: - if variable in self.condition_excludes: - continue - - # Step Function State Machine has a Definition Substitution that allows usage of special variables outside of a !Sub - # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stepfunctions-statemachine-definitionsubstitutions.html - - if 'DefinitionString' in parameter_string_path: - modified_parameter_string_path = parameter_string_path - index = parameter_string_path.index('DefinitionString') - modified_parameter_string_path[index] = 'DefinitionSubstitutions' - modified_parameter_string_path = modified_parameter_string_path[:index+1] - modified_parameter_string_path.append(variable[2:-1]) - if reduce(lambda c, k: c.get(k, {}), modified_parameter_string_path, cfn.template): - continue + # The variable to be substituted + variable = parameter_string_path[-1] # Exclude variables that match custom exclude filters, if configured # (for third-party tools that pre-process templates before uploading them to AWS) if self._variable_custom_excluded(variable): continue - # Exclude literals (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html) - if variable.startswith('${!'): + if self._excluded_by_additional_specs(variable, parameter_string_path, cfn): continue found_sub = False # Does the path contain an 'Fn::Sub'? for step in parameter_string_path: - if step in self.api_excludes: - if self._api_exceptions(parameter_string_path[-1]): - found_sub = True - elif step == 'Fn::Sub' or step in self.excludes: + if step == 'Fn::Sub': found_sub = True # If we didn't find an 'Fn::Sub' it means a string containing a ${parameter} may not be evaluated correctly
diff --git a/test/fixtures/schemas/SubNeededExcludes.json b/test/fixtures/schemas/SubNeededExcludes.json new file mode 100644 --- /dev/null +++ b/test/fixtures/schemas/SubNeededExcludes.json @@ -0,0 +1,66 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "Product", + "description": "Exclusion critera for the Fn::Sub Needed rule (E1029)", + "type": "object", + "additionalProperties": false, + "properties": { + "ResourceTypes": { + "$ref": "#/definitions/resourcetypes" + } + }, + "definitions": { + "resourcetypes": { + "patternProperties": { + "^[a-zA-Z0-9]+::[a-zA-Z0-9]+::[a-zA-Z0-9]+$": { + "$ref": "#/definitions/resource" + } + }, + "additionalProperties": false, + "uniqueItems": true + }, + "resource": { + "type": "object", + "properties": { + "ExcludeRegex": { + "description": "A regex to match variables to exclude from the rule", + "type": "string" + }, + "ExcludeAll": { + "description": "Exclude all variables from the rule", + "type": "boolean" + }, + "ExcludeValues": { + "description": "Exclude any variable matching these values from the rule", + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + }, + "ExcludeBasedOnProperties": { + "description": "Exclude any variables defined in these properties from the rule", + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + }, + "Metadata": { + "description": "Exclusion critera for metadata associated with a resource", + "$ref": "#/definitions/resource" + }, + "Properties": { + "description": "Exclusion critera for properties associated with a resource", + "$ref": "#/definitions/resource" + } + }, + "additionalProperties": { + "$ref": "#/definitions/resource" + } + } + }, + "required": [ + "ResourceTypes" + ] +} \ No newline at end of file diff --git a/test/fixtures/templates/bad/functions/sub_needed.yaml b/test/fixtures/templates/bad/functions/sub_needed.yaml --- a/test/fixtures/templates/bad/functions/sub_needed.yaml +++ b/test/fixtures/templates/bad/functions/sub_needed.yaml @@ -31,6 +31,53 @@ Resources: Type: AWS::SNS::Topic Properties: TopicName: "${aws:username}-topic" + MultilineYAMLTestPolicy: + Type: AWS::IoT::Policy + Properties: + PolicyDocument: > + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "iot:Connect", + "Resource": "arn:aws:iot:eu-central-1:123456789012:${badstringsubstitution}/${iot:Connection.Thing.ThingName}" + } + ] + } + PolicyName: ConnectWithThingName + GreetingRequest: + Type: AWS::ApiGateway::Method + Properties: + AuthorizationType: NONE + HttpMethod: GET + Integration: + Type: AWS + IntegrationHttpMethod: POST + Uri: + Fn::Join: + - "" + - - "arn:aws:apigateway:" + - !Ref "AWS::Region" + - ":lambda:path/2015-03-31/functions/" + - !GetAtt GreetingLambda.Arn + - ":${notAstageVariable.LambdaAlias}" + - "/invocations" + IntegrationResponses: + - StatusCode: '200' + RequestTemplates: + application/json: + Fn::Join: + - "" + - - "{" + - " \"name\": \"$input.params('name')\"" + - "}" + RequestParameters: + method.request.querystring.name: false + ResourceId: !Ref GreetingResource + RestApiId: !Ref GreetingApi + MethodResponses: + - StatusCode: '200' TestBadStateMachine1: Type: AWS::StepFunctions::StateMachine diff --git a/test/fixtures/templates/good/functions/sub_needed.yaml b/test/fixtures/templates/good/functions/sub_needed.yaml --- a/test/fixtures/templates/good/functions/sub_needed.yaml +++ b/test/fixtures/templates/good/functions/sub_needed.yaml @@ -134,6 +134,21 @@ Resources: - !Ref AWS::Region - !Ref AWS::AccountId - thing/${iot:Connection.Thing.ThingName}* + MultilineYAMLTestPolicy: + Type: AWS::IoT::Policy + Properties: + PolicyDocument: > + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "iot:Connect", + "Resource": "arn:aws:iot:eu-central-1:123456789012:client/${iot:Connection.Thing.ThingName}" + } + ] + } + PolicyName: ConnectWithThingName TestGoodStateMachine1: Type: AWS::StepFunctions::StateMachine Properties: diff --git a/test/unit/rules/functions/test_sub_needed.py b/test/unit/rules/functions/test_sub_needed.py --- a/test/unit/rules/functions/test_sub_needed.py +++ b/test/unit/rules/functions/test_sub_needed.py @@ -36,4 +36,4 @@ def test_template_config(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/functions/sub_needed.yaml', 8) + self.helper_file_negative('test/fixtures/templates/bad/functions/sub_needed.yaml', 10) diff --git a/test/unit/specs/test_required_based_on_value.py b/test/unit/specs/test_required_based_on_value.py --- a/test/unit/specs/test_required_based_on_value.py +++ b/test/unit/specs/test_required_based_on_value.py @@ -6,6 +6,7 @@ import test.fixtures.schemas from jsonschema import validate from test.testlib.testcase import BaseTestCase +from cfnlint.data import AdditionalSpecs import cfnlint.helpers diff --git a/test/unit/specs/test_sub_needed_excludes_schema.py b/test/unit/specs/test_sub_needed_excludes_schema.py new file mode 100644 --- /dev/null +++ b/test/unit/specs/test_sub_needed_excludes_schema.py @@ -0,0 +1,23 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +import logging +import test.fixtures.schemas +from jsonschema import validate +from test.testlib.testcase import BaseTestCase +from cfnlint.data import AdditionalSpecs +import cfnlint.helpers + + +LOGGER = logging.getLogger('cfnlint.maintenance') +LOGGER.addHandler(logging.NullHandler()) + + +class TestSubNeededExcludesSchema(BaseTestCase): + + + def test_validate_additional_specs_schema(self): + spec = cfnlint.helpers.load_resource(cfnlint.data.AdditionalSpecs, 'SubNeededExcludes.json') + schema = cfnlint.helpers.load_resource(test.fixtures.schemas, 'SubNeededExcludes.json') + validate(instance=spec, schema=schema)
E1029 - False positive with multiline YAML string *cfn-lint version: (`cfn-lint --version`)* 0.35.0 *Description of issue.* Using ${iot:Connection.Thing.ThingName} inside an AWS::IoT::Policy PolicyDocument is flagged as an embedded parameter outside of Fn::Sub. Freshly installed cfn-lint this morning. I'm using Python 2.7 and VS Code * Sample Template: ``` AWSTemplateFormatVersion: '2010-09-09' Resources: TestPolicy: Type: AWS::IoT::Policy Properties: PolicyDocument: > { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iot:Connect", "Resource": "arn:aws:iot:eu-central-1:123456789012:client/${iot:Connection.Thing.ThingName}" } ] } PolicyName: ConnectWithThingName ``` In the second example in their developer guide on AWS IoT they use the exact same policy document. https://docs.aws.amazon.com/iot/latest/developerguide/connect-policy.html * Feature request: Like with IAM policies, IoT policies shouldn't have variables flagged as embedded parameters. E1029 - False positive with multiline YAML string *cfn-lint version: (`cfn-lint --version`)* 0.35.0 *Description of issue.* Using ${iot:Connection.Thing.ThingName} inside an AWS::IoT::Policy PolicyDocument is flagged as an embedded parameter outside of Fn::Sub. Freshly installed cfn-lint this morning. I'm using Python 2.7 and VS Code * Sample Template: ``` AWSTemplateFormatVersion: '2010-09-09' Resources: TestPolicy: Type: AWS::IoT::Policy Properties: PolicyDocument: > { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iot:Connect", "Resource": "arn:aws:iot:eu-central-1:123456789012:client/${iot:Connection.Thing.ThingName}" } ] } PolicyName: ConnectWithThingName ``` In the second example in their developer guide on AWS IoT they use the exact same policy document. https://docs.aws.amazon.com/iot/latest/developerguide/connect-policy.html * Feature request: Like with IAM policies, IoT policies shouldn't have variables flagged as embedded parameters.
**Seems like the [multiline YAML string](https://yaml-multiline.info/) isn't handled by this:** https://github.com/aws-cloudformation/cfn-python-lint/blob/766f47072f8b93f13be3129a59c06e5cee5f2bc3/src/cfnlint/rules/functions/SubNeeded.py#L33-L38 https://github.com/aws-cloudformation/cfn-python-lint/blob/766f47072f8b93f13be3129a59c06e5cee5f2bc3/src/cfnlint/rules/functions/SubNeeded.py#L121-L123 --- **Can workaround with [resource-level ignores](https://github.com/aws-cloudformation/cfn-python-lint#resource-based-metadata) until this is fixed:** ```yaml Resource: Type: AWS::IoT::Policy Metadata: cfn-lint: config: ignore_checks: - E1029 ``` **or switch from using the [multiline YAML string](https://yaml-multiline.info/) (may cause [resource replacement](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-replacement)):** ```yaml Resources: TestPolicy: Type: AWS::IoT::Policy Properties: PolicyDocument: Version: "2012-10-17" Statement: Effect: "Allow" Action: "iot:Connect" Resource: "arn:aws:iot:eu-central-1:123456789012:client/${iot:Connection.Thing.ThingName}" PolicyName: ConnectWithThingName ``` [`AWS::IoT::Policy`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-policy.html#aws-resource-iot-policy--examples) I ended up fixing the issue by using Fn::Sub, since I didn't like the hardcoded `region` and `account ID`: ``` Resources: TestPolicy: Type: AWS::IoT::Policy Properties: PolicyDocument: !Sub > { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iot:Connect", "Resource": "arn:aws:iot:${AWS::Region}:${AWS::AccountId}:client/${!iot:Connection.Thing.ThingName}" } ] } PolicyName: ConnectWithThingName ``` With the exclamation mark inside ${}, `iot:Connection.Thing.ThingName` will not be replaced. **Seems like the [multiline YAML string](https://yaml-multiline.info/) isn't handled by this:** https://github.com/aws-cloudformation/cfn-python-lint/blob/766f47072f8b93f13be3129a59c06e5cee5f2bc3/src/cfnlint/rules/functions/SubNeeded.py#L33-L38 https://github.com/aws-cloudformation/cfn-python-lint/blob/766f47072f8b93f13be3129a59c06e5cee5f2bc3/src/cfnlint/rules/functions/SubNeeded.py#L121-L123 --- **Can workaround with [resource-level ignores](https://github.com/aws-cloudformation/cfn-python-lint#resource-based-metadata) until this is fixed:** ```yaml Resource: Type: AWS::IoT::Policy Metadata: cfn-lint: config: ignore_checks: - E1029 ``` **or switch from using the [multiline YAML string](https://yaml-multiline.info/) (may cause [resource replacement](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-replacement)):** ```yaml Resources: TestPolicy: Type: AWS::IoT::Policy Properties: PolicyDocument: Version: "2012-10-17" Statement: Effect: "Allow" Action: "iot:Connect" Resource: "arn:aws:iot:eu-central-1:123456789012:client/${iot:Connection.Thing.ThingName}" PolicyName: ConnectWithThingName ``` [`AWS::IoT::Policy`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-policy.html#aws-resource-iot-policy--examples) I ended up fixing the issue by using Fn::Sub, since I didn't like the hardcoded `region` and `account ID`: ``` Resources: TestPolicy: Type: AWS::IoT::Policy Properties: PolicyDocument: !Sub > { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iot:Connect", "Resource": "arn:aws:iot:${AWS::Region}:${AWS::AccountId}:client/${!iot:Connection.Thing.ThingName}" } ] } PolicyName: ConnectWithThingName ``` With the exclamation mark inside ${}, `iot:Connection.Thing.ThingName` will not be replaced.
2020-11-18T14:33:03Z
[]
[]
aws-cloudformation/cfn-lint
1,900
aws-cloudformation__cfn-lint-1900
[ "1868" ]
b20e59a9a2538f62b77f3821d19cdeccc977e689
diff --git a/src/cfnlint/decode/__init__.py b/src/cfnlint/decode/__init__.py --- a/src/cfnlint/decode/__init__.py +++ b/src/cfnlint/decode/__init__.py @@ -51,8 +51,7 @@ def decode(filename): matches.append(create_match_file_error( filename, 'Cannot read file contents: %s' % filename)) except cfn_yaml.CfnParseError as err: - err.match.Filename = filename - matches = [err.match] + matches = err.matches except ParserError as err: matches = [create_match_yaml_parser_error(err, filename)] except ScannerError as err: @@ -63,8 +62,9 @@ def decode(filename): try: template = cfn_json.load(filename) except cfn_json.JSONDecodeError as json_err: - json_err.match.filename = filename - matches = [json_err.match] + for e in json_err.matches: + e.filename = filename + matches = json_err.matches except JSONDecodeError as json_err: if hasattr(json_err, 'message'): if json_err.message == 'No JSON object could be decoded': # pylint: disable=no-member diff --git a/src/cfnlint/decode/cfn_json.py b/src/cfnlint/decode/cfn_json.py --- a/src/cfnlint/decode/cfn_json.py +++ b/src/cfnlint/decode/cfn_json.py @@ -20,6 +20,11 @@ class DuplicateError(Exception): Error thrown when the template contains duplicates """ + def __init__(self, message, mapping, key): + super(DuplicateError, self).__init__(message) + + self.mapping = mapping + self.key = key class NullError(Exception): """ @@ -38,7 +43,7 @@ def check_duplicates(ordered_pairs, beg_mark, end_mark): if value is None: raise NullError('"{}"'.format(key)) if key in mapping: - raise DuplicateError('"{}"'.format(key)) + raise DuplicateError('"{}"'.format(key), mapping, key) mapping[key] = value return mapping @@ -53,24 +58,40 @@ class JSONDecodeError(ValueError): """ # Note that this exception is used from _json - def __init__(self, msg, doc, pos, key=' '): - lineno = doc.count('\n', 0, pos) + 1 - colno = pos - doc.rfind('\n', 0, pos) - errmsg = '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos) + def __init__(self, doc, pos, errors): + + if isinstance(errors, cfnlint.rules.Match): + errors = [errors] + + errmsg = '%s: line %d column %d (char %d)' % (errors[0].message, errors[0].linenumber, errors[0].linenumber, pos) ValueError.__init__(self, errmsg) - self.msg = msg + self.msg = errors[0].message self.doc = doc self.pos = pos - self.lineno = lineno - self.colno = colno - self.match = cfnlint.rules.Match( - lineno, colno + 1, lineno, - colno + 1 + len(key), '', cfnlint.rules.ParseError(), message=msg) + self.lineno = errors[0].linenumber + self.colno = errors[0].linenumber + self.matches = errors def __reduce__(self): return self.__class__, (self.msg, self.doc, self.pos) +def build_match(message, doc, pos, key=' '): + + lineno = doc.count('\n', 0, pos) + 1 + colno = pos - doc.rfind('\n', 0, pos) + + return cfnlint.rules.Match( + lineno, colno + 1, lineno, + colno + 1 + len(key), '', cfnlint.rules.ParseError(), message=message) + + +def build_match_from_node(message, node, key): + + return cfnlint.rules.Match( + node[key].start_mark.line, node[key].start_mark.column + 1, node[key].end_mark.line, + node[key].end_mark.column + 1 + len(key), '', cfnlint.rules.ParseError(), message=message) + class Mark(object): """Mark of line and column""" line = 1 @@ -98,7 +119,17 @@ def py_scanstring(s, end, strict=True, while 1: chunk = _m(s, end) if chunk is None: - raise JSONDecodeError('Unterminated string starting at', s, begin) + raise JSONDecodeError( + doc=s, + pos=begin, + errors=[ + build_match( + message='Unterminated string starting at', + doc=s, + pos=begin, + ), + ] + ) end = chunk.end() content, terminator = chunk.groups() # Content is contains zero or more unescaped string characters @@ -111,20 +142,50 @@ def py_scanstring(s, end, strict=True, if terminator != '\\': if strict: msg = 'Invalid control character {0!r} at'.format(terminator) - raise JSONDecodeError(msg, s, end) + raise JSONDecodeError( + doc=s, + pos=end, + errors=[ + build_match( + message=msg, + doc=s, + pos=end, + ), + ] + ) _append(terminator) continue try: esc = s[end] except IndexError: - raise JSONDecodeError('Unterminated string starting at', s, begin) + raise JSONDecodeError( + doc=s, + pos=begin, + errors=[ + build_match( + message='Unterminated string starting at', + doc=s, + pos=begin, + ), + ] + ) # If not a unicode escape sequence, must be in the lookup table if esc != 'u': try: char = _b[esc] except KeyError: msg = 'Invalid \\escape: {0!r}'.format(esc) - raise JSONDecodeError(msg, s, end) + raise JSONDecodeError( + doc=s, + pos=end, + errors=[ + build_match( + message=msg, + doc=s, + pos=end, + ), + ] + ) end += 1 else: uni = _decode_uXXXX(s, end) @@ -151,7 +212,17 @@ def _decode_uXXXX(s, pos): except ValueError: pass msg = 'Invalid \\uXXXX escape' - raise JSONDecodeError(msg, s, pos) + raise JSONDecodeError( + doc=s, + pos=pos, + errors=[ + build_match( + message=msg, + doc=s, + pos=pos, + ), + ] + ) def CfnJSONObject(s_and_end, strict, scan_once, object_hook, object_pairs_hook, @@ -181,9 +252,34 @@ def CfnJSONObject(s_and_end, strict, scan_once, object_hook, object_pairs_hook, result = object_pairs_hook(pairs, beg_mark, end_mark) return result, end + 1 except DuplicateError as err: - raise JSONDecodeError('Duplicate found {}'.format(err), s, end) + raise JSONDecodeError( + doc=s, + pos=end, + errors=[ + build_match_from_node( + message='Duplicate found {}'.format(err), + node=err.mapping, + key=err.key, + ), + build_match( + message='Duplicate found {}'.format(err), + doc=s, + pos=end, + ), + ] + ) except NullError as err: - raise JSONDecodeError('Null Error {}'.format(err), s, end) + raise JSONDecodeError( + doc=s, + pos=end, + errors=[ + build_match( + message='Null Error {}'.format(err), + doc=s, + pos=end, + ), + ] + ) pairs = {} if object_hook is not None: beg_mark, end_mark = get_beg_end_mark(s, original_end, end + 1) @@ -191,7 +287,17 @@ def CfnJSONObject(s_and_end, strict, scan_once, object_hook, object_pairs_hook, return pairs, end + 1 if nextchar != '"': - raise JSONDecodeError('Expecting property name enclosed in double quotes', s, end) + raise JSONDecodeError( + doc=s, + pos=end, + errors=[ + build_match( + message='Expecting property name enclosed in double quotes', + doc=s, + pos=end, + ), + ] + ) end += 1 while True: begin = end - 1 @@ -204,7 +310,17 @@ def CfnJSONObject(s_and_end, strict, scan_once, object_hook, object_pairs_hook, if s[end:end + 1] != ':': end = _w(s, end).end() if s[end:end + 1] != ':': - raise JSONDecodeError('Expecting \':\' delimiter', s, end) + raise JSONDecodeError( + doc=s, + pos=end, + errors=[ + build_match( + message='Expecting \':\' delimiter', + doc=s, + pos=end, + ), + ] + ) end += 1 try: @@ -219,7 +335,17 @@ def CfnJSONObject(s_and_end, strict, scan_once, object_hook, object_pairs_hook, try: value, end = scan_once(s, end) except StopIteration as err: - raise JSONDecodeError('Expecting value', s, str(err)) + raise JSONDecodeError( + doc=s, + pos=str(err), + errors=[ + build_match( + message='Expecting value', + doc=s, + pos=str(err), + ), + ] + ) key_str = str_node(key, beg_mark, end_mark) pairs_append((key_str, value)) try: @@ -234,21 +360,65 @@ def CfnJSONObject(s_and_end, strict, scan_once, object_hook, object_pairs_hook, if nextchar == '}': break if nextchar != ',': - raise JSONDecodeError('Expecting \',\' delimiter', s, end - 1) + raise JSONDecodeError( + doc=s, + pos=end - 1, + errors=[ + build_match( + message='Expecting \',\' delimiter', + doc=s, + pos=end - 1, + ), + ] + ) end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar != '"': raise JSONDecodeError( - 'Expecting property name enclosed in double quotes', s, end - 1) + doc=s, + pos=end - 1, + errors=[ + build_match( + message='Expecting property name enclosed in double quotes', + doc=s, + pos=end - 1, + ), + ] + ) if object_pairs_hook is not None: try: beg_mark, end_mark = get_beg_end_mark(s, original_end, end) result = object_pairs_hook(pairs, beg_mark, end_mark) except DuplicateError as err: - raise JSONDecodeError('Duplicate found {}'.format(err), s, begin, key) + raise JSONDecodeError( + doc=s, + pos=end, + errors=[ + build_match_from_node( + message='Duplicate found {}'.format(err), + node=err.mapping, + key=err.key, + ), + build_match( + message='Duplicate found {}'.format(err), + doc=s, + pos=end, + ), + ] + ) except NullError as err: - raise JSONDecodeError('Null Error {}'.format(err), s, begin, key) + raise JSONDecodeError( + doc=s, + pos=end, + errors=[ + build_match( + message='Null Error {}'.format(err), + doc=s, + pos=end, + ), + ] + ) return result, end pairs = dict(pairs) diff --git a/src/cfnlint/decode/cfn_yaml.py b/src/cfnlint/decode/cfn_yaml.py --- a/src/cfnlint/decode/cfn_yaml.py +++ b/src/cfnlint/decode/cfn_yaml.py @@ -36,20 +36,22 @@ class CfnParseError(ConstructorError): Error thrown when the template contains Cfn Error """ - def __init__(self, filename, message, line_number, column_number, key=' '): + def __init__(self, filename, errors): + + if isinstance(errors, cfnlint.rules.Match): + errors = [errors] # Call the base class constructor with the parameters it needs - super(CfnParseError, self).__init__(message) + super(CfnParseError, self).__init__(errors[0].message) # Now for your custom code... self.filename = filename - self.line_number = line_number - self.column_number = column_number - self.message = message - self.match = cfnlint.rules.Match( - line_number + 1, column_number + 1, line_number + 1, - column_number + 1 + len(key), filename, cfnlint.rules.ParseError(), message=message) + self.matches = errors +def build_match(filename, message, line_number, column_number, key): + return cfnlint.rules.Match( + line_number + 1, column_number + 1, line_number + 1, + column_number + 1 + len(key), filename, cfnlint.rules.ParseError(), message=message) class NodeConstructor(SafeConstructor): """ @@ -81,9 +83,25 @@ def construct_yaml_map(self, node): if key in mapping: raise CfnParseError( self.filename, - 'Duplicate resource found "{}" (line {})'.format( - key, key_node.start_mark.line + 1), - key_node.start_mark.line, key_node.start_mark.column, key) + [ + build_match( + filename=self.filename, + message='Duplicate resource found "{}" (line {})'.format( + key, key_node.start_mark.line + 1), + line_number=key_node.start_mark.line, + column_number=key_node.start_mark.column, + key=key + ), + build_match( + filename=self.filename, + message='Duplicate resource found "{}" (line {})'.format( + key, mapping[key].start_mark.line + 1), + line_number=mapping[key].start_mark.line, + column_number=mapping[key].start_mark.column, + key=key + ) + ] + ) mapping[key] = value obj, = SafeConstructor.construct_yaml_map(self, node) @@ -103,9 +121,17 @@ def construct_yaml_null_error(self, node): """Throw a null error""" raise CfnParseError( self.filename, - 'Null value at line {0} column {1}'.format( - node.start_mark.line + 1, node.start_mark.column + 1), - node.start_mark.line, node.start_mark.column, ' ') + [ + build_match( + filename=self.filename, + message='Null value at line {0} column {1}'.format( + node.start_mark.line + 1, node.start_mark.column + 1), + line_number=node.start_mark.line, + column_number=node.start_mark.column, + key=' ', + ) + ] + ) NodeConstructor.add_constructor(
diff --git a/test/unit/module/test_duplicate.py b/test/unit/module/test_duplicate.py --- a/test/unit/module/test_duplicate.py +++ b/test/unit/module/test_duplicate.py @@ -44,8 +44,8 @@ def test_fail_run(self): try: with open(filename) as fp: json.load(fp, cls=cfnlint.decode.cfn_json.CfnJSONDecoder) - except cfnlint.decode.cfn_json.JSONDecodeError: - assert(True) + except cfnlint.decode.cfn_json.JSONDecodeError as e: + self.assertEqual(len(e.matches), 2) return assert(False) @@ -57,8 +57,8 @@ def test_fail_yaml_run(self): try: cfnlint.decode.cfn_yaml.load(filename) - except cfnlint.decode.cfn_yaml.CfnParseError: - assert(True) + except cfnlint.decode.cfn_yaml.CfnParseError as e: + self.assertEqual(len(e.matches), 2) return assert(False)
Only the first Resource Duplicate is found - E0000 *cfn-lint version: (`cfn-lint 0.44.3`)* *Description of issue.* I get the error `E0000 Duplicate resource found "DevRouteTableRoute2" (line 18)` when I try to validate a CFn template with duplicated resources. I should get has many errors has the number of duplicated resources on the template. The template had more than one duplication, but the linter only showed the 1st. Please provide as much information as possible: * Test Template: ```yaml --- AWSTemplateFormatVersion: "2010-09-09" Resources: DevRouteTableRoute1: Type: AWS::EC2::TransitGatewayRoute Properties: Blackhole: true DestinationCidrBlock: 10.1.1.0/24 TransitGatewayRouteTableId: tgw-rtb-d65d85280f2c9e51c DevRouteTableRoute2: Type: AWS::EC2::TransitGatewayRoute Properties: DestinationCidrBlock: 10.1.2.0/24 TransitGatewayAttachmentId: tgw-attach-9bdf1fdfb44d9c7d7 TransitGatewayRouteTableId: tgw-rtb-d65d85280f2c9e51c DevRouteTableRoute2: Type: AWS::EC2::TransitGatewayRoute Properties: DestinationCidrBlock: 10.1.3.0/24 TransitGatewayAttachmentId: tgw-attach-b16ea962254d4373e TransitGatewayRouteTableId: tgw-rtb-d65d85280f2c9e51c DevRouteTableRoute4: Type: AWS::EC2::TransitGatewayRoute Properties: DestinationCidrBlock: 10.1.4.0/24 TransitGatewayAttachmentId: tgw-attach-b16ea962254d4373e TransitGatewayRouteTableId: tgw-rtb-d65d85280f2c9e51c ProdRouteTableRoute1: Type: AWS::EC2::TransitGatewayRoute Properties: Blackhole: true DestinationCidrBlock: 10.1.1.0/24 TransitGatewayRouteTableId: tgw-rtb-5e9891f700a3af932 ProdRouteTableRoute2: Type: AWS::EC2::TransitGatewayRoute Properties: DestinationCidrBlock: 10.1.2.0/24 TransitGatewayAttachmentId: tgw-attach-9bdf1fdfb44d9c7d7 TransitGatewayRouteTableId: tgw-rtb-5e9891f700a3af932 ProdRouteTableRoute2: Type: AWS::EC2::TransitGatewayRoute Properties: DestinationCidrBlock: 10.1.3.0/24 TransitGatewayAttachmentId: tgw-attach-b16ea962254d4373e TransitGatewayRouteTableId: tgw-rtb-5e9891f700a3af932 ProdRouteTableRoute4: Type: AWS::EC2::TransitGatewayRoute Properties: DestinationCidrBlock: 10.1.4.0/24 TransitGatewayAttachmentId: tgw-attach-b16ea962254d4373e TransitGatewayRouteTableId: tgw-rtb-5e9891f700a3af932 ``` * Validation Output ``` cfn-lint -t template.yml E0000 Duplicate resource found "DevRouteTableRoute2" (line 18) template.yml:18:3 ``` * Expected Output ``` cfn-lint -t template.yml E0000 Duplicate resource found "DevRouteTableRoute2" (line 18) template.yml:18:3 E0000 Duplicate resource found "ProdRouteTableRoute2" (line 43) template.yml:43:3 ``` I've run manually cfn-lint -u but the validation on cfn-lint only shows on duplicate instead of the two that exist in the template.
2021-02-12T20:58:21Z
[]
[]
aws-cloudformation/cfn-lint
1,915
aws-cloudformation__cfn-lint-1915
[ "1193" ]
8580cae93ab9218455fd7eebeb719dc16146a02b
diff --git a/src/cfnlint/config.py b/src/cfnlint/config.py --- a/src/cfnlint/config.py +++ b/src/cfnlint/config.py @@ -425,6 +425,10 @@ def __call__(self, parser, namespace, values, option_string=None): '--output-file', type=str, default=None, help='Writes the output to the specified file, ideal for producing reports' ) + standard.add_argument( + '--merge-configs', default=False, action='store_true', + help='Merges lists between configuration layers' + ) return parser @@ -472,6 +476,7 @@ def set_template_args(self, template): template_args = property(get_template_args, set_template_args) +# pylint: disable=too-many-public-methods class ConfigMixIn(TemplateArgs, CliArgs, ConfigFileArgs, object): """ Mixin for the Configs """ @@ -487,6 +492,22 @@ def _get_argument_value(self, arg_name, is_template, is_config_file): cli_value = getattr(self.cli_args, arg_name) template_value = self.template_args.get(arg_name) file_value = self.file_args.get(arg_name) + + # merge list configurations + # make sure we don't do an infinite loop so skip this check for merge_configs + if arg_name != 'merge_configs': + if self.merge_configs: + # the CLI will always have an empty list when the item is a list + # we will use that to evaluate if we need to merge the lists + if isinstance(cli_value, list): + result = cli_value + if isinstance(template_value, list): + result.extend(template_value) + if isinstance(file_value, list): + result.extend(file_value) + return result + + # return individual items if cli_value: return cli_value if template_value and is_template: @@ -642,3 +663,7 @@ def output_file(self): @property def registry_schemas(self): return self._get_argument_value('registry_schemas', False, True) + + @property + def merge_configs(self): + return self._get_argument_value('merge_configs', True, True)
diff --git a/test/unit/module/config/test_config_mixin.py b/test/unit/module/config/test_config_mixin.py --- a/test/unit/module/config/test_config_mixin.py +++ b/test/unit/module/config/test_config_mixin.py @@ -159,3 +159,29 @@ def test_config_expand_ignore_templates(self, yaml_mock): self.assertNotIn( 'test/fixtures/templates/bad/resources/iam/resource_policy.yaml', config.templates) self.assertEqual(len(config.templates), 4) + + @patch('cfnlint.config.ConfigFileArgs._read_config', create=True) + def test_config_merge(self, yaml_mock): + """ Test merging lists """ + + yaml_mock.side_effect = [ + {"include_checks": ["I"], "ignore_checks": ["E3001"], "regions": ["us-west-2"]}, + {} + ] + config = cfnlint.config.ConfigMixIn(['--include-checks', 'I1234', 'I4321', '--merge-configs']) + config.template_args = { + 'Metadata': { + 'cfn-lint': { + 'config': { + 'include_checks': ['I9876'], + 'ignore_checks': ['W3001'] + } + } + } + } + # config files wins + self.assertEqual(config.regions, ['us-west-2']) + # CLI should win + self.assertEqual(config.include_checks, ['W', 'E', 'I1234', 'I4321', 'I9876', 'I']) + # template file wins over config file + self.assertEqual(config.ignore_checks, ['W3001', 'E3001'])
Use of -i IGNORE_CHECKS conflicts with Metadata ignore_checks *cfn-lint version: 0.25.0 *Description of issue.* When specifying -i <CHECK> on the command line cfn-lint no longer honours ignore_checks metadata in the template (at last for template level metadata). *Background* The recently introduced I1022 rule has trigger a large number of hits across our templates, some of which are questionably false positives (I intend to open an issue for this once I have collected the details / example), so for now I tried to disable it globally by adding '-i I1022' in the pipeline that runs cfn-lint checks for our templates. After doing this the other checks that have been suppressed using ignore_checks metadata in individual template files all started being reported again instead of being ignored.
The way it works today is that things are overrode and not merged. So adding `-i I1022` will override ignore checks in .cfnlintrc and any template level Metadata ignore checks. We could work on a way to merge those settings instead of overriding. At least for the list based settings. Were you able to investigate the false positives? @kddejong I've opened #1195 with some examples of what I feel are inappropriate / false-positive triggering of I1022. Regarding merging if I moved the ignore to a .cfnlinrc will that merge with template level metadata? that would be a reasonable workaround. Ultimately I would suggest that -i should stack with other config, but if it's not possible / practical / desired then it would be good to note that it doesn't in the --help output and readme, since it took me a while to figure out why I suddenly saw checks I thought I'd already addressed. I think this could be possible. @PatMyron what do you think? We have also been asked to add a required rule parameter which I think would allow us to switch the -i to append. I just ran into a similar issue that I think should be considered if anyone goes to implement this. I was surprised when I added a top-level `Metadata` to ignore a check, my `ignore_checks` list declared in `.cfnlintrc.yml` were suddenly ignored. I think a valid use case is a top level `.cfnlintrc.yml` to ignore checks globally for a group of templates in a collective project, and any `metadata` config within templates should be merged over that global config. currently if any ignore_checks are declared in a template they have to also redeclare ignore_checks from the `.cfnlintrc.yml`. I'd propose add a flag to merge configurations, and make that flag the default functionality in a future version.
2021-02-22T18:42:57Z
[]
[]
aws-cloudformation/cfn-lint
1,952
aws-cloudformation__cfn-lint-1952
[ "1951" ]
a8853c866d16a2258828f680b23842f3175fe513
diff --git a/src/cfnlint/maintenance.py b/src/cfnlint/maintenance.py --- a/src/cfnlint/maintenance.py +++ b/src/cfnlint/maintenance.py @@ -234,7 +234,10 @@ def update_iam_policies(): content = content.split('app.PolicyEditorConfig=')[1] content = json.loads(content) - content['serviceMap']['Manage Amazon API Gateway']['Actions'].extend( + content['serviceMap']['Amazon API Gateway Management']['Actions'].extend( + ['HEAD', 'OPTIONS'] + ) + content['serviceMap']['Amazon API Gateway Management V2']['Actions'].extend( ['HEAD', 'OPTIONS'] ) content['serviceMap']['Amazon Kinesis Video Streams']['Actions'].append(
diff --git a/test/unit/module/maintenance/test_update_iam_policies.py b/test/unit/module/maintenance/test_update_iam_policies.py --- a/test/unit/module/maintenance/test_update_iam_policies.py +++ b/test/unit/module/maintenance/test_update_iam_policies.py @@ -19,7 +19,7 @@ class TestUpdateIamPolicies(BaseTestCase): def test_update_iam_policies(self, mock_json_dump, mock_content): """Success update iam policies""" - mock_content.return_value = 'app.PolicyEditorConfig={"serviceMap":{"Manage Amazon API Gateway":{"Actions":[]},"Amazon Kinesis Video Streams":{"Actions":[]}}}' + mock_content.return_value = 'app.PolicyEditorConfig={"serviceMap":{"Amazon API Gateway Management":{"Actions":[]},"Amazon API Gateway Management V2":{"Actions":[]},"Amazon Kinesis Video Streams":{"Actions":[]}}}' if sys.version_info.major == 3: builtin_module_name = 'builtins' @@ -31,7 +31,10 @@ def test_update_iam_policies(self, mock_json_dump, mock_content): mock_json_dump.assert_called_with( { 'serviceMap': { - 'Manage Amazon API Gateway': { + 'Amazon API Gateway Management': { + 'Actions': ['HEAD', 'OPTIONS'] + }, + 'Amazon API Gateway Management V2': { 'Actions': ['HEAD', 'OPTIONS'] }, 'Amazon Kinesis Video Streams': {
"Manage Amazon API Gateway" key cannot be found when running with flag --update-iam-policies *cfn-lint version: (`cfn-lint --version`)* 0.48.0 *Description of issue.* Running the commands: ``` pip install cfn-lint cfn-lint --update-specs cfn-lint --update-iam-policies ``` in an empty Python 3.8 Docker container results in the following exception: ``` Traceback (most recent call last): File "/usr/local/bin/cfn-lint", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.8/site-packages/cfnlint/__main__.py", line 23, in main (args, filenames, formatter) = cfnlint.core.get_args_filenames(sys.argv[1:]) File "/usr/local/lib/python3.8/site-packages/cfnlint/core.py", line 144, in get_args_filenames cfnlint.maintenance.update_iam_policies() File "/usr/local/lib/python3.8/site-packages/cfnlint/maintenance.py", line 237, in update_iam_policies content['serviceMap']['Manage Amazon API Gateway']['Actions'].extend( KeyError: 'Manage Amazon API Gateway' ``` Looking at the code under `maintenance.py`, I see that the error happens after a file is downloaded on [line 226](https://github.com/aws-cloudformation/cfn-python-lint/blob/master/src/cfnlint/maintenance.py#L226). The file in question is https://awspolicygen.s3.amazonaws.com/js/policies.js, which is missing the string "Manage Amazon API Gateway". I can only find "Amazon API Gateway Management" and "Amazon API Gateway Management V2". Unfortunately, I do not have the requisite knowledge to know which of the two is meant and if a simple swap is sufficient to submit a merge request, but would be glad to do so if a swap is sufficient.
I'll take a look. Thanks for reporting this.
2021-03-23T18:32:44Z
[]
[]
aws-cloudformation/cfn-lint
1,978
aws-cloudformation__cfn-lint-1978
[ "1977" ]
73dc3d505ecdb085b7f1684f8711592082cafef3
diff --git a/src/cfnlint/rules/resources/ectwo/Ebs.py b/src/cfnlint/rules/resources/ectwo/Ebs.py --- a/src/cfnlint/rules/resources/ectwo/Ebs.py +++ b/src/cfnlint/rules/resources/ectwo/Ebs.py @@ -9,10 +9,10 @@ class Ebs(CloudFormationLintRule): - """Check if Ec2 Ebs Resource Properties""" + """Check Ec2 Ebs Resource Properties""" id = 'E2504' shortdesc = 'Check Ec2 Ebs Properties' - description = 'See if Ec2 Eb2 Properties are valid' + description = 'See if Ec2 Ebs Properties are valid' source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html' tags = ['properties', 'ec2', 'ebs'] @@ -26,13 +26,15 @@ def _checkEbs(self, cfn, ebs, path): for volume_type_obj in volume_types_obj: volume_type = volume_type_obj.get('Value') if isinstance(volume_type, six.string_types): - if volume_type == 'io1': + if volume_type in ('io1', 'io2'): if iops_obj is None: pathmessage = path[:] + ['VolumeType'] - message = 'VolumeType io1 requires Iops to be specified for {0}' + message = 'VolumeType {0} requires Iops to be specified for {1}' matches.append( - RuleMatch(pathmessage, message.format('/'.join(map(str, pathmessage))))) - elif volume_type: + RuleMatch( + pathmessage, + message.format(volume_type, '/'.join(map(str, pathmessage))))) + elif volume_type in ('gp2', 'st1', 'sc1', 'standard'): if iops_obj is not None: pathmessage = path[:] + ['Iops'] message = 'Iops shouldn\'t be defined for type {0} for {1}'
diff --git a/test/fixtures/templates/good/resources/ec2/ebs.yaml b/test/fixtures/templates/good/resources/ec2/ebs.yaml --- a/test/fixtures/templates/good/resources/ec2/ebs.yaml +++ b/test/fixtures/templates/good/resources/ec2/ebs.yaml @@ -46,6 +46,12 @@ Resources: DeleteOnTermination: false VolumeSize: 20 - DeviceName: /dev/sdn + Ebs: + VolumeType: io2 + Iops: !Ref myIops + DeleteOnTermination: false + VolumeSize: 20 + - DeviceName: /dev/sdo Ebs: VolumeType: standard DeleteOnTermination: false diff --git a/test/unit/rules/resources/ec2/test_ec2_ebs.py b/test/unit/rules/resources/ec2/test_ec2_ebs.py --- a/test/unit/rules/resources/ec2/test_ec2_ebs.py +++ b/test/unit/rules/resources/ec2/test_ec2_ebs.py @@ -23,4 +23,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/resources/ec2/ebs.yaml', 5) + self.helper_file_negative('test/fixtures/templates/bad/resources/ec2/ebs.yaml', 4)
E2504 incorrectly rejects "Iops" property for io2/gp3 volumes *cfn-lint version: (`cfn-lint --version`)* cfn-lint 0.44.6 *Description of issue.* cfn-lint produces an error "E2504: Iops shouldn't be defined for type io2 for Resource ... LaunchConfiguration/Properties/BlockDeviceMappings/0/Ebs/Iops" when setting Iops on a io2 EBS volume. The Iops property is required for io2 and optional for gp3. [1] Cfn-lint treats the Iops property as required for io1 and forbidden for all other volume types, which is very much not correct [1] https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-iops
2021-04-12T05:44:53Z
[]
[]
aws-cloudformation/cfn-lint
1,989
aws-cloudformation__cfn-lint-1989
[ "1987" ]
c8f6c3e42dff492e167b3df10c39cbbe4d58ca82
diff --git a/src/cfnlint/rules/functions/RelationshipConditions.py b/src/cfnlint/rules/functions/RelationshipConditions.py --- a/src/cfnlint/rules/functions/RelationshipConditions.py +++ b/src/cfnlint/rules/functions/RelationshipConditions.py @@ -24,7 +24,7 @@ def match(self, cfn): matches = [] # Start with Ref checks - ref_objs = cfn.search_deep_keys('Ref') + ref_objs = cfn.search_deep_keys(searchText='Ref', includeGlobals=False) for ref_obj in ref_objs: value = ref_obj[-1] if value not in PSEUDOPARAMS: @@ -42,7 +42,7 @@ def match(self, cfn): '/'.join(map(str, ref_obj[:-1]))))) # The do GetAtt - getatt_objs = cfn.search_deep_keys('Fn::GetAtt') + getatt_objs = cfn.search_deep_keys(searchText='Fn::GetAtt', includeGlobals=False) for getatt_obj in getatt_objs: value_obj = getatt_obj[-1] value = None diff --git a/src/cfnlint/template.py b/src/cfnlint/template.py --- a/src/cfnlint/template.py +++ b/src/cfnlint/template.py @@ -309,7 +309,7 @@ def _search_deep_keys(self, searchText, cfndict, path): return keys - def search_deep_keys(self, searchText): + def search_deep_keys(self, searchText, includeGlobals=True): """ Search for a key in all parts of the template. :return if searchText is "Ref", an array like ['Resources', 'myInstance', 'Properties', 'ImageId', 'Ref', 'Ec2ImageId'] @@ -318,7 +318,10 @@ def search_deep_keys(self, searchText): results = [] results.extend(self._search_deep_keys(searchText, self.template, [])) # Globals are removed during a transform. They need to be checked manually - results.extend(self._search_deep_keys(searchText, self.transform_pre.get('Globals'), [])) + if includeGlobals: + pre_results = self._search_deep_keys(searchText, self.transform_pre.get('Globals'), []) + for pre_result in pre_results: + results.append(['Globals'] + pre_result) return results def get_condition_values(self, template, path=[]):
diff --git a/test/fixtures/templates/good/functions/relationship_conditions_sam.yaml b/test/fixtures/templates/good/functions/relationship_conditions_sam.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/functions/relationship_conditions_sam.yaml @@ -0,0 +1,37 @@ +--- +AWSTemplateFormatVersion: 2010-09-09 +Transform: AWS::Serverless-2016-10-31 +Parameters: + DeploymentMode: + Type: String + AllowedValues: + - sandbox + - live + Default: sandbox + ConstraintDescription: Value must be a known deployment mode. +Conditions: + IsLive: !Equals [ !Ref DeploymentMode, live ] +Globals: + Function: + Environment: + Variables: + AppConfig__Environment: !If + - IsLive + - !Ref ConfigEnvironment + - !ImportValue ConfigEnvironment-blah +Resources: + ConfigApplication: + Type: AWS::AppConfig::Application + Properties: + Name: Application-A + ConfigEnvironment: + Type: AWS::AppConfig::Environment + Condition: IsLive + Properties: + ApplicationId: !Ref ConfigApplication + Name: Environment-B + FunctionC: + Type: AWS::Serverless::Function + Properties: + Runtime: provided.al2 + Handler: provided \ No newline at end of file diff --git a/test/unit/rules/functions/test_relationship_conditions.py b/test/unit/rules/functions/test_relationship_conditions.py --- a/test/unit/rules/functions/test_relationship_conditions.py +++ b/test/unit/rules/functions/test_relationship_conditions.py @@ -15,6 +15,7 @@ def setUp(self): self.collection.register(RelationshipConditions()) self.success_templates = [ 'test/fixtures/templates/good/functions/relationship_conditions.yaml', + 'test/fixtures/templates/good/functions/relationship_conditions_sam.yaml' ] def test_file_positive(self):
SAM Function Global Environment Variables Interact Oddly with `!If` and Conditional Values *cfn-lint version: (`cfn-lint --version`)* cfn-lint 0.46.0 *Description of issue.* When the `!If` intrinsic function is used with conditional values in SAM's Global Environment Variables, cfn-lint warns that the value on the `true` side of the condition may not be available when the condition is not true. For example, given an [`AWS::AppConfig::Environment`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appconfig-environment.html) in the current template, an importable instance of same, and an environment variable meant to pass the ID of one of them to a Function: ```yaml --- AWSTemplateFormatVersion: 2010-09-09 Transform: AWS::Serverless-2016-10-31 Parameters: DeploymentMode: Type: String AllowedValues: - sandbox - live Default: sandbox ConstraintDescription: Value must be a known deployment mode. Conditions: IsLive: !Equals [ !Ref DeploymentMode, live ] Globals: Function: Environment: Variables: AppConfig__Environment: !If - IsLive - !Ref ConfigEnvironment - !ImportValue ConfigEnvironment-blah Resources: ConfigApplication: Type: AWS::AppConfig::Application Properties: Name: Application-A ConfigEnvironment: Type: AWS::AppConfig::Environment Condition: IsLive Properties: ApplicationId: !Ref ConfigApplication Name: Environment-B FunctionC: Type: AWS::Serverless::Function Properties: Runtime: provided.al2 Handler: provided ``` …cfn-lint reports this: > [cfn-lint] W1001: Ref to resource "ConfigEnvironment" that may not be available when condition "IsLive" is False at Function/Environment/Variables/AppConfig__Environment/Fn::If/1/Ref Oddly, the error is reported at a location in `Function` (under `Globals`, presumably), which I think isn't a location which exists in the transformed template. More oddly, this error is reported _only_ there. If the `!If` is removed and `ConfigEnvironment` is `!Ref`ed directly, the following are reported: > [cfn-lint] W1001: Ref to resource "ConfigEnvironment" that may not be available when condition "IsLive" is False at Function/Environment/Variables/AppConfig__Environment/Ref > > [cfn-lint] W1001: Ref to resource "ConfigEnvironment" that may not be available when condition "IsLive" is False at Resources/FunctionC/Properties/Environment/Variables/AppConfig__Environment/Ref That is, the error is reported both in the Globals section and in the `Environment.Variables` of `FunctionC` itself. But when the `!If` is present (as it should be), the error remains in `Globals`. If the environment variables are moved from `Globals` to directly within `FunctionC`, no error is reported. Unfortunately, this does not scale. Suppressing W1001 globally for deployments is our current workaround. Nothing in cfn-lint jumps out at me as responsible for this issue, so I don't have any leads for you to track down. The thing that looked closest was how this section is considered to have "non-strict" values, but that appears to be related to string vs. number, so it didn't seem right to me.
Mapping from the violation in the transformed template back to the line in the original source template is a bit best effort Still looking into the violation itself though I think that it's because [Line 933 in template.py][key] is key-not-found'ing on `text[path[0]]`. At that time, `path[0]` is "Function", which isn't a location which exists in the transformed template. This is causing the path conditions to be empty. When [the comparison is made][comparison] between the scenario count (0) and the number of path conditions (0), the scenario is appended to the results. Does that sound reasonable? I'm afraid I don't know what the best fix to apply is, if so. ~~Maybe early-return `results` if `len(path_conditions) == 0`? It works in my testing, at least. I could whip up that PR.~~ ha ha disregard that fails a bunch of unit tests [key]: https://github.com/aws-cloudformation/cfn-python-lint/blob/c8f6c3e42dff492e167b3df10c39cbbe4d58ca82/src/cfnlint/template.py#L933 [comparison]: https://github.com/aws-cloudformation/cfn-python-lint/blob/c8f6c3e42dff492e167b3df10c39cbbe4d58ca82/src/cfnlint/template.py#L619 Translated template for reference ``` { "AWSTemplateFormatVersion": null, "Conditions": { "IsLive": { "Fn::Equals": [ { "Ref": "DeploymentMode" }, "live" ] } }, "Parameters": { "DeploymentMode": { "AllowedValues": [ "sandbox", "live" ], "ConstraintDescription": "Value must be a known deployment mode.", "Default": "sandbox", "Type": "String" } }, "Resources": { "ConfigApplication": { "Properties": { "Name": "Application-A" }, "Type": "AWS::AppConfig::Application" }, "ConfigEnvironment": { "Condition": "IsLive", "Properties": { "ApplicationId": { "Ref": "ConfigApplication" }, "Name": "Environment-B" }, "Type": "AWS::AppConfig::Environment" }, "FunctionC": { "Properties": { "Code": { "S3Bucket": "bucket", "S3Key": "value" }, "Environment": { "Variables": { "AppConfig__Environment": { "Fn::If": [ "IsLive", { "Ref": "ConfigEnvironment" }, { "Fn::ImportValue": "ConfigEnvironment-blah" } ] } } }, "Handler": "provided", "Role": { "Fn::GetAtt": [ "FunctionCRole", "Arn" ] }, "Runtime": "provided.al2", "Tags": [ { "Key": "lambda:createdBy", "Value": "SAM" } ] }, "Type": "AWS::Lambda::Function" }, "FunctionCRole": { "Properties": { "AssumeRolePolicyDocument": { "Statement": [ { "Action": [ "sts:AssumeRole" ], "Effect": "Allow", "Principal": { "Service": [ "lambda.amazonaws.com" ] } } ], "Version": "2012-10-17" }, "ManagedPolicyArns": [ "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" ], "Tags": [ { "Key": "lambda:createdBy", "Value": "SAM" } ] }, "Type": "AWS::IAM::Role" } } } ``` A first glance this looks okay. I need to look into this a little more. Seeing what @chrisoverzero is seeing. Trying to figure out why now. That path is for sure jacked and need to figure out why. Figured out the fix. Working on a resolution.
2021-04-22T16:29:01Z
[]
[]
aws-cloudformation/cfn-lint
2,006
aws-cloudformation__cfn-lint-2006
[ "2004" ]
490e75c69cb9a7290f4ed25174d7f5c47a0ba986
diff --git a/src/cfnlint/rules/mappings/KeyName.py b/src/cfnlint/rules/mappings/KeyName.py --- a/src/cfnlint/rules/mappings/KeyName.py +++ b/src/cfnlint/rules/mappings/KeyName.py @@ -17,14 +17,26 @@ class KeyName(CloudFormationLintRule): source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html' tags = ['mappings'] - def check_key(self, key, path, check_alphanumeric=True): + def check_attribute(self, key, path): + """ Check the key name for string and alphanumeric""" + matches = [] + if not isinstance(key, six.string_types): + message = 'Mapping attribute ({0}) has to be a string.' + matches.append(RuleMatch(path[:], message.format(key))) + elif not re.match(REGEX_ALPHANUMERIC, key): + message = 'Mapping attribute ({0}) has invalid name. Name has to be alphanumeric.' + matches.append(RuleMatch(path[:], message.format(key))) + + return matches + + def check_key(self, key, path): """ Check the key name for string and alphanumeric""" matches = [] if not isinstance(key, six.string_types): message = 'Mapping key ({0}) has to be a string.' matches.append(RuleMatch(path[:], message.format(key))) - elif not re.match(REGEX_ALPHANUMERIC, key) and check_alphanumeric: - message = 'Mapping key ({0}) has invalid name. Name has to be alphanumeric.' + elif not re.match('^[a-zA-Z0-9.-]{1,255}$', key): + message = 'Mapping key ({0}) has invalid name. Name has to be alphanumeric, \'-\' or \'.\'' matches.append(RuleMatch(path[:], message.format(key))) return matches @@ -37,11 +49,11 @@ def match(self, cfn): if isinstance(mapping_value, dict): for key_name, key_value in mapping_value.items(): matches.extend(self.check_key( - key_name, ['Mappings', mapping_name, key_name], False)) + key_name, ['Mappings', mapping_name, key_name])) if isinstance(key_value, dict): for sub_key_name, _ in key_value.items(): matches.extend( - self.check_key( + self.check_attribute( sub_key_name, ['Mappings', mapping_name, key_name, sub_key_name])) return matches
diff --git a/test/fixtures/templates/bad/mappings/key_name.yaml b/test/fixtures/templates/bad/mappings/key_name.yaml --- a/test/fixtures/templates/bad/mappings/key_name.yaml +++ b/test/fixtures/templates/bad/mappings/key_name.yaml @@ -7,4 +7,8 @@ Mappings: us-east-1a: 123456789012: "ami-951945d0" us-east-1b: "ami-951945d1" + NameServers: + 10.90.0.0/16: + NameServer1: 10.90.0.10 + NameServer2: 10.90.4.10 Resources: {} diff --git a/test/unit/rules/mappings/test_key_name.py b/test/unit/rules/mappings/test_key_name.py --- a/test/unit/rules/mappings/test_key_name.py +++ b/test/unit/rules/mappings/test_key_name.py @@ -23,4 +23,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/mappings/key_name.yaml', 3) + self.helper_file_negative('test/fixtures/templates/bad/mappings/key_name.yaml', 4)
cfn-lint 0.49.1 does not catch `/` as an invalid character in a Mapping element name *cfn-lint version: cfn-lint 0.49.1* *cfn-lint did not catch `/` as an invalid character in a Mapping element name* cfn-lint passed successfully with this mapping included in the template: ```yaml Mappings: NameServers: 10.90.0.0/16: NameServer1: 10.90.0.10 NameServer2: 10.90.4.10 10.91.0.0/16: NameServer1: 10.91.0.10 NameServer2: 10.91.4.10 ``` However AWS rejected it: > Template format error: Mappings element name '10.93.0.0/16' must be non-empty and can contain only alphanumerics, '-' or '.' ![Screen Shot 2021-05-12 at 11 34 41](https://user-images.githubusercontent.com/7205587/117905164-0e917c00-b316-11eb-8132-2da240ff892a.png)
Thanks for reporting, does seem to be missing that level: <img width="656" alt="Screen Shot 2021-05-11 at 9 49 34 PM" src="https://user-images.githubusercontent.com/7014355/117906384-ce44e600-b2a2-11eb-9ad7-1d900c5ec4bd.png"> @PatMyron According to the [documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html) `The name can contain only alphanumeric characters (A-Za-z0-9)` This isn't fully true as you can do regions like `us-east-1` in the key names. Do you know what characters are valid. We actually disabled the alphanumeric check for this because I couldn't find what a correct regex would be. https://github.com/aws-cloudformation/cfn-python-lint/blob/853522ff0e4c977331ac677a47059cf96b6f3189/src/cfnlint/rules/mappings/KeyName.py#L40 I think I could convert to `^[a-zA-Z0-9._-]{1,255}$` but not sure that is valid for all levels either. Going to test a few things. ```yaml Mappings: region-name: us-east-1: key-1: value ``` `Mappings name 'region-name' is non alphanumeric.` `Mappings attribute name 'key-1' must contain only alphanumeric characters.` So it appears just the key where `us-east-1` has a different pattern :/
2021-05-12T16:08:08Z
[]
[]
aws-cloudformation/cfn-lint
2,017
aws-cloudformation__cfn-lint-2017
[ "2016" ]
854471346e368e46e4097fa35867cfcda44269f8
diff --git a/src/cfnlint/rules/mappings/KeyName.py b/src/cfnlint/rules/mappings/KeyName.py --- a/src/cfnlint/rules/mappings/KeyName.py +++ b/src/cfnlint/rules/mappings/KeyName.py @@ -35,7 +35,7 @@ def check_key(self, key, path): if not isinstance(key, six.string_types): message = 'Mapping key ({0}) has to be a string.' matches.append(RuleMatch(path[:], message.format(key))) - elif not re.match('^[a-zA-Z0-9.-]{1,255}$', key): + elif not re.match('^[a-zA-Z0-9.-]{1,255}$', key) and key != 'Fn::Transform': message = 'Mapping key ({0}) has invalid name. Name has to be alphanumeric, \'-\' or \'.\'' matches.append(RuleMatch(path[:], message.format(key)))
diff --git a/test/fixtures/templates/good/mappings/key_name.yaml b/test/fixtures/templates/good/mappings/key_name.yaml --- a/test/fixtures/templates/good/mappings/key_name.yaml +++ b/test/fixtures/templates/good/mappings/key_name.yaml @@ -1,5 +1,10 @@ AWSTemplateFormatVersion: "2010-09-09" Mappings: + AwsAgentPlatformMap: + Fn::Transform: + Name: AWS::Include + Parameters: + Location: s3://my-bucket-name/version/3.0.1/amazonlinux2/a-json-file.json myMap: '123456789012': AMI: "ami-7f418316"
E7003 Errors when using Fn::Transform inside a Mapping *cfn-lint version: 0.49.2* *Description of issue.* #2006 tightened what is considered valid for use in a Mapping. This causes it to reject what otherwise appears to be a valid use of `Fn::Transform` as the body of a Mapping. For example, this snippet is valid CFN: ```yaml Mappings: AwsAgentPlatformMap: Fn::Transform: Name: AWS::Include Parameters: Location: s3://my-bucket-name/version/3.0.1/amazonlinux2/a-json-file.json ``` This usage trips the newly enhanced regex: ``` E7003 Mapping key (Fn::Transform) has invalid name. Name has to be alphanumeric, '-' or '.' ```
see https://github.com/aws-cloudformation/cfn-lint/issues/2014, planning on continuing to track this in https://github.com/aws-cloudformation/cfn-lint/issues/476
2021-05-21T16:28:52Z
[]
[]
aws-cloudformation/cfn-lint
2,023
aws-cloudformation__cfn-lint-2023
[ "2021" ]
14d5d416e1172563f3453e977cf3d711bf61c7dc
diff --git a/src/cfnlint/rules/resources/iam/Policy.py b/src/cfnlint/rules/resources/iam/Policy.py --- a/src/cfnlint/rules/resources/iam/Policy.py +++ b/src/cfnlint/rules/resources/iam/Policy.py @@ -5,7 +5,7 @@ import json from datetime import date import six -from cfnlint.helpers import convert_dict +from cfnlint.helpers import convert_dict, FUNCTIONS_SINGLE from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch @@ -154,6 +154,23 @@ def _check_policy_statement(self, branch, statement, is_identity_policy, resourc matches.append( RuleMatch(branch[:], message)) + resources = statement.get('Resource', []) + if isinstance(resources, six.string_types): + resources = [resources] + + for index, resource in enumerate(resources): + if isinstance(resource, dict): + if len(resource) == 1: + for k in resource.keys(): + if k not in FUNCTIONS_SINGLE: + message = 'IAM Policy statement Resource incorrectly formatted' + matches.append( + RuleMatch(branch[:] + ['Resource', index], message)) + else: + message = 'IAM Policy statement Resource incorrectly formatted' + matches.append( + RuleMatch(branch[:] + ['Resource', index], message)) + return(matches) def match_resource_properties(self, properties, resourcetype, path, cfn):
diff --git a/test/fixtures/templates/bad/properties_iam_policy.yaml b/test/fixtures/templates/bad/resources/iam/iam_policy.yaml similarity index 77% rename from test/fixtures/templates/bad/properties_iam_policy.yaml rename to test/fixtures/templates/bad/resources/iam/iam_policy.yaml --- a/test/fixtures/templates/bad/properties_iam_policy.yaml +++ b/test/fixtures/templates/bad/resources/iam/iam_policy.yaml @@ -22,6 +22,15 @@ Resources: - Resource: '*' Effect: 'NotAllow' Principal: [123456789012] + - Effect: Allow + Action: + - cloudwatch:* + Resource: + - Effect: Allow + - Effect: Allow + Action: + - cloudwatch:* + Resource: '*' rIamPolicy: Type: AWS::IAM::Policy Properties: diff --git a/test/unit/module/config/test_config_mixin.py b/test/unit/module/config/test_config_mixin.py --- a/test/unit/module/config/test_config_mixin.py +++ b/test/unit/module/config/test_config_mixin.py @@ -158,7 +158,7 @@ def test_config_expand_ignore_templates(self, yaml_mock): # test defaults self.assertNotIn( 'test/fixtures/templates/bad/resources/iam/resource_policy.yaml', config.templates) - self.assertEqual(len(config.templates), 4) + self.assertEqual(len(config.templates), 5) @patch('cfnlint.config.ConfigFileArgs._read_config', create=True) def test_config_merge(self, yaml_mock): diff --git a/test/unit/rules/resources/iam/test_iam_policy.py b/test/unit/rules/resources/iam/test_iam_policy.py --- a/test/unit/rules/resources/iam/test_iam_policy.py +++ b/test/unit/rules/resources/iam/test_iam_policy.py @@ -24,7 +24,7 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/properties_iam_policy.yaml', 10) + self.helper_file_negative('test/fixtures/templates/bad/resources/iam/iam_policy.yaml', 12) def test_file_resource_negative(self): """Test failure"""
Linter does not catch MalformedPolicyDocument syntax error *cfn-lint version: 0.25.0* *Description of issue.* `cfn-lint` fails to catch the following syntax error pre-deployment, which is caught by CloudFormation during deployment: ``` Syntax errors in policy. (Service: AmazonIdentityManagement; Status Code: 400; Error Code: MalformedPolicyDocument; Request ID: ccd05e19-aa60-4b26-bfcc-8fbafca40c61; Proxy: null) ``` The policy in question has the following template: ```yaml APILambdaExecutionPolicy: Type: AWS::IAM::ManagedPolicy Properties: Description: Allows API Gateway triggered Lambdas access to service resources Path: / ManagedPolicyName: Fn::Sub: ${Project}-APILambdaExecutionPolicy-${AWS::Region} PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - dynamodb:*Get* - dynamodb:*Item* - dynamodb:Describe* - dynamodb:Query Resource: - Fn::GetAtt: - DynamoDB - Outputs.TaskDBTableARN - Fn::Sub: ${DynamoDB.Outputs.TaskDBTableARN}/* - Effect: Allow Action: - cloudwatch:PutMetricAlarm - cloudwatch:PutMetricData Resource: - '*' - Effect: Allow Action: - xray:PutTraceSegments - xray:PutTelemetryRecords Resource: - '*' - Effect: Allow Action: - sqs:GetQueueUrl - sqs:SendMessage Resource: - Fn::GetAtt: - SQS - Outputs.QueueARN - Effect: Allow Action: - sns:Publish Resource: - arn:aws:sns:*:*:* ```
To clarify, is the syntax error for this template just the indentation?
2021-05-26T22:14:54Z
[]
[]
aws-cloudformation/cfn-lint
2,031
aws-cloudformation__cfn-lint-2031
[ "2026" ]
3d30463ec1cf3eca5141230729ab33070aa7b753
diff --git a/src/cfnlint/rules/functions/SubNeeded.py b/src/cfnlint/rules/functions/SubNeeded.py --- a/src/cfnlint/rules/functions/SubNeeded.py +++ b/src/cfnlint/rules/functions/SubNeeded.py @@ -4,6 +4,7 @@ """ from functools import reduce # pylint: disable=redefined-builtin import re +import copy import six from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch @@ -17,40 +18,6 @@ class SubNeeded(CloudFormationLintRule): source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html' tags = ['functions', 'sub'] - # Free-form text properties to exclude from this rule - excludes = ['UserData', 'ZipFile', 'Condition', 'AWS::CloudFormation::Init', - 'CloudWatchAlarmDefinition', 'TopicRulePayload', 'BuildSpec', - 'RequestMappingTemplate', 'LogFormat', 'TemplateBody', 'ResponseMappingTemplate', - 'RouteSelectionExpression'] - api_excludes = ['Uri', 'Body', 'ConnectionId'] - - - # IAM Policy has special variables that don't require !Sub, Check for these - # https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html - # https://docs.aws.amazon.com/iot/latest/developerguide/basic-policy-variables.html - # https://docs.aws.amazon.com/iot/latest/developerguide/thing-policy-variables.html - # https://docs.aws.amazon.com/transfer/latest/userguide/users.html#users-policies-scope-down - # https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html - resource_excludes = ['${aws:CurrentTime}', '${aws:EpochTime}', - '${aws:TokenIssueTime}', '${aws:principaltype}', - '${aws:SecureTransport}', '${aws:SourceIp}', - '${aws:UserAgent}', '${aws:userid}', - '${aws:username}', '${ec2:SourceInstanceARN}', - '${iot:Connection.Thing.ThingName}', - '${iot:Connection.Thing.ThingTypeName}', - '${iot:Connection.Thing.IsAttached}', - '${iot:ClientId}', '${transfer:HomeBucket}', - '${transfer:HomeDirectory}', '${transfer:HomeFolder}', - '${transfer:UserName}', '${redshift:DbUser}', - '${cognito-identity.amazonaws.com:aud}', - '${cognito-identity.amazonaws.com:sub}', - '${cognito-identity.amazonaws.com:amr}'] - - # https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-access-control-identity-based.html - condition_excludes = [ - '${redshift:DbUser}', - ] - def __init__(self): """Init""" super(SubNeeded, self).__init__() @@ -110,61 +77,46 @@ def _variable_custom_excluded(self, value): def match(self, cfn): matches = [] + refs = cfn.get_valid_refs() + getatts = cfn.get_valid_getatts() + # Get a list of paths to every leaf node string containing at least one ${parameter} parameter_string_paths = self.match_values(cfn) # We want to search all of the paths to check if each one contains an 'Fn::Sub' for parameter_string_path in parameter_string_paths: - if parameter_string_path[0] in ['Parameters']: - continue - # Exclude the special IAM variables - variable = parameter_string_path[-1] - - if 'Resource' in parameter_string_path: - if variable in self.resource_excludes: - continue - if 'NotResource' in parameter_string_path: - if variable in self.resource_excludes: - continue - if 'Condition' in parameter_string_path: - if variable in self.condition_excludes: - continue + # Get variable + var = parameter_string_path[-1] # Step Function State Machine has a Definition Substitution that allows usage of special variables outside of a !Sub # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stepfunctions-statemachine-definitionsubstitutions.html if 'DefinitionString' in parameter_string_path: - modified_parameter_string_path = parameter_string_path + modified_parameter_string_path = copy.copy(parameter_string_path) index = parameter_string_path.index('DefinitionString') modified_parameter_string_path[index] = 'DefinitionSubstitutions' modified_parameter_string_path = modified_parameter_string_path[:index+1] - modified_parameter_string_path.append(variable[2:-1]) + modified_parameter_string_path.append(var[2:-1]) if reduce(lambda c, k: c.get(k, {}), modified_parameter_string_path, cfn.template): continue # Exclude variables that match custom exclude filters, if configured # (for third-party tools that pre-process templates before uploading them to AWS) - if self._variable_custom_excluded(variable): + if self._variable_custom_excluded(var): continue # Exclude literals (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html) - if variable.startswith('${!'): + if var.startswith('${!'): continue - found_sub = False - # Does the path contain an 'Fn::Sub'? - for step in parameter_string_path: - if step in self.api_excludes: - if self._api_exceptions(parameter_string_path[-1]): - found_sub = True - elif step == 'Fn::Sub' or step in self.excludes: - found_sub = True + var_stripped = var[2:-1].strip() # If we didn't find an 'Fn::Sub' it means a string containing a ${parameter} may not be evaluated correctly - if not found_sub: - # Remove the last item (the variable) to prevent multiple errors on 1 line errors - path = parameter_string_path[:-1] - message = 'Found an embedded parameter "{}" outside of an "Fn::Sub" at {}'.format( - variable, '/'.join(map(str, path))) - matches.append(RuleMatch(path, message)) + if not 'Fn::Sub' in parameter_string_path: + if (var_stripped in refs or var_stripped in getatts) or 'DefinitionString' in parameter_string_path: + # Remove the last item (the variable) to prevent multiple errors on 1 line errors + path = parameter_string_path[:-1] + message = 'Found an embedded parameter "{}" outside of an "Fn::Sub" at {}'.format( + var, '/'.join(map(str, path))) + matches.append(RuleMatch(path, message)) return matches diff --git a/src/cfnlint/template.py b/src/cfnlint/template.py --- a/src/cfnlint/template.py +++ b/src/cfnlint/template.py @@ -133,7 +133,6 @@ def get_parameter_names(self): return results def get_valid_refs(self): - LOGGER.debug('Get all valid REFs from template...') results = cfnlint.helpers.RegexDict() parameters = self.template.get('Parameters', {}) if parameters: @@ -166,7 +165,6 @@ def get_valid_refs(self): return results def get_valid_getatts(self): - LOGGER.debug('Get valid GetAtts from template...') resourcetypes = cfnlint.helpers.RESOURCE_SPECS['us-east-1'].get('ResourceTypes') results = {} resources = self.template.get('Resources', {})
diff --git a/test/fixtures/templates/good/functions/sub_needed_custom_excludes.yaml b/test/fixtures/templates/good/functions/sub_needed_custom_excludes.yaml --- a/test/fixtures/templates/good/functions/sub_needed_custom_excludes.yaml +++ b/test/fixtures/templates/good/functions/sub_needed_custom_excludes.yaml @@ -1,10 +1,13 @@ AWSTemplateFormatVersion: "2010-09-09" Description: Template containing third-party preprocessor-like variables to test custom ignore filters +Parameters: + Stage: + Type: String Resources: TestRole: Type: AWS::IAM::Role Properties: - RoleName: TestRole-${self:provider.stage} + RoleName: TestRole-${Stage} AssumeRolePolicyDocument: Version: '2012-10-17' Statement: diff --git a/test/unit/rules/functions/test_sub_needed.py b/test/unit/rules/functions/test_sub_needed.py --- a/test/unit/rules/functions/test_sub_needed.py +++ b/test/unit/rules/functions/test_sub_needed.py @@ -27,13 +27,13 @@ def test_template_config(self): """Test custom excludes configuration""" self.helper_file_rule_config( 'test/fixtures/templates/good/functions/sub_needed_custom_excludes.yaml', - {'custom_excludes': '^\\$\\{self.+\\}$'}, 0 + {'custom_excludes': '^\\$\\{Stage\\}$'}, 0 ) self.helper_file_rule_config( 'test/fixtures/templates/good/functions/sub_needed_custom_excludes.yaml', - {}, 4 + {}, 1 ) def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/functions/sub_needed.yaml', 8) + self.helper_file_negative('test/fixtures/templates/bad/functions/sub_needed.yaml', 7)
E1029 - false positive with X.509 Certificate AWS IoT Core policy variables cfn-lint version: (cfn-lint 0.49.2) I got a false positive on X.509 Certificate AWS IoT Core policy variables. I think that `cfn-lint` may not support X.509 Certificate AWS IoT Core policy variables. https://docs.aws.amazon.com/iot/latest/developerguide/cert-policy-variables.html As noted above, X.509 certificate attributes can contain one or more values, but `resource_excludes` does not support specification by regex. This problem is a similar case in the past, `${iot:Connection.Thing.Attributes[attributeName]}` could not be supported (see also #765). However, I think that just supporting the first value covers many cases. If you are okay with this idea, I can contribute. Do you have any comments? **Output:** ```shell-session ❯ cfn-lint iot-policy.cfn.yml E1019 Parameter iot:Certificate.Subject.CommonName for Fn::Sub not found at Resources/IoTPolicy/Properties/PolicyDocument/Statement/1/Resource/0/Fn::Sub iot-policy.cfn.yml:18:13 ``` **For reproduction:** ```yaml AWSTemplateFormatVersion: 2010-09-09 Resources: IoTPolicy: Type: AWS::IoT::Policy Properties: PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - iot:Connect Resource: - arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName} - Effect: Allow Action: - iot:Publish Resource: - !Sub "arn:aws:iot:us-east-1:123456789012:topic/my/topic/${iot:Certificate.Subject.CommonName}" ```
@xeres when I use this template to create a stack i get `Template error: instance of Fn::Sub references invalid resource attribute iot:Certificate.Subject.CommonName` which is similar to the error we provide. You will want to make sure you use the literal string like this `!Sub "arn:aws:iot:us-east-1:123456789012:topic/my/topic/${!iot:Certificate.Subject.CommonName}"` This will make the error remove but it will bring back W1020 which says the sub isn't needed. Oh, I'm sorry. The reproduction template is wrong. https://docs.aws.amazon.com/iot/latest/developerguide/certificate-policy-examples.html A similar as the third case, but I want to use with `!Sub` for `${AWS::Partition}`, `${AWS::Region}` and `${AWS::AccountId}`. ```yaml AWSTemplateFormatVersion: 2010-09-09 Resources: IoTPolicy: Type: AWS::IoT::Policy Properties: PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - iot:Connect Resource: - arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName} - Effect: Allow Action: - iot:Publish Resource: - !Join - "" - - !Sub "arn:${AWS::Partition}:iot:${AWS::Region}:${AWS::AccountId}:topic/my/topic/" - "${iot:Certificate.Subject.CommonName}" ```
2021-06-02T16:31:57Z
[]
[]
aws-cloudformation/cfn-lint
2,140
aws-cloudformation__cfn-lint-2140
[ "2139" ]
0c5d63e0f681fde3c385514c08aefb9aac13fbaa
diff --git a/src/cfnlint/rules/functions/Cidr.py b/src/cfnlint/rules/functions/Cidr.py --- a/src/cfnlint/rules/functions/Cidr.py +++ b/src/cfnlint/rules/functions/Cidr.py @@ -18,6 +18,91 @@ class Cidr(CloudFormationLintRule): source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-cidr.html' tags = ['functions', 'cidr'] + supported_functions = [ + 'Fn::FindInMap', + 'Fn::Select', + 'Ref', + 'Fn::GetAtt', + 'Fn::Sub', + 'Fn::ImportValue', + ] + + def check_ip_block(self, value, path): + matches = [] + if isinstance(value, dict): + if len(value) == 1: + for index_key, _ in value.items(): + if index_key not in self.supported_functions: + if index_key == 'Fn::If': + if len(value.get('Fn::If')) == 3 and isinstance(value.get('Fn::If'), list): + matches.extend(self.check_ip_block(value.get('Fn::If')[1], path=path[:] + [index_key , 1])) + matches.extend(self.check_ip_block(value.get('Fn::If')[2], path=path[:] + [index_key , 2])) + else: + message = 'Cidr ipBlock should be Cidr Range, Ref, GetAtt, Sub or Select for {0}' + matches.append(RuleMatch( + path, message.format('/'.join(map(str, value))))) + elif isinstance(value, (six.text_type, six.string_types)): + if not re.match(REGEX_CIDR, value): + message = 'Cidr ipBlock should be a Cidr Range based string for {0}' + matches.append(RuleMatch( + path, message.format('/'.join(map(str, path))))) + else: + message = 'Cidr ipBlock should be a string for {0}' + matches.append(RuleMatch( + path, message.format('/'.join(map(str, path))))) + + return matches + + def check_count(self, value, path): + matches = [] + count_parameters = [] + if isinstance(value, dict): + if len(value) == 1: + for index_key, index_value in value.items(): + if index_key not in self.supported_functions: + if index_key == 'Fn::If': + if len(value.get('Fn::If')) == 3 and isinstance(value.get('Fn::If'), list): + matches.extend(self.check_count(value.get('Fn::If')[1], path=path[:] + [index_key , 1])) + matches.extend(self.check_count(value.get('Fn::If')[2], path=path[:] + [index_key , 2])) + else: + message = 'Cidr count should be Int, Ref, or Select for {0}' + matches.append(RuleMatch( + path, message.format('/'.join(map(str, path))))) + if index_key == 'Ref': + count_parameters.append(index_value) + elif not isinstance(value, six.integer_types): + message = 'Cidr count should be a int for {0}' + extra_args = {'actual_type': type(value).__name__, 'expected_type': six.integer_types[0].__name__} + matches.append(RuleMatch( + path, message.format('/'.join(map(str, path))), **extra_args)) + + return count_parameters, matches + + def check_size_mask(self, value, path): + matches = [] + size_mask_parameters = [] + if isinstance(value, dict): + if len(value) == 1: + for index_key, index_value in value.items(): + if index_key not in self.supported_functions: + if index_key == 'Fn::If': + if len(value.get('Fn::If')) == 3 and isinstance(value.get('Fn::If'), list): + matches.extend(self.check_size_mask(value.get('Fn::If')[1], path=path[:] + [index_key , 1])) + matches.extend(self.check_size_mask(value.get('Fn::If')[2], path=path[:] + [index_key , 2])) + else: + message = 'Cidr sizeMask should be Int, Ref, or Select for {0}' + matches.append(RuleMatch( + path, message.format('/'.join(map(str, path))))) + if index_key == 'Ref': + size_mask_parameters.append(index_value) + elif not isinstance(value, six.integer_types): + message = 'Cidr sizeMask should be a int for {0}' + extra_args = {'actual_type': type(value).__name__, 'expected_type': six.integer_types[0].__name__} + matches.append(RuleMatch( + path, message.format('/'.join(map(str, path))), **extra_args)) + + return size_mask_parameters, matches + def check_parameter_count(self, cfn, parameter_name): """Check Count Parameter if used""" matches = [] @@ -75,15 +160,6 @@ def match(self, cfn): cidr_objs = cfn.search_deep_keys('Fn::Cidr') - supported_functions = [ - 'Fn::FindInMap', - 'Fn::Select', - 'Ref', - 'Fn::GetAtt', - 'Fn::Sub', - 'Fn::ImportValue' - ] - count_parameters = [] size_mask_parameters = [] @@ -99,52 +175,15 @@ def match(self, cfn): else: size_mask_obj = None - if isinstance(ip_block_obj, dict): - if len(ip_block_obj) == 1: - for index_key, _ in ip_block_obj.items(): - if index_key not in supported_functions: - message = 'Cidr ipBlock should be Cidr Range, Ref, GetAtt, Sub or Select for {0}' - matches.append(RuleMatch( - tree[:] + [0], message.format('/'.join(map(str, tree[:] + [0]))))) - elif isinstance(ip_block_obj, (six.text_type, six.string_types)): - if not re.match(REGEX_CIDR, ip_block_obj): - message = 'Cidr ipBlock should be a Cidr Range based string for {0}' - matches.append(RuleMatch( - tree[:] + [0], message.format('/'.join(map(str, tree[:] + [0]))))) - else: - message = 'Cidr ipBlock should be a string for {0}' - matches.append(RuleMatch( - tree[:] + [0], message.format('/'.join(map(str, tree[:] + [0]))))) - - if isinstance(count_obj, dict): - if len(count_obj) == 1: - for index_key, index_value in count_obj.items(): - if index_key not in supported_functions: - message = 'Cidr count should be Int, Ref, or Select for {0}' - matches.append(RuleMatch( - tree[:] + [1], message.format('/'.join(map(str, tree[:] + [1]))))) - if index_key == 'Ref': - count_parameters.append(index_value) - elif not isinstance(count_obj, six.integer_types): - message = 'Cidr count should be a int for {0}' - extra_args = {'actual_type': type(count_obj).__name__, 'expected_type': six.integer_types[0].__name__} - matches.append(RuleMatch( - tree[:] + [1], message.format('/'.join(map(str, tree[:] + [1]))), **extra_args)) - - if isinstance(size_mask_obj, dict): - if len(size_mask_obj) == 1: - for index_key, index_value in size_mask_obj.items(): - if index_key not in supported_functions: - message = 'Cidr sizeMask should be Int, Ref, or Select for {0}' - matches.append(RuleMatch( - tree[:] + [2], message.format('/'.join(map(str, tree[:] + [2]))))) - if index_key == 'Ref': - size_mask_parameters.append(index_value) - elif not isinstance(size_mask_obj, six.integer_types): - message = 'Cidr sizeMask should be a int for {0}' - extra_args = {'actual_type': type(count_obj).__name__, 'expected_type': six.integer_types[0].__name__} - matches.append(RuleMatch( - tree[:] + [2], message.format('/'.join(map(str, tree[:] + [2]))), **extra_args)) + matches.extend(self.check_ip_block(ip_block_obj, tree[:] + [0])) + + new_count_parameters, new_matches = self.check_count(count_obj, tree[:] + [1]) + count_parameters.extend(new_count_parameters) + matches.extend(new_matches) + + new_size_mask_parameters , new_matches = self.check_size_mask(size_mask_obj, tree[:] + [2]) + size_mask_parameters.extend(new_size_mask_parameters) + matches.extend(new_matches) else: message = 'Cidr should be a list of 2 or 3 elements for {0}'
diff --git a/test/fixtures/templates/bad/functions_cidr.yaml b/test/fixtures/templates/bad/functions_cidr.yaml --- a/test/fixtures/templates/bad/functions_cidr.yaml +++ b/test/fixtures/templates/bad/functions_cidr.yaml @@ -1,58 +1,106 @@ AWSTemplateFormatVersion: 2010-09-09 Parameters: - cidrBlock : - Type: String - count: - Type: String - count1: - Type: Number - MinValue: 0 - MaxValue: 3000 - maskSizeForIPv4: - Type: String - maskSizeForIPv6: - Type: String - maskSizeForIPv41: - Type: Number - MinValue: 0 - MaxValue: 750 + cidrBlock: + Type: String + count: + Type: String + count1: + Type: Number + MinValue: 0 + MaxValue: 3000 + maskSizeForIPv4: + Type: String + maskSizeForIPv6: + Type: String + maskSizeForIPv41: + Type: Number + MinValue: 0 + MaxValue: 750 +Conditions: + IsProd: !Equals [!Ref AWS::AccountId, '123456789012'] Resources: - Subnet1: - Type: AWS::EC2::Subnet - Properties: - AssignIpv6AddressOnCreation: true - VpcId: !Ref VPC - #Test Ipv4 CidrBlock - CidrBlock: !Select [0, !Cidr [!Ref cidrBlock, 'a', '/32']] - #Test Ipv6 CidrBlock - Ipv6CidrBlock: !Select [0, !Cidr [!Select [0, !GetAtt VPC.Ipv6CidrBlocks], !Ref count, !Ref maskSizeForIPv6]] - DependsOn: Ipv6VPCCidrBlock - Subnet2: - Type: AWS::EC2::Subnet - Properties: - AssignIpv6AddressOnCreation: true - VpcId: !Ref VPC - #Test Ipv4 CidrBlock - CidrBlock: !Select [1, !Cidr [!Ref cidrBlock, !Ref count1, !Ref maskSizeForIPv41]] - #Test Ipv6 CidrBlock - Ipv6CidrBlock: !Select [1, !Cidr [!FindInMap [0, !GetAtt VPC.Ipv6CidrBlocks], !Ref count, !Ref maskSizeForIPv6]] - DependsOn: Ipv6VPCCidrBlock - Subnet3: - Type: AWS::EC2::Subnet - Properties: - AssignIpv6AddressOnCreation: true - VpcId: !Ref VPC - #Test Ipv4 CidrBlock - CidrBlock: !Select [0, !Cidr [!Ref cidrBlock, !Ref count, !Ref maskSizeForIPv4]] - #Test Ipv6 CidrBlock - Ipv6CidrBlock: !Select [0, !Cidr [!Select [0, !GetAtt VPC.Ipv6CidrBlocks], !Ref count, !Ref maskSizeForIPv6]] - DependsOn: Ipv6VPCCidrBlock - VPC: - Type: AWS::EC2::VPC - Properties: - CidrBlock: !Ref cidrBlock - Ipv6VPCCidrBlock: - Type: AWS::EC2::VPCCidrBlock - Properties: - AmazonProvidedIpv6CidrBlock: true - VpcId: !Ref VPC + Subnet1: + Type: AWS::EC2::Subnet + Properties: + AssignIpv6AddressOnCreation: true + VpcId: !Ref VPC + #Test Ipv4 CidrBlock + CidrBlock: !Select [0, !Cidr [!Ref cidrBlock, "a", "/32"]] + #Test Ipv6 CidrBlock + Ipv6CidrBlock: + !Select [ + 0, + !Cidr [ + !Select [0, !GetAtt VPC.Ipv6CidrBlocks], + !Ref count, + !Ref maskSizeForIPv6, + ], + ] + DependsOn: Ipv6VPCCidrBlock + Subnet2: + Type: AWS::EC2::Subnet + Properties: + AssignIpv6AddressOnCreation: true + VpcId: !Ref VPC + #Test Ipv4 CidrBlock + CidrBlock: + !Select [1, !Cidr [!Ref cidrBlock, !Ref count1, !Ref maskSizeForIPv41]] + #Test Ipv6 CidrBlock + Ipv6CidrBlock: + !Select [ + 1, + !Cidr [ + !FindInMap [0, !GetAtt VPC.Ipv6CidrBlocks], + !Ref count, + !Ref maskSizeForIPv6, + ], + ] + DependsOn: Ipv6VPCCidrBlock + Subnet3: + Type: AWS::EC2::Subnet + Properties: + AssignIpv6AddressOnCreation: true + VpcId: !Ref VPC + #Test Ipv4 CidrBlock + CidrBlock: + !Select [0, !Cidr [!Ref cidrBlock, !Ref count, !Ref maskSizeForIPv4]] + #Test Ipv6 CidrBlock + Ipv6CidrBlock: + !Select [ + 0, + !Cidr [ + !Select [0, !GetAtt VPC.Ipv6CidrBlocks], + !Ref count, + !Ref maskSizeForIPv6, + ], + ] + DependsOn: Ipv6VPCCidrBlock + VPC: + Type: AWS::EC2::VPC + Properties: + CidrBlock: !Ref cidrBlock + Ipv6VPCCidrBlock: + Type: AWS::EC2::VPCCidrBlock + Properties: + AmazonProvidedIpv6CidrBlock: true + VpcId: !Ref VPC + SubnetWithConditions: + Type: AWS::EC2::Subnet + Properties: + # /28 block #1 (VPC Allocation), inside /26 block #3, inside /24 block #3 (prod) or block #15 (non-prod) + CidrBlock: + Fn::Select: + - 1 + - Fn::Cidr: + - Fn::Select: + - 3 + - Fn::Cidr: + - Fn::If: + - IsProd + - "a" + - "b" + - 4 + - 6 + - 2 + - 4 + VpcId: "vpc-123456" diff --git a/test/fixtures/templates/good/functions/cidr.yaml b/test/fixtures/templates/good/functions/cidr.yaml --- a/test/fixtures/templates/good/functions/cidr.yaml +++ b/test/fixtures/templates/good/functions/cidr.yaml @@ -17,6 +17,8 @@ Mappings: CidrBitsMap: "2": AZCidrBits: 16 +Conditions: + IsProd: !Equals [!Ref AWS::AccountId, '123456789012'] Resources: Subnet: Type: 'AWS::EC2::Subnet' @@ -28,3 +30,37 @@ Resources: Properties: VpcId: 'vpc-123456' CidrBlock: !Select [ 2, !Cidr [ {'Fn::ImportValue': 'vpc-CidrBlock'}, 4, !FindInMap [CidrBitsMap, !Ref Size, AZCidrBits] ]] + MyVPC: + Type: AWS::EC2::VPC + Properties: + CidrBlock: 10.0.0.0/16 + SubnetWithConditions: + Type: AWS::EC2::Subnet + Properties: + # /28 block #1 (VPC Allocation), inside /26 block #3, inside /24 block #3 (prod) or block #15 (non-prod) + CidrBlock: + Fn::Select: + - 1 + - Fn::Cidr: + - Fn::Select: + - 3 + - Fn::Cidr: + - Fn::If: + - IsProd + - Fn::Select: + - 3 + - Fn::Cidr: + - Fn::GetAtt: MyVPC.CidrBlock + - 4 + - 8 + - Fn::Select: + - 15 + - Fn::Cidr: + - Fn::GetAtt: MyVPC.CidrBlock + - 16 + - 8 + - 4 + - 6 + - 2 + - 4 + VpcId: 'vpc-123456' diff --git a/test/unit/rules/functions/test_cidr.py b/test/unit/rules/functions/test_cidr.py --- a/test/unit/rules/functions/test_cidr.py +++ b/test/unit/rules/functions/test_cidr.py @@ -27,4 +27,4 @@ def test_file_positive_extra(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/functions_cidr.yaml', 9) + self.helper_file_negative('test/fixtures/templates/bad/functions_cidr.yaml', 11)
E1024 Fn::Cidr should allow Fn::If that returns valid types *cfn-lint version: (`0.52.0+`)* *Description of issue.* We cut down Subnets from the VPC CIDR by scoping down CIDRs in increasing sizes and using the `Fn::Cidr` function with select to pick the appropriate subnet. Currently, it looks like `E1024` allows a Cidr Range, Ref, GetAtt, Sub or a Select function, but doesn't allow an If function that returns a valid type. The below syntax is valid in CloudFormation, and because both possible return values are appropriately typed should not return an error. ```yaml ExampleSubnet: Type: AWS::EC2::Subnet Properties: # /28 block #1 (VPC Allocation), inside /26 block #3, inside /24 block #3 (prod) or block #15 (non-prod) CidrBlock: !Select [ 1, !Cidr [ !Select [ 3, !Cidr [ !If [ IsProd, !Select [ 3, !Cidr [ !GetAtt MyVPC.CidrBlock, 4, 8 ]], !Select [ 15, !Cidr [ !GetAtt MyVPC.CidrBlock, 16, 8 ]] ], 4, 6 ]], 2, 4 ]] VpcId: !Ref MyVPC ``` Tested on cfn-lint versions: * `0.52.0` * `0.54.2`
2021-10-14T16:33:21Z
[]
[]
aws-cloudformation/cfn-lint
2,208
aws-cloudformation__cfn-lint-2208
[ "2189" ]
d68125b644cd09a3bdb0040e4e1040e1a2bdad9a
diff --git a/src/cfnlint/rules/custom/Operators.py b/src/cfnlint/rules/custom/Operators.py --- a/src/cfnlint/rules/custom/Operators.py +++ b/src/cfnlint/rules/custom/Operators.py @@ -49,7 +49,7 @@ def _check_value(self, value, path, property_chain, cfn): cfn=cfn, )) return matches - if value: + if value is not None: matches.extend(self.rule_func(value, self.property_value, path)) return matches
diff --git a/test/fixtures/custom_rules/bad/custom_rule_invalid_boolean.txt b/test/fixtures/custom_rules/bad/custom_rule_invalid_boolean.txt new file mode 100644 --- /dev/null +++ b/test/fixtures/custom_rules/bad/custom_rule_invalid_boolean.txt @@ -0,0 +1 @@ +AWS::EC2::Instance BlockDeviceMappings.Ebs.DeleteOnTermination == True ERROR diff --git a/test/fixtures/custom_rules/good/custom_rule_boolean.txt b/test/fixtures/custom_rules/good/custom_rule_boolean.txt new file mode 100644 --- /dev/null +++ b/test/fixtures/custom_rules/good/custom_rule_boolean.txt @@ -0,0 +1 @@ +AWS::EC2::Instance BlockDeviceMappings.Ebs.DeleteOnTermination == False ERROR diff --git a/test/unit/module/custom_rules/test_custom_rules.py b/test/unit/module/custom_rules/test_custom_rules.py --- a/test/unit/module/custom_rules/test_custom_rules.py +++ b/test/unit/module/custom_rules/test_custom_rules.py @@ -28,6 +28,8 @@ def setUp(self): } self.perfect_rule = 'test/fixtures/custom_rules/good/custom_rule_perfect.txt' + self.valid_boolean = 'test/fixtures/custom_rules/good/custom_rule_boolean.txt' + self.invalid_boolean = 'test/fixtures/custom_rules/bad/custom_rule_invalid_boolean.txt' self.invalid_op = 'test/fixtures/custom_rules/bad/custom_rule_invalid_op.txt' self.invalid_prop = 'test/fixtures/custom_rules/bad/custom_rule_invalid_prop.txt' self.invalid_propkey = 'test/fixtures/custom_rules/bad/custom_rule_invalid_propkey.txt' @@ -71,6 +73,14 @@ def test_invalid_less_than(self): """Test Successful Custom_Rule Parsing""" assert (self.run_tests(self.invalid_less_than)[0].message.find('Lesser than check') > -1) + def test_valid_boolean_value(self): + """Test Boolean values""" + assert (self.run_tests(self.valid_boolean) == []) + + def test_invalid_boolean_value(self): + """Test Boolean values""" + assert (self.run_tests(self.invalid_boolean)[0].message.find('Must equal check failed') > -1) + def test_invalid_prop(self): """Test Successful Custom_Rule Parsing""" assert (self.run_tests(self.invalid_prop) == []) @@ -92,4 +102,3 @@ def run_tests(self, rulename): rules.create_from_custom_rules_file(rulename) runner = cfnlint.runner.Runner(rules, filename, template, None, None) return runner.run() -
Custom Rule not working for boolean values *cfn-lint version: (`cfn-lint --version`)* 0.54.4 *Description of issue.* Attempting to create a custom rule to detect KMS keys that do not have auto rotate enabled. I discovered https://github.com/aws-cloudformation/cfn-lint/issues/2185 which covers the inability to react to absence of a value, but I'm just having issues with booleans. I'm able to trip the rules, so I know custom rules are registering, but I'm unable to get it to trip only against KMS Key resources who's EnableKeyRotation is false Please provide as much information as possible: * Template linting issues: * Please provide a CloudFormation sample that generated the issue. * If present, please add links to the (official) documentation for clarification. * Validate if the issue still exists with the latest version of `cfn-lint` and/or the latest Spec files * Feature request: * Please provide argumentation about the missing feature. Context is key! Example cfn ``` --- AWSTemplateFormatVersion: '2010-09-09' Resources: TestKey: Properties: EnableKeyRotation: false KeyPolicy: Statement: - Action: kms:* Effect: Allow Principal: AWS: Fn::Sub: arn:${AWS::Partition}:iam::${AWS::AccountId}:root Resource: "*" Sid: Enable key management, including IAM user permissions Version: '2012-10-17' Type: AWS::KMS::Key ``` rules file (showing different casings/quotings in case it's relevant)- ``` AWS::KMS::Key EnableKeyRotation == True ERROR "KMS keys should be configured to auto rotate" AWS::KMS::Key EnableKeyRotation == true ERROR "KMS keys should be configured to auto rotate" AWS::KMS::Key EnableKeyRotation == TRUE ERROR "KMS keys should be configured to auto rotate" AWS::KMS::Key EnableKeyRotation == "True" ERROR "KMS keys should be configured to auto rotate" AWS::KMS::Key EnableKeyRotation == "true" ERROR "KMS keys should be configured to auto rotate" AWS::KMS::Key EnableKeyRotation == "TRUE" ERROR "KMS keys should be configured to auto rotate" ``` if I flip the rules to ``` AWS::KMS::Key EnableKeyRotation == false ERROR "KMS keys should be configured to auto rotate" ``` No change. But if I then flip the cfn template's EnableKeyRotation to `true` it is then flagged in violation Cfn-lint uses the [CloudFormation Resource Specifications](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) as the base to do validation. These files are included as part of the application version. Please update to the latest version of `cfn-lint` or update the spec files manually (`cfn-lint -u`)
2022-01-28T22:07:06Z
[]
[]
aws-cloudformation/cfn-lint
2,226
aws-cloudformation__cfn-lint-2226
[ "2224" ]
b95629a833270f87e16acf99674e53b339b588ff
diff --git a/src/cfnlint/decode/cfn_yaml.py b/src/cfnlint/decode/cfn_yaml.py --- a/src/cfnlint/decode/cfn_yaml.py +++ b/src/cfnlint/decode/cfn_yaml.py @@ -103,7 +103,21 @@ def construct_yaml_map(self, node): ), ] ) - mapping[key] = value + try: + mapping[key] = value + except: + raise CfnParseError( + self.filename, + [ + build_match( + filename=self.filename, + message=f'Unhashable type "{key}" (line {key.start_mark.line + 1})', + line_number=key.start_mark.line, + column_number=key.start_mark.column, + key=key + ), + ] + ) obj, = SafeConstructor.construct_yaml_map(self, node)
diff --git a/test/fixtures/templates/bad/core/parse_invalid_map.yaml b/test/fixtures/templates/bad/core/parse_invalid_map.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/core/parse_invalid_map.yaml @@ -0,0 +1,23 @@ +Resources: + NodeGroup: + Type: "AWS::AutoScaling::AutoScalingGroup" + Properties: + DesiredCapacity: !Ref NodeAutoScalingGroupDesiredCapacity + LaunchTemplate: + LaunchTemplateId: !Ref NodeLaunchTemplate + Version: !GetAtt NodeLaunchTemplate.LatestVersionNumber + MaxSize: !Ref NodeAutoScalingGroupMaxSize + MinSize: !Ref NodeAutoScalingGroupMinSize + Tags: + - Key: Name + PropagateAtLaunch: true + Value: !Sub Cluster-Group-Node + - Key: !Sub kubernetes.io/cluster/Cluster + PropagateAtLaunch: true + Value: owned + VPCZoneIdentifier: !Join [ ',', [ !ImportValue Fn::Sub: "${NetworkStackName}-SubnetsPrivate01", !ImportValue Fn::Sub: "${NetworkStackName}-SubnetsPrivate02" ] ] + UpdatePolicy: + AutoScalingRollingUpdate: + MaxBatchSize: 1 + MinInstancesInService: !Ref NodeAutoScalingGroupDesiredCapacity + PauseTime: PT5M \ No newline at end of file diff --git a/test/unit/module/cfn_yaml/test_yaml.py b/test/unit/module/cfn_yaml/test_yaml.py --- a/test/unit/module/cfn_yaml/test_yaml.py +++ b/test/unit/module/cfn_yaml/test_yaml.py @@ -61,3 +61,10 @@ def test_success_parse_stdin(self): matches.extend(self.rules.run(filename, cfn)) assert len(matches) == failures, 'Expected {} failures, got {} on {}'.format( failures, len(matches), values.get('filename')) + + + def test_map_failure(self): + """Test a failure is passed on unhashable map""" + filename = 'test/fixtures/templates/bad/core/parse_invalid_map.yaml' + + self.assertRaises(cfnlint.decode.cfn_yaml.CfnParseError, cfnlint.decode.cfn_yaml.load, filename)
construct_yaml_map leading to TypeError: unhashable type: 'dict_node' *cfn-lint version: 0.58.1* *Unhandled `TypeError: unhashable type: 'dict_node'` thrown from construct_yaml_map.* Please provide as much information as possible: Utilising some slightly edited form of the example eks-nodegroup cfn, [see here for the failing cfn](https://github.com/SaltKhan/_cfn-breaking-cfn-lint/blob/main/eks-nodegroup.yaml) or [here, for the stacktrace](https://github.com/SaltKhan/_cfn-breaking-cfn-lint/blob/main/README.md). The problem occurrs on line 259 `VPCZoneIdentifier: !Join [ ',', [ !ImportValue Fn::Sub: "${NetworkStackName}-SubnetsPrivate01", !ImportValue Fn::Sub: "${NetworkStackName}-SubnetsPrivate02" ] ]`. (Was trying to provide a list by string concat as that's what's listed as the example input when subnets is a parameter as in the example cfn, but I've changed that for the example I provide here.) I changed the line to an expanded `!Join` ~ ``` VPCZoneIdentifier: !Join - ',' - - Fn::ImportValue: !Sub "${NetworkStackName}-SubnetsPrivate01" - Fn::ImportValue: !Sub "${NetworkStackName}-SubnetsPrivate02" ``` And it now correctly yields a normal error, rather than hitting the exception. I found this similar previous issue ~ https://github.com/aws-cloudformation/cfn-lint/issues/348
Looking into it.
2022-02-28T20:18:08Z
[]
[]
aws-cloudformation/cfn-lint
2,230
aws-cloudformation__cfn-lint-2230
[ "2229" ]
40b87cc41e76b8ce04c0089643df5b510e468ee1
diff --git a/src/cfnlint/rules/resources/backup/BackupPlanLifecycleRule.py b/src/cfnlint/rules/resources/backup/BackupPlanLifecycleRule.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/resources/backup/BackupPlanLifecycleRule.py @@ -0,0 +1,31 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from cfnlint.rules import CloudFormationLintRule +from cfnlint.rules import RuleMatch + + +class BackupPlanLifecycleRule(CloudFormationLintRule): + """Check Backup Plan rules with lifecycle has minimum period between cold and delete""" + id = 'E3504' + shortdesc = 'Check minimum 90 period is met between BackupPlan cold and delete' + description = 'Check that Backup plans with lifecycle rules have >= 90 days between cold and delete' + source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-backup-backupplan-lifecycleresourcetype.html' + tags = ['properties', 'backup', 'plan', 'lifecycle'] + + def match(self, cfn): + """Check cold storage and deletion lifecycle period differences""" + matches = [] + results = cfn.get_resource_properties(['AWS::Backup::BackupPlan', 'BackupPlan', 'BackupPlanRule', 'Lifecycle']) + + for result in results: + backup_rule = result['Value'] + # if 'MoveToColdStorageAfterDays' in backup_rule and 'DeleteAfterDays' in backup_rule: + if isinstance(backup_rule.get('MoveToColdStorageAfterDays'), int) and isinstance(backup_rule.get('DeleteAfterDays'), int): + if backup_rule['DeleteAfterDays'] - backup_rule['MoveToColdStorageAfterDays'] < 90: + message = 'DeleteAfterDays in {0} must be at least 90 days after MoveToColdStorageAfterDays' + rule_match = RuleMatch(result['Path'], message.format('/'.join(map(str, result['Path'])))) + matches.append(rule_match) + + return matches diff --git a/src/cfnlint/rules/resources/backup/__init__.py b/src/cfnlint/rules/resources/backup/__init__.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/resources/backup/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +"""
diff --git a/test/fixtures/templates/bad/resources/backup/test_backup_plan_lifecycle_rule.yml b/test/fixtures/templates/bad/resources/backup/test_backup_plan_lifecycle_rule.yml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources/backup/test_backup_plan_lifecycle_rule.yml @@ -0,0 +1,17 @@ +--- +Resources: + + BackupPlan: + Type: AWS::Backup::BackupPlan + DeletionPolicy: Delete + UpdateReplacePolicy: Delete + Properties: + BackupPlan: + BackupPlanName: "test-backup-plan" + BackupPlanRule: + - RuleName: "test-backup-plan-rule" + TargetBackupVault: "test-backup-vault" + ScheduleExpression: "cron(0 0 ? * MON *)" + Lifecycle: + MoveToColdStorageAfterDays: 7 + DeleteAfterDays: 30 # 30 - 7 is less than 90 diff --git a/test/fixtures/templates/good/resources/backup/test_backup_plan_lifecycle_rule.yml b/test/fixtures/templates/good/resources/backup/test_backup_plan_lifecycle_rule.yml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/backup/test_backup_plan_lifecycle_rule.yml @@ -0,0 +1,43 @@ +--- +Resources: + + BackupPlanWithValidLifecycle: + Type: AWS::Backup::BackupPlan + DeletionPolicy: Delete + UpdateReplacePolicy: Delete + Properties: + BackupPlan: + BackupPlanName: "test-backup-plan-valid-lifecycle" + BackupPlanRule: + - RuleName: "test-backup-plan-rule-valid-lifecycle" + TargetBackupVault: "test-backup-vault" + ScheduleExpression: "cron(0 0 ? * MON *)" + Lifecycle: + MoveToColdStorageAfterDays: 7 + DeleteAfterDays: 100 # 100 - 7 is greater than 90 + + BackupPlanWithIrrelevantLifecycle: + Type: AWS::Backup::BackupPlan + DeletionPolicy: Delete + UpdateReplacePolicy: Delete + Properties: + BackupPlan: + BackupPlanName: "test-backup-plan-irrelevant-lifecycle" + BackupPlanRule: + - RuleName: "test-backup-plan-rule-irrelevant-lifecycle" + TargetBackupVault: "test-backup-vault" + ScheduleExpression: "cron(0 0 ? * MON *)" + Lifecycle: + MoveToColdStorageAfterDays: 7 + + BackupPlanWithoutLifecycle: + Type: AWS::Backup::BackupPlan + DeletionPolicy: Delete + UpdateReplacePolicy: Delete + Properties: + BackupPlan: + BackupPlanName: "test-backup-plan-no-lifecycle" + BackupPlanRule: + - RuleName: "test-backup-plan-rule-no-lifecycle" + TargetBackupVault: "test-backup-vault" + ScheduleExpression: "cron(0 0 ? * MON *)" \ No newline at end of file diff --git a/test/unit/rules/resources/backup/__init__.py b/test/unit/rules/resources/backup/__init__.py new file mode 100644 --- /dev/null +++ b/test/unit/rules/resources/backup/__init__.py @@ -0,0 +1,4 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" diff --git a/test/unit/rules/resources/backup/test_backup_plan_lifecycle_rule.py b/test/unit/rules/resources/backup/test_backup_plan_lifecycle_rule.py new file mode 100644 --- /dev/null +++ b/test/unit/rules/resources/backup/test_backup_plan_lifecycle_rule.py @@ -0,0 +1,26 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from test.unit.rules import BaseRuleTestCase +from cfnlint.rules.resources.backup.BackupPlanLifecycleRule import BackupPlanLifecycleRule # pylint: disable=E0401 + + +class TestBackupPlanLifecycleRule(BaseRuleTestCase): + """Check Backup Plan rules with lifecycle has minimum 90 day period between cold and delete""" + + def setUp(self): + """Setup""" + super(TestBackupPlanLifecycleRule, self).setUp() + self.collection.register(BackupPlanLifecycleRule()) + self.success_templates = [ + 'test/fixtures/templates/good/resources/backup/test_backup_plan_lifecycle_rule.yml', + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative(self): + """Test failure""" + self.helper_file_negative('test/fixtures/templates/bad/resources/backup/test_backup_plan_lifecycle_rule.yml', 1)
[New Rule] BackupPlan Lifecycle cold to delete minimum difference *cfn-lint version:* 0.58.2 *Description of issue.* In CloudFormation, when deploying a stack with an `AWS::Backup::BackupPlan` lifecycle rule to age off data after moving it to cold storage, the deployment will fail if the `DeleteAfterDays` value is less than 90 days apart from the `MoveToColdStorageAfterDays` period. As an example: <details> <summary>Example failing backup plan</summary> CloudFormation error: ![image](https://user-images.githubusercontent.com/1835431/156852439-202a56a9-e9ca-4cb5-8cdb-3ed19e87d80b.png) Example resource: ```yaml BackupPlan: Type: AWS::Backup::BackupPlan DeletionPolicy: Delete UpdateReplacePolicy: Delete Properties: BackupPlan: BackupPlanName: "invalid-backup-plan" BackupPlanRule: - RuleName: "invalid-rule" TargetBackupVault: !Ref BackupVault ScheduleExpression: "cron(0 0 ? * MON *)" Lifecycle: MoveToColdStorageAfterDays: 7 DeleteAfterDays: 30 ``` </details> Currently this is not picked up by `cfn-lint`. <hr><br> I've opened a PR at #2230 to add in a rule that I think would resolve it, but not entirely sure on the process of adding a brand new rule / service to `cfn-lint`, so please shout if there's anything missing or extra to do. Thanks!
2022-03-04T23:00:21Z
[]
[]
aws-cloudformation/cfn-lint
2,236
aws-cloudformation__cfn-lint-2236
[ "1828" ]
d8e87268175fff335f31d7173354e54e3f28cc68
diff --git a/src/cfnlint/transform.py b/src/cfnlint/transform.py --- a/src/cfnlint/transform.py +++ b/src/cfnlint/transform.py @@ -76,7 +76,10 @@ def _replace_local_codeuri(self): if resource_type == 'AWS::Serverless::Function': - Transform._update_to_s3_uri('CodeUri', resource_dict) + if resource_dict.get('PackageType') == 'Image': + Transform._update_to_s3_uri('ImageUri', resource_dict) + else: + Transform._update_to_s3_uri('CodeUri', resource_dict) auto_publish_alias = resource_dict.get('AutoPublishAlias') if isinstance(auto_publish_alias, dict): if len(auto_publish_alias) == 1:
diff --git a/test/fixtures/templates/good/transform/function_using_image.yaml b/test/fixtures/templates/good/transform/function_using_image.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/transform/function_using_image.yaml @@ -0,0 +1,11 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function + Properties: + PackageType: Image + Metadata: + DockerTag: nodejs14.x-v1 + DockerContext: ./hello-world + Dockerfile: Dockerfile \ No newline at end of file diff --git a/test/unit/module/transform/test_transform.py b/test/unit/module/transform/test_transform.py --- a/test/unit/module/transform/test_transform.py +++ b/test/unit/module/transform/test_transform.py @@ -51,3 +51,12 @@ def test_parameter_for_autopublish_version_bad(self): transformed_template = Transform(filename, template, region) transformed_template.transform_template() self.assertDictEqual(transformed_template._parameters, {}) + + def test_test_function_using_image_good(self): + """Test Parameter is created for autopublish version run""" + filename = 'test/fixtures/templates/good/transform/function_using_image.yaml' + region = 'us-east-1' + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + transformed_template.transform_template() + self.assertDictEqual(transformed_template._parameters, {})
Support for the docker lambda runtime cfn-lint 0.43.0 This is a feature request for supporting docker lambda sam templates. Please provide as much information as possible: * SAM templates produced by aws-sam-cli with the docker deploy option don't pass validation Running on the template.yaml in the base directory outputs the following: ``` % cfn-lint template.yaml E0001 Error transforming template: Resource with id [HelloWorldFunction] is invalid. 'ImageUri' must be set. template.yaml:1:1 ``` Running on the packaged template at `.aws-sam/build/template.yaml` produces the following: ``` E3002 Invalid Property Resources/HelloWorldFunction/Properties/Code/ImageUri .aws-sam/build/template.yaml:12:3 E3002 Invalid Property Resources/HelloWorldFunction/Properties/PackageType .aws-sam/build/template.yaml:12:3 E3003 Property Handler missing at Resources/HelloWorldFunction/Properties .aws-sam/build/template.yaml:12:3 E3003 Property Runtime missing at Resources/HelloWorldFunction/Properties .aws-sam/build/template.yaml:12:3 ```
could you include your template? The second half likely involves https://github.com/aws-cloudformation/cfn-python-lint/issues/1219 since no [Resource Specfications](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) have been released for weeks The first half may be fixed by upgrading SAM: `pip3 install aws-sam-translator --upgrade` [fixes for the second half just merged in yesterday](https://github.com/aws-cloudformation/cfn-python-lint/pull/1831), so the second half will be fixed in the next release This template is working with the newest version of the sam translator. If you leave that value out you will get the error that you have specified but that error is coming from https://github.com/aws/serverless-application-model if you believe it shouldn't exist we may need to create an issue there. ``` Transform: AWS::Serverless-2016-10-31 Resources: HelloWorldFunction: Type: AWS::Serverless::Function Properties: PackageType: Image ImageUri: 123456789.dkr.ecr.region.amazonaws.suffix/myimage:latest ImageConfig: Command: - "app.lambda_handler" EntryPoint: - "entrypoint1" WorkingDirectory: "workDir" ``` v0.44.2 is out and includes the 2nd half fixes that @PatMyron mentioned. @kddejong - I think this needs to be re-opened. The original issue is still present. It was fixed in `sam validate` [here](https://github.com/aws/aws-sam-cli/pull/2892). From that fix, [here ](https://github.com/aws/aws-sam-cli/blob/develop/tests/functional/commands/validate/lib/models/function_with_image_in_metadata.yaml) is a test that will fail cfn-lint. The problem is that cfn-lint passes the template as-is to the transalator, but sam will deploy an image to ECR then add an `ImageUri` before translating.
2022-03-18T15:43:04Z
[]
[]
aws-cloudformation/cfn-lint
2,242
aws-cloudformation__cfn-lint-2242
[ "1657" ]
695055f5a7d7555e07729392a60aa26458cad9c3
diff --git a/src/cfnlint/config.py b/src/cfnlint/config.py --- a/src/cfnlint/config.py +++ b/src/cfnlint/config.py @@ -443,34 +443,36 @@ def get_template_args(self): def set_template_args(self, template): defaults = {} if isinstance(template, dict): - configs = template.get('Metadata', {}).get('cfn-lint', {}).get('config', {}) - - if isinstance(configs, dict): - for config_name, config_value in configs.items(): - if config_name == 'ignore_checks': - if isinstance(config_value, list): - defaults['ignore_checks'] = config_value - if config_name == 'regions': - if isinstance(config_value, list): - defaults['regions'] = config_value - if config_name == 'append_rules': - if isinstance(config_value, list): - defaults['append_rules'] = config_value - if config_name == 'override_spec': - if isinstance(config_value, (str)): - defaults['override_spec'] = config_value - if config_name == 'custom_rules': - if isinstance(config_value, (str)): - defaults['custom_rules'] = config_value - if config_name == 'ignore_bad_template': - if isinstance(config_value, bool): - defaults['ignore_bad_template'] = config_value - if config_name == 'include_checks': - if isinstance(config_value, list): - defaults['include_checks'] = config_value - if config_name == 'configure_rules': - if isinstance(config_value, dict): - defaults['configure_rules'] = config_value + metadata = template.get('Metadata', {}) + if metadata: + configs = template.get('Metadata', {}).get('cfn-lint', {}).get('config', {}) + + if isinstance(configs, dict): + for config_name, config_value in configs.items(): + if config_name == 'ignore_checks': + if isinstance(config_value, list): + defaults['ignore_checks'] = config_value + if config_name == 'regions': + if isinstance(config_value, list): + defaults['regions'] = config_value + if config_name == 'append_rules': + if isinstance(config_value, list): + defaults['append_rules'] = config_value + if config_name == 'override_spec': + if isinstance(config_value, (str)): + defaults['override_spec'] = config_value + if config_name == 'custom_rules': + if isinstance(config_value, (str)): + defaults['custom_rules'] = config_value + if config_name == 'ignore_bad_template': + if isinstance(config_value, bool): + defaults['ignore_bad_template'] = config_value + if config_name == 'include_checks': + if isinstance(config_value, list): + defaults['include_checks'] = config_value + if config_name == 'configure_rules': + if isinstance(config_value, dict): + defaults['configure_rules'] = config_value self._template_args = defaults diff --git a/src/cfnlint/decode/cfn_json.py b/src/cfnlint/decode/cfn_json.py --- a/src/cfnlint/decode/cfn_json.py +++ b/src/cfnlint/decode/cfn_json.py @@ -26,11 +26,6 @@ def __init__(self, message, mapping, key): self.mapping = mapping self.key = key -class NullError(Exception): - """ - Error thrown when the template contains Nulls - """ - def check_duplicates(ordered_pairs, beg_mark, end_mark): """ @@ -40,8 +35,6 @@ def check_duplicates(ordered_pairs, beg_mark, end_mark): """ mapping = dict_node({}, beg_mark, end_mark) for key, value in ordered_pairs: - if value is None: - raise NullError('"{}"'.format(key)) if key in mapping: raise DuplicateError('"{}"'.format(key), mapping, key) mapping[key] = value @@ -424,18 +417,6 @@ def cfn_json_object(self, s_and_end, strict, scan_once, object_hook, object_pair ), ] ) - except NullError as err: - raise JSONDecodeError( - doc=s, - pos=end, - errors=[ - build_match( - message='Null Error {}'.format(err), - doc=s, - pos=end, - ), - ] - ) pairs = {} if object_hook is not None: beg_mark, end_mark = get_beg_end_mark(orginal_end, end + 1, self.newline_indexes) @@ -563,18 +544,6 @@ def cfn_json_object(self, s_and_end, strict, scan_once, object_hook, object_pair ), ] ) - except NullError as err: - raise JSONDecodeError( - doc=s, - pos=end, - errors=[ - build_match( - message='Null Error {}'.format(err), - doc=s, - pos=end, - ), - ] - ) return result, end pairs = dict(pairs) diff --git a/src/cfnlint/decode/cfn_yaml.py b/src/cfnlint/decode/cfn_yaml.py --- a/src/cfnlint/decode/cfn_yaml.py +++ b/src/cfnlint/decode/cfn_yaml.py @@ -136,22 +136,6 @@ def construct_yaml_seq(self, node): assert isinstance(obj, list) return list_node(obj, node.start_mark, node.end_mark) - def construct_yaml_null_error(self, node): - """Throw a null error""" - raise CfnParseError( - self.filename, - [ - build_match( - filename=self.filename, - message='Null value at line {0} column {1}'.format( - node.start_mark.line + 1, node.start_mark.column + 1), - line_number=node.start_mark.line, - column_number=node.start_mark.column, - key=' ', - ) - ] - ) - NodeConstructor.add_constructor( u'tag:yaml.org,2002:map', @@ -165,10 +149,6 @@ def construct_yaml_null_error(self, node): u'tag:yaml.org,2002:seq', NodeConstructor.construct_yaml_seq) -NodeConstructor.add_constructor( - u'tag:yaml.org,2002:null', - NodeConstructor.construct_yaml_null_error) - class MarkedLoader(Reader, Scanner, Parser, Composer, NodeConstructor, Resolver): """ diff --git a/src/cfnlint/rules/conditions/Exists.py b/src/cfnlint/rules/conditions/Exists.py --- a/src/cfnlint/rules/conditions/Exists.py +++ b/src/cfnlint/rules/conditions/Exists.py @@ -45,7 +45,7 @@ def match(self, cfn): ref_conditions[condtree[-1]] = path # Get Output Conditions - for _, output_values in cfn.template.get('Outputs', {}).items(): + for _, output_values in cfn.get_outputs_valid().items(): if 'Condition' in output_values: path = ['Outputs', output_values['Condition']] ref_conditions[output_values['Condition']] = path diff --git a/src/cfnlint/rules/functions/Sub.py b/src/cfnlint/rules/functions/Sub.py --- a/src/cfnlint/rules/functions/Sub.py +++ b/src/cfnlint/rules/functions/Sub.py @@ -35,7 +35,8 @@ def _get_parameters(self, cfn): for param_name, param_values in parameters.items(): # This rule isn't here to check the Types but we need # something valid if it doesn't exist - results[param_name] = param_values.get('Type', 'String') + if isinstance(param_values, dict): + results[param_name] = param_values.get('Type', 'String') return results diff --git a/src/cfnlint/rules/metadata/Config.py b/src/cfnlint/rules/metadata/Config.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/metadata/Config.py @@ -0,0 +1,53 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from cfnlint.rules import CloudFormationLintRule +from cfnlint.rules import RuleMatch + + +class Config(CloudFormationLintRule): + """Check if Metadata configuration is properly configured""" + id = 'E4002' + shortdesc = 'Validate the configuration of the Metadata section' + description = 'Validates that Metadata section is an object and has no null values' + source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/metadata-section-structure.html' + tags = ['metadata'] + + + def _check_object(self, obj, path): + results = [] + if isinstance(obj, (dict)): + for k, v in obj.items(): + results.extend(self._check_object(v, path + [k])) + if isinstance(obj, (list)): + for i, v in enumerate(obj): + results.extend(self._check_object(v, path + [i])) + if obj is None: + message = 'Metadata value cannot be null' + results.append(RuleMatch( + path, + message.format(message) + )) + + return results + + + def match(self, cfn): + """Check CloudFormation Metadata Interface Configuration""" + + matches = [] + + metadata_obj = cfn.template.get('Metadata', {}) + if metadata_obj is None: + message = 'Metadata value has to be an object' + matches.append(RuleMatch( + ['Metadata'], + message.format(message) + )) + + if metadata_obj: + if isinstance(metadata_obj, dict): + matches.extend(self._check_object(metadata_obj, ['Metadata'])) + + return matches diff --git a/src/cfnlint/rules/outputs/Configuration.py b/src/cfnlint/rules/outputs/Configuration.py --- a/src/cfnlint/rules/outputs/Configuration.py +++ b/src/cfnlint/rules/outputs/Configuration.py @@ -88,20 +88,34 @@ def match(self, cfn): if outputs: if isinstance(outputs, dict): for output_name, output_value in outputs.items(): - for prop in output_value: - if prop not in self.valid_keys: - message = 'Output {0} has invalid property {1}' - matches.append(RuleMatch( - ['Outputs', output_name, prop], - message.format(output_name, prop) - )) - value = output_value.get('Value') - if value: - matches.extend(self.check_func(value, ['Outputs', output_name, 'Value'])) - export = output_value.get('Export') - if export: - matches.extend(self.check_export( - export, ['Outputs', output_name, 'Export'])) + if not isinstance(output_value, dict): + message = 'Output {0} is not an object' + matches.append(RuleMatch( + ['Outputs', output_name], + message.format(output_name) + )) + else: + for propname, propvalue in output_value.items(): + if propname not in self.valid_keys: + message = 'Output {0} has invalid property {1}' + matches.append(RuleMatch( + ['Outputs', output_name, propname], + message.format(output_name, propname) + )) + else: + if propvalue is None: + message = 'Output {0} has property {1} has invalid type' + matches.append(RuleMatch( + ['Outputs', output_name, propname], + message.format(output_name, propname) + )) + value = output_value.get('Value') + if value: + matches.extend(self.check_func(value, ['Outputs', output_name, 'Value'])) + export = output_value.get('Export') + if export: + matches.extend(self.check_export( + export, ['Outputs', output_name, 'Export'])) else: matches.append(RuleMatch(['Outputs'], 'Outputs do not follow correct format.')) diff --git a/src/cfnlint/rules/outputs/Description.py b/src/cfnlint/rules/outputs/Description.py --- a/src/cfnlint/rules/outputs/Description.py +++ b/src/cfnlint/rules/outputs/Description.py @@ -17,7 +17,7 @@ class Description(CloudFormationLintRule): def match(self, cfn): matches = [] - outputs = cfn.template.get('Outputs', {}) + outputs = cfn.get_outputs_valid() if outputs: for output_name, output_value in outputs.items(): description = output_value.get('Description') diff --git a/src/cfnlint/rules/outputs/LimitDescription.py b/src/cfnlint/rules/outputs/LimitDescription.py --- a/src/cfnlint/rules/outputs/LimitDescription.py +++ b/src/cfnlint/rules/outputs/LimitDescription.py @@ -17,7 +17,7 @@ class LimitDescription(CloudFormationLintRule): def match(self, cfn): matches = [] - for output_name, output_value in cfn.template.get('Outputs', {}).items(): + for output_name, output_value in cfn.get_outputs_valid().items(): description = output_value.get('Description') if description: path = ['Outputs', output_name, 'Description'] diff --git a/src/cfnlint/rules/outputs/Required.py b/src/cfnlint/rules/outputs/Required.py --- a/src/cfnlint/rules/outputs/Required.py +++ b/src/cfnlint/rules/outputs/Required.py @@ -20,11 +20,12 @@ def match(self, cfn): outputs = cfn.template.get('Outputs', {}) if outputs: for output_name, output_value in outputs.items(): - if 'Value' not in output_value: - message = 'Output {0} is missing property {1}' - matches.append(RuleMatch( - ['Outputs', output_name, 'Value'], - message.format(output_name, 'Value') - )) + if isinstance(output_value, dict): + if 'Value' not in output_value: + message = 'Output {0} is missing property {1}' + matches.append(RuleMatch( + ['Outputs', output_name, 'Value'], + message.format(output_name, 'Value') + )) return matches diff --git a/src/cfnlint/rules/parameters/Configuration.py b/src/cfnlint/rules/parameters/Configuration.py --- a/src/cfnlint/rules/parameters/Configuration.py +++ b/src/cfnlint/rules/parameters/Configuration.py @@ -87,6 +87,11 @@ def check_type(self, value, path, props): """ Check the type and handle recursion with lists """ results = [] prop_type = props.get('Type') + if value is None: + message = 'Property %s should be of type %s' % ( + '/'.join(map(str, path)), prop_type) + results.append(RuleMatch(path, message)) + return results try: if prop_type in ['List']: if isinstance(value, list): @@ -128,34 +133,41 @@ def match(self, cfn): matches = [] for paramname, paramvalue in cfn.get_parameters().items(): - for propname, propvalue in paramvalue.items(): - if propname not in self.valid_keys: - message = 'Parameter {0} has invalid property {1}' - matches.append(RuleMatch( - ['Parameters', paramname, propname], - message.format(paramname, propname) - )) - else: - props = self.valid_keys.get(propname) - prop_path = ['Parameters', paramname, propname] - matches.extend(self.check_type( - propvalue, prop_path, props)) - # Check that the property is needed for the current type - valid_for = props.get('ValidForTypes') - if valid_for is not None and paramvalue.get('Type'): - if paramvalue.get('Type') not in valid_for: - message = 'Parameter {0} has property {1} which is only valid for {2}' - matches.append(RuleMatch( - ['Parameters', paramname, propname], - message.format(paramname, propname, valid_for) - )) + if isinstance(paramvalue, dict): + for propname, propvalue in paramvalue.items(): + if propname not in self.valid_keys: + message = 'Parameter {0} has invalid property {1}' + matches.append(RuleMatch( + ['Parameters', paramname, propname], + message.format(paramname, propname) + )) + else: + props = self.valid_keys.get(propname) + prop_path = ['Parameters', paramname, propname] + matches.extend(self.check_type( + propvalue, prop_path, props)) + # Check that the property is needed for the current type + valid_for = props.get('ValidForTypes') + if valid_for is not None: + if paramvalue.get('Type') not in valid_for: + message = 'Parameter {0} has property {1} which is only valid for {2}' + matches.append(RuleMatch( + ['Parameters', paramname, propname], + message.format(paramname, propname, valid_for) + )) - for reqname in self.required_keys: - if reqname not in paramvalue.keys(): - message = 'Parameter {0} is missing required property {1}' - matches.append(RuleMatch( - ['Parameters', paramname], - message.format(paramname, reqname) - )) + for reqname in self.required_keys: + if reqname not in paramvalue.keys(): + message = 'Parameter {0} is missing required property {1}' + matches.append(RuleMatch( + ['Parameters', paramname], + message.format(paramname, reqname) + )) + else: + message = 'Parameter {0} is not an object' + matches.append(RuleMatch( + ['Parameters', paramname], + message.format(paramname, reqname) + )) return matches diff --git a/src/cfnlint/rules/parameters/Default.py b/src/cfnlint/rules/parameters/Default.py --- a/src/cfnlint/rules/parameters/Default.py +++ b/src/cfnlint/rules/parameters/Default.py @@ -93,7 +93,7 @@ def check_max_length(self, allowed_value, max_length, path): def match(self, cfn): matches = [] - for paramname, paramvalue in cfn.get_parameters().items(): + for paramname, paramvalue in cfn.get_parameters_valid().items(): default_value = paramvalue.get('Default') if default_value is not None: path = ['Parameters', paramname, 'Default'] diff --git a/src/cfnlint/rules/parameters/LimitValue.py b/src/cfnlint/rules/parameters/LimitValue.py --- a/src/cfnlint/rules/parameters/LimitValue.py +++ b/src/cfnlint/rules/parameters/LimitValue.py @@ -23,7 +23,7 @@ def match(self, cfn): # There are no real "Values" in the template, check the "meta" information # (Default, AllowedValue and MaxLength) against the limit - for paramname, paramvalue in cfn.get_parameters().items(): + for paramname, paramvalue in cfn.get_parameters_valid().items(): # Check Default value default_value = paramvalue.get('Default') diff --git a/src/cfnlint/rules/parameters/Types.py b/src/cfnlint/rules/parameters/Types.py --- a/src/cfnlint/rules/parameters/Types.py +++ b/src/cfnlint/rules/parameters/Types.py @@ -18,7 +18,7 @@ class Types(CloudFormationLintRule): def match(self, cfn): matches = [] - for paramname, paramvalue in cfn.get_parameters().items(): + for paramname, paramvalue in cfn.get_parameters_valid().items(): # If the type isn't found we create a valid one # this test isn't about missing required properties for a # parameter. diff --git a/src/cfnlint/rules/resources/NoEcho.py b/src/cfnlint/rules/resources/NoEcho.py --- a/src/cfnlint/rules/resources/NoEcho.py +++ b/src/cfnlint/rules/resources/NoEcho.py @@ -18,10 +18,10 @@ def _get_no_echo_params(self, cfn): """ Get no Echo Params""" no_echo_params = [] for parameter_name, parameter_value in cfn.get_parameters().items(): - noecho = parameter_value.get('NoEcho', default=False) - if bool_compare(noecho, True): - no_echo_params.append(parameter_name) - + if isinstance(parameter_value, dict): + noecho = parameter_value.get('NoEcho', default=False) + if bool_compare(noecho, True): + no_echo_params.append(parameter_name) return no_echo_params def _check_ref(self, cfn, no_echo_params): diff --git a/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py b/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py --- a/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py +++ b/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py @@ -125,7 +125,11 @@ def check_value(self, value, path, **kwargs): primitive_type = kwargs.get('primitive_type', {}) item_type = kwargs.get('item_type', {}) strict_check = kwargs.get('non_strict', self.config['strict']) - if item_type in ['Map']: + + if value is None: + message = 'Property value cannot be null %s' % ('/'.join(map(str, path))) + matches.append(RuleMatch(path, message)) + elif item_type in ['Map']: if isinstance(value, dict): for map_key, map_value in value.items(): if not isinstance(map_value, dict): @@ -165,6 +169,7 @@ def check(self, cfn, properties, specs, spec_type, path): primitive_type=primitive_type, item_type=item_type, non_strict=strict_check, + pass_if_null=True, ) ) @@ -183,6 +188,7 @@ def match_resource_sub_properties(self, properties, property_type, path, cfn): def match_resource_properties(self, properties, resource_type, path, cfn): """Check CloudFormation Properties""" matches = [] + resource_specs = self.resource_specs.get(resource_type, {}).get('Properties', {}) matches.extend(self.check(cfn, properties, resource_specs, resource_type, path)) diff --git a/src/cfnlint/rules/templates/Base.py b/src/cfnlint/rules/templates/Base.py --- a/src/cfnlint/rules/templates/Base.py +++ b/src/cfnlint/rules/templates/Base.py @@ -2,6 +2,7 @@ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ +import datetime from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch @@ -29,6 +30,32 @@ def __init__(self): } self.configure() + def _validate_version(self, template): + results = [] + valid_version = '2010-09-09' + if 'AWSTemplateFormatVersion' in template: + version = template.get('AWSTemplateFormatVersion') + if not isinstance(version, (str, datetime.date)): + message = 'AWSTemplateFormatVersion only valid value is {0}' + results.append(RuleMatch(['AWSTemplateFormatVersion'], message.format(valid_version))) + else: + if version != valid_version and version != datetime.datetime.strptime(valid_version, '%Y-%m-%d').date(): + message = 'AWSTemplateFormatVersion only valid value is {0}' + results.append(RuleMatch(['AWSTemplateFormatVersion'], message.format(valid_version))) + return results + + def _validate_transform(self, transforms): + results = [] + if not isinstance(transforms, (list, str)): + message = 'Transform has to be a list or string' + results.append(RuleMatch(['Transform'], message.format())) + return results + + if not isinstance(transforms, list): + transforms = [transforms] + + return results + def match(self, cfn): matches = [] @@ -44,4 +71,7 @@ def match(self, cfn): message = 'Missing top level template section {0}' matches.append(RuleMatch([y], message.format(y))) + matches.extend(self._validate_version(cfn.template)) + if 'Transform' in cfn.template: + matches.extend(self._validate_transform(cfn.template.get('Transform'))) return matches diff --git a/src/cfnlint/rules/templates/Description.py b/src/cfnlint/rules/templates/Description.py --- a/src/cfnlint/rules/templates/Description.py +++ b/src/cfnlint/rules/templates/Description.py @@ -18,9 +18,10 @@ def match(self, cfn): matches = [] description = cfn.template.get('Description') + if not 'Description' in cfn.template: + return matches - if description: - if not isinstance(description, str): - message = 'Description can only be a string' - matches.append(RuleMatch(['Description'], message)) + if not isinstance(description, str): + message = 'Description can only be a string' + matches.append(RuleMatch(['Description'], message)) return matches diff --git a/src/cfnlint/rules/templates/LimitDescription.py b/src/cfnlint/rules/templates/LimitDescription.py --- a/src/cfnlint/rules/templates/LimitDescription.py +++ b/src/cfnlint/rules/templates/LimitDescription.py @@ -18,7 +18,8 @@ class LimitDescription(CloudFormationLintRule): def match(self, cfn): matches = [] description = cfn.template.get('Description', '') - if len(description) > LIMITS['template']['description']: - message = 'The template description ({0} bytes) exceeds the limit ({1} bytes)' - matches.append(RuleMatch(['Description'], message.format(len(description), LIMITS['template']['description']))) + if isinstance(description, str): + if len(description) > LIMITS['template']['description']: + message = 'The template description ({0} bytes) exceeds the limit ({1} bytes)' + matches.append(RuleMatch(['Description'], message.format(len(description), LIMITS['template']['description']))) return matches diff --git a/src/cfnlint/template.py b/src/cfnlint/template.py --- a/src/cfnlint/template.py +++ b/src/cfnlint/template.py @@ -12,7 +12,7 @@ LOGGER = logging.getLogger(__name__) -class Template(object): # pylint: disable=R0904 +class Template(object): # pylint: disable=R0904,too-many-lines """Class for a CloudFormation template""" # pylint: disable=dangerous-default-value @@ -88,6 +88,30 @@ def get_parameters(self): return parameters + def get_parameters_valid(self): + LOGGER.debug('Get parameters from template...') + result = {} + if isinstance(self.template.get('Parameters'), dict): + parameters = self.template.get('Parameters') + for parameter_name, parameter_value in parameters.items(): + if isinstance(parameter_value, dict): + if isinstance(parameter_value.get('Type'), str): + result[parameter_name] = parameter_value + + return result + + def get_outputs_valid(self): + LOGGER.debug('Get outputs from template...') + result = {} + if isinstance(self.template.get('Outputs'), dict): + parameters = self.template.get('Outputs') + for parameter_name, parameter_value in parameters.items(): + if isinstance(parameter_value, dict): + if isinstance(parameter_value.get('Value'), (str, dict)): + result[parameter_name] = parameter_value + + return result + def get_modules(self): """Get Modules""" LOGGER.debug('Get modules from template...') @@ -136,11 +160,12 @@ def get_valid_refs(self): parameters = self.template.get('Parameters', {}) if parameters: for name, value in parameters.items(): - if 'Type' in value: - element = {} - element['Type'] = value['Type'] - element['From'] = 'Parameters' - results[name] = element + if isinstance(value, dict): + if 'Type' in value: + element = {} + element['Type'] = value['Type'] + element['From'] = 'Parameters' + results[name] = element resources = self.template.get('Resources', {}) if resources: for name, value in resources.items(): @@ -567,56 +592,62 @@ def check_value(self, obj, key, path, check_value=None, check_ref=None, check_get_att=None, check_find_in_map=None, check_split=None, check_join=None, check_import_value=None, check_sub=None, - **kwargs): + pass_if_null=False, **kwargs): LOGGER.debug('Check value %s for %s', key, obj) matches = [] values_obj = self.get_values(obj=obj, key=key) new_path = path[:] + [key] - if not values_obj: + if values_obj is None and pass_if_null: + if check_value: + matches.extend( + check_value( + value=values_obj, path=new_path[:], **kwargs)) + elif not values_obj: return matches - for value_obj in values_obj: - value = value_obj['Value'] - child_path = value_obj['Path'] - if not isinstance(value, dict): - if check_value: - matches.extend( - check_value( - value=value, path=new_path[:] + child_path, **kwargs)) - else: - if len(value) == 1: - for dict_name, _ in value.items(): - # If this is a function we shouldn't fall back to a check_value check - if dict_name in cfnlint.helpers.FUNCTIONS: - # convert the function name from camel case to underscore - # Example: Fn::FindInMap becomes check_find_in_map - function_name = 'check_%s' % camel_to_snake( - dict_name.replace('Fn::', '')) - if function_name == 'check_ref': - if check_ref: - matches.extend( - check_ref( - value=value.get('Ref'), path=new_path[:] + child_path + ['Ref'], - parameters=self.get_parameters(), - resources=self.get_resources(), - **kwargs)) - else: - if locals().get(function_name): - matches.extend( - locals()[function_name]( - value=value.get(dict_name), - path=new_path[:] + child_path + [dict_name], - **kwargs) - ) - else: - if check_value: - matches.extend( - check_value( - value=value, path=new_path[:] + child_path, **kwargs)) - else: + else: + for value_obj in values_obj: + value = value_obj['Value'] + child_path = value_obj['Path'] + if not isinstance(value, dict): if check_value: matches.extend( check_value( value=value, path=new_path[:] + child_path, **kwargs)) + else: + if len(value) == 1: + for dict_name, _ in value.items(): + # If this is a function we shouldn't fall back to a check_value check + if dict_name in cfnlint.helpers.FUNCTIONS: + # convert the function name from camel case to underscore + # Example: Fn::FindInMap becomes check_find_in_map + function_name = 'check_%s' % camel_to_snake( + dict_name.replace('Fn::', '')) + if function_name == 'check_ref': + if check_ref: + matches.extend( + check_ref( + value=value.get('Ref'), path=new_path[:] + child_path + ['Ref'], + parameters=self.get_parameters(), + resources=self.get_resources(), + **kwargs)) + else: + if locals().get(function_name): + matches.extend( + locals()[function_name]( + value=value.get(dict_name), + path=new_path[:] + child_path + [dict_name], + **kwargs) + ) + else: + if check_value: + matches.extend( + check_value( + value=value, path=new_path[:] + child_path, **kwargs)) + else: + if check_value: + matches.extend( + check_value( + value=value, path=new_path[:] + child_path, **kwargs)) return matches
diff --git a/test/fixtures/templates/bad/conditions.yaml b/test/fixtures/templates/bad/conditions.yaml --- a/test/fixtures/templates/bad/conditions.yaml +++ b/test/fixtures/templates/bad/conditions.yaml @@ -48,6 +48,7 @@ Conditions: "Fn::Of": - !Not [!Equals [!Ref EnvType, ""]] - !Not [!Equals [!Ref EnableGeoBlocking, ""]] + NullCondition: null Resources: EC2Instance: Type: "AWS::EC2::Instance" diff --git a/test/fixtures/templates/bad/conditions/and.yaml b/test/fixtures/templates/bad/conditions/and.yaml --- a/test/fixtures/templates/bad/conditions/and.yaml +++ b/test/fixtures/templates/bad/conditions/and.yaml @@ -18,4 +18,6 @@ Conditions: - {'Condition': 'TestAndToLittle'} TestAndBadCondition: !And [{'Condition': 'TestAndToMany', 'Extra': 'ThisIsBad'}, {'Bad': 'TestAndToMany'}] TestAndBadArray: !And ['Test', 'Test2'] + TestAndNull: + Fn::And: null Resources: {} diff --git a/test/fixtures/templates/bad/conditions/equals.yaml b/test/fixtures/templates/bad/conditions/equals.yaml --- a/test/fixtures/templates/bad/conditions/equals.yaml +++ b/test/fixtures/templates/bad/conditions/equals.yaml @@ -19,5 +19,6 @@ Conditions: - Ref: AWS::Region Fn::Select: [Environments, 0] - "dev" - + NullEquals: + Fn::Equals: null Resources: {} diff --git a/test/fixtures/templates/bad/conditions/not.yaml b/test/fixtures/templates/bad/conditions/not.yaml --- a/test/fixtures/templates/bad/conditions/not.yaml +++ b/test/fixtures/templates/bad/conditions/not.yaml @@ -5,4 +5,6 @@ Conditions: TestNotToMany: !Not [{'Condition': 'TestNotToMany'}, {'Condition': 'TestNotToMany'}] TestNotBadCondition: !Not [{'Condition': 'TestOrToMany', 'Extra': 'ThisIsBad'}] TestNotBadArray: !Not ['Test'] + NotNull: + Fn::Not: null Resources: {} diff --git a/test/fixtures/templates/bad/conditions/or.yaml b/test/fixtures/templates/bad/conditions/or.yaml --- a/test/fixtures/templates/bad/conditions/or.yaml +++ b/test/fixtures/templates/bad/conditions/or.yaml @@ -18,4 +18,6 @@ Conditions: - {'Condition': 'TestOrToLittle'} TestOrBadCondition: !Or [{'Condition': 'TestOrToMany', 'Extra': 'ThisIsBad'}, {'Bad': 'Value'}] TestOrBadArray: !Or ['Test', 'Test2'] + OrNull: + Fn::Or: null Resources: {} diff --git a/test/fixtures/templates/bad/mappings/configuration.yaml b/test/fixtures/templates/bad/mappings/configuration.yaml --- a/test/fixtures/templates/bad/mappings/configuration.yaml +++ b/test/fixtures/templates/bad/mappings/configuration.yaml @@ -26,6 +26,12 @@ Mappings: "64": - Extra - Values + MapNull: null + MapKeyNull: + Key: null + MapNameNull: + Key: + Name: null Resources: myEC2Instance: Type: "AWS::EC2::Instance" diff --git a/test/fixtures/templates/bad/metadata/config.yaml b/test/fixtures/templates/bad/metadata/config.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/metadata/config.yaml @@ -0,0 +1,7 @@ +Metadata: + nullkey: null + nestednull: + key: null + listnull: + - key: null +Resources: {} \ No newline at end of file diff --git a/test/fixtures/templates/bad/metadata/config_null.yaml b/test/fixtures/templates/bad/metadata/config_null.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/metadata/config_null.yaml @@ -0,0 +1,2 @@ +Metadata: null +Resources: {} diff --git a/test/fixtures/templates/bad/null_values.json b/test/fixtures/templates/bad/null_values.json deleted file mode 100644 --- a/test/fixtures/templates/bad/null_values.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "AWSTemplateFormatVersion": "2010-09-09", - "Resources": { - "myInstance": { - "Type": "AWS::EC2::Instance", - "Properties": { - "ImageId": "ami-123456", - "EbsOptimized": null - } - } - } -} diff --git a/test/fixtures/templates/bad/null_values.yaml b/test/fixtures/templates/bad/null_values.yaml deleted file mode 100644 --- a/test/fixtures/templates/bad/null_values.yaml +++ /dev/null @@ -1,8 +0,0 @@ -AWSTemplateFormatVersion: "2010-09-09" - -Resources: - myInstance: - Type: AWS::EC2::Instance - Properties: - ImageId: ami-123456 - EbsOptimized: diff --git a/test/fixtures/templates/bad/outputs/configuration.yaml b/test/fixtures/templates/bad/outputs/configuration.yaml --- a/test/fixtures/templates/bad/outputs/configuration.yaml +++ b/test/fixtures/templates/bad/outputs/configuration.yaml @@ -61,3 +61,13 @@ Outputs: Bad: key invalidDescription: Description: !Ref test + outputDescriptionNull: + Description: null + Value: test + outputExportNull: + Export: null + Value: test + outputNull: null + outputConditionNull: + Condition: null + Value: test diff --git a/test/fixtures/templates/bad/parameters/configuration.yaml b/test/fixtures/templates/bad/parameters/configuration.yaml --- a/test/fixtures/templates/bad/parameters/configuration.yaml +++ b/test/fixtures/templates/bad/parameters/configuration.yaml @@ -28,6 +28,33 @@ Parameters: mySsmParam: # Invalid SSM Parameter type Type: AWS::SSM::Parameter::Value<Test> + #### + # A bunch of NULL value tests + #### + NullParameter: null + NullParamType: + Type: null + NullParamDefault: + Type: String + Default: null + NullParamDescription: + Type: String + Description: null + NullParamMaxValue: + Type: Number + MaxValue: null + NullParamMinValue: + Type: Number + MinValue: null + NullParamMaxLength: + Type: String + MaxLength: null + NullParamMinLength: + Type: String + MinLength: null + NullParamNoEcho: + Type: String + NoEcho: null Resources: # Helps tests map resource types IamPipeline: diff --git a/test/fixtures/templates/bad/resources/properties/primitive_types.yaml b/test/fixtures/templates/bad/resources/properties/primitive_types.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources/properties/primitive_types.yaml @@ -0,0 +1,18 @@ +AWSTemplateFormatVersion: 2010-09-09 + +Resources: + rIamRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: {'test': 'test'} + rLambda: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !Ref rIamRole + Runtime: + Code: + ZipFile: | + def handler(event, context): + print(event) + return \ No newline at end of file diff --git a/test/fixtures/templates/bad/templates/base.yaml b/test/fixtures/templates/bad/templates/base.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/templates/base.yaml @@ -0,0 +1,4 @@ +AWSTemplateFormatVersion: "2010-09-10" +Transform: + key: ATransform +Resources: {} \ No newline at end of file diff --git a/test/fixtures/templates/bad/templates/base_date.yaml b/test/fixtures/templates/bad/templates/base_date.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/templates/base_date.yaml @@ -0,0 +1,2 @@ +AWSTemplateFormatVersion: 2010-09-10 +Resources: {} \ No newline at end of file diff --git a/test/fixtures/templates/bad/templates/base_null.yaml b/test/fixtures/templates/bad/templates/base_null.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/templates/base_null.yaml @@ -0,0 +1,3 @@ +AWSTemplateFormatVersion: null +Transform: null +Resources: {} \ No newline at end of file diff --git a/test/fixtures/templates/bad/templates/description_null.yaml b/test/fixtures/templates/bad/templates/description_null.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/templates/description_null.yaml @@ -0,0 +1,4 @@ +--- +AWSTemplateFormatVersion: "2010-09-09" +Description: null +Resources: {} diff --git a/test/unit/module/test_null_values.py b/test/unit/module/test_null_values.py --- a/test/unit/module/test_null_values.py +++ b/test/unit/module/test_null_values.py @@ -36,29 +36,3 @@ def test_success_run(self): def test_fail_json_run(self): """Test failure run""" - def test_fail_run(self): - """Test failure run""" - - filename = 'test/fixtures/templates/bad/null_values.json' - - try: - with open(filename) as fp: - json.load(fp, cls=cfnlint.decode.cfn_json.CfnJSONDecoder) - except cfnlint.decode.cfn_json.JSONDecodeError as err: - self.assertIn("Null Error \"EbsOptimized\"", err.msg) - return - - assert(False) - - def test_fail_yaml_run(self): - """Test failure run""" - - filename = 'test/fixtures/templates/bad/null_values.yaml' - - try: - cfnlint.decode.cfn_yaml.load(filename) - except cfnlint.decode.cfn_yaml.CfnParseError: - assert(True) - return - - assert(False) diff --git a/test/unit/rules/conditions/test_and.py b/test/unit/rules/conditions/test_and.py --- a/test/unit/rules/conditions/test_and.py +++ b/test/unit/rules/conditions/test_and.py @@ -24,4 +24,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/conditions/and.yaml', 7) + self.helper_file_negative('test/fixtures/templates/bad/conditions/and.yaml', 8) diff --git a/test/unit/rules/conditions/test_configuration.py b/test/unit/rules/conditions/test_configuration.py --- a/test/unit/rules/conditions/test_configuration.py +++ b/test/unit/rules/conditions/test_configuration.py @@ -20,4 +20,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/conditions.yaml', 3) + self.helper_file_negative('test/fixtures/templates/bad/conditions.yaml', 4) diff --git a/test/unit/rules/conditions/test_equals.py b/test/unit/rules/conditions/test_equals.py --- a/test/unit/rules/conditions/test_equals.py +++ b/test/unit/rules/conditions/test_equals.py @@ -23,4 +23,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/conditions/equals.yaml', 8) + self.helper_file_negative('test/fixtures/templates/bad/conditions/equals.yaml', 9) diff --git a/test/unit/rules/conditions/test_not.py b/test/unit/rules/conditions/test_not.py --- a/test/unit/rules/conditions/test_not.py +++ b/test/unit/rules/conditions/test_not.py @@ -24,4 +24,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/conditions/not.yaml', 4) + self.helper_file_negative('test/fixtures/templates/bad/conditions/not.yaml', 5) diff --git a/test/unit/rules/conditions/test_or.py b/test/unit/rules/conditions/test_or.py --- a/test/unit/rules/conditions/test_or.py +++ b/test/unit/rules/conditions/test_or.py @@ -24,4 +24,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/conditions/or.yaml', 7) + self.helper_file_negative('test/fixtures/templates/bad/conditions/or.yaml', 8) diff --git a/test/unit/rules/conditions/test_used.py b/test/unit/rules/conditions/test_used.py --- a/test/unit/rules/conditions/test_used.py +++ b/test/unit/rules/conditions/test_used.py @@ -24,4 +24,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/conditions.yaml', 4) + self.helper_file_negative('test/fixtures/templates/bad/conditions.yaml', 5) diff --git a/test/unit/rules/mappings/test_configuration.py b/test/unit/rules/mappings/test_configuration.py --- a/test/unit/rules/mappings/test_configuration.py +++ b/test/unit/rules/mappings/test_configuration.py @@ -23,4 +23,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/mappings/configuration.yaml', 3) + self.helper_file_negative('test/fixtures/templates/bad/mappings/configuration.yaml', 6) diff --git a/test/unit/rules/metadata/test_config.py b/test/unit/rules/metadata/test_config.py new file mode 100644 --- /dev/null +++ b/test/unit/rules/metadata/test_config.py @@ -0,0 +1,27 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from test.unit.rules import BaseRuleTestCase +from cfnlint.rules.metadata.Config import Config # pylint: disable=E0401 + + +class TestOutputRequired(BaseRuleTestCase): + """Test template parameter configurations""" + + def setUp(self): + """Setup""" + super(TestOutputRequired, self).setUp() + self.collection.register(Config()) + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative(self): + """Test failure""" + self.helper_file_negative('test/fixtures/templates/bad/metadata/config.yaml', 3) + + def test_file_config_null(self): + """Test failure""" + self.helper_file_negative('test/fixtures/templates/bad/metadata/config_null.yaml', 1) diff --git a/test/unit/rules/outputs/test_configuration.py b/test/unit/rules/outputs/test_configuration.py --- a/test/unit/rules/outputs/test_configuration.py +++ b/test/unit/rules/outputs/test_configuration.py @@ -20,4 +20,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/outputs/configuration.yaml', 8) + self.helper_file_negative('test/fixtures/templates/bad/outputs/configuration.yaml', 12) diff --git a/test/unit/rules/parameters/test_configuration.py b/test/unit/rules/parameters/test_configuration.py --- a/test/unit/rules/parameters/test_configuration.py +++ b/test/unit/rules/parameters/test_configuration.py @@ -20,4 +20,4 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/parameters/configuration.yaml', 7) + self.helper_file_negative('test/fixtures/templates/bad/parameters/configuration.yaml', 16) diff --git a/test/unit/rules/parameters/test_used.py b/test/unit/rules/parameters/test_used.py --- a/test/unit/rules/parameters/test_used.py +++ b/test/unit/rules/parameters/test_used.py @@ -24,7 +24,7 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative('test/fixtures/templates/bad/parameters/configuration.yaml', 8) + self.helper_file_negative('test/fixtures/templates/bad/parameters/configuration.yaml', 17) def test_file_negative_removed(self): """Test failure""" diff --git a/test/unit/rules/resources/properties/test_value_primitive_type.py b/test/unit/rules/resources/properties/test_value_primitive_type.py --- a/test/unit/rules/resources/properties/test_value_primitive_type.py +++ b/test/unit/rules/resources/properties/test_value_primitive_type.py @@ -24,6 +24,12 @@ def test_file_positive(self): """Test Positive""" self.helper_file_positive() + def test_bad_null_values(self): + """Test strict false""" + self.helper_file_negative( + 'test/fixtures/templates/bad/resources/properties/primitive_types.yaml', 1 + ) + def test_template_config(self): """Test strict false""" self.helper_file_rule_config( diff --git a/test/unit/rules/templates/test_base_template.py b/test/unit/rules/templates/test_base_template.py --- a/test/unit/rules/templates/test_base_template.py +++ b/test/unit/rules/templates/test_base_template.py @@ -29,3 +29,15 @@ def test_file_positive_configured(self): def test_file_negative(self): """Test failure""" self.helper_file_negative('test/fixtures/templates/bad/generic.yaml', 1) + + def test_file_base(self): + """Test failure""" + self.helper_file_negative('test/fixtures/templates/bad/templates/base.yaml', 2) + + def test_file_base_date(self): + """Test failure""" + self.helper_file_negative('test/fixtures/templates/bad/templates/base_date.yaml', 1) + + def test_file_base_null(self): + """Test failure""" + self.helper_file_negative('test/fixtures/templates/bad/templates/base_null.yaml', 2) diff --git a/test/unit/rules/templates/test_description.py b/test/unit/rules/templates/test_description.py --- a/test/unit/rules/templates/test_description.py +++ b/test/unit/rules/templates/test_description.py @@ -24,3 +24,7 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" self.helper_file_negative('test/fixtures/templates/bad/templates/description.yaml', 1) + + def test_file_description_null(self): + """Test failure""" + self.helper_file_negative('test/fixtures/templates/bad/templates/description_null.yaml', 1)
Using null in AWS::Serverless::StateMachine in the ResultPath throws incorrect E0000 error StateMachines allow for a null value in the ResultPath Property to [pass input directly to the output](https://docs.aws.amazon.com/step-functions/latest/dg/input-output-resultpath.html) Below is a minimal example of a template that is proper but flagged as invalid ``` AWSTemplateFormatVersion: 2010-09-09 Transform: AWS::Serverless-2016-10-31 Resources: rLambda: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: python3.6 InlineCode: | def handler(event, context): print(event) return rTestMachine: Type: AWS::Serverless::StateMachine Properties: Definition: StartAt: myState States: myState: Type: Task Resource: !GetAtt rLambda.Arn ResultPath: null End: true Policies: - Statement: - Sid: Test Effect: Allow Action: - lambda:Invoke* Resource: !GetAtt rLambda.Arn ``` Adding quotes around null does not resolve the issue as the value of the property needs to evaluate to null. An exception for null checking should be added for this Parameter
Thanks for submitting this issue. For my tracking this is the translated template. This gets translated to string which masks the null to the CloudFormation service. The cfn-lint ordering may be adjust to handle this situation correctly. ``` "DefinitionString": { "Fn::Join": [ "\n", [ "{", " \"StartAt\": \"myState\",", " \"States\": {", " \"myState\": {", " \"End\": true,", " \"Resource\": \"${definition_substitution_1}\",", " \"ResultPath\": null,", " \"Type\": \"Task\"", " }", " }", "}" ] ] }, ``` If this remained as yaml or json (not as a string) and wasn't translated by SAM there would be a `[/Resources/rTestMachine/Type/DefinitionString/States/myState/ResultPath] 'null' values are not allowed in templates` error. Hi is there any workaround for this until the bug is resolved? Other than using json! Thanks. I tried this but it doesn't stop it erroring. ``` Resources: StateMachine: Type: AWS::Serverless::StateMachine Metadata: cfn-lint: config: ignore_checks: - E0000 ``` Unfortunately, the [Serverless Transform](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-aws-serverless.html) drops [attributes like `Metadata`](https://github.com/aws/serverless-application-model/issues/450#issuecomment-643420308) for [`AWS::Serverless` resource types](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-resources-and-properties.html) Thanks for getting back to me so quickly. Does this apply for whole template as well? I tried the below but still have the same problem: ``` AWSTemplateFormatVersion: "2010-09-09" Transform: AWS::Serverless-2016-10-31 Description: UI Cypress testing resources Metadata: cfn-lint: config: ignore_checks: - E0000 ``` Hi, With [SAM v1.36.0](https://github.com/aws/serverless-application-model/releases/tag/v1.36.0) and [SAM CLI v1.24.0](https://github.com/aws/aws-sam-cli/releases/tag/v1.24.0) versions, we now support adding Metadata to the serverless resources. Can you verify if that will help with your use case? Thanks! Where are we at with this? It's 2022 and the problem still persists in CloudFormation with YAML. Any ETA as to when this will be fixed? it's forcing our step after our map to handle our incoming input in a remarkably awkward way
2022-03-25T19:54:53Z
[]
[]
aws-cloudformation/cfn-lint
2,253
aws-cloudformation__cfn-lint-2253
[ "2063" ]
bc2dff3bb97f0a95c35c6daedbf4e3a573f3d171
diff --git a/src/cfnlint/rules/resources/properties/Properties.py b/src/cfnlint/rules/resources/properties/Properties.py --- a/src/cfnlint/rules/resources/properties/Properties.py +++ b/src/cfnlint/rules/resources/properties/Properties.py @@ -36,7 +36,7 @@ def primitivetypecheck(self, value, primtype, proppath): """ matches = [] - if isinstance(value, list) or value == {'Ref': 'AWS::NotificationARNs'}: + if (isinstance(value, list) and primtype != 'Json') or value == {'Ref': 'AWS::NotificationARNs'}: message = 'Property should be of type %s not List at %s' % ( primtype, '/'.join(map(str, proppath))) matches.append(RuleMatch(proppath, message))
diff --git a/test/fixtures/templates/good/resource_properties.yaml b/test/fixtures/templates/good/resource_properties.yaml --- a/test/fixtures/templates/good/resource_properties.yaml +++ b/test/fixtures/templates/good/resource_properties.yaml @@ -740,3 +740,14 @@ Resources: Status: Enabled - - !Ref "AWS::NoValue" + SSMParameterJsonList: + Type: AWS::SSM::Parameter + Properties: + Description: Human Readable Description + Name: /path/of/param + Tags: + - {Key: ENVIRONMENT, Value: test} + - {Key: RESOURCE_NAME, Value: broker_dns_addresses} + - {Key: STACK_NAME, Value: example-service} + Type: StringList + Value: ValueOfParam
E3012 Property should be of type Json - incorrectly flagging official examples *cfn-lint version:* 0.51.0 *Description of issue.* After upgrading to 0.51.0 today, we are now seeing new lint issues. Specifically `E3012 Property should be of type Json` on the parameters section of `AWS::SSM::Association` Even the example from the official docs is flagged by cfn-lint now. e.g. ```yaml Resources: SpecificInstanceIdAssociation: Type: AWS::SSM::Association Properties: Name: AWS-RunShellScript Targets: - Key: InstanceIds Values: - i-1234567890abcdef0 Parameters: commands: - ls workingDirectory: - "/" WaitForSuccessTimeoutSeconds: 300 ``` `E3012 Property should be of type Json at Resources/SpecificInstanceIdAssociation/Properties/Parameters/commands test.yaml:11:9` `E3012 Property should be of type Json at Resources/SpecificInstanceIdAssociation/Properties/Parameters/workingDirectory test.yaml:13:9`
See pinned issue https://github.com/aws-cloudformation/cfn-lint/issues/547 @PatMyron This appears to be more than an issue of strict typing. Templates that are accepted by cloudformation are failing the linting checks. For example, this template deploys without error ```yaml AWSTemplateFormatVersion: '2010-09-09' Resources: SSMGetInventoryAssociation: Type: AWS::SSM::Association Properties: Name: AWS-GatherSoftwareInventory AssociationName: gather-inventory Parameters: applications: - Enabled awsComponents: - Enabled customInventory: - Enabled instanceDetailedInformation: - Enabled networkConfig: - Enabled services: - Enabled windowsRoles: - Enabled windowsUpdates: - Enabled ScheduleExpression: rate(3 days) Targets: - Key: InstanceIds Values: - '*' ``` But cfn-lint produces ```E3012 Property should be of type Json at Resources/SSMGetInventoryAssociation/Properties/Parameters/applications test-assoc.yaml:9:11 E3012 Property should be of type Json at Resources/SSMGetInventoryAssociation/Properties/Parameters/awsComponents test-assoc.yaml:11:11 E3012 Property should be of type Json at Resources/SSMGetInventoryAssociation/Properties/Parameters/customInventory test-assoc.yaml:13:11 E3012 Property should be of type Json at Resources/SSMGetInventoryAssociation/Properties/Parameters/instanceDetailedInformation test-assoc.yaml:15:11 E3012 Property should be of type Json at Resources/SSMGetInventoryAssociation/Properties/Parameters/networkConfig test-assoc.yaml:17:11 E3012 Property should be of type Json at Resources/SSMGetInventoryAssociation/Properties/Parameters/services test-assoc.yaml:19:11 E3012 Property should be of type Json at Resources/SSMGetInventoryAssociation/Properties/Parameters/windowsRoles test-assoc.yaml:21:11 E3012 Property should be of type Json at Resources/SSMGetInventoryAssociation/Properties/Parameters/windowsUpdates test-assoc.yaml:23:11``` looking into this Not sure what started the issue as that rule didn't change but a list is still valid json and we should consider it so. Fixing the issue inside E3012 @kddejong The changes in the cloudspecs in https://github.com/aws-cloudformation/cfn-lint/pull/2039/ line up with when we started seeing errors on our end. > Not sure what started the issue as that rule didn't change but a list is still valid json and we should consider it so. Fixing the issue inside E3012 think @omkhegde [changed resource specification format recently](https://code.amazon.com/r/CR-51080450) since [`List` isn't a documented primitive type](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification-format.html#cfn-resource-specification-format-propertytypes) Thanks for the quick fix all - really appreciate it. Hello. I am a bit new and am seeing this on the following data: ``` [E3002: Resource properties are valid] (Property should be of type Json not List at Resources/ResourceName/Properties/Tags) ``` the tags in question: ```yaml Resources: ResourceName: Properties: Description: Human Readable Description Name: /path/of/param Tags: - {Key: ENVIRONMENT, Value: test} - {Key: RESOURCE_NAME, Value: broker_dns_addresses} - {Key: STACK_NAME, Value: example-service} Type: StringList Value: ValueOfParam ``` Could you hint me if the problem lies on my end? Thank you! @evilensky that can be the same template? Maybe a spacing issue. That template gives me ``` E3001 Type not defined for resource ResourceName local/issue/2063-1.yaml:2:3 ``` I'm guessing you meant ``` Resources: ResourceName: Type: AWS::SSM::Parameter Properties: Description: Human Readable Description Name: /path/of/param Tags: - {Key: ENVIRONMENT, Value: test} - {Key: RESOURCE_NAME, Value: broker_dns_addresses} - {Key: STACK_NAME, Value: example-service} Type: StringList Value: ValueOfParam ``` Putting in another fix for that
2022-04-19T15:16:41Z
[]
[]
aws-cloudformation/cfn-lint
2,317
aws-cloudformation__cfn-lint-2317
[ "2313" ]
e9eee01f5f75c215ab927601b927e4b0326273ea
diff --git a/src/cfnlint/rules/resources/RetentionPeriodOnResourceTypesWithAutoExpiringContent.py b/src/cfnlint/rules/resources/RetentionPeriodOnResourceTypesWithAutoExpiringContent.py --- a/src/cfnlint/rules/resources/RetentionPeriodOnResourceTypesWithAutoExpiringContent.py +++ b/src/cfnlint/rules/resources/RetentionPeriodOnResourceTypesWithAutoExpiringContent.py @@ -2,6 +2,7 @@ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ +import re from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch @@ -17,7 +18,6 @@ class RetentionPeriodOnResourceTypesWithAutoExpiringContent(CloudFormationLintRu tags = ['resources', 'retentionperiod'] def _check_ref(self, value, parameters, resources, path): # pylint: disable=W0613 - print('called') print(value) def match(self, cfn): @@ -62,7 +62,9 @@ def match(self, cfn): 'AWS::RDS::DBInstance': [ { 'Attribute': 'BackupRetentionPeriod', - 'SourceUrl': 'http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-backupretentionperiod' + 'SourceUrl': 'http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-backupretentionperiod', + 'CheckAttribute': 'Engine', + 'CheckAttributeRegex': re.compile('^((?!aurora).)*$'), } ], 'AWS::RDS::DBCluster': [ @@ -81,23 +83,29 @@ def match(self, cfn): for property_set, path in property_sets: error_path = ['Resources', r_name] + path if not property_set: - message = 'The default retention period will delete the data after a pre-defined time. Set an explicit values to avoid data loss on resource : %s' % '/'.join( - str(x) for x in error_path) + message = f'The default retention period will delete the data after a pre-defined time. Set an explicit values to avoid data loss on resource : {"/".join(str(x) for x in error_path)}' matches.append(RuleMatch(error_path, message)) else: value = property_set.get(attr_def.get('Attribute')) if not value: - message = 'The default retention period will delete the data after a pre-defined time. Set an explicit values to avoid data loss on resource : %s' % '/'.join( - str(x) for x in error_path) - matches.append(RuleMatch(error_path, message)) + message = f'The default retention period will delete the data after a pre-defined time. Set an explicit values to avoid data loss on resource : {"/".join(str(x) for x in error_path)}' + if attr_def.get('CheckAttribute'): + if self._validate_property(property_set.get(attr_def.get('CheckAttribute')), attr_def.get('CheckAttributeRegex')): + matches.append(RuleMatch(error_path, message)) + else: + matches.append(RuleMatch(error_path, message)) if isinstance(value, dict): # pylint: disable=protected-access refs = cfn._search_deep_keys( 'Ref', value, error_path + [attr_def.get('Attribute')]) for ref in refs: if ref[-1] == 'AWS::NoValue': - message = 'The default retention period will delete the data after a pre-defined time. Set an explicit values to avoid data loss on resource : %s' % '/'.join( - str(x) for x in ref[0:-1]) + message = f'The default retention period will delete the data after a pre-defined time. Set an explicit values to avoid data loss on resource : {"/".join(str(x) for x in ref[0:-1])}' matches.append(RuleMatch(ref[0:-1], message)) return matches + + def _validate_property(self, value, regex) -> bool: + if regex.match(value): + return True + return False
diff --git a/test/fixtures/templates/bad/resources/rds/retention_period.yaml b/test/fixtures/templates/bad/resources/rds/retention_period.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources/rds/retention_period.yaml @@ -0,0 +1,21 @@ +Resources: + AuroraInstance: + Type: AWS::RDS::DBInstance + DeletionPolicy: Retain + UpdateReplacePolicy: Retain + Properties: + AllowMajorVersionUpgrade: false + AutoMinorVersionUpgrade: !Ref AutoMinorVersionUpgrade + DBClusterIdentifier: !Ref AuroraCluster + DBInstanceClass: !Ref InstanceClass + DBInstanceIdentifier: "MyAuroraInstance" + DBParameterGroupName: !Ref ParamGroup + DBSubnetGroupName: !Ref SubnetGroup + DeleteAutomatedBackups: !Ref DeleteAutomatedBackups + EnablePerformanceInsights: !Ref EnablePerformanceInsights + Engine: sqlserver-ee + EngineVersion: !Ref EngineVersion + PerformanceInsightsKMSKeyId: !Ref KmsKey + PerformanceInsightsRetentionPeriod: 7 + PubliclyAccessible: false + \ No newline at end of file diff --git a/test/fixtures/templates/good/resources/rds/retention_period.yaml b/test/fixtures/templates/good/resources/rds/retention_period.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/rds/retention_period.yaml @@ -0,0 +1,21 @@ +Resources: + AuroraInstance: + Type: AWS::RDS::DBInstance + DeletionPolicy: Retain + UpdateReplacePolicy: Retain + Properties: + AllowMajorVersionUpgrade: false + AutoMinorVersionUpgrade: !Ref AutoMinorVersionUpgrade + DBClusterIdentifier: !Ref AuroraCluster + DBInstanceClass: !Ref InstanceClass + DBInstanceIdentifier: "MyAuroraInstance" + DBParameterGroupName: !Ref ParamGroup + DBSubnetGroupName: !Ref SubnetGroup + DeleteAutomatedBackups: !Ref DeleteAutomatedBackups + EnablePerformanceInsights: !Ref EnablePerformanceInsights + Engine: aurora-postgresql + EngineVersion: !Ref EngineVersion + PerformanceInsightsKMSKeyId: !Ref KmsKey + PerformanceInsightsRetentionPeriod: 7 + PubliclyAccessible: false + \ No newline at end of file diff --git a/test/unit/rules/resources/test_retentionperiod.py b/test/unit/rules/resources/test_retentionperiod.py --- a/test/unit/rules/resources/test_retentionperiod.py +++ b/test/unit/rules/resources/test_retentionperiod.py @@ -14,7 +14,8 @@ def setUp(self): super(TestRetentionPeriodOnResourceTypesWithAutoExpiringContent, self).setUp() self.collection.register(RetentionPeriodOnResourceTypesWithAutoExpiringContent()) self.success_templates = [ - 'test/fixtures/templates/good/resources/sqs/retention_period.yaml' + 'test/fixtures/templates/good/resources/sqs/retention_period.yaml', + 'test/fixtures/templates/good/resources/rds/retention_period.yaml', ] def test_file_positive(self): @@ -25,3 +26,8 @@ def test_file_negative_alias(self): """Test failure""" self.helper_file_negative( 'test/fixtures/templates/bad/resources/sqs/retention_period.yaml', 3) + + def test_file_negative_rds(self): + """Test failure""" + self.helper_file_negative( + 'test/fixtures/templates/bad/resources/rds/retention_period.yaml', 1)
I3013 - Incorrectly flagged for aurora-<engine> database instances **cfn-lint version**: 0.61.3 cfn-lint is falsely flagging the missing `BackupRetentionPeriod` property and it's subsequent value from `AWS::RDS:DBInstance` for an Aurora based database instance. This property and a set value **is not required** if it is part of an Aurora cluster. Assumption is the `Engine` property value would need to be checked for the presence of `aurora-<engine>` to not flag this linting issue. I suspect if the value is set via a CloudFormation function cfn-lint would still incorrectly flag this. **AWS Documentation reference** - https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-backupretentionperiod > Amazon Aurora > Not applicable. The retention period for automated backups is managed by the DB cluster. **CloudFormation example** ```yaml AuroraInstance: Type: AWS::RDS::DBInstance DeletionPolicy: Retain UpdateReplacePolicy: Retain Properties: AllowMajorVersionUpgrade: false AutoMinorVersionUpgrade: !Ref AutoMinorVersionUpgrade DBClusterIdentifier: !Ref AuroraCluster DBInstanceClass: !Ref InstanceClass DBInstanceIdentifier: "MyAuroraInstance" DBParameterGroupName: !Ref ParamGroup DBSubnetGroupName: !Ref SubnetGroup DeleteAutomatedBackups: !Ref DeleteAutomatedBackups EnablePerformanceInsights: !Ref EnablePerformanceInsights Engine: aurora-postgresql EngineVersion: !Ref EngineVersion PerformanceInsightsKMSKeyId: !Ref KmsKey PerformanceInsightsRetentionPeriod: 7 PubliclyAccessible: false ```
https://github.com/aws-cloudformation/cfn-lint/issues/2311 --- (nice to see more informational rule feedback coming in, assuming https://github.com/aws-cloudformation/cfn-lint-visual-studio-code/pull/223 is surfacing them more based on that being released this week)
2022-07-29T16:54:20Z
[]
[]
aws-cloudformation/cfn-lint
2,364
aws-cloudformation__cfn-lint-2364
[ "2363" ]
77145d90938af9f86bb970fc973eb6c54fc9e794
diff --git a/src/cfnlint/rules/functions/SubNotJoin.py b/src/cfnlint/rules/functions/SubNotJoin.py --- a/src/cfnlint/rules/functions/SubNotJoin.py +++ b/src/cfnlint/rules/functions/SubNotJoin.py @@ -7,12 +7,34 @@ class SubNotJoin(CloudFormationLintRule): """Check if Join is being used with no join characters""" + id = 'I1022' shortdesc = 'Use Sub instead of Join' - description = 'Prefer a sub instead of Join when using a join delimiter that is empty' + description = ( + 'Prefer a sub instead of Join when using a join delimiter that is empty' + ) source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html' tags = ['functions', 'sub', 'join'] + def _check_element(self, element): + if isinstance(element, dict): + if len(element) == 1: + for key, value in element.items(): + if key in ['Fn::Sub']: + if not isinstance(value, str): + return False + elif key not in ['Ref', 'Fn::GetAtt']: + return False + + return True + + def _check_elements(self, elements): + for element in elements: + if not self._check_element(element): + return False + + return True + def match(self, cfn): matches = [] @@ -21,8 +43,15 @@ def match(self, cfn): for join_obj in join_objs: if isinstance(join_obj[-1], list): join_operator = join_obj[-1][0] + join_elements = join_obj[-1][1] if isinstance(join_operator, str): if join_operator == '': - matches.append(RuleMatch( - join_obj[0:-1], 'Prefer using Fn::Sub over Fn::Join with an empty delimiter')) + if isinstance(join_elements, list): + if self._check_elements(join_elements): + matches.append( + RuleMatch( + join_obj[0:-1], + 'Prefer using Fn::Sub over Fn::Join with an empty delimiter', + ) + ) return matches
diff --git a/test/fixtures/results/public/watchmaker.json b/test/fixtures/results/public/watchmaker.json --- a/test/fixtures/results/public/watchmaker.json +++ b/test/fixtures/results/public/watchmaker.json @@ -95,70 +95,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, - { - "Filename": "test/fixtures/templates/public/watchmaker.json", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 47, - "LineNumber": 689 - }, - "Path": [ - "Resources", - "WatchmakerInstance", - "Metadata", - "AWS::CloudFormation::Init", - "cw-agent-install", - "files", - "/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json", - "content", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 37, - "LineNumber": 689 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/public/watchmaker.json", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 47, - "LineNumber": 803 - }, - "Path": [ - "Resources", - "WatchmakerInstance", - "Metadata", - "AWS::CloudFormation::Init", - "finalize", - "commands", - "10-signal-success", - "command", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 37, - "LineNumber": 803 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/public/watchmaker.json", "Level": "Informational", @@ -297,38 +233,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, - { - "Filename": "test/fixtures/templates/public/watchmaker.json", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 47, - "LineNumber": 914 - }, - "Path": [ - "Resources", - "WatchmakerInstance", - "Metadata", - "AWS::CloudFormation::Init", - "setup", - "files", - "/etc/cfn/cfn-hup.conf", - "content", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 37, - "LineNumber": 914 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/public/watchmaker.json", "Level": "Informational", @@ -403,38 +307,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, - { - "Filename": "test/fixtures/templates/public/watchmaker.json", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 47, - "LineNumber": 977 - }, - "Path": [ - "Resources", - "WatchmakerInstance", - "Metadata", - "AWS::CloudFormation::Init", - "setup", - "files", - "/etc/cfn/hooks.d/cfn-auto-reloader.conf", - "content", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 37, - "LineNumber": 977 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/public/watchmaker.json", "Level": "Informational", @@ -541,38 +413,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, - { - "Filename": "test/fixtures/templates/public/watchmaker.json", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 47, - "LineNumber": 1091 - }, - "Path": [ - "Resources", - "WatchmakerInstance", - "Metadata", - "AWS::CloudFormation::Init", - "watchmaker-launch", - "commands", - "10-watchmaker-launch", - "command", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 37, - "LineNumber": 1091 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/public/watchmaker.json", "Level": "Informational", @@ -795,38 +635,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, - { - "Filename": "test/fixtures/templates/public/watchmaker.json", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 47, - "LineNumber": 1215 - }, - "Path": [ - "Resources", - "WatchmakerInstance", - "Metadata", - "AWS::CloudFormation::Init", - "watchmaker-update", - "commands", - "10-watchmaker-update", - "command", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 37, - "LineNumber": 1215 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/public/watchmaker.json", "Level": "Informational", @@ -1049,36 +857,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, - { - "Filename": "test/fixtures/templates/public/watchmaker.json", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 39, - "LineNumber": 1345 - }, - "Path": [ - "Resources", - "WatchmakerInstance", - "Properties", - "BlockDeviceMappings", - 0, - "DeviceName", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 29, - "LineNumber": 1345 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/public/watchmaker.json", "Level": "Informational", @@ -1109,69 +887,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, - { - "Filename": "test/fixtures/templates/public/watchmaker.json", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 35, - "LineNumber": 1453 - }, - "Path": [ - "Resources", - "WatchmakerInstance", - "Properties", - "UserData", - "Fn::Base64", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 25, - "LineNumber": 1453 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/public/watchmaker.json", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 55, - "LineNumber": 1470 - }, - "Path": [ - "Resources", - "WatchmakerInstance", - "Properties", - "UserData", - "Fn::Base64", - "Fn::Join", - 1, - 10, - "Fn::If", - 1, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 45, - "LineNumber": 1470 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/public/watchmaker.json", "Level": "Informational", @@ -1313,7 +1028,7 @@ "Level": "Informational", "Location": { "End": { - "ColumnNumber": 29, + "ColumnNumber": 37, "LineNumber": 1687 }, "Path": [ @@ -1321,7 +1036,7 @@ "WatchmakerInstanceLogGroup" ], "Start": { - "ColumnNumber": 3, + "ColumnNumber": 9, "LineNumber": 1687 } }, diff --git a/test/fixtures/results/quickstart/nist_application.json b/test/fixtures/results/quickstart/nist_application.json --- a/test/fixtures/results/quickstart/nist_application.json +++ b/test/fixtures/results/quickstart/nist_application.json @@ -1464,35 +1464,6 @@ "Source": "https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/cfn-resource-specification.md#valueprimitivetype" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 19, - "LineNumber": 813 - }, - "Path": [ - "Resources", - "rPostProcInstance", - "Properties", - "UserData", - "Fn::Base64", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 11, - "LineNumber": 813 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", "Level": "Informational", @@ -1664,7 +1635,7 @@ "Location": { "End": { "ColumnNumber": 22, - "LineNumber": 1025 + "LineNumber": 1026 }, "Path": [ "Resources", @@ -1672,7 +1643,7 @@ ], "Start": { "ColumnNumber": 3, - "LineNumber": 1025 + "LineNumber": 1026 } }, "Message": "Both UpdateReplacePolicy and DeletionPolicy are needed to protect Resources/rS3AccessLogsPolicy from deletion", @@ -1683,44 +1654,13 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 1042 - }, - "Path": [ - "Resources", - "rS3AccessLogsPolicy", - "Properties", - "PolicyDocument", - "Statement", - 0, - "Resource", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 1042 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", "Level": "Warning", "Location": { "End": { "ColumnNumber": 16, - "LineNumber": 1057 + "LineNumber": 1058 }, "Path": [ "Resources", @@ -1731,7 +1671,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1057 + "LineNumber": 1058 } }, "Message": "IAM Policy Version should be updated to '2012-10-17'.", @@ -1748,7 +1688,7 @@ "Location": { "End": { "ColumnNumber": 19, - "LineNumber": 1059 + "LineNumber": 1060 }, "Path": [ "Resources", @@ -1756,7 +1696,7 @@ ], "Start": { "ColumnNumber": 3, - "LineNumber": 1059 + "LineNumber": 1060 } }, "Message": "Both UpdateReplacePolicy and DeletionPolicy are needed to protect Resources/rS3ELBAccessLogs from deletion", @@ -1773,7 +1713,7 @@ "Location": { "End": { "ColumnNumber": 17, - "LineNumber": 1069 + "LineNumber": 1070 }, "Path": [ "Resources", @@ -1785,7 +1725,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1069 + "LineNumber": 1070 } }, "Message": "Property Resources/rSecurityGroupApp/Properties/SecurityGroupEgress/0/FromPort should be of type Integer", @@ -1802,7 +1742,7 @@ "Location": { "End": { "ColumnNumber": 15, - "LineNumber": 1071 + "LineNumber": 1072 }, "Path": [ "Resources", @@ -1814,7 +1754,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1071 + "LineNumber": 1072 } }, "Message": "Property Resources/rSecurityGroupApp/Properties/SecurityGroupEgress/0/ToPort should be of type Integer", @@ -1831,7 +1771,7 @@ "Location": { "End": { "ColumnNumber": 17, - "LineNumber": 1073 + "LineNumber": 1074 }, "Path": [ "Resources", @@ -1843,7 +1783,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1073 + "LineNumber": 1074 } }, "Message": "Property Resources/rSecurityGroupApp/Properties/SecurityGroupEgress/1/FromPort should be of type Integer", @@ -1860,7 +1800,7 @@ "Location": { "End": { "ColumnNumber": 15, - "LineNumber": 1075 + "LineNumber": 1076 }, "Path": [ "Resources", @@ -1872,7 +1812,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1075 + "LineNumber": 1076 } }, "Message": "Property Resources/rSecurityGroupApp/Properties/SecurityGroupEgress/1/ToPort should be of type Integer", @@ -1889,7 +1829,7 @@ "Location": { "End": { "ColumnNumber": 17, - "LineNumber": 1079 + "LineNumber": 1080 }, "Path": [ "Resources", @@ -1901,7 +1841,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1079 + "LineNumber": 1080 } }, "Message": "Property Resources/rSecurityGroupApp/Properties/SecurityGroupIngress/0/FromPort should be of type Integer", @@ -1918,7 +1858,7 @@ "Location": { "End": { "ColumnNumber": 15, - "LineNumber": 1081 + "LineNumber": 1082 }, "Path": [ "Resources", @@ -1930,7 +1870,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1081 + "LineNumber": 1082 } }, "Message": "Property Resources/rSecurityGroupApp/Properties/SecurityGroupIngress/0/ToPort should be of type Integer", @@ -1947,7 +1887,7 @@ "Location": { "End": { "ColumnNumber": 17, - "LineNumber": 1097 + "LineNumber": 1098 }, "Path": [ "Resources", @@ -1959,7 +1899,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1097 + "LineNumber": 1098 } }, "Message": "Property Resources/rSecurityGroupAppInstance/Properties/SecurityGroupIngress/0/FromPort should be of type Integer", @@ -1976,7 +1916,7 @@ "Location": { "End": { "ColumnNumber": 15, - "LineNumber": 1099 + "LineNumber": 1100 }, "Path": [ "Resources", @@ -1988,7 +1928,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1099 + "LineNumber": 1100 } }, "Message": "Property Resources/rSecurityGroupAppInstance/Properties/SecurityGroupIngress/0/ToPort should be of type Integer", @@ -2005,7 +1945,7 @@ "Location": { "End": { "ColumnNumber": 17, - "LineNumber": 1102 + "LineNumber": 1103 }, "Path": [ "Resources", @@ -2017,7 +1957,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1102 + "LineNumber": 1103 } }, "Message": "Property Resources/rSecurityGroupAppInstance/Properties/SecurityGroupIngress/1/FromPort should be of type Integer", @@ -2034,7 +1974,7 @@ "Location": { "End": { "ColumnNumber": 15, - "LineNumber": 1104 + "LineNumber": 1105 }, "Path": [ "Resources", @@ -2046,7 +1986,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1104 + "LineNumber": 1105 } }, "Message": "Property Resources/rSecurityGroupAppInstance/Properties/SecurityGroupIngress/1/ToPort should be of type Integer", @@ -2063,7 +2003,7 @@ "Location": { "End": { "ColumnNumber": 17, - "LineNumber": 1107 + "LineNumber": 1108 }, "Path": [ "Resources", @@ -2075,7 +2015,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1107 + "LineNumber": 1108 } }, "Message": "Property Resources/rSecurityGroupAppInstance/Properties/SecurityGroupIngress/2/FromPort should be of type Integer", @@ -2092,7 +2032,7 @@ "Location": { "End": { "ColumnNumber": 15, - "LineNumber": 1109 + "LineNumber": 1110 }, "Path": [ "Resources", @@ -2104,7 +2044,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1109 + "LineNumber": 1110 } }, "Message": "Property Resources/rSecurityGroupAppInstance/Properties/SecurityGroupIngress/2/ToPort should be of type Integer", @@ -2121,7 +2061,7 @@ "Location": { "End": { "ColumnNumber": 17, - "LineNumber": 1123 + "LineNumber": 1124 }, "Path": [ "Resources", @@ -2133,7 +2073,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1123 + "LineNumber": 1124 } }, "Message": "Property Resources/rSecurityGroupRDS/Properties/SecurityGroupIngress/0/FromPort should be of type Integer", @@ -2150,7 +2090,7 @@ "Location": { "End": { "ColumnNumber": 15, - "LineNumber": 1127 + "LineNumber": 1128 }, "Path": [ "Resources", @@ -2162,7 +2102,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1127 + "LineNumber": 1128 } }, "Message": "Property Resources/rSecurityGroupRDS/Properties/SecurityGroupIngress/0/ToPort should be of type Integer", @@ -2179,7 +2119,7 @@ "Location": { "End": { "ColumnNumber": 17, - "LineNumber": 1142 + "LineNumber": 1143 }, "Path": [ "Resources", @@ -2191,7 +2131,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1142 + "LineNumber": 1143 } }, "Message": "Property Resources/rSecurityGroupWeb/Properties/SecurityGroupIngress/0/FromPort should be of type Integer", @@ -2208,7 +2148,7 @@ "Location": { "End": { "ColumnNumber": 15, - "LineNumber": 1144 + "LineNumber": 1145 }, "Path": [ "Resources", @@ -2220,7 +2160,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1144 + "LineNumber": 1145 } }, "Message": "Property Resources/rSecurityGroupWeb/Properties/SecurityGroupIngress/0/ToPort should be of type Integer", @@ -2237,7 +2177,7 @@ "Location": { "End": { "ColumnNumber": 17, - "LineNumber": 1154 + "LineNumber": 1155 }, "Path": [ "Resources", @@ -2249,7 +2189,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1154 + "LineNumber": 1155 } }, "Message": "Property Resources/rSecurityGroupWebInstance/Properties/SecurityGroupIngress/0/FromPort should be of type Integer", @@ -2266,7 +2206,7 @@ "Location": { "End": { "ColumnNumber": 15, - "LineNumber": 1156 + "LineNumber": 1157 }, "Path": [ "Resources", @@ -2278,7 +2218,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1156 + "LineNumber": 1157 } }, "Message": "Property Resources/rSecurityGroupWebInstance/Properties/SecurityGroupIngress/0/ToPort should be of type Integer", @@ -2295,7 +2235,7 @@ "Location": { "End": { "ColumnNumber": 17, - "LineNumber": 1159 + "LineNumber": 1160 }, "Path": [ "Resources", @@ -2307,7 +2247,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1159 + "LineNumber": 1160 } }, "Message": "Property Resources/rSecurityGroupWebInstance/Properties/SecurityGroupIngress/1/FromPort should be of type Integer", @@ -2324,7 +2264,7 @@ "Location": { "End": { "ColumnNumber": 15, - "LineNumber": 1161 + "LineNumber": 1162 }, "Path": [ "Resources", @@ -2336,7 +2276,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1161 + "LineNumber": 1162 } }, "Message": "Property Resources/rSecurityGroupWebInstance/Properties/SecurityGroupIngress/1/ToPort should be of type Integer", @@ -2353,7 +2293,7 @@ "Location": { "End": { "ColumnNumber": 17, - "LineNumber": 1164 + "LineNumber": 1165 }, "Path": [ "Resources", @@ -2365,7 +2305,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1164 + "LineNumber": 1165 } }, "Message": "Property Resources/rSecurityGroupWebInstance/Properties/SecurityGroupIngress/2/FromPort should be of type Integer", @@ -2382,7 +2322,7 @@ "Location": { "End": { "ColumnNumber": 15, - "LineNumber": 1166 + "LineNumber": 1167 }, "Path": [ "Resources", @@ -2394,7 +2334,7 @@ ], "Start": { "ColumnNumber": 9, - "LineNumber": 1166 + "LineNumber": 1167 } }, "Message": "Property Resources/rSecurityGroupWebInstance/Properties/SecurityGroupIngress/2/ToPort should be of type Integer", @@ -2411,7 +2351,7 @@ "Location": { "End": { "ColumnNumber": 27, - "LineNumber": 1182 + "LineNumber": 1183 }, "Path": [ "Resources", @@ -2424,7 +2364,7 @@ ], "Start": { "ColumnNumber": 11, - "LineNumber": 1182 + "LineNumber": 1183 } }, "Message": "Property Resources/rWebContentBucket/Properties/LifecycleConfiguration/Rules/0/ExpirationInDays should be of type Integer", @@ -2441,7 +2381,7 @@ "Location": { "End": { "ColumnNumber": 29, - "LineNumber": 1191 + "LineNumber": 1192 }, "Path": [ "Resources", @@ -2455,7 +2395,7 @@ ], "Start": { "ColumnNumber": 13, - "LineNumber": 1191 + "LineNumber": 1192 } }, "Message": "Property Resources/rWebContentBucket/Properties/LifecycleConfiguration/Rules/0/Transition/TransitionInDays should be of type Integer", @@ -2472,7 +2412,7 @@ "Location": { "End": { "ColumnNumber": 14, - "LineNumber": 1197 + "LineNumber": 1198 }, "Path": [ "Resources", @@ -2481,7 +2421,7 @@ ], "Start": { "ColumnNumber": 5, - "LineNumber": 1197 + "LineNumber": 1198 } }, "Message": "Obsolete DependsOn on resource (rWebContentBucket), dependency already enforced by a \"Ref\" at Resources/rWebContentS3Policy/Properties/Bucket/Ref", @@ -2498,7 +2438,7 @@ "Location": { "End": { "ColumnNumber": 14, - "LineNumber": 1197 + "LineNumber": 1198 }, "Path": [ "Resources", @@ -2507,7 +2447,7 @@ ], "Start": { "ColumnNumber": 5, - "LineNumber": 1197 + "LineNumber": 1198 } }, "Message": "Obsolete DependsOn on resource (rWebContentBucket), dependency already enforced by a \"Ref\" at Resources/rWebContentS3Policy/Properties/PolicyDocument/Statement/0/Resource/Fn::Join/1/3/Ref", @@ -2524,7 +2464,7 @@ "Location": { "End": { "ColumnNumber": 14, - "LineNumber": 1197 + "LineNumber": 1198 }, "Path": [ "Resources", @@ -2533,7 +2473,7 @@ ], "Start": { "ColumnNumber": 5, - "LineNumber": 1197 + "LineNumber": 1198 } }, "Message": "Obsolete DependsOn on resource (rWebContentBucket), dependency already enforced by a \"Ref\" at Resources/rWebContentS3Policy/Properties/PolicyDocument/Statement/1/Resource/Fn::Join/1/3/Ref", @@ -2543,67 +2483,5 @@ "ShortDescription": "Check obsolete DependsOn configuration for Resources", "Source": "https://aws.amazon.com/blogs/devops/optimize-aws-cloudformation-templates/" } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 1210 - }, - "Path": [ - "Resources", - "rWebContentS3Policy", - "Properties", - "PolicyDocument", - "Statement", - 0, - "Resource", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 1210 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 1227 - }, - "Path": [ - "Resources", - "rWebContentS3Policy", - "Properties", - "PolicyDocument", - "Statement", - 1, - "Resource", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 1227 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } } ] diff --git a/test/fixtures/results/quickstart/nist_high_main.json b/test/fixtures/results/quickstart/nist_high_main.json --- a/test/fixtures/results/quickstart/nist_high_main.json +++ b/test/fixtures/results/quickstart/nist_high_main.json @@ -95,7 +95,7 @@ "LineNumber": 278 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pAppPrivateSubnetB/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pAppPrivateSubnetA/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -122,7 +122,7 @@ "LineNumber": 278 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDBPrivateSubnetA/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pAppPrivateSubnetB/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -149,7 +149,7 @@ "LineNumber": 278 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDBPrivateSubnetB/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDBPrivateSubnetA/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -176,7 +176,7 @@ "LineNumber": 278 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDMZSubnetA/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDBPrivateSubnetB/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -203,7 +203,7 @@ "LineNumber": 278 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDMZSubnetB/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDMZSubnetA/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -230,7 +230,7 @@ "LineNumber": 278 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pAppPrivateSubnetA/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDMZSubnetB/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -551,34 +551,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 17, - "LineNumber": 377 - }, - "Path": [ - "Resources", - "ApplicationTemplate", - "Properties", - "TemplateURL", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 9, - "LineNumber": 377 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", "Level": "Error", @@ -712,34 +684,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 17, - "LineNumber": 401 - }, - "Path": [ - "Resources", - "ConfigRulesTemplate", - "Properties", - "TemplateURL", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 9, - "LineNumber": 401 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", "Level": "Error", @@ -792,34 +736,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 17, - "LineNumber": 414 - }, - "Path": [ - "Resources", - "IamTemplate", - "Properties", - "TemplateURL", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 9, - "LineNumber": 414 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", "Level": "Error", @@ -872,34 +788,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 17, - "LineNumber": 435 - }, - "Path": [ - "Resources", - "LoggingTemplate", - "Properties", - "TemplateURL", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 9, - "LineNumber": 435 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", "Level": "Error", @@ -996,7 +884,7 @@ "LineNumber": 445 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ManagementVpcTemplate/Properties/Parameters/pRouteTableProdPublic/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ManagementVpcTemplate/Properties/Parameters/pProductionVPC/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -1048,7 +936,7 @@ "LineNumber": 445 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ManagementVpcTemplate/Properties/Parameters/pProductionVPC/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ManagementVpcTemplate/Properties/Parameters/pRouteTableProdPublic/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -1143,34 +1031,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 17, - "LineNumber": 516 - }, - "Path": [ - "Resources", - "ManagementVpcTemplate", - "Properties", - "TemplateURL", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 9, - "LineNumber": 516 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", "Level": "Error", @@ -1223,34 +1083,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 17, - "LineNumber": 570 - }, - "Path": [ - "Resources", - "ProductionVpcTemplate", - "Properties", - "TemplateURL", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 9, - "LineNumber": 570 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", "Level": "Error", diff --git a/test/fixtures/results/quickstart/nist_logging.json b/test/fixtures/results/quickstart/nist_logging.json --- a/test/fixtures/results/quickstart/nist_logging.json +++ b/test/fixtures/results/quickstart/nist_logging.json @@ -189,102 +189,6 @@ "Source": "https://aws.amazon.com/blogs/devops/optimize-aws-cloudformation-templates/" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 74 - }, - "Path": [ - "Resources", - "rArchiveLogsBucketPolicy", - "Properties", - "PolicyDocument", - "Statement", - 0, - "Resource", - 0, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 74 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 89 - }, - "Path": [ - "Resources", - "rArchiveLogsBucketPolicy", - "Properties", - "PolicyDocument", - "Statement", - 1, - "Resource", - 0, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 89 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 107 - }, - "Path": [ - "Resources", - "rArchiveLogsBucketPolicy", - "Properties", - "PolicyDocument", - "Statement", - 2, - "Resource", - 0, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 107 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", "Level": "Warning", @@ -469,74 +373,6 @@ "Source": "https://aws.amazon.com/blogs/devops/optimize-aws-cloudformation-templates/" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 23, - "LineNumber": 204 - }, - "Path": [ - "Resources", - "rCloudTrailRole", - "Properties", - "Policies", - 0, - "PolicyDocument", - "Statement", - 0, - "Resource", - 0, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 15, - "LineNumber": 204 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 23, - "LineNumber": 218 - }, - "Path": [ - "Resources", - "rCloudTrailRole", - "Properties", - "Policies", - 0, - "PolicyDocument", - "Statement", - 1, - "Resource", - 0, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 15, - "LineNumber": 218 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", "Level": "Warning", @@ -693,234 +529,6 @@ "Source": "https://aws.amazon.com/blogs/devops/optimize-aws-cloudformation-templates/" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 243 - }, - "Path": [ - "Resources", - "rCloudTrailS3Policy", - "Properties", - "PolicyDocument", - "Statement", - 0, - "Resource", - 0, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 243 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 261 - }, - "Path": [ - "Resources", - "rCloudTrailS3Policy", - "Properties", - "PolicyDocument", - "Statement", - 1, - "Resource", - 0, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 261 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 279 - }, - "Path": [ - "Resources", - "rCloudTrailS3Policy", - "Properties", - "PolicyDocument", - "Statement", - 2, - "Resource", - 0, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 279 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 294 - }, - "Path": [ - "Resources", - "rCloudTrailS3Policy", - "Properties", - "PolicyDocument", - "Statement", - 3, - "Resource", - 0, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 294 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 312 - }, - "Path": [ - "Resources", - "rCloudTrailS3Policy", - "Properties", - "PolicyDocument", - "Statement", - 4, - "Resource", - 0, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 312 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 23, - "LineNumber": 342 - }, - "Path": [ - "Resources", - "rCloudWatchLogsRole", - "Properties", - "Policies", - 0, - "PolicyDocument", - "Statement", - 0, - "Resource", - 0, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 15, - "LineNumber": 342 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 23, - "LineNumber": 361 - }, - "Path": [ - "Resources", - "rCloudWatchLogsRole", - "Properties", - "Policies", - 0, - "PolicyDocument", - "Statement", - 1, - "Resource", - 0, - "Fn::Join" - ], - "Start": { - "ColumnNumber": 15, - "LineNumber": 361 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_logging.yaml", "Level": "Error", diff --git a/test/fixtures/results/quickstart/non_strict/nist_application.json b/test/fixtures/results/quickstart/non_strict/nist_application.json --- a/test/fixtures/results/quickstart/non_strict/nist_application.json +++ b/test/fixtures/results/quickstart/non_strict/nist_application.json @@ -723,35 +723,6 @@ "Source": "https://aws.amazon.com/blogs/devops/optimize-aws-cloudformation-templates/" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 19, - "LineNumber": 813 - }, - "Path": [ - "Resources", - "rPostProcInstance", - "Properties", - "UserData", - "Fn::Base64", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 11, - "LineNumber": 813 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", "Level": "Informational", @@ -888,37 +859,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 1043 - }, - "Path": [ - "Resources", - "rS3AccessLogsPolicy", - "Properties", - "PolicyDocument", - "Statement", - 0, - "Resource", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 1043 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", "Level": "Warning", @@ -1049,67 +989,5 @@ "ShortDescription": "Check obsolete DependsOn configuration for Resources", "Source": "https://aws.amazon.com/blogs/devops/optimize-aws-cloudformation-templates/" } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 1211 - }, - "Path": [ - "Resources", - "rWebContentS3Policy", - "Properties", - "PolicyDocument", - "Statement", - 0, - "Resource", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 1211 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_application.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 21, - "LineNumber": 1228 - }, - "Path": [ - "Resources", - "rWebContentS3Policy", - "Properties", - "PolicyDocument", - "Statement", - 1, - "Resource", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 13, - "LineNumber": 1228 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } } ] diff --git a/test/fixtures/results/quickstart/non_strict/nist_high_main.json b/test/fixtures/results/quickstart/non_strict/nist_high_main.json --- a/test/fixtures/results/quickstart/non_strict/nist_high_main.json +++ b/test/fixtures/results/quickstart/non_strict/nist_high_main.json @@ -95,7 +95,7 @@ "LineNumber": 278 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pAppPrivateSubnetB/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pAppPrivateSubnetA/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -122,7 +122,7 @@ "LineNumber": 278 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDBPrivateSubnetA/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pAppPrivateSubnetB/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -149,7 +149,7 @@ "LineNumber": 278 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDBPrivateSubnetB/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDBPrivateSubnetA/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -176,7 +176,7 @@ "LineNumber": 278 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDMZSubnetA/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDBPrivateSubnetB/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -203,7 +203,7 @@ "LineNumber": 278 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDMZSubnetB/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDMZSubnetA/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -230,7 +230,7 @@ "LineNumber": 278 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pAppPrivateSubnetA/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ApplicationTemplate/Properties/Parameters/pDMZSubnetB/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -551,34 +551,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 17, - "LineNumber": 377 - }, - "Path": [ - "Resources", - "ApplicationTemplate", - "Properties", - "TemplateURL", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 9, - "LineNumber": 377 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", "Level": "Informational", @@ -685,34 +657,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 17, - "LineNumber": 401 - }, - "Path": [ - "Resources", - "ConfigRulesTemplate", - "Properties", - "TemplateURL", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 9, - "LineNumber": 401 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", "Level": "Informational", @@ -738,34 +682,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 17, - "LineNumber": 414 - }, - "Path": [ - "Resources", - "IamTemplate", - "Properties", - "TemplateURL", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 9, - "LineNumber": 414 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", "Level": "Informational", @@ -791,34 +707,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 17, - "LineNumber": 435 - }, - "Path": [ - "Resources", - "LoggingTemplate", - "Properties", - "TemplateURL", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 9, - "LineNumber": 435 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", "Level": "Informational", @@ -888,7 +776,7 @@ "LineNumber": 445 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ManagementVpcTemplate/Properties/Parameters/pRouteTableProdPublic/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ManagementVpcTemplate/Properties/Parameters/pProductionVPC/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -940,7 +828,7 @@ "LineNumber": 445 } }, - "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ManagementVpcTemplate/Properties/Parameters/pProductionVPC/Fn::GetAtt", + "Message": "Obsolete DependsOn on resource (ProductionVpcTemplate), dependency already enforced by a \"Fn:GetAtt\" at Resources/ManagementVpcTemplate/Properties/Parameters/pRouteTableProdPublic/Fn::GetAtt", "Rule": { "Description": "Check if DependsOn is specified if not needed. A Ref or a Fn::GetAtt already is an implicit dependency.", "Id": "W3005", @@ -1035,34 +923,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 17, - "LineNumber": 516 - }, - "Path": [ - "Resources", - "ManagementVpcTemplate", - "Properties", - "TemplateURL", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 9, - "LineNumber": 516 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", "Level": "Informational", @@ -1087,33 +947,5 @@ "ShortDescription": "Check stateful resources have a set UpdateReplacePolicy/DeletionPolicy", "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html" } - }, - { - "Filename": "test/fixtures/templates/quickstart/nist_high_main.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 17, - "LineNumber": 570 - }, - "Path": [ - "Resources", - "ProductionVpcTemplate", - "Properties", - "TemplateURL", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 9, - "LineNumber": 570 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } } ] diff --git a/test/fixtures/results/quickstart/non_strict/openshift.json b/test/fixtures/results/quickstart/non_strict/openshift.json --- a/test/fixtures/results/quickstart/non_strict/openshift.json +++ b/test/fixtures/results/quickstart/non_strict/openshift.json @@ -194,35 +194,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/openshift.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 19, - "LineNumber": 377 - }, - "Path": [ - "Resources", - "AnsibleConfigServer", - "Properties", - "UserData", - "Fn::Base64", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 11, - "LineNumber": 377 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/openshift.yaml", "Level": "Warning", @@ -368,35 +339,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/openshift.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 19, - "LineNumber": 922 - }, - "Path": [ - "Resources", - "OpenShiftEtcdLaunchConfig", - "Properties", - "UserData", - "Fn::Base64", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 11, - "LineNumber": 922 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/openshift.yaml", "Level": "Warning", @@ -455,35 +397,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/openshift.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 19, - "LineNumber": 1147 - }, - "Path": [ - "Resources", - "OpenShiftMasterASLaunchConfig", - "Properties", - "UserData", - "Fn::Base64", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 11, - "LineNumber": 1147 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/openshift.yaml", "Level": "Informational", @@ -516,35 +429,6 @@ "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" } }, - { - "Filename": "test/fixtures/templates/quickstart/openshift.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 19, - "LineNumber": 1481 - }, - "Path": [ - "Resources", - "OpenShiftNodesLaunchConfig", - "Properties", - "UserData", - "Fn::Base64", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 11, - "LineNumber": 1481 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/openshift.yaml", "Level": "Informational", diff --git a/test/fixtures/results/quickstart/openshift.json b/test/fixtures/results/quickstart/openshift.json --- a/test/fixtures/results/quickstart/openshift.json +++ b/test/fixtures/results/quickstart/openshift.json @@ -252,35 +252,6 @@ "Source": "https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/cfn-resource-specification.md#valueprimitivetype" } }, - { - "Filename": "test/fixtures/templates/quickstart/openshift.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 19, - "LineNumber": 377 - }, - "Path": [ - "Resources", - "AnsibleConfigServer", - "Properties", - "UserData", - "Fn::Base64", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 11, - "LineNumber": 377 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/openshift.yaml", "Level": "Warning", @@ -539,35 +510,6 @@ "Source": "https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/cfn-resource-specification.md#valueprimitivetype" } }, - { - "Filename": "test/fixtures/templates/quickstart/openshift.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 19, - "LineNumber": 922 - }, - "Path": [ - "Resources", - "OpenShiftEtcdLaunchConfig", - "Properties", - "UserData", - "Fn::Base64", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 11, - "LineNumber": 922 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/openshift.yaml", "Level": "Error", @@ -712,35 +654,6 @@ "Source": "https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/cfn-resource-specification.md#valueprimitivetype" } }, - { - "Filename": "test/fixtures/templates/quickstart/openshift.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 19, - "LineNumber": 1147 - }, - "Path": [ - "Resources", - "OpenShiftMasterASLaunchConfig", - "Properties", - "UserData", - "Fn::Base64", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 11, - "LineNumber": 1147 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/openshift.yaml", "Level": "Error", @@ -1005,35 +918,6 @@ "Source": "https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/cfn-resource-specification.md#valueprimitivetype" } }, - { - "Filename": "test/fixtures/templates/quickstart/openshift.yaml", - "Level": "Informational", - "Location": { - "End": { - "ColumnNumber": 19, - "LineNumber": 1481 - }, - "Path": [ - "Resources", - "OpenShiftNodesLaunchConfig", - "Properties", - "UserData", - "Fn::Base64", - "Fn::Join" - ], - "Start": { - "ColumnNumber": 11, - "LineNumber": 1481 - } - }, - "Message": "Prefer using Fn::Sub over Fn::Join with an empty delimiter", - "Rule": { - "Description": "Prefer a sub instead of Join when using a join delimiter that is empty", - "Id": "I1022", - "ShortDescription": "Use Sub instead of Join", - "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html" - } - }, { "Filename": "test/fixtures/templates/quickstart/openshift.yaml", "Level": "Error", diff --git a/test/fixtures/templates/bad/functions/subnotjoin.yaml b/test/fixtures/templates/bad/functions/subnotjoin.yaml --- a/test/fixtures/templates/bad/functions/subnotjoin.yaml +++ b/test/fixtures/templates/bad/functions/subnotjoin.yaml @@ -19,6 +19,6 @@ Resources: UserData: Fn::Base64: Fn::Join: - - '' - - - !Sub 'yum install ${myPackage}' - - !Sub 'yum install ${myAppPackage}' \ No newline at end of file + - "" + - - !Sub "yum install ${myPackage}" + - !Sub "yum install ${myAppPackage}" diff --git a/test/fixtures/templates/good/functions/subnotjoin.yaml b/test/fixtures/templates/good/functions/subnotjoin.yaml --- a/test/fixtures/templates/good/functions/subnotjoin.yaml +++ b/test/fixtures/templates/good/functions/subnotjoin.yaml @@ -20,4 +20,18 @@ Resources: Fn::Base64: Fn::Sub: | yum install ${myPackage} - yum install ${myAppPackage} \ No newline at end of file + yum install ${myAppPackage} + myInstance2: + Type: AWS::EC2::Instance + Properties: + ImageId: String + UserData: + Fn::Base64: + Fn::Join: + - "" + - - Fn::Select: + - 0 + - Fn::Split: + - "/" + - "a/path/" + - !Sub "yum install ${myAppPackage}"
Update I1022 to only suggest sub if all values can be in the sub ### CloudFormation Lint Version 0.64.1 ### What operating system are you using? All ### Describe the bug Original feedback provided by @iann0036. Translated to an issue for tracking. ```yaml Fn::Join: - "" - - Fn::Select: - 0 - Fn::Split: - "/" - !Ref MySubnet1CIDR - !Ref MySubnetsCIDRSize ``` ``` I1022: Prefer using Fn::Sub over Fn::Join with an empty delimiter ``` ### Expected behavior Currently the way to make this comply would be ```yaml Fn::Sub: - ${CIDR}${MySubnetsCIDRSize} - CIDR: Fn::Select: - 0 - Fn::Split: - "/" - !Ref MySubnet1CIDR ``` which may not be as optimal ### Reproduction template ```yaml Fn::Join: - "" - - Fn::Select: - 0 - Fn::Split: - "/" - !Ref MySubnet1CIDR - !Ref MySubnetsCIDRSize ````
2022-09-08T18:36:02Z
[]
[]
aws-cloudformation/cfn-lint
2,387
aws-cloudformation__cfn-lint-2387
[ "2337" ]
1c42cb657b3c65690b957d944fbf3bdfd62adb7c
diff --git a/src/cfnlint/rules/resources/properties/Properties.py b/src/cfnlint/rules/resources/properties/Properties.py --- a/src/cfnlint/rules/resources/properties/Properties.py +++ b/src/cfnlint/rules/resources/properties/Properties.py @@ -2,6 +2,7 @@ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ +from difflib import SequenceMatcher from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch import cfnlint.helpers @@ -264,8 +265,16 @@ def propertycheck(self, text, proptype, parenttype, resourcename, path, root): elif len(text) == 1 and prop in 'Ref' and text.get(prop) == 'AWS::NoValue': pass elif not supports_additional_properties: - message = 'Invalid Property %s' % ('/'.join(map(str, proppath))) - matches.append(RuleMatch(proppath, message)) + close_match = False + for key in resourcespec.keys(): + if SequenceMatcher(a=prop,b=key).ratio() > 0.8: + message = 'Invalid Property %s. Did you mean %s?' % ('/'.join(map(str, proppath)), key) + matches.append(RuleMatch(proppath, message)) + close_match = True + break + if not close_match: + message = 'Invalid Property %s' % ('/'.join(map(str, proppath))) + matches.append(RuleMatch(proppath, message)) else: if 'Type' in resourcespec[prop]: if resourcespec[prop]['Type'] == 'List':
diff --git a/test/integration/test_directives.py b/test/integration/test_directives.py --- a/test/integration/test_directives.py +++ b/test/integration/test_directives.py @@ -36,7 +36,7 @@ class TestDirectives(BaseCliTestCase): 'LineNumber': 17 } }, - 'Message': 'Invalid Property Resources/myBucketFail/Properties/BucketName1', + 'Message': 'Invalid Property Resources/myBucketFail/Properties/BucketName1. Did you mean BucketName?', 'Rule': { 'Description': 'Making sure that resources properties are properly configured', 'Id': 'E3002', diff --git a/test/integration/test_mandatory_checks.py b/test/integration/test_mandatory_checks.py --- a/test/integration/test_mandatory_checks.py +++ b/test/integration/test_mandatory_checks.py @@ -26,7 +26,7 @@ class TestDirectives(BaseCliTestCase): ], "Start": {"ColumnNumber": 7, "LineNumber": 17}, }, - "Message": "Invalid Property Resources/myBucketFail/Properties/BucketName1", + "Message": "Invalid Property Resources/myBucketFail/Properties/BucketName1. Did you mean BucketName?", "Rule": { "Description": "Making sure that resources properties are properly configured", "Id": "E3002", @@ -131,7 +131,7 @@ class TestDirectives(BaseCliTestCase): ], 'Start': {'ColumnNumber': 7, 'LineNumber': 13} }, - 'Message': 'Invalid Property Resources/myBucketPass/Properties/BucketName1', + 'Message': 'Invalid Property Resources/myBucketPass/Properties/BucketName1. Did you mean BucketName?', 'Rule': { 'Description': 'Making sure that resources properties are properly configured', 'Id': 'E3002',
Identify capitalisation errors in property names *cfn-lint version: 0.62.0 * Feature request: * It can be hard to identify captalisation errors in cfn property names. It would be useful if cfn-lint would call out these things. An example is: ``` TransformFunction: Type: AWS::Lambda::Function Properties: Code: Zipfile: | ``` In this case, Zipfile should be ZipFile... This took me several hours to identify :/ The cfn-lint did pick up the error as: E3002 Invalid Property Resources/TransformFunction/Properties/Code/Zipfile Feature request is to call it out more clearly as a capitalisation error and that it might be ZipFile. This is not the first time this has happened. There are a number of Property names that have unusual capitalisations.
2022-09-29T15:25:28Z
[]
[]
aws-cloudformation/cfn-lint
2,425
aws-cloudformation__cfn-lint-2425
[ "1194" ]
c3bf32c8f45e1dcd72216302826fccc41cda791b
diff --git a/src/cfnlint/transform.py b/src/cfnlint/transform.py --- a/src/cfnlint/transform.py +++ b/src/cfnlint/transform.py @@ -105,8 +105,9 @@ def _replace_local_codeuri(self): Transform._update_to_s3_uri('ContentUri', resource_dict) if resource_type == 'AWS::Serverless::Application': if resource_dict.get('Location'): - resource_dict['Location'] = '' - Transform._update_to_s3_uri('Location', resource_dict) + if isinstance(resource_dict.get('Location'), dict): + resource_dict['Location'] = '' + Transform._update_to_s3_uri('Location', resource_dict) if resource_type == 'AWS::Serverless::Api': if ( 'DefinitionBody' not in resource_dict
diff --git a/test/fixtures/templates/good/transform/applications_location.yaml b/test/fixtures/templates/good/transform/applications_location.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/transform/applications_location.yaml @@ -0,0 +1,11 @@ +Transform: AWS::Serverless-2016-10-31 +Resources: + App1: + Type: AWS::Serverless::Application + Properties: + Location: ./step_function_local_definition.yaml + App2: + Type: AWS::Serverless::Application + Properties: + Location: + ApplicationId: '1' diff --git a/test/unit/module/transform/test_transform.py b/test/unit/module/transform/test_transform.py --- a/test/unit/module/transform/test_transform.py +++ b/test/unit/module/transform/test_transform.py @@ -43,6 +43,37 @@ def test_conversion_of_step_function_definition_uri(self): 'Key': 'value' }) + def test_conversion_of_application_location(self): + """ Tests if serverless application converts location to string when dict """ + filename = 'test/fixtures/templates/good/transform/applications_location.yaml' + region = 'us-east-1' + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + transformed_template.transform_template() + self.assertEqual( + transformed_template._template.get('Resources').get( + 'App1').get('Properties').get('TemplateURL'), + './step_function_local_definition.yaml') + self.assertEqual( + transformed_template._template.get('Resources').get( + 'App2').get('Properties').get('TemplateURL'), + 's3://bucket/value') + + def test_conversion_of_step_function_definition_uri(self): + """ Tests that the a serverless step function can convert a local path to a s3 path """ + filename = 'test/fixtures/templates/good/transform/step_function_local_definition.yaml' + region = 'us-east-1' + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + transformed_template.transform_template() + self.assertDictEqual( + transformed_template._template.get('Resources').get( + 'StateMachine').get('Properties').get('DefinitionS3Location'), + { + 'Bucket': 'bucket', + 'Key': 'value' + }) + def test_parameter_for_autopublish_version_bad(self): """Test Parameter is created for autopublish version run""" filename = 'test/fixtures/templates/bad/transform/auto_publish_alias.yaml'
AWS::Serverless::Application parameters *Description of issue.* When creating a `AWS::Serverless::Application` input parameters should match parameters required in the nested template. * Supplying parameters to `AWS::Serverless::Application` resources that do not exist in the child template will succeed in creating a Change Set but fail upon deployment. * Neglecting to provide parameters `AWS::Serverless::Application` resources that do exist in the child template will fail in creating a Change Set.
@redbaron09 agreed here. We have tried not to reach out to validate things in an AWS account. Is there a way to do this without actually querying the account? Or maybe we need to start thinking about a way to query live accounts when requested. Following `Location` on the local file system, reading the parameters section, and comparing against the parameters supplied in the parent stack would be sufficient. I'm using [`AWS::Serverless::Application`](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-application.html) in place of [`AWS::CloudFormation::Stack`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stack.html) We are doing this for `AWS::CloudFormation::Stack` with rule [E3043](https://github.com/aws-cloudformation/cfn-lint/blob/3492649d613a61fff3063ce0ffa404e1055c6a3a/src/cfnlint/rules/resources/cloudformation/NestedStackParameters.py). Need to update the transform logic to leave strings as is.
2022-10-20T19:50:23Z
[]
[]
aws-cloudformation/cfn-lint
2,426
aws-cloudformation__cfn-lint-2426
[ "1267" ]
b08b8f65be2c68e833cb5db177d842ebff44f38e
diff --git a/src/cfnlint/rules/conditions/EqualsIsUseful.py b/src/cfnlint/rules/conditions/EqualsIsUseful.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/conditions/EqualsIsUseful.py @@ -0,0 +1,44 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +import json +from cfnlint.rules import CloudFormationLintRule +from cfnlint.rules import RuleMatch + + +class EqualsIsUseful(CloudFormationLintRule): + """Validate that the Equals will return true/false and not always be true or false""" + + id = 'W8003' + shortdesc = 'Fn::Equals will always return true or false' + description = 'Validate Fn::Equals to see if its comparing two strings or two equal items. While this works it may not be intended.' + source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-equals' + tags = ['functions', 'equals'] + + function = 'Fn::Equals' + + def _check_equal_values(self, values, path): + matches = [] + + if json.dumps(values[0]) == json.dumps(values[1]): + message = self.function + ' element will alway return true' + matches.append(RuleMatch(path, message)) + elif isinstance(values[0], str) and isinstance(values[1], str): + message = self.function + ' element will alway return false' + matches.append(RuleMatch(path, message)) + return matches + + def match(self, cfn): + matches = [] + # Build the list of functions + trees = cfn.search_deep_keys(self.function) + + for tree in trees: + # Test when in Conditions + if tree[0] == 'Conditions': + value = tree[-1] + if isinstance(value, list) and len(value) == 2: + matches.extend(self._check_equal_values(value, tree[:-1])) + + return matches
diff --git a/test/fixtures/results/quickstart/nist_config_rules.json b/test/fixtures/results/quickstart/nist_config_rules.json --- a/test/fixtures/results/quickstart/nist_config_rules.json +++ b/test/fixtures/results/quickstart/nist_config_rules.json @@ -1,4 +1,32 @@ [ + { + "Filename": "test/fixtures/templates/quickstart/nist_config_rules.yaml", + "Level": "Warning", + "Location": { + "End": { + "ColumnNumber": 17, + "LineNumber": 5 + }, + "Path": [ + "Conditions", + "cApprovedAMIsRule", + "Fn::Not", + 0, + "Fn::Equals" + ], + "Start": { + "ColumnNumber": 7, + "LineNumber": 5 + } + }, + "Message": "Fn::Equals element will alway return true", + "Rule": { + "Description": "Validate Fn::Equals to see if its comparing two strings or two equal items. While this works it may not be intended.", + "Id": "W8003", + "ShortDescription": "Fn::Equals will not always return true or false", + "Source": "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-equals" + } + }, { "Filename": "test/fixtures/templates/quickstart/nist_config_rules.yaml", "Level": "Warning", diff --git a/test/fixtures/templates/bad/conditions/equals_not_useful.yaml b/test/fixtures/templates/bad/conditions/equals_not_useful.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/conditions/equals_not_useful.yaml @@ -0,0 +1,11 @@ +--- +AWSTemplateFormatVersion: "2010-09-09" +Parameters: + Environment: + Type: String + Default: dev +Conditions: + IsTrue: !Equals ['true', 'true'] + IsFalse: !Equals ['true', 'false'] + IsDevEnvironment: !Equals [!Ref Environment, !Ref Environment] +Resources: {} diff --git a/test/unit/module/cfn_json/test_cfn_json.py b/test/unit/module/cfn_json/test_cfn_json.py --- a/test/unit/module/cfn_json/test_cfn_json.py +++ b/test/unit/module/cfn_json/test_cfn_json.py @@ -24,7 +24,7 @@ def setUp(self): self.filenames = { "config_rule": { "filename": 'test/fixtures/templates/quickstart/config-rules.json', - "failures": 4 + "failures": 5 }, "iam": { "filename": 'test/fixtures/templates/quickstart/iam.json', diff --git a/test/unit/module/cfn_yaml/test_yaml.py b/test/unit/module/cfn_yaml/test_yaml.py --- a/test/unit/module/cfn_yaml/test_yaml.py +++ b/test/unit/module/cfn_yaml/test_yaml.py @@ -28,7 +28,7 @@ def setUp(self): }, "generic_bad": { "filename": 'test/fixtures/templates/bad/generic.yaml', - "failures": 29 + "failures": 30 } } diff --git a/test/unit/module/test_rules_collections.py b/test/unit/module/test_rules_collections.py --- a/test/unit/module/test_rules_collections.py +++ b/test/unit/module/test_rules_collections.py @@ -50,7 +50,7 @@ def test_fail_run(self): filename = 'test/fixtures/templates/bad/generic.yaml' template = cfnlint.decode.cfn_yaml.load(filename) cfn = Template(filename, template, ['us-east-1']) - expected_err_count = 32 + expected_err_count = 33 matches = [] matches.extend(self.rules.run(filename, cfn)) assert len(matches) == expected_err_count, 'Expected {} failures, got {}'.format( diff --git a/test/unit/rules/conditions/test_equals_is_useful.py b/test/unit/rules/conditions/test_equals_is_useful.py new file mode 100644 --- /dev/null +++ b/test/unit/rules/conditions/test_equals_is_useful.py @@ -0,0 +1,25 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from test.unit.rules import BaseRuleTestCase +from cfnlint.rules.conditions.EqualsIsUseful import EqualsIsUseful # pylint: disable=E0401 + + +class TestEqualsIsUseful(BaseRuleTestCase): + """Test template mapping configurations""" + + def setUp(self): + """Setup""" + super(TestEqualsIsUseful, self).setUp() + self.collection.register(EqualsIsUseful()) + + success_templates = [] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative(self): + """Test failure""" + self.helper_file_negative('test/fixtures/templates/bad/conditions/equals_not_useful.yaml', 3)
Add check for missing !Ref in condition *cfn-lint version: (`cfn-lint --version`)*: cfn-lint 0.26.0 *Description of issue.* It'd be helpful if cfn-lint had a check when parameter names or psuedo-parameters are used in conditions without a `!Ref` much like it checks for strings with `${PARAMETER}` without a `!Sub`. This would prevent accidental comparisons with a string literal. It might also be helpful to check for conditions that will always evaluate to true/false. For example: ```yaml --- AWSTemplateFormatVersion: "2010-09-09" Parameters: MyTestParameter: Type: String Default: "" Conditions: CreateFooResource: !Not [!Equals [MyTestParameter, ""]] Resources: Foo: Type: AWS::IAM::User Condition: CreateFooResource Properties: {} ``` It would be helpful to get a warning that `CreateFooResource` always evaluates to true or that it's comparing two string literals, one of which is a parameter name.
2022-10-20T21:55:21Z
[]
[]
aws-cloudformation/cfn-lint
2,428
aws-cloudformation__cfn-lint-2428
[ "1906" ]
27ca3c4340ebd47e56f764cd69804fcd2490e262
diff --git a/src/cfnlint/decode/cfn_json.py b/src/cfnlint/decode/cfn_json.py --- a/src/cfnlint/decode/cfn_json.py +++ b/src/cfnlint/decode/cfn_json.py @@ -20,11 +20,13 @@ class DuplicateError(Exception): Error thrown when the template contains duplicates """ - def __init__(self, message, mapping, key): + def __init__(self, message, key): super().__init__(message) + self.duplicates = [] + self.append(key) - self.mapping = mapping - self.key = key + def append(self, key): + self.duplicates.append(key) def check_duplicates(ordered_pairs, beg_mark, end_mark): @@ -33,11 +35,21 @@ def check_duplicates(ordered_pairs, beg_mark, end_mark): because a dict does not support this. It overwrites it with the last occurrence, which can give unexpected results """ + err = None mapping = dict_node({}, beg_mark, end_mark) for key, value in ordered_pairs: - if key in mapping: - raise DuplicateError(f'"{key}"', mapping, key) - mapping[key] = value + for m_key in mapping: + if m_key == key: + if err is None: + err = DuplicateError(f'"{key}"', key) + err.append(m_key) + else: + err.append(key) + if key not in mapping: + mapping[key] = value + + if err is not None: + raise err if len(mapping) == 1: if 'Fn::Sub' in mapping: @@ -90,13 +102,12 @@ def build_match(message, doc, pos, key=' '): ) -def build_match_from_node(message, node, key): - +def build_match_from_key(message, key): return cfnlint.rules.Match( - node[key].start_mark.line, - node[key].start_mark.column + 1, - node[key].end_mark.line, - node[key].end_mark.column + 1 + len(key), + key.start_mark.line, + key.start_mark.column + 1, + key.end_mark.line, + key.end_mark.column + 1 + len(key), '', cfnlint.rules.ParseError(), message=message, @@ -438,21 +449,18 @@ def cfn_json_object( result = object_pairs_hook(pairs, beg_mark, end_mark) return result, end + 1 except DuplicateError as err: + errs = [] + for m in err.duplicates: + errs.append( + build_match_from_key( + message=f'Duplicate found {err}', + key=m, + ) + ) raise JSONDecodeError( doc=s, pos=end, - errors=[ - build_match_from_node( - message=f'Duplicate found {err}', - node=err.mapping, - key=err.key, - ), - build_match( - message=f'Duplicate found {err}', - doc=s, - pos=end, - ), - ], + errors=errs, ) from err pairs = {} if object_hook is not None: @@ -571,21 +579,18 @@ def cfn_json_object( ) result = object_pairs_hook(pairs, beg_mark, end_mark) except DuplicateError as err: + errs = [] + for m in err.duplicates: + errs.append( + build_match_from_key( + message=f'Duplicate found {err}', + key=m, + ) + ) raise JSONDecodeError( doc=s, pos=end, - errors=[ - build_match_from_node( - message=f'Duplicate found {err}', - node=err.mapping, - key=err.key, - ), - build_match( - message=f'Duplicate found {err}', - doc=s, - pos=end, - ), - ], + errors=errs, ) from err return result, end diff --git a/src/cfnlint/decode/cfn_yaml.py b/src/cfnlint/decode/cfn_yaml.py --- a/src/cfnlint/decode/cfn_yaml.py +++ b/src/cfnlint/decode/cfn_yaml.py @@ -85,31 +85,42 @@ def construct_yaml_map(self, node): # occurance, which can give unexpected results mapping = {} self.flatten_mapping(node) + matches = [] for key_node, value_node in node.value: key = self.construct_object(key_node, False) value = self.construct_object(value_node, False) for key_dup in mapping: if key_dup == key: - raise CfnParseError( - self.filename, - [ + if not matches: + matches.extend( + [ + build_match( + filename=self.filename, + message=f'Duplicate found "{key}" (line {key_dup.start_mark.line + 1})', + line_number=key_dup.start_mark.line, + column_number=key_dup.start_mark.column, + key=key, + ), + build_match( + filename=self.filename, + message=f'Duplicate found "{key}" (line {key_node.start_mark.line + 1})', + line_number=key_node.start_mark.line, + column_number=key_node.start_mark.column, + key=key, + ), + ], + ) + else: + matches.append( build_match( filename=self.filename, - message=f'Duplicate resource found "{key}" (line {key_dup.start_mark.line + 1})', - line_number=key_dup.start_mark.line, - column_number=key_dup.start_mark.column, - key=key, - ), - build_match( - filename=self.filename, - message=f'Duplicate resource found "{key}" (line {key_node.start_mark.line + 1})', + message=f'Duplicate found "{key}" (line {key_node.start_mark.line + 1})', line_number=key_node.start_mark.line, column_number=key_node.start_mark.column, key=key, ), - ], - ) + ) try: mapping[key] = value except Exception as exc: @@ -126,6 +137,12 @@ def construct_yaml_map(self, node): ], ) from exc + if matches: + raise CfnParseError( + self.filename, + matches, + ) + (obj,) = SafeConstructor.construct_yaml_map(self, node) if len(mapping) == 1:
diff --git a/test/fixtures/templates/bad/duplicate.json b/test/fixtures/templates/bad/duplicate.json --- a/test/fixtures/templates/bad/duplicate.json +++ b/test/fixtures/templates/bad/duplicate.json @@ -19,6 +19,12 @@ "Properties" : { "TopicName" : "deployed-topic" } - } + }, + "MySNSTopic" : { + "Type" : "AWS::SNS::Topic", + "Properties" : { + "TopicName" : "deployed-topic" + } + } } } diff --git a/test/fixtures/templates/bad/duplicate.yaml b/test/fixtures/templates/bad/duplicate.yaml --- a/test/fixtures/templates/bad/duplicate.yaml +++ b/test/fixtures/templates/bad/duplicate.yaml @@ -10,3 +10,7 @@ Resources: Type: AWS::SNS::Topic Parameters: TopicName: "used-topic-name" + mySnsTopic: + Type: AWS::SNS::Topic + Parameters: + TopicName: "used-topic-name" diff --git a/test/unit/module/test_api.py b/test/unit/module/test_api.py --- a/test/unit/module/test_api.py +++ b/test/unit/module/test_api.py @@ -42,7 +42,7 @@ def test_noecho_yaml_template_warnings_ignored(self): def test_duplicate_json_template(self): filename = 'test/fixtures/templates/bad/duplicate.json' matches = self.helper_lint_string_from_file(filename) - self.assertEqual(['E0000', 'E0000'], [match.rule.id for match in matches]) + self.assertEqual(['E0000', 'E0000', 'E0000'], [match.rule.id for match in matches]) def test_invalid_yaml_template(self): filename = 'test/fixtures/templates/bad/core/config_invalid_yaml.yaml' diff --git a/test/unit/module/test_duplicate.py b/test/unit/module/test_duplicate.py --- a/test/unit/module/test_duplicate.py +++ b/test/unit/module/test_duplicate.py @@ -42,10 +42,9 @@ def test_fail_run(self): filename = 'test/fixtures/templates/bad/duplicate.json' try: - with open(filename) as fp: - json.load(fp, cls=cfnlint.decode.cfn_json.CfnJSONDecoder) + cfnlint.decode.cfn_json.load(filename) except cfnlint.decode.cfn_json.JSONDecodeError as e: - self.assertEqual(len(e.matches), 2) + self.assertEqual(len(e.matches), 3) return assert(False) @@ -58,7 +57,7 @@ def test_fail_yaml_run(self): try: cfnlint.decode.cfn_yaml.load(filename) except cfnlint.decode.cfn_yaml.CfnParseError as e: - self.assertEqual(len(e.matches), 2) + self.assertEqual(len(e.matches), 3) return assert(False)
Only the first two Resource Duplicate are found - E0000 *cfn-lint version: (`cfn-lint 0.45.0`) Build from source: Commit: 002b3d1* *Description of issue.* This issue was 1st described on #1868 and fixed on #1900 I was validating the fix and it works if there are two duplicated resources, but not if you have 3 or more duplicated resources. I get the error `E0000 Duplicate resource found "DevRouteTableRoute2" (line 18)` and `E0000 Duplicate resource found "DevRouteTableRoute2" (line 13)` when I try to validate a CFn template with duplicated resources. I **should get has many errors has the number of duplicated resources on the template**. The template had more than one duplication (in this case 5) , but the linter only showed the 1st and 2nd. Please provide as much information as possible: * Test template: ```yaml --- AWSTemplateFormatVersion: "2010-09-09" Resources: DevRouteTableRoute1: Type: AWS::EC2::TransitGatewayRoute Properties: Blackhole: true DestinationCidrBlock: 10.1.1.0/24 TransitGatewayRouteTableId: tgw-rtb-d65d85280f2c9e51c DevRouteTableRoute2: Type: AWS::EC2::TransitGatewayRoute Properties: DestinationCidrBlock: 10.1.2.0/24 TransitGatewayAttachmentId: tgw-attach-9bdf1fdfb44d9c7d7 TransitGatewayRouteTableId: tgw-rtb-d65d85280f2c9e51c DevRouteTableRoute2: Type: AWS::EC2::TransitGatewayRoute Properties: DestinationCidrBlock: 10.1.3.0/24 TransitGatewayAttachmentId: tgw-attach-b16ea962254d4373e TransitGatewayRouteTableId: tgw-rtb-d65d85280f2c9e51c DevRouteTableRoute2: Type: AWS::EC2::TransitGatewayRoute Properties: DestinationCidrBlock: 10.1.4.0/24 TransitGatewayAttachmentId: tgw-attach-b16ea962254d4373e TransitGatewayRouteTableId: tgw-rtb-d65d85280f2c9e51c ProdRouteTableRoute1: Type: AWS::EC2::TransitGatewayRoute Properties: Blackhole: true DestinationCidrBlock: 10.1.1.0/24 TransitGatewayRouteTableId: tgw-rtb-5e9891f700a3af932 ProdRouteTableRoute2: Type: AWS::EC2::TransitGatewayRoute Properties: DestinationCidrBlock: 10.1.2.0/24 TransitGatewayAttachmentId: tgw-attach-9bdf1fdfb44d9c7d7 TransitGatewayRouteTableId: tgw-rtb-5e9891f700a3af932 ProdRouteTableRoute2: Type: AWS::EC2::TransitGatewayRoute Properties: DestinationCidrBlock: 10.1.3.0/24 TransitGatewayAttachmentId: tgw-attach-b16ea962254d4373e TransitGatewayRouteTableId: tgw-rtb-5e9891f700a3af932 ProdRouteTableRoute4: Type: AWS::EC2::TransitGatewayRoute Properties: DestinationCidrBlock: 10.1.4.0/24 TransitGatewayAttachmentId: tgw-attach-b16ea962254d4373e TransitGatewayRouteTableId: tgw-rtb-5e9891f700a3af932 ``` * Validation Output ``` E0000 Duplicate resource found "DevRouteTableRoute2" (line 18) template.yml:18:3 E0000 Duplicate resource found "DevRouteTableRoute2" (line 13) template.yml:13:5 ``` * Expected Output ``` E0000 Duplicate resource found "ProdRouteTableRoute2" (line 43) template.yml:43:3 E0000 Duplicate resource found "ProdRouteTableRoute2" (line 37) template.yml:37:3 E0000 Duplicate resource found "DevRouteTableRoute2" (line 24) template.yml:24:3 E0000 Duplicate resource found "DevRouteTableRoute2" (line 18) template.yml:18:3 E0000 Duplicate resource found "DevRouteTableRoute2" (line 13) template.yml:13:5 ``` We should get has many errors has the number of duplicated resources on the template. This is how the linter is working for the other errors cc/ @kddejong
Yea agreed. I'm going to leave this open for tracking. Since we handle these errors in the parser we are somewhat subject to the parser can do for passing and handling errors. I think I can do this but it may take a little work to get it working the right way.
2022-10-21T00:56:40Z
[]
[]
aws-cloudformation/cfn-lint
2,441
aws-cloudformation__cfn-lint-2441
[ "2416" ]
ae76d89ccabc4cb106df37297fa61faa5eefb312
diff --git a/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py b/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py --- a/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py +++ b/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py @@ -162,6 +162,26 @@ def check_value(self, value, path, **kwargs): strict_check, ) ) + else: + # types that represent a singular value (not json) + cfnlint.helpers.FUNCTIONS_SINGLE.sort() + if primitive_type in ['String', 'Boolean', 'Integer', 'Double']: + if len(map_value) != 1: + matches.append( + RuleMatch( + path, + f'Use a valid function [{", ".join(cfnlint.helpers.FUNCTIONS_SINGLE)}] when providing a value of type [{primitive_type}]', + ) + ) + else: + for k in map_value.keys(): + if k not in cfnlint.helpers.FUNCTIONS_SINGLE: + matches.append( + RuleMatch( + path, + f'Use a valid function [{", ".join(cfnlint.helpers.FUNCTIONS_SINGLE)}] when providing a value of type [{primitive_type}]', + ) + ) else: # some properties support primitive types and objects # skip in the case it could be an object and the value is a object
diff --git a/test/unit/rules/resources/properties/test_value_primitive_type.py b/test/unit/rules/resources/properties/test_value_primitive_type.py --- a/test/unit/rules/resources/properties/test_value_primitive_type.py +++ b/test/unit/rules/resources/properties/test_value_primitive_type.py @@ -104,3 +104,42 @@ def test_file_positive(self): self.assertEqual(len(self.rule._value_check(1, ['test'], 'Unknown', False, {})), 0) self.assertEqual(len(self.rule._value_check('1', ['test'], 'Unknown', False, {})), 0) self.assertEqual(len(self.rule._value_check(True, ['test'], 'Unknown', False, {})), 0) + +class TestResourceValuePrimitiveTypeCheckValue(BaseRuleTestCase): + """Test Check Value for maps""" + + def setUp(self): + """Setup""" + self.rule = ValuePrimitiveType() + self.rule.config['strict'] = False + + def test_file_check_value_good_function(self): + results = self.rule.check_value({'key': {'Ref': ['Parameter']}}, [], primitive_type='String', item_type='Map') + self.assertEqual(len(results), 0) + + def test_file_check_value_is_string(self): + results = self.rule.check_value({'key': 1}, [], primitive_type='Integer', item_type='Map') + self.assertEqual(len(results), 0) + + def test_file_check_value_is_json(self): + results = self.rule.check_value({'key': {}}, [], primitive_type='Json', item_type='Map') + self.assertEqual(len(results), 0) + + def test_file_check_value_bad_function(self): + results = self.rule.check_value({'key': {'Func': ['Parameter']}}, [], primitive_type='Boolean', item_type='Map') + self.assertEqual(len(results), 1) + self.assertEqual(results[0].message, 'Use a valid function [Fn::Base64, Fn::Cidr, Fn::Contains, ' + 'Fn::FindInMap, Fn::GetAtt, Fn::If, Fn::ImportValue, Fn::Join, Fn::Length, ' + 'Fn::Select, Fn::Sub, Fn::ToJsonString, Ref] when ' + 'providing a value of type [Boolean]') + + def test_file_check_value_bad_object(self): + results = self.rule.check_value({'key': {'Func': ['Parameter'], 'Func2': ['Parameter']}}, [], primitive_type='String', item_type='Map') + self.assertEqual(len(results), 1) + self.assertEqual(results[0].message, 'Use a valid function [Fn::Base64, Fn::Cidr, Fn::Contains, ' + 'Fn::FindInMap, Fn::GetAtt, Fn::If, Fn::ImportValue, Fn::Join, Fn::Length, ' + 'Fn::Select, Fn::Sub, Fn::ToJsonString, Ref] when ' + 'providing a value of type [String]') + + +
typo not being caught in Stack Parameters ### CloudFormation Lint Version 0.67.0 ### What operating system are you using? WSL2 ### Describe the bug Type is not getting caught inside stack parameters: ```yaml AWSTemplateFormatVersion: '2010-09-09' Description: 'Typo not caught by cfn-lint' Parameters: WakandaBucket: Type: String Description: Something. Resources: WakandaStack: Type: AWS::CloudFormation::Stack Properties: TemplateURL: "https://somewhere/foo.yaml" Parameters: Foobar: !Red WakandaBucket Wakanda4EverBucket: Type: AWS::S3::Bucket Properties: BucketName: !Ref WakandaBucket ``` >Note that after Foobar comes `!Red` insead of `!Ref`. cfn-lint output for above template is empty, exitcode 0. When I change the BucketName !Ref to !Red, that one gives me a proper error. But not for the Stack Parameters. ### Expected behavior I expect something like `Property X/Y/Z has an illegal function Fn::Red` ### Reproduction template ```yaml AWSTemplateFormatVersion: '2010-09-09' Description: 'Typo not caught by cfn-lint' Parameters: WakandaBucket: Type: String Description: Something. Resources: WakandaStack: Type: AWS::CloudFormation::Stack Properties: TemplateURL: "https://somewhere/foo.yaml" Parameters: Foobar: !Red WakandaBucket Wakanda4EverBucket: Type: AWS::S3::Bucket Properties: BucketName: !Ref WakandaBucket ```
reproduced with another property-type that was also a map of strings as well
2022-10-25T18:08:59Z
[]
[]
aws-cloudformation/cfn-lint
2,466
aws-cloudformation__cfn-lint-2466
[ "2464" ]
50e36b696d88cbe0f2db569b985c088492c88823
diff --git a/src/cfnlint/rules/__init__.py b/src/cfnlint/rules/__init__.py --- a/src/cfnlint/rules/__init__.py +++ b/src/cfnlint/rules/__init__.py @@ -302,9 +302,7 @@ def extend(self, more): self.register(rule) def __repr__(self): - return '\n'.join( - [rule.verbose() for rule in sorted(self.rules, key=lambda x: x.id)] - ) + return '\n'.join([self.rules[id].verbose() for id in sorted(self.rules)]) def is_rule_enabled(self, rule: CloudFormationLintRule): """Checks if an individual rule is valid"""
diff --git a/test/unit/module/test_rules_collections.py b/test/unit/module/test_rules_collections.py --- a/test/unit/module/test_rules_collections.py +++ b/test/unit/module/test_rules_collections.py @@ -2,6 +2,7 @@ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ +import re from cfnlint.exceptions import DuplicateRuleError from test.testlib.testcase import BaseTestCase from cfnlint.template import Template @@ -231,6 +232,26 @@ class rule1_e0000(CloudFormationLintRule): rules = RulesCollection() self.assertRaises(DuplicateRuleError, rules.extend, rules_to_add) + def test_repr(self): + class rule0_e0000(CloudFormationLintRule): + """Error Rule""" + id = 'E0000' + shortdesc = 'Rule A' + description = 'First rule' + class rule1_e0001(CloudFormationLintRule): + """Error Rule""" + id = 'E0001' + shortdesc = 'Rule B' + description = 'Second rule' + rules = RulesCollection() + rules.extend([rule0_e0000(), rule1_e0001()]) + + retval = repr(rules) + pattern = r"\AE0000: Rule A\nFirst rule\nE0001: Rule B\nSecond rule\Z" + match = re.match(pattern, retval) + assert match, f"{retval} does not match {pattern}" + + class TestCreateFromModule(BaseTestCase): """Test loading a rules collection from a module"""
Cannot list all the rules ### CloudFormation Lint Version 0.70.0 ### What operating system are you using? Windows ### Describe the bug `cfn-lint --list-rules` throws below Error.(username is masked.) ``` Traceback (most recent call last): File "C:\Users\${username}\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\${username}\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\${username}\AppData\Local\Programs\Python\Python39\Scripts\cfn-lint.exe\__main__.py", line 7, in <module> File "C:\Users\${username}\AppData\Local\Programs\Python\Python39\lib\site-packages\cfnlint\__main__.py", line 38, in main (args, filenames, formatter) = cfnlint.core.get_args_filenames(sys.argv[1:]) File "C:\Users\${username}\AppData\Local\Programs\Python\Python39\lib\site-packages\cfnlint\core.py", line 235, in get_args_filenames print(rules) File "C:\Users\${username}\AppData\Local\Programs\Python\Python39\lib\site-packages\cfnlint\rules\__init__.py", line 306, in __repr__ [rule.verbose() for rule in sorted(self.rules, key=lambda x: x.id)] File "C:\Users\${username}\AppData\Local\Programs\Python\Python39\lib\site-packages\cfnlint\rules\__init__.py", line 306, in <lambda> [rule.verbose() for rule in sorted(self.rules, key=lambda x: x.id)] AttributeError: 'str' object has no attribute 'id' ``` ### Expected behavior show list all the rules. ### Reproduction template This is not bug of linting.
2022-11-02T16:36:43Z
[]
[]
aws-cloudformation/cfn-lint
2,470
aws-cloudformation__cfn-lint-2470
[ "2469" ]
4cf84248e1c9818f38257adedb2944d06a3a4115
diff --git a/src/cfnlint/config.py b/src/cfnlint/config.py --- a/src/cfnlint/config.py +++ b/src/cfnlint/config.py @@ -677,7 +677,7 @@ def templates(self): elif templates_args: filenames = templates_args else: - return None + return ['-'] # if only one is specified convert it to array if isinstance(filenames, str): diff --git a/src/cfnlint/decode/cfn_json.py b/src/cfnlint/decode/cfn_json.py --- a/src/cfnlint/decode/cfn_json.py +++ b/src/cfnlint/decode/cfn_json.py @@ -366,8 +366,14 @@ def load(filename): content = '' if not sys.stdin.isatty(): - for line in fileinput.input(files=filename): - content = content + line + if sys.version_info.major <= 3 and sys.version_info.minor <= 9: + for line in fileinput.input(files=filename): + content = content + line + else: + for line in fileinput.input( # pylint: disable=unexpected-keyword-arg + files=filename, encoding='utf-8' + ): + content = content + line else: with open(filename, encoding='utf-8') as fp: content = fp.read() diff --git a/src/cfnlint/decode/cfn_yaml.py b/src/cfnlint/decode/cfn_yaml.py --- a/src/cfnlint/decode/cfn_yaml.py +++ b/src/cfnlint/decode/cfn_yaml.py @@ -256,8 +256,14 @@ def load(filename): content = '' if not sys.stdin.isatty(): - for line in fileinput.input(files=filename): - content = content + line + if sys.version_info.major <= 3 and sys.version_info.minor <= 9: + for line in fileinput.input(files=filename): + content = content + line + else: + for line in fileinput.input( # pylint: disable=unexpected-keyword-arg + files=filename, encoding='utf-8' + ): + content = content + line else: with open(filename, encoding='utf-8') as fp: content = fp.read()
diff --git a/test/unit/module/core/test_run_cli.py b/test/unit/module/core/test_run_cli.py --- a/test/unit/module/core/test_run_cli.py +++ b/test/unit/module/core/test_run_cli.py @@ -108,7 +108,7 @@ def test_template_via_stdin(self): with patch('sys.stdin', StringIO(file_content)): (_, filenames, _) = cfnlint.core.get_args_filenames([]) - assert filenames == [None] + assert filenames == ['-'], filenames with patch('sys.stdin', StringIO(file_content)): (_, filenames, _) = cfnlint.core.get_args_filenames(['--template', filename])
cfnlint via stdin has issues when parameters are present ### CloudFormation Lint Version v0.70.1 ### What operating system are you using? Mac ### Describe the bug ```sh echo 'Resources: {}' | cfn-lint --include-checks I 2022-11-03 11:14:45,106 - cfnlint.decode - ERROR - Template file not found: None E0000 Template file not found: None None:1:1 ``` when no parameters: ```sh echo '{"Resources": {}}' | cfn-lint echo $? 0 ``` ### Expected behavior ```sh echo 'Resources: {}' | cfn-lint --include-checks I echo $? 0 ``` ### Reproduction template ```yaml Resources: {} ``` ```json { "Resources": {} } ```
2022-11-03T18:34:46Z
[]
[]
aws-cloudformation/cfn-lint
2,502
aws-cloudformation__cfn-lint-2502
[ "2501" ]
bb7cad6229214a48af53c2742141e08e573d1fa8
diff --git a/src/cfnlint/graph.py b/src/cfnlint/graph.py --- a/src/cfnlint/graph.py +++ b/src/cfnlint/graph.py @@ -240,6 +240,7 @@ def _add_subs(self, cfn: Any) -> None: def _add_node(self, node_id, label, settings): if settings.node_type in ['Parameter', 'Output']: node_id = f'{settings.node_type}-{node_id}' + self.graph.add_node( node_id, label=label, @@ -255,7 +256,6 @@ def _add_edge(self, source_id, target_id, source_path, settings): source_paths=source_path, label=settings.label, color=settings.color, - penwidth=1, ) def _is_resource(self, cfn, identifier): diff --git a/src/cfnlint/runner.py b/src/cfnlint/runner.py --- a/src/cfnlint/runner.py +++ b/src/cfnlint/runner.py @@ -6,7 +6,8 @@ from typing import List, Optional, Sequence, Union from cfnlint.template import Template from cfnlint.transform import Transform -from .rules import Match, RulesCollection +from cfnlint.graph import Graph +from cfnlint.rules import Match, RulesCollection LOGGER = logging.getLogger(__name__) @@ -52,6 +53,7 @@ def transform(self): transform = Transform(self.filename, self.cfn.template, self.cfn.regions[0]) matches = transform.transform_template() self.cfn.template = transform.template() + self.cfn.graph = Graph(self.cfn) return matches def run(self) -> List[Match]:
diff --git a/test/unit/module/test_template.py b/test/unit/module/test_template.py --- a/test/unit/module/test_template.py +++ b/test/unit/module/test_template.py @@ -53,10 +53,10 @@ def test_build_graph(self): IamPipeline [color=black, label="IamPipeline\\n<AWS::CloudFormation::Stack>", shape=ellipse, type=Resource]; CustomResource [color=black, label="CustomResource\\n<Custom::Function>", shape=ellipse, type=Resource]; WaitCondition [color=black, label="WaitCondition\\n<AWS::CloudFormation::WaitCondition>", shape=ellipse, type=Resource]; -RolePolicies -> RootRole [color=black, key=0, label=Ref, penwidth=1, source_paths="['Properties', 'Roles', 0]"]; -RootInstanceProfile -> RootRole [color=black, key=0, label=Ref, penwidth=1, source_paths="['Properties', 'Roles', 0]"]; -MyEC2Instance -> RootInstanceProfile [color=black, key=0, label=Ref, penwidth=1, source_paths="['Properties', 'IamInstanceProfile']"]; -ElasticLoadBalancer -> MyEC2Instance [color=black, key=0, label=Ref, penwidth=1, source_paths="['Properties', 'Instances', 0]"]; +RolePolicies -> RootRole [color=black, key=0, label=Ref, source_paths="['Properties', 'Roles', 0]"]; +RootInstanceProfile -> RootRole [color=black, key=0, label=Ref, source_paths="['Properties', 'Roles', 0]"]; +MyEC2Instance -> RootInstanceProfile [color=black, key=0, label=Ref, source_paths="['Properties', 'IamInstanceProfile']"]; +ElasticLoadBalancer -> MyEC2Instance [color=black, key=0, label=Ref, source_paths="['Properties', 'Instances', 0]"]; } """.split('\n')
False positive E3004 circular dependency for SAM templates ### CloudFormation Lint Version cfn-lint 0.72.0 ### What operating system are you using? Linux ### Describe the bug When `AWS::Serverless::Function` references an alarm in its `DeploymentPreference.Alarms` and the `AWS::CloudWatch::Alarm` references the function (eg. in Dimensions), a `E3004 Circular dependency` error is reported by cfn-lint. Afaik this is a valid use case. This was introduced in cfn-lint 0.72.0 (0.71.1 did not report E3004), most likely as part of PR aws-cloudformation/cfn-lint#2452. ``` E3004 Circular Dependencies for resource TestFunction. Circular dependency with [LatestVersionErrorMetricGreaterThanZeroAlarm] template.yaml:5:3 E3004 Circular Dependencies for resource LatestVersionErrorMetricGreaterThanZeroAlarm. Circular dependency with [TestFunction] template.yaml:28:3 ``` (The template is based on https://gist.github.com/alexcasalboni/242071568a6adde805027345cfbb6d99. But we first noticed this in one of our production functions when upgrading cfn-lint to 0.72.0.) ### Expected behavior No E3004 is reported. ### Reproduction template ```yaml AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::Serverless-2016-10-31' Resources: TestFunction: Type: AWS::Serverless::Function Properties: Handler: index.test Runtime: nodejs16.x MemorySize: 128 Timeout: 30 Tracing: Active CodeUri: ./ Events: GetResource: Type: Api Properties: Path: /test Method: get RestApiId: !Ref 'Api' AutoPublishAlias: live DeploymentPreference: Type: Linear10PercentEvery1Minute Alarms: - !Ref LatestVersionErrorMetricGreaterThanZeroAlarm LatestVersionErrorMetricGreaterThanZeroAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmName: alarm-sam-demo-latestversion AlarmDescription: "alarm to check for errors in the function" ComparisonOperator: GreaterThanOrEqualToThreshold TreatMissingData: missing Dimensions: - Name: FunctionName Value: !Ref TestFunction - Name: Resource Value: !Join [":", [!Ref TestFunction, !Select ["7", !Split [":", !Ref TestFunction.Version]]]] EvaluationPeriods: 1 MetricName: Errors Namespace: AWS/Lambda Period: 60 Statistic: Sum Threshold: 1 Api: Type: AWS::Serverless::Api Properties: StageName: foo TracingEnabled: true LogGroup: Type: AWS::Logs::LogGroup Properties: LogGroupName: !Sub - /aws/lambda/${FunctionName} - FunctionName: !Ref 'TestFunction' RetentionInDays: 1 DeletionPolicy: Delete UpdateReplacePolicy: Delete ```
2022-11-25T17:52:19Z
[]
[]
aws-cloudformation/cfn-lint
2,513
aws-cloudformation__cfn-lint-2513
[ "2483" ]
c6252d6b815127a21c58259dbe914e864844ff44
diff --git a/src/cfnlint/rules/resources/HardCodedArnProperties.py b/src/cfnlint/rules/resources/HardCodedArnProperties.py --- a/src/cfnlint/rules/resources/HardCodedArnProperties.py +++ b/src/cfnlint/rules/resources/HardCodedArnProperties.py @@ -71,9 +71,13 @@ def match_values(self, cfn): return results def match(self, cfn): - """Check CloudFormation Resources""" matches = [] + transforms = cfn.transform_pre["Transform"] + transforms = transforms if isinstance(transforms, list) else [transforms] + if "AWS::Serverless-2016-10-31" in cfn.transform_pre["Transform"]: + return matches + # Get a list of paths to every leaf node string containing at least one ${parameter} parameter_string_paths = self.match_values(cfn) # We want to search all of the paths to check if each one contains an 'Fn::Sub'
diff --git a/test/fixtures/templates/good/resources/properties/hard_coded_arn_properties_sam.yaml b/test/fixtures/templates/good/resources/properties/hard_coded_arn_properties_sam.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/properties/hard_coded_arn_properties_sam.yaml @@ -0,0 +1,80 @@ +AWSTemplateFormatVersion: 2010-09-09 +Transform: AWS::Serverless-2016-10-31 +Resources: + S3BadBucket: + Type: AWS::S3::Bucket + Properties: + AccessControl: Private + NotificationConfiguration: + TopicConfigurations: + - Topic: !Sub arn:aws:sns:us-east-1:123456789012:TestTopic + Event: s3:ReducedRedundancyLostObject + + SampleBadBucketPolicy: + Type: AWS::S3::BucketPolicy + Properties: + Bucket: !Ref S3BadBucket + PolicyDocument: + Statement: + - Action: + - s3:GetObject + Effect: Allow + Resource: !Sub arn:aws:s3:::${S3BadBucket} + Principal: "*" + + SampleRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Principal: + Service: + - ec2.amazonaws.com + Action: + - 'sts:AssumeRole' + Path: / + + + SampleBadIAMPolicy1: + Type: AWS::IAM::ManagedPolicy + Properties: + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - sns:Publish + Resource: !Sub arn:${AWS::Partition}:sns:us-east-1:${AWS::AccountId}:TestTopic + Roles: + - !Ref SampleRole + + SampleBadIAMPolicy2: + Type: AWS::IAM::ManagedPolicy + Properties: + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - sns:Publish + Resource: + - !Sub arn:${AWS::Partition}:sns:us-east-1:${AWS::AccountId}:TestTopic + - !Sub arn:${AWS::Partition}:sns:${AWS::Region}:${AWS::AccountId}:TestTopic + Roles: + - !Ref SampleRole + + SampleBadIAMPolicy3: + Type: AWS::IAM::ManagedPolicy + Properties: + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - sns:Publish + Resource: + - !Sub arn:${AWS::Partition}:sns:${AWS::Partition}:${AWS::AccountId}:TestTopic + Roles: + - !Ref SampleRole diff --git a/test/unit/rules/resources/test_hardcodedarnproperties.py b/test/unit/rules/resources/test_hardcodedarnproperties.py --- a/test/unit/rules/resources/test_hardcodedarnproperties.py +++ b/test/unit/rules/resources/test_hardcodedarnproperties.py @@ -16,6 +16,9 @@ def setUp(self): """Setup""" super(TestHardCodedArnProperties, self).setUp() self.collection.register(HardCodedArnProperties()) + self.success_templates = [ + "test/fixtures/templates/good/resources/properties/hard_coded_arn_properties_sam.yaml", + ] def test_file_positive(self): """Test Positive"""
Don't validate SAM transformed resources for rule I3042 ### CloudFormation Lint Version v0.71.1 ### What operating system are you using? Mac ### Describe the bug When SAM transforms templates it can create hardcoded ARNs based on its scenario. It would make sense to not validate those ARNs against rule I3042 ### Expected behavior To not raise I3042 on resources that are created by SAM transform. ### Reproduction template ```yaml ```
2022-12-07T05:58:06Z
[]
[]
aws-cloudformation/cfn-lint
2,525
aws-cloudformation__cfn-lint-2525
[ "2227" ]
03987e8aef2044108023c57870ddc03993754918
diff --git a/src/cfnlint/rules/functions/RelationshipConditions.py b/src/cfnlint/rules/functions/RelationshipConditions.py --- a/src/cfnlint/rules/functions/RelationshipConditions.py +++ b/src/cfnlint/rules/functions/RelationshipConditions.py @@ -17,7 +17,7 @@ class RelationshipConditions(CloudFormationLintRule): "condition." ) source_url = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html" - tags = ["conditions", "resources", "relationships", "ref", "getatt"] + tags = ["conditions", "resources", "relationships", "ref", "getatt", "sub"] def match(self, cfn): """Check CloudFormation Ref/GetAtt for Conditions""" @@ -83,4 +83,46 @@ def match(self, cfn): ) ) + # The do Sub + sub_objs = cfn.search_deep_keys(searchText="Fn::Sub", includeGlobals=False) + for sub_obj in sub_objs: + sub_string = sub_obj[-1] + # Filter out bad types of sub_strings. + # Lists have two be two items and it can be just a string + if not isinstance(sub_string, (list, str)): + continue + if isinstance(sub_string, str): + sub_string = [sub_string, {}] + if len(sub_string) != 2: + continue + sub_params = sub_string[1] + string_params = cfn.get_sub_parameters(sub_string[0]) + + for string_param in string_params: + if string_param not in sub_params: + # deal with GetAtts by dropping everything after the . + string_param = string_param.split(".")[0] + if string_param in cfn.template.get("Resources", {}): + scenarios = cfn.is_resource_available( + sub_obj[:-1], string_param + ) + for scenario in scenarios: + scenario_text = " and ".join( + [ + f'when condition "{k}" is {v}' + for (k, v) in scenario.items() + ] + ) + message = 'Fn::Sub to resource "{0}" that may not be available {1} at {2}' + matches.append( + RuleMatch( + sub_obj[:-1], + message.format( + string_param, + scenario_text, + "/".join(map(str, sub_obj[:-1])), + ), + ) + ) + return matches
diff --git a/test/fixtures/templates/bad/functions/relationship_conditions.yaml b/test/fixtures/templates/bad/functions/relationship_conditions.yaml --- a/test/fixtures/templates/bad/functions/relationship_conditions.yaml +++ b/test/fixtures/templates/bad/functions/relationship_conditions.yaml @@ -45,6 +45,19 @@ Resources: Timeout: 25 TracingConfig: Mode: Active + + SubCondRefParam: + Type: AWS::SSM::Parameter + Properties: + Type: String + Value: !Sub ${LambdaExecutionRole} + + SubCondGetAttParam: + Type: AWS::SSM::Parameter + Properties: + Type: String + Value: !Sub ${LambdaExecutionRole.Arn} + Outputs: lambdaArn: Value: !GetAtt LambdaExecutionRole.Arn diff --git a/test/unit/rules/functions/test_relationship_conditions.py b/test/unit/rules/functions/test_relationship_conditions.py --- a/test/unit/rules/functions/test_relationship_conditions.py +++ b/test/unit/rules/functions/test_relationship_conditions.py @@ -28,5 +28,5 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" self.helper_file_negative( - "test/fixtures/templates/bad/functions/relationship_conditions.yaml", 3 + "test/fixtures/templates/bad/functions/relationship_conditions.yaml", 5 )
Feature Request: !Sub equivalent of W1001 *cfn-lint version: 0.58.2* I believe that `!Sub` parameters should be checked to see if they depend on conditional resources the same way W1001 checks this for `!Ref` (e.g. `SubCondParam.Value` should produce a warning). I suspect this is possible since E1019 checks for non-existent parameters within a `!Sub`. ``` --- AWSTemplateFormatVersion: 2010-09-09 Conditions: CreateContainerRepository: !Equals ["yes", "no"] Resources: Repository: Type: AWS::ECR::Repository Condition: CreateContainerRepository SubCondParam: Type: AWS::SSM::Parameter Properties: Type: String Value: !Sub ${Repository} RefCondParam: Type: AWS::SSM::Parameter Properties: Type: String Value: !Ref Repository SubFakeParam: Type: AWS::SSM::Parameter Properties: Type: String Value: !Sub ${Fake} RefFakeParam: Type: AWS::SSM::Parameter Properties: Type: String Value: !Ref Fake ``` * SubCondParam.Value shows no error or warning, I believe it should show a warning * RefCondParam.Value shows W1001 * SubFakeParam.Value shows E1019 * RefFakeParam.Value shows E1012
2022-12-15T18:33:15Z
[]
[]
aws-cloudformation/cfn-lint
2,548
aws-cloudformation__cfn-lint-2548
[ "2537" ]
1380fa27e35c50c6dbdfd7884ed22e46563c370c
diff --git a/src/cfnlint/rules/resources/properties/Properties.py b/src/cfnlint/rules/resources/properties/Properties.py --- a/src/cfnlint/rules/resources/properties/Properties.py +++ b/src/cfnlint/rules/resources/properties/Properties.py @@ -380,6 +380,21 @@ def propertycheck(self, text, proptype, parenttype, resourcename, path, root): and text.get(prop) == "AWS::NoValue" ): pass + elif len(text) == 1 and prop in "Fn::GetAtt": + getatt = text.get(prop) + getatt_type = ( + self.cfn.template.get("Resources", {}) + .get(getatt[0], {}) + .get("Type", "") + ) + if ( + getatt_type == "AWS::CloudFormation::CustomResource" + or getatt_type.startswith("Custom::") + ): + pass + else: + message = f'GetAtt must refer to a custom resource {"/".join(map(str, proppath))}' + matches.append(RuleMatch(proppath, message)) elif not supports_additional_properties: close_match = False for key in resourcespec.keys():
diff --git a/test/fixtures/templates/bad/resource_properties.yaml b/test/fixtures/templates/bad/resource_properties.yaml --- a/test/fixtures/templates/bad/resource_properties.yaml +++ b/test/fixtures/templates/bad/resource_properties.yaml @@ -48,3 +48,13 @@ Resources: VpcConfig: SubnetIds: !ImportValue foobar1 SecurityGroupIds: !ImportValue foobar2 + Custom: + Type: AWS::CloudFormation::CustomResource + Properties: + ServiceToken: arn.example + Helper: + Type: 'AWS::Lambda::Function' + Properties: + Handler: 'helper.lambda_handler' + Role: arn:aws:iam::123456789012:role/role-name-with-path + Code: !GetAtt myInstance.AvailabilityZone # returns a string not an object diff --git a/test/fixtures/templates/good/resource_properties.yaml b/test/fixtures/templates/good/resource_properties.yaml --- a/test/fixtures/templates/good/resource_properties.yaml +++ b/test/fixtures/templates/good/resource_properties.yaml @@ -641,7 +641,12 @@ Resources: Type: AWS::CloudFormation::CustomResource Properties: ServiceToken: arn.example - + Helper: + Type: 'AWS::Lambda::Function' + Properties: + Handler: 'helper.lambda_handler' + Role: arn:aws:iam::123456789012:role/role-name-with-path + Code: !GetAtt Custom.Code LB1: Type: AWS::ElasticLoadBalancingV2::LoadBalancer Properties: diff --git a/test/unit/rules/resources/properties/test_properties.py b/test/unit/rules/resources/properties/test_properties.py --- a/test/unit/rules/resources/properties/test_properties.py +++ b/test/unit/rules/resources/properties/test_properties.py @@ -42,7 +42,7 @@ def test_file_negative_2(self): def test_file_negative_3(self): """Failure test""" self.helper_file_negative( - "test/fixtures/templates/bad/resource_properties.yaml", 7 + "test/fixtures/templates/bad/resource_properties.yaml", 8 ) def test_E3012_in_bad_template(self):
E3002 false positives with intrinsics returning complex types ### CloudFormation Lint Version 0.72.5 ### What operating system are you using? Linux (Fedora) ### Describe the bug When using intrinsic functions to retrieve complex (ie structured) data from custom resources for other resources E3002 incorrectly marks the intrinsic as invalid properties of the resource. For example, given a custom resource which returns an AWS::Lambda::Function _Code_ object: ``` "Code": { "S3Bucket": "<name>", "S3Key": "<object-key>", "S3ObjectVersion": "<object-version>" } ``` Then referencing this as the Code: property of another AWS::Lambda::Function, eg ``` Code: !GetAtt CustomResource.Output.Code ``` cfn-lint raises an E3002 of the form: ```E3002 Invalid Property Resources/Helper/Properties/Code/Fn::GetAtt``` This can be suppressed in the resource's Metadata, but only by suppressing all E3002 errors for that resource, where other instances of the error could be legitimate. While I imagine that the vast majority of values returned from custom resources are scalars, they are no required to be, and therefore can provide structure as well as values. Certainly at least in the specific case described here the various Code.<Name> attributes are all correctly referenced when actually running the template. ### Expected behavior E3002 Should not be raised when an intrinsic is used to return information for a valid partial attribute path. Since scalars are the most common return values it may be a reasonable compromise to raise a context specific W or I code At the very least even if metadata annotation is required to suppress this case it should be a unique code, which can be supressed without also supressing common errors such as attribute name typos ### Reproduction template ```yaml Parameters: RoleArn: Type: String FunctionArn: Type: String Resources: GetCodeForLatestS3Object: Type: Custom::LambdaSource Properties: ServiceToken: !Ref FunctionArn S3Url: "s3://some-bucket/lambdazips/helper.zip" Helper: Type: 'AWS::Lambda::Function' Properties: Handler: 'helper.lambda_handler' Role: !Ref RoleArn Code: !GetAtt GetCodeForLatestS3Object.Code ```
Yea I think we are handling custom resources for simple types but not for complex types. Let me double check it and correct it.
2023-01-06T00:07:54Z
[]
[]
aws-cloudformation/cfn-lint
2,649
aws-cloudformation__cfn-lint-2649
[ "2648" ]
7192944b5840321f3b3115cd6427e4071cdee2b7
diff --git a/src/cfnlint/conditions/conditions.py b/src/cfnlint/conditions/conditions.py --- a/src/cfnlint/conditions/conditions.py +++ b/src/cfnlint/conditions/conditions.py @@ -115,9 +115,15 @@ def _build_cnf( if param.hash not in allowed_values: continue if isinstance(equal_1.left, str): - allowed_values[param.hash].remove(get_hash(equal_1.left)) + if get_hash(equal_1.left) in allowed_values[param.hash]: + allowed_values[param.hash].remove(get_hash(equal_1.left)) + else: + equal_vars[equal_1.hash] = BooleanFalse() if isinstance(equal_1.right, str): - allowed_values[param.hash].remove(get_hash(equal_1.right)) + if get_hash(equal_1.right) in allowed_values[param.hash]: + allowed_values[param.hash].remove(get_hash(equal_1.right)) + else: + equal_vars[equal_1.hash] = BooleanFalse() # iteration 2 builds the cnf formulas to make sure any empty lists # are now full not equals @@ -157,10 +163,10 @@ def build_scenarios(self, condition_names: List[str]) -> Iterator[Dict[str, bool return # if only one condition we will assume its True/False - if len(condition_names) == 1: - yield {condition_names[0]: True} - yield {condition_names[0]: False} - return + # if len(condition_names) == 1: + # yield {condition_names[0]: True} + # yield {condition_names[0]: False} + # return try: # build a large matric of True/False options based on the provided conditions
diff --git a/test/unit/module/conditions/test_conditions.py b/test/unit/module/conditions/test_conditions.py --- a/test/unit/module/conditions/test_conditions.py +++ b/test/unit/module/conditions/test_conditions.py @@ -127,7 +127,7 @@ def test_check_never_false(self): ], ) - def test_check_can_be_salfe(self): + def test_check_can_be_false(self): """With allowed values two conditions can both be false""" template = decode_str( """ @@ -151,3 +151,32 @@ def test_check_can_be_salfe(self): {"IsProd": False, "IsDev": False}, ], ) + + def test_check_can_be_good_when_condition_value(self): + """Some times a condition Equals doesn't match to allowed values""" + template = decode_str( + """ + Parameters: + Environment: + Type: String + AllowedValues: ["prod", "dev", "stage"] + Conditions: + IsGamma: !Equals [!Ref Environment, "gamma"] + IsBeta: !Equals ["beta", !Ref Environment] + """ + )[0] + + cfn = Template("", template) + self.assertEqual(len(cfn.conditions._conditions), 2) + self.assertListEqual( + list(cfn.conditions.build_scenarios(["IsGamma", "IsBeta"])), + [ + {"IsBeta": False, "IsGamma": False}, + ], + ) + self.assertListEqual( + list(cfn.conditions.build_scenarios(["IsGamma"])), + [ + {"IsGamma": False}, + ], + )
ValueError: list.remove(x): x not in list ### CloudFormation Lint Version 0.76.0 ### What operating system are you using? macOS ### Describe the bug We run latest `cfn-lint` on all templates in the [AWS SAM repository](https://github.com/aws/serverless-application-model/); looks like 0.76.0 introduced a bug. Since today, `cfn-lint` fails with: ```text Traceback (most recent call last): File "/Users/rehnc/Desktop/tmp/serverless-application-model/.venv_cfn_lint/bin/cfn-lint", line 8, in <module> sys.exit(main()) File "/Users/rehnc/Desktop/tmp/serverless-application-model/.venv_cfn_lint/lib/python3.10/site-packages/cfnlint/__main__.py", line 39, in main matches = list(cfnlint.core.get_matches(filenames, args)) File "/Users/rehnc/Desktop/tmp/serverless-application-model/.venv_cfn_lint/lib/python3.10/site-packages/cfnlint/core.py", line 173, in get_matches matches = run_cli( File "/Users/rehnc/Desktop/tmp/serverless-application-model/.venv_cfn_lint/lib/python3.10/site-packages/cfnlint/core.py", line 78, in run_cli return run_checks(filename, template, rules, regions, mandatory_rules) File "/Users/rehnc/Desktop/tmp/serverless-application-model/.venv_cfn_lint/lib/python3.10/site-packages/cfnlint/core.py", line 334, in run_checks runner = cfnlint.runner.Runner( File "/Users/rehnc/Desktop/tmp/serverless-application-model/.venv_cfn_lint/lib/python3.10/site-packages/cfnlint/runner.py", line 32, in __init__ self.cfn = Template(filename, template, regions) File "/Users/rehnc/Desktop/tmp/serverless-application-model/.venv_cfn_lint/lib/python3.10/site-packages/cfnlint/template/template.py", line 44, in __init__ self.conditions = cfnlint.conditions.Conditions(self) File "/Users/rehnc/Desktop/tmp/serverless-application-model/.venv_cfn_lint/lib/python3.10/site-packages/cfnlint/conditions/conditions.py", line 34, in __init__ self._cnf, self._solver_params = self._build_cnf(list(self._conditions.keys())) File "/Users/rehnc/Desktop/tmp/serverless-application-model/.venv_cfn_lint/lib/python3.10/site-packages/cfnlint/conditions/conditions.py", line 118, in _build_cnf allowed_values[param.hash].remove(get_hash(equal_1.left)) ValueError: list.remove(x): x not in list ``` ### Expected behavior Expected it not to fail, or to fail like a template violation would. ### Reproduction template Not sure yet which one is causing the issue, but this reproduces it: ```bash git clone https://github.com/aws/serverless-application-model.git --depth 1 cd serverless-application-model python3 -m venv .venv .venv/bin/python -m pip install cfn-lint==0.76.0 .venv/bin/cfn-lint ``` However, if you try with `.venv/bin/python -m pip install cfn-lint==0.75.0`, it succeeds.
Working on the issue but also found a use case for a new rule. This is one of those scenarios of an always False case. ``` "Conditions": { "CreateProdResources": { "Fn::Equals": [ { "Ref": "InstanceTypeParameter" }, "prod" ] } }, ... "Parameters": { "InstanceTypeParameter": { "AllowedValues": [ "t2.micro", "m1.small", "m1.large" ], ```
2023-03-27T19:12:05Z
[]
[]
aws-cloudformation/cfn-lint
2,661
aws-cloudformation__cfn-lint-2661
[ "2658" ]
792406f07bda48ac94e598cb2a068b0a76ba78b0
diff --git a/src/cfnlint/transform.py b/src/cfnlint/transform.py --- a/src/cfnlint/transform.py +++ b/src/cfnlint/transform.py @@ -218,7 +218,7 @@ def _update_to_s3_uri( if isinstance(uri_property, dict): if len(uri_property) == 1: for k in uri_property.keys(): - if k == "Ref": + if k in ["Ref", "Fn::Sub"]: resource_property_dict[property_key] = s3_uri_value return if Transform.is_s3_uri(uri_property):
diff --git a/test/fixtures/templates/good/transform/function_use_s3_uri.yaml b/test/fixtures/templates/good/transform/function_use_s3_uri.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/transform/function_use_s3_uri.yaml @@ -0,0 +1,28 @@ +AWSTemplateFormatVersion: "2010-09-09" +Transform: + - 'AWS::LanguageExtensions' + - 'AWS::Serverless-2016-10-31' + +Description: cfn-lint test case + +Mappings: + RegionMap: + us-east-1: + InsightsArn: arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:21 + us-west-2: + InsightsArn: arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:21 + +Resources: + Function: + Type: AWS::Serverless::Function + Properties: + FunctionName: !Sub "my-custom-authorizer-${AWS::Region}" + Description: Custom authorizer for APIGW + Runtime: nodejs16.x + Handler: index.handler + CodeUri: !Sub "s3://custom-authz-${AWS::AccountId}-${AWS::Region}/function-v1.0.zip" + Policies: + - arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy + - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole + Layers: + - !FindInMap [RegionMap, !Ref AWS::Region, "InsightsArn"] diff --git a/test/unit/module/transform/test_transform.py b/test/unit/module/transform/test_transform.py --- a/test/unit/module/transform/test_transform.py +++ b/test/unit/module/transform/test_transform.py @@ -90,6 +90,21 @@ def test_conversion_of_step_function_definition_uri(self): {"Bucket": "bucket", "Key": "value"}, ) + def test_conversion_of_serverless_function_uri(self): + """Tests that the a serverless function can convert a CodeUri Sub""" + filename = "test/fixtures/templates/good/transform/function_use_s3_uri.yaml" + region = "us-east-1" + template = cfn_yaml.load(filename) + transformed_template = Transform(filename, template, region) + transformed_template.transform_template() + self.assertDictEqual( + transformed_template._template.get("Resources") + .get("Function") + .get("Properties") + .get("Code"), + {"S3Bucket": "bucket", "S3Key": "value"}, + ) + def test_parameter_for_autopublish_version_bad(self): """Test Parameter is created for autopublish version run""" filename = "test/fixtures/templates/bad/transform/auto_publish_alias.yaml"
False positive E0001 for CodeUri in AWS::Serverless::Function ### CloudFormation Lint Version cfn-lint 0.76.1 ### What operating system are you using? Mac ### Describe the bug cfn-lint gives a false-positive error when CodeUri is an S3 URI. ```E0001 Error transforming template: Resource with id [rCustomAuthorizerFunction] is invalid. 'CodeUri' requires Bucket and Key properties to be specified.``` Not only does this template deploy via CloudFormation, the warning from cfn-lint contradicts the [public documentation for this resource type](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html#Examples) ### Expected behavior cfn-lint should not give a false positive that contradicts public documentation ### Reproduction template ```yaml AWSTemplateFormatVersion: "2010-09-09" Transform: - 'AWS::LanguageExtensions' - 'AWS::Serverless-2016-10-31' Description: cfn-lint test case Mappings: RegionMap: us-east-1: InsightsArn: arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:21 us-west-2: InsightsArn: arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:21 Resources: rCustomAuthorizerFunction: Type: AWS::Serverless::Function Properties: FunctionName: !Sub "my-custom-authorizer-${AWS::Region}" Description: Custom authorizer for APIGW Runtime: nodejs16.x Handler: index.handler CodeUri: !Sub "s3://custom-authz-${AWS::AccountId}-${AWS::Region}/function-v1.0.zip" Policies: - arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole Layers: - !FindInMap [RegionMap, !Ref AWS::Region, "InsightsArn"] ```
2023-04-03T19:38:29Z
[]
[]
aws-cloudformation/cfn-lint
2,665
aws-cloudformation__cfn-lint-2665
[ "2664" ]
7b442c881c912cb166ea3e7463a499334823d625
diff --git a/src/cfnlint/languageExtensions.py b/src/cfnlint/languageExtensions.py --- a/src/cfnlint/languageExtensions.py +++ b/src/cfnlint/languageExtensions.py @@ -29,7 +29,11 @@ def validate_pseudo_parameters( ): if isinstance(fn_object_val, dict): ref = "Ref" - ref_list = [val[ref] for key, val in fn_object_val.items() if ref in val] + ref_list = [ + val[ref] + for _, val in fn_object_val.items() + if hasattr(val, "__iter__") and ref in val + ] for ref in ref_list: if ref in pseudo_params: message = (
diff --git a/test/fixtures/templates/good/functions_findinmap_default_value.yaml b/test/fixtures/templates/good/functions_findinmap_default_value.yaml --- a/test/fixtures/templates/good/functions_findinmap_default_value.yaml +++ b/test/fixtures/templates/good/functions_findinmap_default_value.yaml @@ -75,6 +75,7 @@ Resources: - 'Fn::ToJsonString': To: Json String: Function + Value: 1 - SecondKey1 - DefaultValue: Mesh2 Mesh3:
cfn-lint throws error when !ToJsonString contains int value ### CloudFormation Lint Version 0.76.2 ### What operating system are you using? Ubuntu ### Describe the bug Unexpected internal error during linting of rule E1031, involving `ToJsonString` of numerical value ``` 2023-04-06 20:20:31,922 - cfnlint - DEBUG - Completed linting of file: templates/lambda.yml E0002 Unknown exception while processing rule E1031: Traceback (most recent call last): File "/home/kftse/anaconda3/envs/aws/lib/python3.10/site-packages/cfnlint/rules/__init__.py", line 320, in run_check return check(*args) File "/home/kftse/anaconda3/envs/aws/lib/python3.10/site-packages/cfnlint/rules/__init__.py", line 44, in wrapper results = match_function(self, filename, cfn, *args, **kwargs) File "/home/kftse/anaconda3/envs/aws/lib/python3.10/site-packages/cfnlint/rules/__init__.py", line 202, in matchall return self.match(cfn) # pylint: disable=E1102 File "/home/kftse/anaconda3/envs/aws/lib/python3.10/site-packages/cfnlint/rules/functions/ToJsonString.py", line 39, in match LanguageExtensions.validate_pseudo_parameters( File "/home/kftse/anaconda3/envs/aws/lib/python3.10/site-packages/cfnlint/languageExtensions.py", line 32, in validate_pseudo_parameters ref_list = [val[ref] for key, val in fn_object_val.items() if ref in val] File "/home/kftse/anaconda3/envs/aws/lib/python3.10/site-packages/cfnlint/languageExtensions.py", line 32, in <listcomp> ref_list = [val[ref] for key, val in fn_object_val.items() if ref in val] TypeError: argument of type 'int' is not iterable cfn-secrets-stack.yml:1:1 E0002 Unknown exception while processing rule E1031: Traceback (most recent call last): File "/home/kftse/anaconda3/envs/aws/lib/python3.10/site-packages/cfnlint/rules/__init__.py", line 320, in run_check return check(*args) File "/home/kftse/anaconda3/envs/aws/lib/python3.10/site-packages/cfnlint/rules/__init__.py", line 44, in wrapper results = match_function(self, filename, cfn, *args, **kwargs) File "/home/kftse/anaconda3/envs/aws/lib/python3.10/site-packages/cfnlint/rules/__init__.py", line 202, in matchall return self.match(cfn) # pylint: disable=E1102 File "/home/kftse/anaconda3/envs/aws/lib/python3.10/site-packages/cfnlint/rules/functions/ToJsonString.py", line 39, in match LanguageExtensions.validate_pseudo_parameters( File "/home/kftse/anaconda3/envs/aws/lib/python3.10/site-packages/cfnlint/languageExtensions.py", line 32, in validate_pseudo_parameters ref_list = [val[ref] for key, val in fn_object_val.items() if ref in val] File "/home/kftse/anaconda3/envs/aws/lib/python3.10/site-packages/cfnlint/languageExtensions.py", line 32, in <listcomp> ref_list = [val[ref] for key, val in fn_object_val.items() if ref in val] TypeError: argument of type 'int' is not iterable cfn-secrets-stack.yml:1:1 ``` ### Expected behavior String quoted int should work as well as int, both are valid json ### Reproduction template This works ```yaml Resources: DeploymentProperties: Properties: Description: "testing" Name: 'Test' SecretString: !ToJsonString SomeNumber: '3' Type: AWS::SecretsManager::Secret Transform: AWS::LanguageExtensions ``` This does not, with the above error ```yaml Resources: DeploymentProperties: Properties: Description: "testing" Name: 'Test' SecretString: !ToJsonString SomeNumber: 3 Type: AWS::SecretsManager::Secret Transform: AWS::LanguageExtensions ```
2023-04-06T14:56:17Z
[]
[]
aws-cloudformation/cfn-lint
2,666
aws-cloudformation__cfn-lint-2666
[ "2596" ]
8d59393e6462cf6a1869edc7451871b34c9dd75a
diff --git a/scripts/fix_data_files.py b/scripts/fix_data_files.py --- a/scripts/fix_data_files.py +++ b/scripts/fix_data_files.py @@ -18,6 +18,7 @@ "AdditionalSpecs", "CfnLintCli", "Serverless", + "ProviderSchemasPatches", ] for module in modules: diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -37,7 +37,8 @@ def get_version(filename): 'data/AdditionalSpecs/*.json', 'data/Serverless/*.json', 'data/ExtendedSpecs/*/*.json', - 'data/CfnLintCli/config/schema.json' + 'data/ProviderSchemasPatches/*/*.json', + 'data/CfnLintCli/config/schema.json', ]}, packages=find_packages('src'), zip_safe=False, diff --git a/src/cfnlint/data/ProviderSchemasPatches/__init__.py b/src/cfnlint/data/ProviderSchemasPatches/__init__.py new file mode 100644 diff --git a/src/cfnlint/data/ProviderSchemasPatches/all/__init__.py b/src/cfnlint/data/ProviderSchemasPatches/all/__init__.py new file mode 100644 diff --git a/src/cfnlint/maintenance.py b/src/cfnlint/maintenance.py --- a/src/cfnlint/maintenance.py +++ b/src/cfnlint/maintenance.py @@ -10,6 +10,7 @@ import subprocess import warnings import zipfile +from copy import deepcopy from io import BytesIO from urllib.request import Request, urlopen @@ -57,7 +58,7 @@ def update_resource_spec(region, url, schema_cache, force: bool = False): filename = os.path.join( os.path.dirname(cfnlint.__file__), f"data/CloudSpecs/{region}.json" ) - + schema_cache = deepcopy(schema_cache) multiprocessing_logger = multiprocessing.log_to_stderr() multiprocessing_logger.debug("Downloading template %s into %s", url, filename) @@ -116,6 +117,9 @@ def update_resource_spec(region, url, schema_cache, force: bool = False): "Parent element not found for patch (%s) in region %s", patch, region ) + # Patch provider schema data + spec = patch_spec(spec, "all", "ProviderSchemasPatches") + botocore_cache = {} def search_and_replace_botocore_types(obj): @@ -252,13 +256,11 @@ def update_documentation(rules): new_file.write("\n\\* experimental rules\n") -def patch_spec(content, region): +def patch_spec(content, region, patch_types="ExtendedSpecs"): """Patch the spec file""" LOGGER.info('Patching spec file for region "%s"', region) - append_dir = os.path.join( - os.path.dirname(__file__), "data", "ExtendedSpecs", region - ) + append_dir = os.path.join(os.path.dirname(__file__), "data", patch_types, region) for dirpath, _, filenames in os.walk(append_dir): filenames.sort() for filename in fnmatch.filter(filenames, "*.json"): @@ -268,7 +270,7 @@ def patch_spec(content, region): ) all_patches = jsonpatch.JsonPatch( cfnlint.helpers.load_resource( - f"cfnlint.data.ExtendedSpecs.{module}", file_path + f"cfnlint.data.{patch_types}.{module}", file_path ) )
diff --git a/test/integration/test_data_files.py b/test/integration/test_data_files.py --- a/test/integration/test_data_files.py +++ b/test/integration/test_data_files.py @@ -21,6 +21,7 @@ def setUp(self) -> None: "AdditionalSpecs", "CfnLintCli", "Serverless", + "AdditionalSpecs", ] super().setUp() diff --git a/test/unit/module/maintenance/test_update_resource_specs.py b/test/unit/module/maintenance/test_update_resource_specs.py --- a/test/unit/module/maintenance/test_update_resource_specs.py +++ b/test/unit/module/maintenance/test_update_resource_specs.py @@ -13,11 +13,9 @@ LOGGER.addHandler(logging.NullHandler()) -class TestUpdateResourceSpecs(BaseTestCase): - """Used for Testing Resource Specs""" - - side_effect = [ - { +def patch_spec_sideffect(content, region, patch_types="ExtendedSpecs"): + if region == "all" and patch_types == "ExtendedSpecs": + return { "PropertyTypes": { "AWS::Lambda::CodeSigningConfig.AllowedPublishers": { "Properties": { @@ -48,8 +46,9 @@ class TestUpdateResourceSpecs(BaseTestCase): } }, "ValueTypes": {}, - }, - { + } + if region in ["us-east-1", "us-west-2"] and patch_types == "ExtendedSpecs": + return { "PropertyTypes": { "AWS::Lambda::CodeSigningConfig.AllowedPublishers": { "Properties": { @@ -82,8 +81,13 @@ class TestUpdateResourceSpecs(BaseTestCase): "ValueTypes": { "AWS::EC2::Instance.Types": ["m2.medium"], }, - }, - ] + } + + return content + + +class TestUpdateResourceSpecs(BaseTestCase): + """Used for Testing Resource Specs""" @patch("cfnlint.maintenance.url_has_newer_version") @patch("cfnlint.maintenance.get_url_content") @@ -103,7 +107,7 @@ def test_update_resource_spec( mock_url_newer_version.return_value = True mock_content.return_value = '{"PropertyTypes": {}, "ResourceTypes": {}}' - mock_patch_spec.side_effect = self.side_effect + mock_patch_spec.side_effect = patch_spec_sideffect cm = MagicMock() cm.getcode.return_value = 200 @@ -199,7 +203,7 @@ def test_update_resource_spec_cache( mock_url_newer_version.return_value = True mock_content.return_value = '{"PropertyTypes": {}, "ResourceTypes": {}}' - mock_patch_spec.side_effect = self.side_effect + mock_patch_spec.side_effect = patch_spec_sideffect cm = MagicMock() cm.getcode.return_value = 200 @@ -334,7 +338,7 @@ def test_update_resource_spec_force( mock_url_newer_version.return_value = False mock_content.return_value = '{"PropertyTypes": {}, "ResourceTypes": {}}' - mock_patch_spec.side_effect = self.side_effect + mock_patch_spec.side_effect = patch_spec_sideffect mock_urlresponse = Mock() cm = MagicMock()
Missing ChecksumAlgorithm in OptionalFields for InventoryConfigurations in S3 Bucket ### CloudFormation Lint Version 0.73.1 ### What operating system are you using? Mac ### Describe the bug [Serverless IDE] E3030: You must specify a valid value for OptionalFields (ChecksumAlgorithm). Valid values are ["Size", "LastModifiedDate", "StorageClass", "ETag", "IsMultipartUploaded", "ReplicationStatus", "EncryptionStatus", "ObjectLockRetainUntilDate", "ObjectLockMode", "ObjectLockLegalHoldStatus", "IntelligentTieringAccessTier", "BucketKeyStatus"] ### Expected behavior Though "ChecksumAlgorithm" missing for "OptionalFields" in CloudFormation doc (opened also ticket for AWS): https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-inventoryconfiguration.html Using "ChecksumAlgorithm" in "OptionalFields" works, but cfn-lint gives above error. ### Reproduction template InventoryConfigurations: -[redacted] OptionalFields: - Size - LastModifiedDate - IsMultipartUploaded - EncryptionStatus - ChecksumAlgorithm
enum being pulled in automatically from [resource provider schema](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-type-schemas.html): ``` "enum" : [ "Size", "LastModifiedDate", "StorageClass", "ETag", "IsMultipartUploaded", "ReplicationStatus", "EncryptionStatus", "ObjectLockRetainUntilDate", "ObjectLockMode", "ObjectLockLegalHoldStatus", "IntelligentTieringAccessTier", "BucketKeyStatus" ] ``` will get picked up in a PR like https://github.com/aws-cloudformation/cfn-lint/pull/2591 if it gets into that resource schema enum I'm going to patch this into the spec so we can close this.
2023-04-06T19:12:55Z
[]
[]
aws-cloudformation/cfn-lint
2,682
aws-cloudformation__cfn-lint-2682
[ "2676" ]
24e6f29029bd64d36e35e2a3db6a30a162466414
diff --git a/src/cfnlint/rules/resources/lmbd/ZipPackageRequiredProperties.py b/src/cfnlint/rules/resources/lmbd/ZipPackageRequiredProperties.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/resources/lmbd/ZipPackageRequiredProperties.py @@ -0,0 +1,76 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from cfnlint.rules import CloudFormationLintRule, RuleMatch + + +class ZipPackageRequiredProperties(CloudFormationLintRule): + id = "W2533" + shortdesc = ( + "Check required properties for Lambda if the deployment package is a .zip file" + ) + description = ( + "When the package type is Zip, " + "you must also specify the `handler` and `runtime` properties." + ) + source_url = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html" + tags = ["resources", "lambda"] + + def match(self, cfn): + matches = [] + required_properties = [ + "Handler", + "Runtime", + ] # required if package is a .zip file + + resources = cfn.get_resources(["AWS::Lambda::Function"]) + + for resource_name, resource in resources.items(): + properties = resource.get("Properties") + if not isinstance(properties, dict): + continue + + for scenario in cfn.get_object_without_conditions( + properties, ["PackageType", "Code", "Handler", "Runtime"] + ): + props = scenario.get("Object") + path = ["Resources", resource_name, "Properties"] + + # check is zip deployment + is_zip_deployment = True + code = props.get("Code") + + if props.get("PackageType") == "Zip": + path.append("PackageType") + elif isinstance(code, dict) and ( + code.get("ZipFile") or code.get("S3Key") + ): + path.append("Code") + else: + is_zip_deployment = False + + if not is_zip_deployment: + continue + + # check required properties for zip deployment + missing_properties = [] + for p in required_properties: + if props.get(p) is None: + missing_properties.append(p) + + if len(missing_properties) > 0: + message = "Properties {0} missing for zip file deployment at {1}" + matches.append( + RuleMatch( + path, + message.format( + missing_properties, + "/".join( + map(str, ["Resources", resource_name, "Properties"]) + ), + ), + ) + ) + + return matches
diff --git a/test/fixtures/templates/bad/resources/lambda/required_properties.yaml b/test/fixtures/templates/bad/resources/lambda/required_properties.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources/lambda/required_properties.yaml @@ -0,0 +1,32 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: Missing properties. +Resources: + Function1: + Type: AWS::Lambda::Function + Properties: +# Handler: index.handler + Role: arn:aws:iam::123456789012:role/lambda-role + Code: + S3Bucket: my-bucket + S3Key: function.zip +# Runtime: nodejs16.x + Function2: + Type: AWS::Lambda::Function + Properties: +# Handler: index.handler + Role: arn:aws:iam::123456789012:role/lambda-role + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: python3.9 + PackageType: Zip + Function3: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: arn:aws:iam::123456789012:role/lambda-role + Code: + ZipFile: | + var aws = require('aws-sdk') + exports.handler = function(event, context) {} +# Runtime: nodejs16.x \ No newline at end of file diff --git a/test/fixtures/templates/good/resources/lambda/required_properties.yaml b/test/fixtures/templates/good/resources/lambda/required_properties.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/lambda/required_properties.yaml @@ -0,0 +1,29 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: Required Properties. +Resources: + Function1: # S3 key to deployment package + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: arn:aws:iam::123456789012:role/lambda-role + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: python3.9 + Function2: # source inline (zipped by CloudFormation) + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: arn:aws:iam::123456789012:role/lambda-role + Code: + ZipFile: | + var aws = require('aws-sdk') + exports.handler = function(event, context) {} + Runtime: nodejs16.x + Function3: # image deployment + Type: AWS::Lambda::Function + Properties: + Role: arn:aws:iam::123456789012:role/lambda-role + Code: + ImageUri : 111122223333.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest + PackageType: Image \ No newline at end of file diff --git a/test/unit/rules/resources/lmbd/test_zip_package_required_properties.py b/test/unit/rules/resources/lmbd/test_zip_package_required_properties.py new file mode 100644 --- /dev/null +++ b/test/unit/rules/resources/lmbd/test_zip_package_required_properties.py @@ -0,0 +1,29 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.lmbd.ZipPackageRequiredProperties import ( + ZipPackageRequiredProperties, +) + + +class TestZipPackageRequiredProperties(BaseRuleTestCase): + """Test required properties""" + + def setUp(self): + super(TestZipPackageRequiredProperties, self).setUp() + self.collection.register(ZipPackageRequiredProperties()) + self.success_templates = [ + "test/fixtures/templates/good/resources/lambda/required_properties.yaml" + ] + + def test_file_positive(self): + self.helper_file_positive() + + def test_file_negative(self): + self.helper_file_negative( + "test/fixtures/templates/bad/resources/lambda/required_properties.yaml", + err_count=3, + )
New rule for package command and Lambda ### Is this feature request related to a new rule or cfn-lint capabilities? _No response_ ### Describe the feature you'd like to request Error message when using the package command and Lambda: `Runtime and Handler are mandatory parameters for functions created with deployment packages. ` ### Describe the solution you'd like A new warning or information rule that determines if you are using the package command and alerts that these parameters are required. ### Additional context _No response_ ### Is this something that you'd be interested in working on? - [X] 👋 I may be able to implement this feature request ### Would this feature include a breaking change? - [ ] ⚠️ This feature might incur a breaking change
2023-04-11T14:24:34Z
[]
[]
aws-cloudformation/cfn-lint
2,691
aws-cloudformation__cfn-lint-2691
[ "2310" ]
2b354fb3da4613bbfab526b87454ee1d10a2a931
diff --git a/src/cfnlint/rules/resources/ectwo/SecurityGroupIngress.py b/src/cfnlint/rules/resources/ectwo/SecurityGroupIngress.py --- a/src/cfnlint/rules/resources/ectwo/SecurityGroupIngress.py +++ b/src/cfnlint/rules/resources/ectwo/SecurityGroupIngress.py @@ -36,19 +36,6 @@ def check_ingress_rule(self, vpc_id, properties, path): ) ) - else: - if properties.get("SourceSecurityGroupId", None): - path_error = path[:] + ["SourceSecurityGroupId"] - message = ( - "SourceSecurityGroupId shouldn't be specified for " - "Non-Vpc Security Group at {0}" - ) - matches.append( - RuleMatch( - path_error, message.format("/".join(map(str, path_error))) - ) - ) - return matches def match(self, cfn):
diff --git a/test/unit/rules/resources/ec2/test_sg_ingress.py b/test/unit/rules/resources/ec2/test_sg_ingress.py --- a/test/unit/rules/resources/ec2/test_sg_ingress.py +++ b/test/unit/rules/resources/ec2/test_sg_ingress.py @@ -27,5 +27,5 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" self.helper_file_negative( - "test/fixtures/templates/bad/properties_sg_ingress.yaml", 2 + "test/fixtures/templates/bad/properties_sg_ingress.yaml", 1 )
E2506 prevents using SourceSecurityGroupId for non-vpc security groups https://github.com/aws-cloudformation/cfn-lint/blob/4a7af2bd53a9ad1ccaba3a509437c53102ade522/src/cfnlint/rules/resources/ectwo/SecurityGroupIngress.py#L33-L40 I couldn't see any reason in the [cloudformation reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule-1.html#cfn-ec2-security-group-rule-sourcesecuritygroupid) that this wouldn't be valid, and I was able successfully create the following stack, where SecurityGroupB seems to be correctly restricted to traffic from SecurityGroupA. I _think_ that this rule is incorrect, unless I'm missing something ```yaml AWSTemplateFormatVersion: '2010-09-09' Resources: SecurityGroupA: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Group A SecurityGroupIngress: - FromPort: 80 ToPort: 80 IpProtocol: tcp CidrIp: 0.0.0.0/0 SecurityGroupB: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Group B SecurityGroupIngress: - FromPort: 80 ToPort: 80 IpProtocol: tcp SourceSecurityGroupId: Fn::GetAtt: - SecurityGroupA - GroupId ```
Yea it'd be nice to know what this rule is for. Also getting this error.. This is an older rule and needs a refresh as there have been some changes from ec2-classic. Validated the following scenarios: * `SourceSecurityGroupId` works for Default VPC (when `VpcId` is NOTspecified) * `SourceSecurityGroupName` works for Default VPC (when `VpcId` is NOTspecified) * `SourceSecurityGroupName` doesn't work when VpcId is specified Docs: ``` SourceSecurityGroupId The ID of the security group. You must specify either the security group ID or the security group name in the request. For security groups in a nondefault VPC, you must specify the security group ID. Required: No Type: String Update requires: [No interruption](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-no-interrupt) SourceSecurityGroupName [Default VPC] The name of the source security group. You must specify either the security group ID or the security group name. You can't specify the group name in combination with an IP address range. Creates rules that grant full ICMP, UDP, and TCP access. For security groups in a nondefault VPC, you must specify the group ID. Required: No Type: String Update requires: [No interruption](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-no-interrupt) ```
2023-04-13T20:51:14Z
[]
[]
aws-cloudformation/cfn-lint
2,693
aws-cloudformation__cfn-lint-2693
[ "2690" ]
e86bd05bba9cf2d2f514eff01c27e048cfb8975a
diff --git a/src/cfnlint/data/schemas/extensions/aws_ec2_vpc/__init__.py b/src/cfnlint/data/schemas/extensions/aws_ec2_vpc/__init__.py new file mode 100644 diff --git a/src/cfnlint/data/schemas/nested/__init__.py b/src/cfnlint/data/schemas/nested/__init__.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/data/schemas/nested/__init__.py @@ -0,0 +1,4 @@ +""" +Cfn-lint created JSON Schemas to validation of nested JSON objects +Example: IAM policy statements, Step functions, etc. +""" diff --git a/src/cfnlint/jsonschema/__init__.py b/src/cfnlint/jsonschema/__init__.py --- a/src/cfnlint/jsonschema/__init__.py +++ b/src/cfnlint/jsonschema/__init__.py @@ -1,2 +1 @@ from cfnlint.jsonschema.exceptions import ValidationError -from cfnlint.jsonschema.validator import create diff --git a/src/cfnlint/jsonschema/_types.py b/src/cfnlint/jsonschema/_types.py deleted file mode 100644 --- a/src/cfnlint/jsonschema/_types.py +++ /dev/null @@ -1,139 +0,0 @@ -""" -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: MIT-0 - -Originally taken from https://raw.githubusercontent.com/python-jsonschema/jsonschema/main/jsonschema/_types.py -adapted for CloudFormation usage -""" - -from __future__ import annotations - -import numbers -import typing - -import attr -from jsonschema.exceptions import UndefinedTypeCheck -from pyrsistent import pmap -from pyrsistent.typing import PMap - - -# unfortunately, the type of pmap is generic, and if used as the attr.ib -# converter, the generic type is presented to mypy, which then fails to match -# the concrete type of a type checker mapping -# this "do nothing" wrapper presents the correct information to mypy -def _typed_pmap_converter( - init_val: typing.Mapping[ - str, - typing.Callable[["TypeChecker", typing.Any], bool], - ], -) -> PMap[str, typing.Callable[["TypeChecker", typing.Any], bool]]: - return pmap(init_val) - - -# pylint: disable=unused-argument -def is_array(checker, instance): - return isinstance(instance, list) - - -# pylint: disable=unused-argument -def is_bool(checker, instance): - return isinstance(instance, bool) - - -# pylint: disable=unused-argument -def is_integer(checker, instance): - # bool inherits from int, so ensure bools aren't reported as ints - if isinstance(instance, bool): - return False - return isinstance(instance, int) - - -# pylint: disable=unused-argument -def is_null(checker, instance): - return instance is None - - -# pylint: disable=unused-argument -def is_number(checker, instance): - # bool inherits from int, so ensure bools aren't reported as ints - if isinstance(instance, bool): - return False - return isinstance(instance, numbers.Number) - - -# pylint: disable=unused-argument -def is_object(checker, instance): - return isinstance(instance, dict) - - -# pylint: disable=unused-argument -def is_string(checker, instance): - return isinstance(instance, str) - - [email protected](frozen=True, repr=False) -class TypeChecker: - """ - A :kw:`type` property checker. - - A `TypeChecker` performs type checking for a `Validator`, converting - between the defined JSON Schema types and some associated Python types or - objects. - - """ - - _type_checkers: PMap[ - str, - typing.Callable[["TypeChecker", typing.Any], bool], - ] = attr.ib( - default=pmap(), - converter=_typed_pmap_converter, - ) - - def __repr__(self): - types = ", ".join(repr(k) for k in sorted(self._type_checkers)) - return f"<{self.__class__.__name__} types={{{types}}}>" - - def is_type(self, instance, t: str) -> bool: - """ - Check if the instance is of the appropriate type. - - Arguments: - - instance: - - The instance to check - - t: - - The name of the type that is expected. - - Raises: - - `jsonschema.exceptions.UndefinedTypeCheck`: - - if ``type`` is unknown to this object. - """ - try: - fn = self._type_checkers[t] - except KeyError: - raise UndefinedTypeCheck(t) from None - - return fn(self, instance) - - -cfn_type_checker = TypeChecker( - { - "array": is_array, - "boolean": is_bool, - "integer": lambda checker, instance: ( - is_integer(checker, instance) - or isinstance(instance, float) - and instance.is_integer() - ), - "object": is_object, - "null": is_null, - "number": is_number, - "string": is_string, - }, -) diff --git a/src/cfnlint/jsonschema/_validators.py b/src/cfnlint/jsonschema/_validators.py --- a/src/cfnlint/jsonschema/_validators.py +++ b/src/cfnlint/jsonschema/_validators.py @@ -8,112 +8,21 @@ """ import re from copy import deepcopy -from fractions import Fraction - -from jsonschema._utils import ( - ensure_list, - equal, - extras_msg, - find_additional_properties, - uniq, -) +from jsonschema._utils import ensure_list, find_additional_properties + +from cfnlint.helpers import ( + FUNCTIONS_MULTIPLE, + FUNCTIONS_SINGLE, + PSEUDOPARAMS_MULTIPLE, + PSEUDOPARAMS_SINGLE, +) from cfnlint.jsonschema._utils import equal as s_equal from cfnlint.jsonschema._utils import unbool from cfnlint.jsonschema.exceptions import ValidationError - -def ignore_ref_siblings(schema): - """ - Ignore siblings of ``$ref`` if it is present. - Otherwise, return all keywords. - Suitable for use with `create`'s ``applicable_validators`` argument. - """ - ref_link = schema.get("$ref") - if ref_link is not None: - return [("$ref", ref_link)] - - return schema.items() - - -# pylint: disable=unused-argument -def dependencies( - validator, - dS, - instance, - schema, -): - if not validator.is_type(instance, "object"): - return - - for prop, dependency in dS.items(): - if prop not in instance: - continue - - if validator.is_type(dependency, "array"): - for each in dependency: - if each not in instance: - message = f"{each!r} is a dependency of {prop!r}" - yield ValidationError(message) - else: - yield from validator.descend( - instance, - dependency, - schema_path=prop, - ) - - -def contains(validator, cs, instance, schema): - if not validator.is_type(instance, "array"): - return - - if not any(validator.evolve(schema=cs).is_valid(element) for element in instance): - yield ValidationError( - f"None of {instance!r} are valid under the given schema", - ) - - -# pylint: disable=unused-argument -def items(validator, iS, instance, schema): - if not validator.is_type(instance, "array"): - return - - if validator.is_type(iS, "array"): - for (index, item), subschema in zip(enumerate(instance), iS): - yield from validator.descend( - item, - subschema, - path=index, - schema_path=index, - ) - else: - for index, item in enumerate(instance): - yield from validator.descend(item, iS, path=index) - - -# pylint: disable=unused-argument -def patternProperties(validator, pProps, instance, schema): - if not validator.is_type(instance, "object"): - return - - for _pattern, subschema in pProps.items(): - for k, v in instance.items(): - if re.search(_pattern, k): - yield from validator.descend( - v, - subschema, - path=k, - schema_path=_pattern, - ) - - -# pylint: disable=unused-argument -def propertyNames(validator, pNames, instance, schema): - if not validator.is_type(instance, "object"): - return - - for prop in instance: - yield from validator.descend(instance=prop, schema=pNames) +_singular_types = ["string", "boolean", "number", "integer"] +_multiple_types = ["array"] def additionalProperties(validator, aP, instance, schema): @@ -144,29 +53,6 @@ def additionalProperties(validator, aP, instance, schema): yield ValidationError(error % extra, path=[extra]) -def additionalItems(validator, aI, instance, schema): - if not validator.is_type(instance, "array") or validator.is_type( - schema.get("items", {}), "object" - ): - return - - len_items = len(schema.get("items", [])) - if validator.is_type(aI, "object"): - for index, item in enumerate(instance[len_items:], start=len_items): - yield from validator.descend(item, aI, path=index) - elif not aI and len(instance) > len(schema.get("items", [])): - error = "Additional items are not allowed (%s %s unexpected)" - yield ValidationError( - error % extras_msg(instance[len(schema.get("items", [])) :]), - ) - - -# pylint: disable=unused-argument -def const(validator, c, instance, schema): - if not equal(instance, c): - yield ValidationError(f"{c!r} was expected") - - # pylint: disable=unused-argument def exclusiveMinimum(validator, m, instance, schema): t_instance = deepcopy(instance) @@ -233,70 +119,12 @@ def maximum(validator, m, instance, schema): yield ValidationError(message) -# pylint: disable=unused-argument -def multipleOf(validator, dB, instance, schema): - if not validator.is_type(instance, "number"): - return - - if isinstance(dB, float): - quotient = instance / dB - try: - failed = int(quotient) != quotient - except OverflowError: - # When `instance` is large and `dB` is less than one, - # quotient can overflow to infinity; and then casting to int - # raises an error. - # - # In this case we fall back to Fraction logic, which is - # exact and cannot overflow. The performance is also - # acceptable: we try the fast all-float option first, and - # we know that fraction(dB) can have at most a few hundred - # digits in each part. The worst-case slowdown is therefore - # for already-slow enormous integers or Decimals. - failed = (Fraction(instance) / Fraction(dB)).denominator != 1 - else: - failed = instance % dB - - if failed: - yield ValidationError(f"{instance!r} is not a multiple of {dB}") - - -# pylint: disable=unused-argument -def minItems(validator, mI, instance, schema): - if validator.is_type(instance, "array") and len(instance) < mI: - yield ValidationError(f"{instance!r} is too short") - - -# pylint: disable=unused-argument -def maxItems(validator, mI, instance, schema): - if validator.is_type(instance, "array") and len(instance) > mI: - yield ValidationError(f"{instance!r} is too long") - - -# pylint: disable=unused-argument -def uniqueItems(validator, uI, instance, schema): - if uI and validator.is_type(instance, "array") and not uniq(instance): - yield ValidationError(f"{instance!r} has non-unique elements") - - # pylint: disable=unused-argument def pattern(validator, patrn, instance, schema): if validator.is_type(instance, "string") and not re.search(patrn, instance): yield ValidationError(f"{instance!r} does not match {patrn!r}") -# pylint: disable=unused-argument -def minLength(validator, mL, instance, schema): - if validator.is_type(instance, "string") and len(instance) < mL: - yield ValidationError(f"{instance!r} is too short") - - -# pylint: disable=unused-argument -def maxLength(validator, mL, instance, schema): - if validator.is_type(instance, "string") and len(instance) > mL: - yield ValidationError(f"{instance!r} is too long") - - # pylint: disable=unused-argument def enum(validator, enums, instance, schema): if instance in (0, 1): @@ -308,129 +136,115 @@ def enum(validator, enums, instance, schema): yield ValidationError(f"{instance!r} is not one of {enums!r}") -# pylint: disable=unused-argument -def ref(validator, r, instance, schema): - resolve = getattr(validator.resolver, "resolve", None) - if resolve is None: - with validator.resolver.resolving(r) as resolved: - yield from validator.descend(instance, resolved) - else: - scope, resolved = validator.resolver.resolve(r) - validator.resolver.push_scope(scope) +def _cfn_type(validator, tS, instance, schema): + reprs = ", ".join(repr(type) for type in tS) + if any(validator.is_type(instance, type) for type in ["object", "array"]): + yield ValidationError( + f"{instance!r} is not of type {reprs}", + extra_args={}, + ) + return + if "string" in tS: + return + if "number" in tS: try: - yield from validator.descend(instance, resolved) - finally: - validator.resolver.pop_scope() + float(instance) + return + except ValueError: + pass + if "integer" in tS: + if isinstance(instance, float): + yield ValidationError( + f"{instance!r} is not of type {reprs}", + extra_args={}, + ) + return + try: + int(instance) + return + except ValueError: + pass + if "boolean" in tS: + if instance in ["true", "false"]: + return + yield ValidationError( + f"{instance!r} is not of type {reprs}", + extra_args={}, + ) + + +# pylint: disable=unused-argument,redefined-builtin +def cfn_type(validator, tS, instance, schema): + """ + When evaluating a type in CloudFormation we have to account + for the intrinsic functions that the values can represent + (Ref, GetAtt, If, ...). This will evaluate if the correct type + is not found and the instance is an object with a function + that we do our best to evaluate if that function represents the + type we are looking for + """ + tS = ensure_list(tS) + reprs = ", ".join(repr(type) for type in tS) + if not any(validator.is_type(instance, type) for type in tS): + if validator.is_type(instance, "object"): + if len(instance) == 1: + k = next(iter(instance), "") + v = instance.get(k, []) + if k == "Fn::If": + if len(v) == 3: + for i in range(1, 3): + for v_err in cfn_type( + validator=validator, + tS=tS, + instance=v[i], + schema=schema, + ): + v_err.path.append("Fn::If") + v_err.path.append(i) + yield v_err + return + if k == "Ref": + if "array" in tS: + if v in PSEUDOPARAMS_SINGLE: + yield ValidationError( + f"{instance!r} is not of type {reprs}", + extra_args={}, + ) + if any(type in _singular_types for type in tS): + if v in PSEUDOPARAMS_MULTIPLE: + yield ValidationError( + f"{instance!r} is not of type {reprs}", + extra_args={}, + ) + return + if k in FUNCTIONS_MULTIPLE: + if "array" in tS: + return + yield ValidationError( + f"{instance!r} is not of type {reprs}", extra_args={} + ) + elif k in FUNCTIONS_SINGLE: + if any(type in _singular_types for type in tS): + return + yield ValidationError( + f"{instance!r} is not of type {reprs}", extra_args={} + ) + else: + yield from _cfn_type(validator, tS, instance, schema) + return + + yield from _cfn_type(validator, tS, instance, schema) # pylint: disable=unused-argument,redefined-builtin def type(validator, tS, instance, schema): + """ + Standard type checking for when we are looking at strings + that are JSON (IAM Policy, Step Functions, ...) + """ tS = ensure_list(tS) if not any(validator.is_type(instance, type) for type in tS): reprs = ", ".join(repr(type) for type in tS) yield ValidationError(f"{instance!r} is not of type {reprs}") - - -# pylint: disable=unused-argument -def properties(validator, props, instance, schema): - if not validator.is_type(instance, "object"): - return - - for prop, subschema in props.items(): - if prop in instance: - yield from validator.descend( - instance[prop], - subschema, - path=prop, - schema_path=prop, - ) - - -# pylint: disable=unused-argument -def required(validator, r, instance, schema): - if not validator.is_type(instance, "object"): - return - for prop in r: - if prop not in instance: - yield ValidationError(f"{prop!r} is a required property") - - -# pylint: disable=unused-argument -def minProperties(validator, mP, instance, schema): - if validator.is_type(instance, "object") and len(instance) < mP: - yield ValidationError(f"{instance!r} does not have enough properties") - - -# pylint: disable=unused-argument -def maxProperties(validator, mP, instance, schema): - if not validator.is_type(instance, "object"): - return - if validator.is_type(instance, "object") and len(instance) > mP: - yield ValidationError(f"{instance!r} has too many properties") - - -# pylint: disable=unused-argument -def allOf(validator, aO, instance, schema): - for index, subschema in enumerate(aO): - yield from validator.descend(instance, subschema, schema_path=index) - - -# pylint: disable=unused-argument -def anyOf(validator, aO, instance, schema): - all_errors = [] - for index, subschema in enumerate(aO): - errs = list(validator.descend(instance, subschema, schema_path=index)) - if not errs: - break - all_errors.extend(errs) - else: - yield ValidationError( - f"{instance!r} is not valid under any of the given schemas", - context=all_errors, - ) - - -# pylint: disable=unused-argument -def oneOf(validator, oO, instance, schema): - subschemas = enumerate(oO) - all_errors = [] - for index, subschema in subschemas: - errs = list(validator.descend(instance, subschema, schema_path=index)) - if not errs: - first_valid = subschema - break - all_errors.extend(errs) - else: - yield ValidationError( - f"{instance!r} is not valid under any of the given schemas", - context=all_errors, - ) - - more_valid = [ - each - for _, each in subschemas - if validator.evolve(schema=each).is_valid(instance) - ] - if more_valid: - more_valid.append(first_valid) - reprs = ", ".join(repr(schema) for schema in more_valid) - yield ValidationError(f"{instance!r} is valid under each of {reprs}") - - -# pylint: disable=unused-argument -def not_(validator, not_schema, instance, schema): - if validator.evolve(schema=not_schema).is_valid(instance): - message = f"{instance!r} should not be valid under {not_schema!r}" - yield ValidationError(message) - - -def if_(validator, if_schema, instance, schema): - if validator.evolve(schema=if_schema).is_valid(instance): - if "then" in schema: - then = schema["then"] - yield from validator.descend(instance, then, schema_path="then") - elif "else" in schema: - else_ = schema["else"] - yield from validator.descend(instance, else_, schema_path="else") diff --git a/src/cfnlint/jsonschema/exceptions.py b/src/cfnlint/jsonschema/exceptions.py --- a/src/cfnlint/jsonschema/exceptions.py +++ b/src/cfnlint/jsonschema/exceptions.py @@ -48,7 +48,7 @@ def __init__( self.rule = rule self.path_override = path_override - def set(self, type_checker=None, **kwargs): + def _set(self, type_checker=None, **kwargs): if type_checker is not None and self._type_checker is _unset: self._type_checker = type_checker diff --git a/src/cfnlint/jsonschema/validator.py b/src/cfnlint/jsonschema/validator.py deleted file mode 100644 --- a/src/cfnlint/jsonschema/validator.py +++ /dev/null @@ -1,291 +0,0 @@ -from __future__ import annotations - -import reprlib -from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Optional - -import attr -from jsonschema import exceptions -from jsonschema.validators import RefResolver, validator_for - -from cfnlint.helpers import load_resource -from cfnlint.jsonschema import _types, _validators -from cfnlint.jsonschema.exceptions import ValidationError - -if TYPE_CHECKING: - from cfnlint.rules import CloudFormationLintRule - from cfnlint.template import Template - - -def _id_of(schema): - """ - Return the ID of a schema for recent JSON Schema drafts. - """ - return schema.get("$id", "") - - -_cfn_validators: Dict[str, Callable[[Any, Any, Any, Any], Any]] = { - "$ref": _validators.ref, - "additionalItems": _validators.additionalItems, - "additionalProperties": _validators.additionalProperties, - "allOf": _validators.allOf, - "anyOf": _validators.anyOf, - "const": _validators.const, - "contains": _validators.contains, - "dependencies": _validators.dependencies, - "enum": _validators.enum, - "exclusiveMaximum": _validators.exclusiveMaximum, - "exclusiveMinimum": _validators.exclusiveMinimum, - "if": _validators.if_, - "items": _validators.items, - "maxItems": _validators.maxItems, - "maxLength": _validators.maxLength, - "maxProperties": _validators.maxProperties, - "maximum": _validators.maximum, - "minItems": _validators.minItems, - "minLength": _validators.minLength, - "minProperties": _validators.minProperties, - "minimum": _validators.minimum, - "multipleOf": _validators.multipleOf, - "not": _validators.not_, - "oneOf": _validators.oneOf, - "pattern": _validators.pattern, - "patternProperties": _validators.patternProperties, - "properties": _validators.properties, - "propertyNames": _validators.propertyNames, - "required": _validators.required, - "type": _validators.type, - "uniqueItems": _validators.uniqueItems, -} - - -def create( - validators=(), - cfn: Optional[Template] = None, - rules: Optional[Dict[str, CloudFormationLintRule]] = None, -): - """ - Create a new validator class. - Arguments: - validators (collections.abc.Mapping): - a mapping from names to callables, where each callable will - validate the schema property with the given name. - Each callable should take 4 arguments: - 1. a validator instance, - 2. the value of the property being validated within the - instance - 3. the instance - 4. the schema - Returns: - a new `jsonschema.protocols.Validator` class - """ - applicable_validators = _validators.ignore_ref_siblings - - validators_arg = _cfn_validators.copy() - validators_arg.update(validators) - if rules is not None: - for js in validators_arg: - rule = rules.get(js) - if rule is not None: - if hasattr(rule, "validate_configure") and callable( - getattr(rule, "validate_configure") - ): - rule.validate_configure(cfn) - if hasattr(rule, js) and callable(getattr(rule, js)): - func = getattr(rule, js) - validators_arg[js] = func - - @attr.s - class Validator: - """ - The protocol to which all validator classes adhere. - Arguments: - schema: - The schema that the validator object will validate with. - It is assumed to be valid, and providing - an invalid schema can lead to undefined behavior. See - `Validator.check_schema` to validate a schema first. - resolver: - a resolver that will be used to resolve :kw:`$ref` - properties (JSON references). If unprovided, one will be created. - format_checker: - if provided, a checker which will be used to assert about - :kw:`format` properties present in the schema. If unprovided, - *no* format validation is done, and the presence of format - within schemas is strictly informational. Certain formats - require additional packages to be installed in order to assert - against instances. Ensure you've installed `jsonschema` with - its `extra (optional) dependencies <index:extras>` when - invoking ``pip``. - """ - - VALIDATORS = dict(validators_arg) - META_SCHEMA = dict( - load_resource( - "cfnlint.data.schemas.extensions.json_schema", filename=("draft7.json") - ) - ) - TYPE_CHECKER = _types.cfn_type_checker - FORMAT_CHECKER = None - ID_OF = staticmethod(_id_of) - - schema = attr.ib(repr=reprlib.repr) - resolver = attr.ib(default=None, repr=False) - format_checker = attr.ib(default=None) - - def __attrs_post_init__(self): - if self.resolver is None: - self.resolver = RefResolver.from_schema( - self.schema, - id_of=_id_of, - ) - - def is_type(self, instance: Any, t: str) -> bool: - """ - Check if the instance is of the given (JSON Schema) type. - Arguments: - instance: - the value to check - t: - the name of a known (JSON Schema) type - Returns: - whether the instance is of the given type - Raises: - `jsonschema.exceptions.UnknownType`: - if ``type`` is not a known type - """ - try: - return self.TYPE_CHECKER.is_type(instance, t) - except exceptions.UndefinedTypeCheck as e: - raise exceptions.UnknownType(t, instance, self.schema) from e - - def is_valid(self, instance: Any) -> bool: - """ - Check if the instance is valid under the current `schema`. - Returns: - whether the instance is valid or not - >>> schema = {"maxItems" : 2} - >>> Draft202012Validator(schema).is_valid([2, 3, 4]) - False - """ - error = next(self.iter_errors(instance), None) - return error is None - - def iter_errors(self, instance: Any) -> Iterable[ValidationError]: - r""" - Lazily yield each of the validation errors in the given instance. - >>> schema = { - ... "type" : "array", - ... "items" : {"enum" : [1, 2, 3]}, - ... "maxItems" : 2, - ... } - >>> v = Draft202012Validator(schema) - >>> for error in sorted(v.iter_errors([2, 3, 4]), key=str): - ... print(error.message) - 4 is not one of [1, 2, 3] - [2, 3, 4] is too long - .. deprecated:: v4.0.0 - Calling this function with a second schema argument is deprecated. - Use `Validator.evolve` instead. - """ - _schema = self.schema - - if self.is_type(instance, "object"): - if len(instance) == 1: - for k, v in instance.items(): - # if the element is a condition lets evaluate both the - # true and false paths of the condition - if k == "Fn::If": - if len(v) == 3: - # just need to evaluate the second and third element - # in the list - for i in range(1, 3): - for error in self.iter_errors(instance=v[i]): - # add the paths for the elements we have removed - error.path.appendleft(i) - error.path.appendleft("Fn::If") - yield error - return - if k == "Ref": - if v == "AWS::NoValue": - # This is equivalent to an empty object - instance = {} - for k, v in applicable_validators(_schema): - validator = self.VALIDATORS.get(k) - if validator is None: - continue - - errors = validator(self, v, instance, _schema) or () - for error in errors: - error.set( - validator=k, - validator_value=v, - instance=instance, - schema=_schema, - type_checker=self.TYPE_CHECKER, - ) - if k not in {"if", "$ref"}: - error.schema_path.appendleft(k) - yield error - - def validate(self, instance: Any) -> None: - """ - Check if the instance is valid under the current `schema`. - Raises: - `jsonschema.exceptions.ValidationError`: - if the instance is invalid - >>> schema = {"maxItems" : 2} - >>> Draft202012Validator(schema).validate([2, 3, 4]) - Traceback (most recent call last): - ... - ValidationError: [2, 3, 4] is too long - """ - for error in self.iter_errors(instance): - raise error - - def evolve(self, **kwargs) -> "Validator": - """ - Create a new validator like this one, but with given changes. - Preserves all other attributes, so can be used to e.g. create a - validator with a different schema but with the same :kw:`$ref` - resolution behavior. - >>> validator = Draft202012Validator({}) - >>> validator.evolve(schema={"type": "number"}) - Draft202012Validator(schema={'type': 'number'}, format_checker=None) - The returned object satisfies the validator protocol, but may not - be of the same concrete class! In particular this occurs - when a :kw:`$ref` occurs to a schema with a different - :kw:`$schema` than this one (i.e. for a different draft). - >>> validator.evolve( - ... schema={"$schema": Draft7Validator.META_SCHEMA["$id"]} - ... ) - Draft7Validator(schema=..., format_checker=None) - """ - cls = self.__class__ - - schema = kwargs.setdefault("schema", self.schema) - NewValidator = validator_for(schema, default=cls) - - for field in attr.fields(cls): - if not field.init: - continue - attr_name = field.name # To deal with private attributes. - init_name = attr_name if attr_name[0] != "_" else attr_name[1:] - if init_name not in kwargs: - kwargs[init_name] = getattr(self, attr_name) - - return NewValidator(**kwargs) - - def descend(self, instance, schema, path=None, schema_path=None): - for error in self.evolve(schema=schema).iter_errors(instance): - if path is not None: - error.path.appendleft(path) - if schema_path is not None: - error.schema_path.appendleft(schema_path) - yield error - - return Validator - - -CfnValidator = create( - validators=(), -) diff --git a/src/cfnlint/rules/BaseJsonSchema.py b/src/cfnlint/rules/BaseJsonSchema.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/BaseJsonSchema.py @@ -0,0 +1,81 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +import logging +from typing import Any, Dict, Optional + +from jsonschema import Draft7Validator, Validator +from jsonschema.validators import extend + +from cfnlint.rules import CloudFormationLintRule, RuleMatch + +LOGGER = logging.getLogger("cfnlint.rules.JsonSchema") + + +class BaseJsonSchema(CloudFormationLintRule): + """The base JSON schema package""" + + def __init__(self) -> None: + """Init""" + super().__init__() + self.rules: Dict[str, Any] = {} + self.rule_set: Dict[str, str] = {} + self.region: Optional[str] = None + self.validators: Dict[str, Any] = {} + + def json_schema_validate(self, validator, properties, path): + matches = [] + for e in validator.iter_errors(properties): + kwargs = {} + if hasattr(e, "extra_args"): + kwargs = getattr(e, "extra_args") + e_path = path + list(e.path) + if len(e.path) > 0: + e_path_override = getattr(e, "path_override", None) + if e_path_override: + e_path = list(e.path_override) + else: + key = e.path[-1] + if hasattr(key, "start_mark"): + kwargs["location"] = ( + key.start_mark.line, + key.start_mark.column, + key.end_mark.line, + key.end_mark.column, + ) + e_rule = None + if hasattr(e, "rule"): + if e.rule: + e_rule = e.rule + if not e_rule: + e_rule = self.child_rules.get(self.rule_set.get(e.validator), self) + + matches.append( + RuleMatch( + e_path, + e.message, + rule=e_rule, + **kwargs, + ) + ) + + return matches + + def setup_validator(self, schema: Any) -> Validator: + validators = self.validators.copy() + if self.child_rules is not None: + for name, rule_id in self.rule_set.items(): + rule = self.child_rules.get(rule_id) + if rule is not None: + if hasattr(rule, "validate_configure") and callable( + getattr(rule, "validate_configure") + ): + rule.validate_configure() + if hasattr(rule, name) and callable(getattr(rule, name)): + validators[name] = getattr(rule, name) + + validator = extend(validator=Draft7Validator, validators=validators)( + schema=schema + ) + return validator diff --git a/src/cfnlint/rules/resources/Configuration.py b/src/cfnlint/rules/resources/Configuration.py --- a/src/cfnlint/rules/resources/Configuration.py +++ b/src/cfnlint/rules/resources/Configuration.py @@ -5,12 +5,14 @@ import cfnlint.helpers from cfnlint.data.schemas.extensions import resource from cfnlint.jsonschema import ValidationError -from cfnlint.jsonschema import create as create_validator -from cfnlint.rules import CloudFormationLintRule, RuleMatch +from cfnlint.jsonschema._validators import additionalProperties +from cfnlint.jsonschema._validators import type as validator_type +from cfnlint.rules import RuleMatch +from cfnlint.rules.BaseJsonSchema import BaseJsonSchema from cfnlint.schema.manager import PROVIDER_SCHEMA_MANAGER -class Configuration(CloudFormationLintRule): +class Configuration(BaseJsonSchema): """Check Base Resource Configuration""" id = "E3001" @@ -25,14 +27,13 @@ def __init__(self): super().__init__() schema = cfnlint.helpers.load_resource(resource, "configuration.json") self.regions = [] - self.validator = create_validator( - validators={ - "awsType": self._awsType, - }, - cfn=None, - rules=None, - )(schema=schema) self.cfn = None + self.validators = { + "awsType": self._awsType, + "type": validator_type, + "additionalProperties": additionalProperties, + } + self.validator = self.setup_validator(schema=schema) def initialize(self, cfn): super().initialize(cfn) diff --git a/src/cfnlint/rules/resources/iam/IdentityPolicy.py b/src/cfnlint/rules/resources/iam/IdentityPolicy.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/resources/iam/IdentityPolicy.py @@ -0,0 +1,114 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +import json + +from jsonschema import RefResolver +from jsonschema.exceptions import best_match + +from cfnlint.helpers import load_resource +from cfnlint.jsonschema import ValidationError +from cfnlint.jsonschema._validators import cfn_type as validator_cfn_type +from cfnlint.jsonschema._validators import type as validator_type +from cfnlint.rules.BaseJsonSchema import BaseJsonSchema + + +class IdentityPolicy(BaseJsonSchema): + """Check IAM identity Policies""" + + id = "E3510" + shortdesc = "Validate identity based IAM polices" + description = "IAM identity polices are embedded JSON in CloudFormation. This rule validates those embedded policies." + source_url = "https://github.com/aws-cloudformation/cfn-python-lint" + tags = ["parameters", "availabilityzone"] + + def __init__(self): + super().__init__() + self.cfn = None + self.validators = { + "anyOf": self._any_of, + "oneOf": self._one_of, + "type": validator_cfn_type, + } + policy_schema = load_resource("cfnlint.data.schemas.nested", "iam_policy.json") + self.identity_schema = load_resource( + "cfnlint.data.schemas.nested", "iam_policy_identity.json" + ) + store = { + "policy": policy_schema, + "identity": self.identity_schema, + } + # To reduce reduntant schemas use a schema resolver + # this is deprecated in 4.18 of jsonschema + self.resolver = RefResolver.from_schema(self.identity_schema, store=store) + + def initialize(self, cfn): + self.cfn = cfn + return super().initialize(cfn) + + def _match_longer_path(self, error): + return len(error.path) + + def _one_of(self, validator, oO, instance, schema): + subschemas = enumerate(oO) + all_errors = [] + for index, subschema in subschemas: + errs = list(validator.descend(instance, subschema, schema_path=index)) + if not errs: + first_valid = subschema + break + all_errors.extend(errs) + else: + best_err = best_match(all_errors, key=self._match_longer_path) + schema_path = best_err.schema_path[0] + for err in all_errors: + if err.schema_path[0] == schema_path: + yield err + + more_valid = [ + each + for _, each in subschemas + if validator.evolve(schema=each).is_valid(instance) + ] + if more_valid: + more_valid.append(first_valid) + reprs = ", ".join(repr(schema) for schema in more_valid) + yield ValidationError(f"{instance!r} is valid under each of {reprs}") + + # pylint: disable=unused-argument + def _any_of(self, validator, aO, instance, schema): + all_errors = [] + for index, subschema in enumerate(aO): + errs = list(validator.descend(instance, subschema, schema_path=index)) + if not errs: + break + all_errors.extend(errs) + else: + best_err = best_match(all_errors, key=self._match_longer_path) + yield best_err + + # pylint: disable=unused-argument + def iamidentitypolicy(self, validator, policy_type, policy, schema): + # First time child rules are configured against the rule + # so we can run this now + + if validator.is_type(policy, "string"): + try: + # Since the policy is a string we cannot + # use functions so switch the type + # validator to the stricter type validation + self.validators["type"] = validator_type + policy = json.loads(policy) + except json.JSONDecodeError: + return + elif validator.is_type(policy, "object"): + self.validators["type"] = validator_cfn_type + + iam_validator = self.setup_validator( + schema=self.identity_schema, + ).evolve(resolver=self.resolver) + + for err in iam_validator.iter_errors(policy): + err.rule = self + yield err diff --git a/src/cfnlint/rules/resources/properties/AwsType.py b/src/cfnlint/rules/resources/properties/AwsType.py --- a/src/cfnlint/rules/resources/properties/AwsType.py +++ b/src/cfnlint/rules/resources/properties/AwsType.py @@ -19,11 +19,13 @@ def __init__(self): self.child_rules = { "W3010": None, + "E3510": None, } self.types = { "AvailabilityZone": "W3010", "AvailabilityZones": "W3010", + "IamIdentityPolicy": "E3510", } def initialize(self, cfn): diff --git a/src/cfnlint/rules/resources/properties/JsonSchema.py b/src/cfnlint/rules/resources/properties/JsonSchema.py --- a/src/cfnlint/rules/resources/properties/JsonSchema.py +++ b/src/cfnlint/rules/resources/properties/JsonSchema.py @@ -18,38 +18,14 @@ load_resource, ) from cfnlint.jsonschema import ValidationError -from cfnlint.jsonschema.validator import create as create_validator -from cfnlint.rules import CloudFormationLintRule, RuleMatch +from cfnlint.rules import RuleMatch +from cfnlint.rules.BaseJsonSchema import BaseJsonSchema from cfnlint.schema.manager import PROVIDER_SCHEMA_MANAGER, ResourceNotFoundError -from cfnlint.template.template import Template LOGGER = logging.getLogger("cfnlint.rules.resources.properties.JsonSchema") -_rule_set = { - "additionalProperties": "E3002", - "properties": "E3002", - "required": "E3003", - "enum": "E3030", - "type": "E3012", - "minLength": "E3033", - "maxLength": "E3033", - "uniqueItems": "E3037", - "maximum": "E3034", - "minimum": "E3034", - "exclusiveMaximum": "E3034", - "exclusiveMinimum": "E3034", - "maxItems": "E3032", - "minItems": "E3032", - "pattern": "E3031", - "oneOf": "E2523", - "awsType": "E3008", - "cfnSchema": "E3017", - "cfnRegionSchema": "E3018", -} - - -class JsonSchema(CloudFormationLintRule): +class JsonSchema(BaseJsonSchema): """Check Base Resource Configuration""" id = "E3000" @@ -57,84 +33,36 @@ class JsonSchema(CloudFormationLintRule): description = "Making sure that resources properties comply with their JSON schema" source_url = "https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/cfn-resource-specification.md#properties" tags = ["resources"] - child_rules = { - "E2523": None, - "E3002": None, - "E3003": None, - "E3012": None, - "E3030": None, - "E3031": None, - "E3032": None, - "E3033": None, - "E3034": None, - "E3037": None, - "E3008": None, - "E3017": None, - "E3018": None, - } def __init__(self): """Init""" super().__init__() - self.cfn = {} - self.validator = None - self.rules = {} - self.region = None - for name, _ in _rule_set.items(): - self.rules[name] = None - - def json_schema_validate(self, validator, properties, path): - matches = [] - for e in validator.iter_errors(properties): - kwargs = {} - if hasattr(e, "extra_args"): - kwargs = getattr(e, "extra_args") - e_path = path + list(e.path) - if len(e.path) > 0: - e_path_override = getattr(e, "path_override", None) - if e_path_override: - e_path = list(e.path_override) - else: - key = e.path[-1] - if hasattr(key, "start_mark"): - kwargs["location"] = ( - key.start_mark.line, - key.start_mark.column, - key.end_mark.line, - key.end_mark.column, - ) - - e_rule = None - if hasattr(e, "rule"): - if e.rule: - e_rule = e.rule - if not e_rule: - e_rule = self.rules.get(e.validator, self) - - matches.append( - RuleMatch( - e_path, - e.message, - rule=e_rule, - **kwargs, - ) - ) - - return matches - - def _setup_validator(self, cfn: Template): - for name, rule_id in _rule_set.items(): - self.rules[name] = self.child_rules.get(rule_id) - - self.validator = create_validator( - validators={ - "awsType": None, - "cfnSchema": self._cfnSchema, - "cfnRegionSchema": self._cfnRegionSchema, - }, - cfn=cfn, - rules=self.rules, - ) + self.validators = { + "cfnSchema": self._cfnSchema, + "cfnRegionSchema": self._cfnRegionSchema, + } + self.rule_set = { + "additionalProperties": "E3002", + "properties": "E3002", + "required": "E3003", + "enum": "E3030", + "type": "E3012", + "minLength": "E3033", + "maxLength": "E3033", + "uniqueItems": "E3037", + "maximum": "E3034", + "minimum": "E3034", + "exclusiveMaximum": "E3034", + "exclusiveMinimum": "E3034", + "maxItems": "E3032", + "minItems": "E3032", + "pattern": "E3031", + "oneOf": "E2523", + "awsType": "E3008", + "cfnSchema": "E3017", + "cfnRegionSchema": "E3018", + } + self.child_rules = dict.fromkeys(list(self.rule_set.values())) # pylint: disable=unused-argument def _cfnSchema(self, validator, schema_paths, instance, schema, region=None): @@ -147,7 +75,8 @@ def _cfnSchema(self, validator, schema_paths, instance, schema, region=None): f"cfnlint.data.schemas.extensions.{schema_details[0]}", filename=(f"{schema_details[1]}.json"), ) - cfn_validator = self.validator(cfn_schema) + cfn_validator = self.setup_validator(schema=cfn_schema) + # cfn_validator = validator.evolve(schema=cfn_schema) errs = list(cfn_validator.iter_errors(instance)) if errs: if cfn_schema.get("description"): @@ -166,7 +95,6 @@ def _cfnRegionSchema(self, validator, schema_paths, instance, schema): def match(self, cfn): """Check CloudFormation Properties""" matches = [] - self.cfn = cfn for schema in REGISTRY_SCHEMAS: resource_type = schema["typeName"] @@ -192,8 +120,6 @@ def match(self, cfn): ) ) - self._setup_validator(cfn=cfn) - for n, values in cfn.get_resources().items(): p = values.get("Properties", {}) t = values.get("Type", None) @@ -215,7 +141,9 @@ def match(self, cfn): # if its cached we already ran the same validation lets not run it again continue cached_validation_run.append(t) - cfn_validator = self.validator(schema.json_schema()) + cfn_validator = self.setup_validator( + schema=schema.json_schema() + ) path = ["Resources", n, "Properties"] for scenario in cfn.get_object_without_nested_conditions( p, path diff --git a/src/cfnlint/rules/resources/properties/Properties.py b/src/cfnlint/rules/resources/properties/Properties.py --- a/src/cfnlint/rules/resources/properties/Properties.py +++ b/src/cfnlint/rules/resources/properties/Properties.py @@ -18,7 +18,7 @@ class Properties(CloudFormationLintRule): tags = ["resources"] # pylint: disable=unused-argument - def properties(self, validator, properties, instance, schema): + def properties(self, validator, props, instance, schema): if not validator.is_type(instance, "object"): return @@ -43,7 +43,7 @@ def properties(self, validator, properties, instance, schema): ) return - for p, subschema in properties.items(): + for p, subschema in props.items(): # use the instance keys because it gives us the start_mark k = [k for k in instance.keys() if k == p] if p in instance: diff --git a/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py b/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py --- a/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py +++ b/src/cfnlint/rules/resources/properties/ValuePrimitiveType.py @@ -2,6 +2,7 @@ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ +import json from typing import Any, List from cfnlint.helpers import ( @@ -12,7 +13,6 @@ ) from cfnlint.jsonschema import ValidationError from cfnlint.rules import CloudFormationLintRule -from cfnlint.template.template import Template class ValuePrimitiveType(CloudFormationLintRule): @@ -38,6 +38,10 @@ def __init__(self): self.configure() self.cfn = None + def initialize(self, cfn): + self.cfn = cfn + return super().initialize(cfn) + # pylint: disable=too-many-return-statements def _schema_value_check( self, value: Any, item_type: str, strict_check: bool @@ -102,15 +106,12 @@ def _schema_check_primitive_type(self, value: Any, types: List[str]) -> bool: return result - def validate_configure(self, cfn: Template): - self.cfn = cfn - # pylint: disable=unused-argument def type(self, validator, types, instance, schema): types = ensure_list(types) reprs = ", ".join(repr(type) for type in types) if not any(validator.is_type(instance, type) for type in types): - if isinstance(instance, dict): + if validator.is_type(instance, "object"): if len(instance) == 1: for k, v in instance.items(): # Most conditions should be eliminated but sometimes they trickle through because @@ -190,8 +191,20 @@ def type(self, validator, types, instance, schema): "actual_type": type(instance).__name__, "expected_type": reprs, } + # JSON types are listed as objects but will take a string + if "object" in types and "properties" not in schema: + if validator.is_type(instance, "string"): + try: + json.loads(instance) + except json.JSONDecodeError: + yield ValidationError( + f"{instance!r} is not of type {reprs}", + extra_args=extra_args, + ) + return yield ValidationError( - f"{instance!r} is not of type {reprs}", extra_args=extra_args + f"{instance!r} is not of type {reprs}", + extra_args=extra_args, )
diff --git a/test/unit/module/jsonschema/test_validators.py b/test/unit/module/jsonschema/test_validators.py --- a/test/unit/module/jsonschema/test_validators.py +++ b/test/unit/module/jsonschema/test_validators.py @@ -4,15 +4,29 @@ """ import unittest -from cfnlint.jsonschema.validator import CfnValidator +from jsonschema import Draft7Validator +from jsonschema.validators import extend + +from cfnlint.jsonschema import _validators class TestValidators(unittest.TestCase): """Test JSON Schema validators""" def run_validation(self, instance, schema, *args, **kwargs): - cls = kwargs.pop("cls", CfnValidator) - validator = cls(schema, *args, **kwargs) + # cls = kwargs.pop("cls", Draft7Validator) + # validator = cls(schema, *args, **kwargs) + validator = extend( + validator=Draft7Validator, + validators={ + "minimum": _validators.minimum, + "maximum": _validators.maximum, + "exclusiveMaximum": _validators.exclusiveMaximum, + "exclusiveMinimum": _validators.exclusiveMinimum, + "additionalProperties": _validators.additionalProperties, + "enum": _validators.enum, + }, + )(schema=schema) return list(validator.iter_errors(instance)) def message_for(self, instance, schema, *args, **kwargs): @@ -29,42 +43,6 @@ def no_error(self, instance, schema, *args, **kwargs): errors = self.run_validation(instance, schema, *args, **kwargs) self.assertEqual(len(errors), 0) - def test_dependencies_array(self): - depend, on = "bar", "foo" - schema = {"dependencies": {depend: [on]}} - message = self.message_for( - instance={"bar": 2}, - schema=schema, - ) - self.assertEqual(message, "'foo' is a dependency of 'bar'") - - self.no_error(instance={"bar": 2, "foo": 1}, schema=schema) - # wrong type so no errors - self.no_error(instance=[], schema=schema) - - def test_dependencies_object(self): - depend, on = "bar", "foo" - schema = {"dependencies": {depend: {"properties": {on: {"type": "number"}}}}} - message = self.message_for( - instance={"bar": 2, "foo": "a"}, - schema=schema, - ) - self.assertEqual(message, "'a' is not of type 'number'") - - self.no_error(instance={"bar": 2, "foo": 1}, schema=schema) - - def test_contains(self): - schema = {"contains": {"type": "number"}} - message = self.message_for( - instance=["a"], - schema=schema, - ) - self.assertEqual(message, "None of ['a'] are valid under the given schema") - - self.no_error(instance=[1], schema=schema) - # wrong type so no errors - self.no_error(instance={}, schema=schema) - def test_pattern_properties(self): schema = { "patternProperties": { @@ -81,22 +59,6 @@ def test_pattern_properties(self): # wrong type so no errors self.no_error(instance=[], schema=schema) - def test_property_names(self): - schema = { - "propertyNames": { - "pattern": "^bar$", - }, - } - message = self.message_for( - instance={"foo": 2}, - schema=schema, - ) - self.assertEqual(message, "'foo' does not match '^bar$'") - - self.no_error(instance={"bar": "a"}, schema=schema) - # wrong type so no errors - self.no_error(instance="a", schema=schema) - def test_additional_properties_single_failure(self): additional = "foo" schema = {"additionalProperties": False} @@ -142,56 +104,12 @@ def test_additional_properties_pattern_properties(self): self.assertEqual(message, "'foo' does not match any of the regexes: '^bar$'") self.no_error(instance={"bar": "a"}, schema=schema) - def test_additional_items(self): - first, additional = "foo", "bar" - schema = {"items": [{"type": "string"}], "additionalItems": {"type": "string"}} - message = self.message_for(instance=[first, 1], schema=schema) - self.assertEqual(message, "1 is not of type 'string'") - self.no_error(instance=[first, additional], schema=schema) - - def test_additional_items_false(self): - schema = {"items": [{"type": "string"}], "additionalItems": False} - message = self.message_for(instance=["a", 1], schema=schema) - self.assertEqual(message, "Additional items are not allowed (1 was unexpected)") - - self.no_error(instance=["a"], schema=schema) - # wrong type so no errors - self.no_error(instance="a", schema=schema) - def test_additional_properties_no_error(self): additional = "foo" schema = {"additionalProperties": True} self.no_error(instance={additional: 2}, schema=schema) - def test_required(self): - schema = {"properties": {"foo": {"type": "string"}}, "required": ["foo"]} - message = self.message_for(instance={}, schema=schema) - self.assertEqual(message, "'foo' is a required property") - self.no_error(instance=[{"foo": "bar"}], schema=schema) - - # wrong type so no errors - self.no_error(instance="a", schema=schema) - - def test_properties(self): - schema = {"properties": {"foo": {"type": "string"}}} - message = self.message_for(instance={"foo": 1}, schema=schema) - self.assertEqual(message, "1 is not of type 'string'") - self.no_error(instance=[{"foo": 1}], schema=schema) - - # wrong type so no errors - self.no_error(instance="a", schema=schema) - - def test_const(self): - schema = {"const": 12} - message = self.message_for( - instance={"foo": "bar"}, - schema=schema, - ) - self.assertIn("12 was expected", message) - - self.no_error(instance=12, schema=schema) - def test_exlusive_minimum(self): schema = {"exclusiveMinimum": 5} message = self.message_for( @@ -312,226 +230,193 @@ def test_maximum_str_non_number(self): schema = {"maximum": 5} self.no_error(instance="a", schema=schema) - def test_multiple_of_number(self): - schema = {"typeOf": "number", "multipleOf": 5} + def test_enum(self): + schema = {"enum": ["foo"]} message = self.message_for( - instance=6, + instance="bar", schema=schema, ) self.assertEqual( message, - "6 is not a multiple of 5", + "'bar' is not one of ['foo']", ) - self.no_error(instance=5, schema=schema) - # wrong type so no errors - self.no_error(instance=[], schema=schema) + self.no_error(instance="foo", schema=schema) - def test_multiple_of_float(self): - schema = {"typeOf": "number", "multipleOf": 5.2} + def test_enum_number(self): + schema = {"enum": [0]} message = self.message_for( - instance=6, + instance=1, schema=schema, ) self.assertEqual( message, - "6 is not a multiple of 5.2", + "1 is not one of [0]", ) - self.no_error(instance=10.4, schema=schema) + self.no_error(instance=0, schema=schema) - def test_min_items(self): - schema = {"minItems": 2} - message = self.message_for( - instance=["foo"], - schema=schema, - ) - self.assertEqual( - message, - "['foo'] is too short", - ) + def test_enum_number_from_string(self): + schema = {"enum": [0]} + self.no_error(instance="0", schema=schema) - self.no_error(instance=["foo", "bar"], schema=schema) - # wrong type so no errors - self.no_error(instance="a", schema=schema) + def test_enum_string_from_number(self): + schema = {"enum": ["10"]} + self.no_error(instance=10, schema=schema) - def test_max_items(self): - schema = {"maxItems": 1} - message = self.message_for( - instance=["foo", "bar"], - schema=schema, - ) + schema = {"enum": ["0"]} + self.no_error(instance=0, schema=schema) + + +class TestValidatorsCfnType(unittest.TestCase): + """Test JSON Schema validators""" + + def run_validation(self, instance, schema, *args, **kwargs): + # cls = kwargs.pop("cls", Draft7Validator) + # validator = cls(schema, *args, **kwargs) + validator = extend( + validator=Draft7Validator, + validators={ + "minimum": _validators.minimum, + "maximum": _validators.maximum, + "exclusiveMaximum": _validators.exclusiveMaximum, + "exclusiveMinimum": _validators.exclusiveMinimum, + "additionalProperties": _validators.additionalProperties, + "enum": _validators.enum, + "type": _validators.cfn_type, + }, + )(schema=schema) + return list(validator.iter_errors(instance)) + + def message_for(self, instance, schema, *args, **kwargs): + errors = self.run_validation(instance, schema, *args, **kwargs) + self.assertTrue(errors, msg=f"No errors were raised for {instance!r}") self.assertEqual( - message, - "['foo', 'bar'] is too long", + len(errors), + 1, + msg=f"Expected exactly one error, found {errors!r}", ) + return errors[0].message - self.no_error(instance=["foo"], schema=schema) - # wrong type so no errors - self.no_error(instance="a", schema=schema) + def no_error(self, instance, schema, *args, **kwargs): + errors = self.run_validation(instance, schema, *args, **kwargs) + self.assertEqual(len(errors), 0) + + def test_cfn_type_object(self): + schema = {"type": "string"} + self.no_error(instance={"Ref": "AWS::Region"}, schema=schema) + self.no_error( + instance={"Fn::Join": [",", {"Fn::GetAzs": "us-east-1"}]}, schema=schema + ) + self.no_error(instance={"Ref": "Unknown"}, schema=schema) - def test_min_length(self): - schema = {"minLength": 2} message = self.message_for( - instance="a", + instance={"Fn::GetAZs": "us-east-1"}, schema=schema, ) self.assertEqual( message, - "'a' is too short", + "{'Fn::GetAZs': 'us-east-1'} is not of type 'string'", ) - self.no_error(instance="foo", schema=schema) - # wrong type so no errors - self.no_error(instance=[], schema=schema) - - def test_max_length(self): - schema = {"maxLength": 2} message = self.message_for( - instance="foo", + instance={"Foo": "Bar"}, schema=schema, ) self.assertEqual( message, - "'foo' is too long", + "{'Foo': 'Bar'} is not of type 'string'", ) - self.no_error(instance="a", schema=schema) - # wrong type so no errors - self.no_error(instance=[], schema=schema) - - def test_unique_items(self): - schema = {"uniqueItems": True} message = self.message_for( - instance=["foo", "foo"], + instance={"Ref": "AWS::NotificationARNs"}, schema=schema, ) self.assertEqual( message, - "['foo', 'foo'] has non-unique elements", + "{'Ref': 'AWS::NotificationARNs'} is not of type 'string'", ) - self.no_error(instance=["foo", "bar"], schema=schema) - # wrong type so no errors - self.no_error(instance="a", schema=schema) + def test_cfn_type_list(self): + schema = {"type": "array", "items": {"type": "string"}} + self.no_error(instance={"Fn::GetAZs": "us-east-1"}, schema=schema) - def test_enum(self): - schema = {"enum": ["foo"]} message = self.message_for( - instance="bar", + instance={"Ref": "AWS::Region"}, schema=schema, ) self.assertEqual( message, - "'bar' is not one of ['foo']", + "{'Ref': 'AWS::Region'} is not of type 'array'", ) - self.no_error(instance="foo", schema=schema) - - def test_enum_number(self): - schema = {"enum": [0]} message = self.message_for( - instance=1, + instance={"Fn::Join": [",", {"Fn::GetAzs": "us-east-1"}]}, schema=schema, ) self.assertEqual( message, - "1 is not one of [0]", + "{'Fn::Join': [',', {'Fn::GetAzs': 'us-east-1'}]} is not of type 'array'", ) - self.no_error(instance=0, schema=schema) - - def test_enum_number_from_string(self): - schema = {"enum": [0]} - self.no_error(instance="0", schema=schema) + def test_cfn_type_number(self): + schema = {"type": "number"} + self.no_error(instance="1", schema=schema) - def test_enum_string_from_number(self): - schema = {"enum": ["10"]} - self.no_error(instance=10, schema=schema) - - schema = {"enum": ["0"]} - self.no_error(instance=0, schema=schema) - - def test_min_properties(self): - schema = {"minProperties": 1} message = self.message_for( - instance={}, + instance="a", schema=schema, ) self.assertEqual( message, - "{} does not have enough properties", + "'a' is not of type 'number'", ) - self.no_error(instance={"foo": "bar"}, schema=schema) - # wrong type so no errors - self.no_error(instance=[], schema=schema) + def test_cfn_type_integer(self): + schema = {"type": "integer"} + self.no_error(instance="1", schema=schema) - def test_max_properties(self): - schema = {"maxProperties": 1} message = self.message_for( - instance={ - "foo": "foo", - "bar": "bar", - }, + instance=1.2, schema=schema, ) self.assertEqual( message, - "{'foo': 'foo', 'bar': 'bar'} has too many properties", + "1.2 is not of type 'integer'", ) - self.no_error(instance={"foo": "bar"}, schema=schema) - # wrong type so no errors - self.no_error(instance=[], schema=schema) - - def test_not(self): - schema = { - "not": { - "type": "string", - } - } message = self.message_for( instance="a", schema=schema, ) self.assertEqual( message, - "'a' should not be valid under {'type': 'string'}", + "'a' is not of type 'integer'", ) - self.no_error(instance=1, schema=schema) + def test_cfn_type_boolean(self): + schema = {"type": "boolean"} + self.no_error(instance="true", schema=schema) + self.no_error(instance="false", schema=schema) - def test_one_of(self): - schema = { - "oneOf": [ - {"type": "string"}, - {"type": "number"}, - ] - } message = self.message_for( - instance=True, + instance="a", schema=schema, ) self.assertEqual( message, - "True is not valid under any of the given schemas", + "'a' is not of type 'boolean'", ) - self.no_error(instance="a", schema=schema) + def test_cfn_type_if(self): + schema = {"type": "integer"} + self.no_error(instance={"Fn::If": ["Unknown", "3", 2]}, schema=schema) - def test_one_of_multiple(self): - schema = { - "oneOf": [ - {"type": "string"}, - {"type": "string"}, - ] - } message = self.message_for( - instance="a", + instance={"Fn::If": ["Unknown", "3", "a"]}, schema=schema, ) self.assertEqual( message, - "'a' is valid under each of {'type': 'string'}, {'type': 'string'}", + "'a' is not of type 'integer'", ) diff --git a/test/unit/rules/resources/iam/test_identity_policy.py b/test/unit/rules/resources/iam/test_identity_policy.py new file mode 100644 --- /dev/null +++ b/test/unit/rules/resources/iam/test_identity_policy.py @@ -0,0 +1,152 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from unittest import TestCase + +from jsonschema import Draft7Validator + +from cfnlint.rules.resources.iam.IdentityPolicy import ( # pylint: disable=E0401 + IdentityPolicy, +) + + +class TestIdentityPolicies(TestCase): + """Test IAM identity Policies""" + + def setUp(self): + """Setup""" + self.rule = IdentityPolicy() + + def test_object_basic(self): + """Test Positive""" + validator = Draft7Validator(schema={}) + + policy = {"Version": "2012-10-18"} + + errs = list( + self.rule.iamidentitypolicy( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 2, errs) + self.assertEqual( + errs[0].message, "'2012-10-18' is not one of ['2008-10-17', '2012-10-17']" + ) + self.assertListEqual(list(errs[0].path), ["Version"]) + self.assertEqual(errs[1].message, "'Statement' is a required property") + self.assertListEqual(list(errs[1].path), []) + + def test_object_multiple_effect(self): + """Test Positive""" + validator = Draft7Validator(schema={}) + + policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "NotAction": "*", + "Action": [ + "cloudformation:*", + ], + "Resource": "*", + } + ], + } + + errs = list( + self.rule.iamidentitypolicy( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 1, errs) + self.assertEqual( + errs[0].message, + "{'Effect': 'Allow', 'NotAction': '*', 'Action': ['cloudformation:*'], 'Resource': '*'} is valid under each of {'required': ['NotAction']}, {'required': ['Action']}", + ) + self.assertListEqual(list(errs[0].path), ["Statement", 0]) + + def test_object_statements(self): + """Test Positive""" + validator = Draft7Validator(schema={}) + + policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "NotAllow", + "Action": [ + "cloudformation:Describe*", + "cloudformation:List*", + "cloudformation:Get*", + ], + "Resource": [ + { + "Fn::Sub": [ + "arn:${AWS::Partition}:iam::123456789012/role/cep-publish-role" + ] + }, + { + "NotValid": [ + "arn:${AWS::Partition}:iam::123456789012/role/cep-publish-role" + ] + }, + ], + } + ], + } + + errs = list( + self.rule.iamidentitypolicy( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 2, errs) + self.assertEqual(errs[0].message, "'NotAllow' is not one of ['Allow', 'Deny']") + self.assertListEqual(list(errs[0].path), ["Statement", 0, "Effect"]) + self.assertEqual( + errs[1].message, + "{'NotValid': ['arn:${AWS::Partition}:iam::123456789012/role/cep-publish-role']} is not of type 'string'", + ) + self.assertListEqual(list(errs[1].path), ["Statement", 0, "Resource", 1]) + + def test_string_statements(self): + """Test Positive""" + validator = Draft7Validator(schema={}) + + policy = """ + { + "Version": "2012-10-18", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "cloudformation:Describe*", + "cloudformation:List*", + "cloudformation:Get*" + ], + "Resource": [ + "*", + {"Fn::Sub": ["arn:${AWS::Partition}:iam::123456789012/role/cep-publish-role"]} + ] + } + ] + } + """ + + errs = list( + self.rule.iamidentitypolicy( + validator=validator, policy=policy, schema={}, policy_type=None + ) + ) + self.assertEqual(len(errs), 2, errs) + self.assertEqual( + errs[0].message, + "{'Fn::Sub': ['arn:${AWS::Partition}:iam::123456789012/role/cep-publish-role']} is not of type 'string'", + ) + self.assertListEqual(list(errs[0].path), ["Statement", 0, "Resource", 1]) + self.assertEqual( + errs[1].message, "'2012-10-18' is not one of ['2008-10-17', '2012-10-17']" + ) + self.assertListEqual(list(errs[1].path), ["Version"]) diff --git a/test/unit/rules/resources/properties/test_json_schema.py b/test/unit/rules/resources/properties/test_json_schema.py --- a/test/unit/rules/resources/properties/test_json_schema.py +++ b/test/unit/rules/resources/properties/test_json_schema.py @@ -22,7 +22,6 @@ from cfnlint.rules.resources.properties import ValuePrimitiveType as RuleType from cfnlint.rules.resources.properties.JsonSchema import ( # pylint: disable=E0401 JsonSchema, - _rule_set, ) @@ -43,7 +42,7 @@ def setUp(self): build_key("F"): 5, build_key("G"): ["A", "A"], } - self.ruleset = _rule_set.copy() + self.ruleset = self.rule.rule_set.copy() self.rule.child_rules = { "E3002": RuleProperties.Properties(), @@ -59,7 +58,6 @@ def setUp(self): } self.cfn = Mock() self.cfn.get_valid_refs = {} - self.rule._setup_validator(self.cfn) self.path = ["Resources", "Table", "Properties"] def build_result( @@ -79,12 +77,11 @@ def build_result( ) def validate(self, schema, expected, object=None): + validator = self.rule.setup_validator(schema=schema) if object is None: object = self.table - matches = self.rule.json_schema_validate( - self.rule.validator(schema), object, self.path - ) + matches = self.rule.json_schema_validate(validator, object, self.path) self.assertListEqual(list(map(vars, expected)), list(map(vars, matches))) diff --git a/test/unit/rules/resources/properties/test_value_primitive_type.py b/test/unit/rules/resources/properties/test_value_primitive_type.py --- a/test/unit/rules/resources/properties/test_value_primitive_type.py +++ b/test/unit/rules/resources/properties/test_value_primitive_type.py @@ -178,7 +178,7 @@ def setUp(self): }, regions=["us-east-1"], ) - self.rule.validate_configure(template) + self.rule.initialize(template) def test_validation(self): """Test type function for json schema""" @@ -385,3 +385,38 @@ def test_validation_ref(self): ), 0, ) + + self.assertEqual( + len( + list( + self.rule.type( + self.validator, + ["object"], + "{}", + { + "type": ["object"], + }, + ) + ) + ), + 0, + ) + + self.assertEqual( + len( + list( + self.rule.type( + self.validator, + ["object"], + "{}", + { + "type": ["object"], + "properties": { + "key": {}, + }, + }, + ) + ) + ), + 1, + )
A VPC needs to have CIDR blocks specified ### Is this feature request related to a new rule or cfn-lint capabilities? rules ### Describe the feature you'd like to request ``` AWSTemplateFormatVersion: '2010-09-09' Resources: Vpc: Type: AWS::EC2::VPC ``` ### Describe the solution you'd like I want to catch the error `Either CIDR Block or IPv4 IPAM Pool and IPv4 Netmask Length must be provided` ### Additional context _No response_ ### Is this something that you'd be interested in working on? - [x] 👋 I may be able to implement this feature request ### Would this feature include a breaking change? - [x] ⚠️ This feature might incur a breaking change
2023-04-13T21:25:55Z
[]
[]
aws-cloudformation/cfn-lint
2,720
aws-cloudformation__cfn-lint-2720
[ "2719" ]
64164b5d58ddbef2d4b2ffee216452d48dc527d9
diff --git a/src/cfnlint/runner.py b/src/cfnlint/runner.py --- a/src/cfnlint/runner.py +++ b/src/cfnlint/runner.py @@ -5,6 +5,7 @@ import logging from typing import List, Optional, Sequence, Union +from cfnlint.conditions import Conditions from cfnlint.graph import Graph from cfnlint.rules import Match, RulesCollection from cfnlint.template import Template @@ -53,6 +54,7 @@ def transform(self): matches = transform.transform_template() self.cfn.template = transform.template() self.cfn.graph = Graph(self.cfn) + self.cfn.conditions = Conditions(self.cfn) return matches def run(self) -> List[Match]:
diff --git a/test/fixtures/templates/issues/sam_w_conditions.yaml b/test/fixtures/templates/issues/sam_w_conditions.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/issues/sam_w_conditions.yaml @@ -0,0 +1,413 @@ +AWSTemplateFormatVersion: 2010-09-09 +Transform: AWS::Serverless-2016-10-31 + +Parameters: + # Deploy Engine parameters + Zone: + Type: String + Site: + Type: String + Solution: + Type: String + Environment: + Type: String + GlobalPrefix: + Type: String + RegionalPrefix: + Type: String + Component: + Type: String + ComponentShortName: + Type: String + Version: + Type: String + Tenant: + Type: String + TenantAwsResource: + Type: String + # VMD Event Source + VmdEnabled: + Type: String + AllowedValues: + - true + - false + VmdEventsSourceArn: + Type: String + VmdEventsSourceRegion: + Type: String + VmdSubscriptionEnabled: + Type: String + AllowedValues: + - true + - false + # DMD Event Source + DmdEnabled: + Type: String + AllowedValues: + - true + - false + DmdEventsSourceArn: + Type: String + DmdEventsSourceRegion: + Type: String + DmdSubscriptionEnabled: + Type: String + AllowedValues: + - true + - false + ConfigS3ReloadInterval: + Type: String + Default: 120 + AliasName: + Type: String + Default: Active + +Conditions: + IsNotProd: !Not [ !Equals [ !Ref Environment, prod ] ] + # VMD + VmdEnabled: + !Equals [ true, !Ref VmdEnabled ] + VmdSubscriptionEnabled: !And + - !Condition VmdEnabled + - !Equals [ true, !Ref VmdSubscriptionEnabled ] + # DMD + DmdEnabled: + !Equals [ true, !Ref DmdEnabled ] + DmdSubscriptionEnabled: !And + - !Condition DmdEnabled + - !Equals [ true, !Ref DmdSubscriptionEnabled ] + +Globals: + Function: + Runtime: java11 + MemorySize: 1024 + Timeout: 60 + CodeUri: functions-java.zip + AutoPublishAlias: Active + Environment: + Variables: + JAVA_TOOL_OPTIONS: -XX:+TieredCompilation -XX:TieredStopAtLevel=1 + SITE: !Ref Site + SOLUTION: !Ref Solution + ENVIRONMENT: !Ref Environment + VERSION: !Ref Version + ACCOUNT_ID: !Sub ${AWS::AccountId} + COMPONENT_SHORT: !Ref ComponentShortName + COMPONENT_LONG: !Ref Component + COMPONENT_VERSION: !Ref Version + TENANT: !Ref Tenant + CONFIG_LIB_COMPONENT_SHORT_NAME: !Ref ComponentShortName + CONFIG_LIB_SOLUTION: !Ref Solution + CONFIG_LIB_ENVIRONMENT: !Ref Environment + CONFIG_LIB_SITE: !Ref Site + CONFIG_LIB_S3_BUCKET: + Fn::ImportValue: !Sub ${RegionalPrefix}-ccerscb-ConfigS3BucketName + CONFIG_LIB_S3_KEY: !Sub ${ComponentShortName}/application.yml + CONFIG_LIB_S3_PLATFORM_BUCKET: + Fn::ImportValue: !Sub ${RegionalPrefix}-ccerscb-ConfigS3BucketName + CONFIG_LIB_S3_PLATFORM_KEY: platform/application.yml + CONFIG_LIB_S3_RELOAD_INTERVAL: !Ref ConfigS3ReloadInterval + +Resources: + #################### + # Generic Policies # + #################### + DeniedPolicies: + Type: AWS::IAM::ManagedPolicy + Properties: + ManagedPolicyName: !Sub ${GlobalPrefix}-${ComponentShortName}-DeniedPolicies-${TenantAwsResource} + Description: Policy for monitoring + Path: / + PolicyDocument: + Version: 2012-10-17 + Statement: + - Effect: Deny + Action: + - aws-portal:* + - cloudtrail:*Logging + - directconnect:Delete* + Resource: '*' + LogMonitoringPolicy: + Type: AWS::IAM::ManagedPolicy + Metadata: + cfn_nag: + rules_to_suppress: + - id: W13 + reason: "TODO: [WPF-29001] Temporarily suppressing wildcard resource warning until fixed by this ticket" + Properties: + ManagedPolicyName: !Sub ${GlobalPrefix}-${ComponentShortName}-LogMonitoringPolicy-${TenantAwsResource} + Description: Policy for monitoring + Path: / + PolicyDocument: + Version: 2012-10-17 + Statement: + - Effect: Allow + Action: + - cloudwatch:PutMetricData + - logs:CreateLogGroup + - logs:CreateLogStream + - logs:PutLogEvents + Resource: '*' + TenantInfoReadPolicy: + Type: AWS::IAM::ManagedPolicy + Properties: + Description: Policy to read Tenant Info secret from Secrets Manager + PolicyDocument: + Version: 2012-10-17 + Statement: + - Effect: Allow + Action: + - secretsmanager:GetSecretValue + - secretsmanager:DescribeSecret + Resource: + - !Sub arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:tenant-info_* + + ########################## + # VMD Events Integration # + ########################## + VmdEventsLambda: + Type: AWS::Serverless::Function + Condition: VmdEnabled + Properties: + Description: Function handling VMD VehicleData image events sent via the VMD Events SQS Queue + FunctionName: !Sub ${RegionalPrefix}-${ComponentShortName}-VmdEventsLambda-${TenantAwsResource} + Handler: com.example.VmdEventHandler::handleRequest + DeploymentPreference: + Enabled: true + PassthroughCondition: true + Type: !If [ IsNotProd, AllAtOnce, Canary10Percent10Minutes ] + Alarms: + - !Ref VmdEventsLambdaErrorsGreaterThanZeroAlarm + ProvisionedConcurrencyConfig: + ProvisionedConcurrentExecutions: 1 + Timeout: 20 + Environment: + Variables: + HANDLER_NAME: VmdEventsLambda + Policies: + - !Ref DeniedPolicies + - !Ref LogMonitoringPolicy + - !Ref TenantInfoReadPolicy + - Fn::ImportValue: !Sub ${Zone}-${Site}-${Solution}-${Environment}-cce-remote-service-db-ReadPolicy + - Fn::ImportValue: !Sub ${Zone}-${Site}-${Solution}-${Environment}-cce-remote-service-db-WritePolicy + - Fn::ImportValue: !Sub ${RegionalPrefix}-ccerscb-ConfigS3BucketReadPolicy + Events: + Batch: + Type: SQS + Properties: + Queue: !GetAtt VmdEventsQueue.Arn + BatchSize: 10 + Enabled: true + FunctionResponseTypes: + - ReportBatchItemFailures + VmdEventsQueue: + Type: AWS::SQS::Queue + Condition: VmdEnabled + Properties: + QueueName: !Sub ${Solution}-${Environment}-${ComponentShortName}-VmdEventsQueue-${TenantAwsResource}.fifo + MessageRetentionPeriod: 10800 # 3 hours + FifoQueue: true + KmsMasterKeyId: alias/sqs-key + RedrivePolicy: + maxReceiveCount: 3 + deadLetterTargetArn: !GetAtt VmdEventsDeadLetterQueue.Arn + VmdEventsDeadLetterQueue: + Type: AWS::SQS::Queue + Condition: VmdEnabled + Properties: + QueueName: !Sub ${Solution}-${Environment}-${ComponentShortName}-VmdEventsDeadLetterQueue-${TenantAwsResource}.fifo + MessageRetentionPeriod: 345600 # 4 days + FifoQueue: true + FifoThroughputLimit: perMessageGroupId + KmsMasterKeyId: alias/sqs-key + ContentBasedDeduplication: true + DeduplicationScope: messageGroup + Tags: + - Key: queueType + Value: dlq + VmdEventsQueueRetryPolicy: + Type: AWS::SQS::QueuePolicy + Condition: VmdEnabled + Properties: + PolicyDocument: + Statement: + Effect: Allow + Principal: + Service: sqs.amazonaws.com + Action: + - sqs:SendMessage + - sqs:ReceiveMessage + Resource: + !GetAtt VmdEventsQueue.Arn + Queues: + - !Ref VmdEventsDeadLetterQueue + VmdEventsQueueSourcePolicy: + Type: AWS::SQS::QueuePolicy + Condition: VmdSubscriptionEnabled + Properties: + Queues: + - !Ref VmdEventsQueue + PolicyDocument: + Statement: + Effect: Allow + Principal: + Service: sns.amazonaws.com + Action: + - sqs:SendMessage + Resource: !GetAtt VmdEventsQueue.Arn + Condition: + ArnEquals: + aws:SourceArn: !Ref VmdEventsSourceArn + VmdEventsSubscription: + Type: AWS::SNS::Subscription + Condition: VmdSubscriptionEnabled + Properties: + Protocol: sqs + Endpoint: !GetAtt VmdEventsQueue.Arn + Region: !Ref VmdEventsSourceRegion + TopicArn: !Ref VmdEventsSourceArn + RawMessageDelivery: true + + VmdEventsLambdaErrorsGreaterThanZeroAlarm: + Type: AWS::CloudWatch::Alarm + Condition: VmdEnabled + Properties: + AlarmDescription: VMD Events Lambda Function Error > 0 + Namespace: AWS/Lambda + MetricName: Errors + Dimensions: + - Name: FunctionName + Value: !Ref VmdEventsLambda + - Name: Resource + Value: !Sub ${VmdEventsLambda}:${AliasName} + TreatMissingData: notBreaching + Statistic: Sum + Threshold: 0 + ComparisonOperator: GreaterThanThreshold + EvaluationPeriods: 1 + Period: 60 + + ########################## + # DMD Events Integration # + ########################## + DmdEventsLambda: + Type: AWS::Serverless::Function + Condition: DmdEnabled + Properties: + Description: Function handling DMD DeviceData image events sent via the DMD Events SQS Queue + FunctionName: !Sub ${RegionalPrefix}-${ComponentShortName}-DmdEventsLambda-${TenantAwsResource} + Handler: com.example.DmdEventHandler::handleRequest + DeploymentPreference: + Enabled: true + PassthroughCondition: true + Type: !If [ IsNotProd, AllAtOnce, Canary10Percent10Minutes ] + Alarms: + - !Ref DmdEventsLambdaErrorsGreaterThanZeroAlarm + ProvisionedConcurrencyConfig: + ProvisionedConcurrentExecutions: 1 + Timeout: 20 + Environment: + Variables: + HANDLER_NAME: DmdEventsLambda + Policies: + - !Ref DeniedPolicies + - !Ref LogMonitoringPolicy + - !Ref TenantInfoReadPolicy + - Fn::ImportValue: !Sub ${Zone}-${Site}-${Solution}-${Environment}-cce-remote-service-db-ReadPolicy + - Fn::ImportValue: !Sub ${Zone}-${Site}-${Solution}-${Environment}-cce-remote-service-db-WritePolicy + - Fn::ImportValue: !Sub ${RegionalPrefix}-ccerscb-ConfigS3BucketReadPolicy + Events: + Batch: + Type: SQS + Properties: + Queue: !GetAtt DmdEventsQueue.Arn + BatchSize: 10 + Enabled: true + FunctionResponseTypes: + - ReportBatchItemFailures + DmdEventsQueue: + Type: AWS::SQS::Queue + Condition: DmdEnabled + Properties: + QueueName: !Sub ${Solution}-${Environment}-${ComponentShortName}-DmdEventsQueue-${TenantAwsResource}.fifo + MessageRetentionPeriod: 10800 # 3 hours + FifoQueue: true + KmsMasterKeyId: alias/sqs-key + RedrivePolicy: + maxReceiveCount: 3 + deadLetterTargetArn: !GetAtt DmdEventsDeadLetterQueue.Arn + DmdEventsDeadLetterQueue: + Type: AWS::SQS::Queue + Condition: DmdEnabled + Properties: + QueueName: !Sub ${Solution}-${Environment}-${ComponentShortName}-DmdEventsDeadLetterQueue-${TenantAwsResource}.fifo + MessageRetentionPeriod: 345600 # 4 days + FifoQueue: true + FifoThroughputLimit: perMessageGroupId + KmsMasterKeyId: alias/sqs-key + ContentBasedDeduplication: true + DeduplicationScope: messageGroup + Tags: + - Key: queueType + Value: dlq + DmdEventsQueueRetryPolicy: + Type: AWS::SQS::QueuePolicy + Condition: DmdEnabled + Properties: + PolicyDocument: + Statement: + Effect: Allow + Principal: + Service: sqs.amazonaws.com + Action: + - sqs:SendMessage + - sqs:ReceiveMessage + Resource: + !GetAtt DmdEventsQueue.Arn + Queues: + - !Ref DmdEventsDeadLetterQueue + DmdEventsQueueSourcePolicy: + Type: AWS::SQS::QueuePolicy + Condition: DmdSubscriptionEnabled + Properties: + Queues: + - !Ref DmdEventsQueue + PolicyDocument: + Statement: + Effect: Allow + Principal: + Service: sns.amazonaws.com + Action: + - sqs:SendMessage + Resource: !GetAtt DmdEventsQueue.Arn + Condition: + ArnEquals: + aws:SourceArn: !Ref DmdEventsSourceArn + DmdEventsSubscription: + Type: AWS::SNS::Subscription + Condition: DmdSubscriptionEnabled + Properties: + Protocol: sqs + Endpoint: !GetAtt DmdEventsQueue.Arn + Region: !Ref DmdEventsSourceRegion + TopicArn: !Ref DmdEventsSourceArn + RawMessageDelivery: true + + DmdEventsLambdaErrorsGreaterThanZeroAlarm: + Type: AWS::CloudWatch::Alarm + Condition: DmdEnabled + Properties: + AlarmDescription: DMD Events Lambda Function Error > 0 + Namespace: AWS/Lambda + MetricName: Errors + Dimensions: + - Name: FunctionName + Value: !Ref DmdEventsLambda + - Name: Resource + Value: !Sub ${DmdEventsLambda}:${AliasName} + TreatMissingData: notBreaching + Statistic: Sum + Threshold: 0 + ComparisonOperator: GreaterThanThreshold + EvaluationPeriods: 1 + Period: 60 diff --git a/test/integration/test_good_templates.py b/test/integration/test_good_templates.py --- a/test/integration/test_good_templates.py +++ b/test/integration/test_good_templates.py @@ -26,6 +26,11 @@ class TestQuickStartTemplates(BaseCliTestCase): "results": [], "exit_code": 0, }, + { + "filename": "test/fixtures/templates/issues/sam_w_conditions.yaml", + "results": [], + "exit_code": 0, + }, { "filename": "test/fixtures/templates/bad/transform_serverless_template.yaml", "results": [
E0002 Unknown exception while processing rule E3001: 'ServerlessCodeDeployCondition' ### CloudFormation Lint Version 0.77.3 ### What operating system are you using? Ubuntu ### Describe the bug Suddenly cfn-lint fails to validate a template that haven't been touched for several months. cfn-lint seems to be generating it's own template behind-the-scenes, and it's failing on one of the _generated_ resources (`ServerlessCodeDeployCondition` & `ServerlessDeploymentApplication`). The output from cfn-lint: ``` 2023-04-28 11:00:56,586 - cfnlint.runner - INFO - Run scan of template infrastructure/template.tenant.anonymous.yml E0002 Unknown exception while processing rule E3001: 'ServerlessCodeDeployCondition' infrastructure/template.tenant.anonymous.yml:1:1 W1001 Ref to resource "ServerlessDeploymentApplication" that may not be available when condition "ServerlessCodeDeployCondition" is False and when condition "VmdEnabled" is True at Resources/VmdEventsLambdaAliasActive/UpdatePolicy/CodeDeployLambdaAliasUpdate/ApplicationName/Ref infrastructure/template.tenant.anonymous.yml:111:1 W1001 Ref to resource "ServerlessDeploymentApplication" that may not be available when condition "ServerlessCodeDeployCondition" is False and when condition "DmdEnabled" is True at Resources/DmdEventsLambdaAliasActive/UpdatePolicy/CodeDeployLambdaAliasUpdate/ApplicationName/Ref infrastructure/template.tenant.anonymous.yml:111:1 W1001 Ref to resource "ServerlessDeploymentApplication" that may not be available when condition "ServerlessCodeDeployCondition" is False and when condition "VmdEnabled" is True at Resources/VmdEventsLambdaDeploymentGroup/Properties/ApplicationName/Ref infrastructure/template.tenant.anonymous.yml:111:1 W1001 Ref to resource "ServerlessDeploymentApplication" that may not be available when condition "ServerlessCodeDeployCondition" is False and when condition "DmdEnabled" is True at Resources/DmdEventsLambdaDeploymentGroup/Properties/ApplicationName/Ref infrastructure/template.tenant.anonymous.yml:111:1 W1001 GetAtt to resource "CodeDeployServiceRole" that may not be available when condition "ServerlessCodeDeployCondition" is False and when condition "VmdEnabled" is True at Resources/VmdEventsLambdaDeploymentGroup/Properties/ServiceRoleArn/Fn::GetAtt infrastructure/template.tenant.anonymous.yml:111:1 W1001 GetAtt to resource "CodeDeployServiceRole" that may not be available when condition "ServerlessCodeDeployCondition" is False and when condition "DmdEnabled" is True at Resources/DmdEventsLambdaDeploymentGroup/Properties/ServiceRoleArn/Fn::GetAtt infrastructure/template.tenant.anonymous.yml:111:1 ``` The _generated template_ has the following conditions. I can't see any issue with the `ServerlessCodeDeployCondition` here: ```yaml Conditions: DmdEnabled: 'Fn::Equals': - true - Ref: DmdEnabled DmdSubscriptionEnabled: 'Fn::And': - Condition: DmdEnabled - 'Fn::Equals': - true - Ref: DmdSubscriptionEnabled IsNotProd: 'Fn::Not': - 'Fn::Equals': - Ref: Environment - prod ServerlessCodeDeployCondition: 'Fn::Or': - Condition: DmdEnabled - Condition: VmdEnabled VmdEnabled: 'Fn::Equals': - true - Ref: VmdEnabled VmdSubscriptionEnabled: 'Fn::And': - Condition: VmdEnabled - 'Fn::Equals': - true - Ref: VmdSubscriptionEnabled ``` ### Expected behavior cfn-lint to _not_ fail due to it's generated resource. ### Reproduction template ```yaml AWSTemplateFormatVersion: 2010-09-09 Transform: AWS::Serverless-2016-10-31 Parameters: # Deploy Engine parameters Zone: Type: String Site: Type: String Solution: Type: String Environment: Type: String GlobalPrefix: Type: String RegionalPrefix: Type: String Component: Type: String ComponentShortName: Type: String Version: Type: String Tenant: Type: String TenantAwsResource: Type: String # VMD Event Source VmdEnabled: Type: String AllowedValues: - true - false VmdEventsSourceArn: Type: String VmdEventsSourceRegion: Type: String VmdSubscriptionEnabled: Type: String AllowedValues: - true - false # DMD Event Source DmdEnabled: Type: String AllowedValues: - true - false DmdEventsSourceArn: Type: String DmdEventsSourceRegion: Type: String DmdSubscriptionEnabled: Type: String AllowedValues: - true - false ConfigS3ReloadInterval: Type: String Default: 120 AliasName: Type: String Default: Active Conditions: IsNotProd: !Not [ !Equals [ !Ref Environment, prod ] ] # VMD VmdEnabled: !Equals [ true, !Ref VmdEnabled ] VmdSubscriptionEnabled: !And - !Condition VmdEnabled - !Equals [ true, !Ref VmdSubscriptionEnabled ] # DMD DmdEnabled: !Equals [ true, !Ref DmdEnabled ] DmdSubscriptionEnabled: !And - !Condition DmdEnabled - !Equals [ true, !Ref DmdSubscriptionEnabled ] Globals: Function: Runtime: java11 MemorySize: 1024 Timeout: 60 CodeUri: functions-java.zip AutoPublishAlias: Active Environment: Variables: JAVA_TOOL_OPTIONS: -XX:+TieredCompilation -XX:TieredStopAtLevel=1 SITE: !Ref Site SOLUTION: !Ref Solution ENVIRONMENT: !Ref Environment VERSION: !Ref Version ACCOUNT_ID: !Sub ${AWS::AccountId} COMPONENT_SHORT: !Ref ComponentShortName COMPONENT_LONG: !Ref Component COMPONENT_VERSION: !Ref Version TENANT: !Ref Tenant CONFIG_LIB_COMPONENT_SHORT_NAME: !Ref ComponentShortName CONFIG_LIB_SOLUTION: !Ref Solution CONFIG_LIB_ENVIRONMENT: !Ref Environment CONFIG_LIB_SITE: !Ref Site CONFIG_LIB_S3_BUCKET: Fn::ImportValue: !Sub ${RegionalPrefix}-ccerscb-ConfigS3BucketName CONFIG_LIB_S3_KEY: !Sub ${ComponentShortName}/application.yml CONFIG_LIB_S3_PLATFORM_BUCKET: Fn::ImportValue: !Sub ${RegionalPrefix}-ccerscb-ConfigS3BucketName CONFIG_LIB_S3_PLATFORM_KEY: platform/application.yml CONFIG_LIB_S3_RELOAD_INTERVAL: !Ref ConfigS3ReloadInterval Resources: #################### # Generic Policies # #################### DeniedPolicies: Type: AWS::IAM::ManagedPolicy Properties: ManagedPolicyName: !Sub ${GlobalPrefix}-${ComponentShortName}-DeniedPolicies-${TenantAwsResource} Description: Policy for monitoring Path: / PolicyDocument: Version: 2012-10-17 Statement: - Effect: Deny Action: - aws-portal:* - cloudtrail:*Logging - directconnect:Delete* Resource: '*' LogMonitoringPolicy: Type: AWS::IAM::ManagedPolicy Metadata: cfn_nag: rules_to_suppress: - id: W13 reason: "TODO: [WPF-29001] Temporarily suppressing wildcard resource warning until fixed by this ticket" Properties: ManagedPolicyName: !Sub ${GlobalPrefix}-${ComponentShortName}-LogMonitoringPolicy-${TenantAwsResource} Description: Policy for monitoring Path: / PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: '*' TenantInfoReadPolicy: Type: AWS::IAM::ManagedPolicy Properties: Description: Policy to read Tenant Info secret from Secrets Manager PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - secretsmanager:GetSecretValue - secretsmanager:DescribeSecret Resource: - !Sub arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:tenant-info_* ########################## # VMD Events Integration # ########################## VmdEventsLambda: Type: AWS::Serverless::Function Condition: VmdEnabled Properties: Description: Function handling VMD VehicleData image events sent via the VMD Events SQS Queue FunctionName: !Sub ${RegionalPrefix}-${ComponentShortName}-VmdEventsLambda-${TenantAwsResource} Handler: com.example.VmdEventHandler::handleRequest DeploymentPreference: Enabled: true PassthroughCondition: true Type: !If [ IsNotProd, AllAtOnce, Canary10Percent10Minutes ] Alarms: - !Ref VmdEventsLambdaErrorsGreaterThanZeroAlarm ProvisionedConcurrencyConfig: ProvisionedConcurrentExecutions: 1 Timeout: 20 Environment: Variables: HANDLER_NAME: VmdEventsLambda Policies: - !Ref DeniedPolicies - !Ref LogMonitoringPolicy - !Ref TenantInfoReadPolicy - Fn::ImportValue: !Sub ${Zone}-${Site}-${Solution}-${Environment}-cce-remote-service-db-ReadPolicy - Fn::ImportValue: !Sub ${Zone}-${Site}-${Solution}-${Environment}-cce-remote-service-db-WritePolicy - Fn::ImportValue: !Sub ${RegionalPrefix}-ccerscb-ConfigS3BucketReadPolicy Events: Batch: Type: SQS Properties: Queue: !GetAtt VmdEventsQueue.Arn BatchSize: 10 Enabled: true FunctionResponseTypes: - ReportBatchItemFailures VmdEventsQueue: Type: AWS::SQS::Queue Condition: VmdEnabled Properties: QueueName: !Sub ${Solution}-${Environment}-${ComponentShortName}-VmdEventsQueue-${TenantAwsResource}.fifo MessageRetentionPeriod: 10800 # 3 hours FifoQueue: true KmsMasterKeyId: alias/sqs-key RedrivePolicy: maxReceiveCount: 3 deadLetterTargetArn: !GetAtt VmdEventsDeadLetterQueue.Arn VmdEventsDeadLetterQueue: Type: AWS::SQS::Queue Condition: VmdEnabled Properties: QueueName: !Sub ${Solution}-${Environment}-${ComponentShortName}-VmdEventsDeadLetterQueue-${TenantAwsResource}.fifo MessageRetentionPeriod: 345600 # 4 days FifoQueue: true FifoThroughputLimit: perMessageGroupId KmsMasterKeyId: alias/sqs-key ContentBasedDeduplication: true DeduplicationScope: messageGroup Tags: - Key: queueType Value: dlq VmdEventsQueueRetryPolicy: Type: AWS::SQS::QueuePolicy Condition: VmdEnabled Properties: PolicyDocument: Statement: Effect: Allow Principal: Service: sqs.amazonaws.com Action: - sqs:SendMessage - sqs:ReceiveMessage Resource: !GetAtt VmdEventsQueue.Arn Queues: - !Ref VmdEventsDeadLetterQueue VmdEventsQueueSourcePolicy: Type: AWS::SQS::QueuePolicy Condition: VmdSubscriptionEnabled Properties: Queues: - !Ref VmdEventsQueue PolicyDocument: Statement: Effect: Allow Principal: Service: sns.amazonaws.com Action: - sqs:SendMessage Resource: !GetAtt VmdEventsQueue.Arn Condition: ArnEquals: aws:SourceArn: !Ref VmdEventsSourceArn VmdEventsSubscription: Type: AWS::SNS::Subscription Condition: VmdSubscriptionEnabled Properties: Protocol: sqs Endpoint: !GetAtt VmdEventsQueue.Arn Region: !Ref VmdEventsSourceRegion TopicArn: !Ref VmdEventsSourceArn RawMessageDelivery: true VmdEventsLambdaErrorsGreaterThanZeroAlarm: Type: AWS::CloudWatch::Alarm Condition: VmdEnabled Properties: AlarmDescription: VMD Events Lambda Function Error > 0 Namespace: AWS/Lambda MetricName: Errors Dimensions: - Name: FunctionName Value: !Ref VmdEventsLambda - Name: Resource Value: !Sub ${VmdEventsLambda}:${AliasName} TreatMissingData: notBreaching Statistic: Sum Threshold: 0 ComparisonOperator: GreaterThanThreshold EvaluationPeriods: 1 Period: 60 ########################## # DMD Events Integration # ########################## DmdEventsLambda: Type: AWS::Serverless::Function Condition: DmdEnabled Properties: Description: Function handling DMD DeviceData image events sent via the DMD Events SQS Queue FunctionName: !Sub ${RegionalPrefix}-${ComponentShortName}-DmdEventsLambda-${TenantAwsResource} Handler: com.example.DmdEventHandler::handleRequest DeploymentPreference: Enabled: true PassthroughCondition: true Type: !If [ IsNotProd, AllAtOnce, Canary10Percent10Minutes ] Alarms: - !Ref DmdEventsLambdaErrorsGreaterThanZeroAlarm ProvisionedConcurrencyConfig: ProvisionedConcurrentExecutions: 1 Timeout: 20 Environment: Variables: HANDLER_NAME: DmdEventsLambda Policies: - !Ref DeniedPolicies - !Ref LogMonitoringPolicy - !Ref TenantInfoReadPolicy - Fn::ImportValue: !Sub ${Zone}-${Site}-${Solution}-${Environment}-cce-remote-service-db-ReadPolicy - Fn::ImportValue: !Sub ${Zone}-${Site}-${Solution}-${Environment}-cce-remote-service-db-WritePolicy - Fn::ImportValue: !Sub ${RegionalPrefix}-ccerscb-ConfigS3BucketReadPolicy Events: Batch: Type: SQS Properties: Queue: !GetAtt DmdEventsQueue.Arn BatchSize: 10 Enabled: true FunctionResponseTypes: - ReportBatchItemFailures DmdEventsQueue: Type: AWS::SQS::Queue Condition: DmdEnabled Properties: QueueName: !Sub ${Solution}-${Environment}-${ComponentShortName}-DmdEventsQueue-${TenantAwsResource}.fifo MessageRetentionPeriod: 10800 # 3 hours FifoQueue: true KmsMasterKeyId: alias/sqs-key RedrivePolicy: maxReceiveCount: 3 deadLetterTargetArn: !GetAtt DmdEventsDeadLetterQueue.Arn DmdEventsDeadLetterQueue: Type: AWS::SQS::Queue Condition: DmdEnabled Properties: QueueName: !Sub ${Solution}-${Environment}-${ComponentShortName}-DmdEventsDeadLetterQueue-${TenantAwsResource}.fifo MessageRetentionPeriod: 345600 # 4 days FifoQueue: true FifoThroughputLimit: perMessageGroupId KmsMasterKeyId: alias/sqs-key ContentBasedDeduplication: true DeduplicationScope: messageGroup Tags: - Key: queueType Value: dlq DmdEventsQueueRetryPolicy: Type: AWS::SQS::QueuePolicy Condition: DmdEnabled Properties: PolicyDocument: Statement: Effect: Allow Principal: Service: sqs.amazonaws.com Action: - sqs:SendMessage - sqs:ReceiveMessage Resource: !GetAtt DmdEventsQueue.Arn Queues: - !Ref DmdEventsDeadLetterQueue DmdEventsQueueSourcePolicy: Type: AWS::SQS::QueuePolicy Condition: DmdSubscriptionEnabled Properties: Queues: - !Ref DmdEventsQueue PolicyDocument: Statement: Effect: Allow Principal: Service: sns.amazonaws.com Action: - sqs:SendMessage Resource: !GetAtt DmdEventsQueue.Arn Condition: ArnEquals: aws:SourceArn: !Ref DmdEventsSourceArn DmdEventsSubscription: Type: AWS::SNS::Subscription Condition: DmdSubscriptionEnabled Properties: Protocol: sqs Endpoint: !GetAtt DmdEventsQueue.Arn Region: !Ref DmdEventsSourceRegion TopicArn: !Ref DmdEventsSourceArn RawMessageDelivery: true DmdEventsLambdaErrorsGreaterThanZeroAlarm: Type: AWS::CloudWatch::Alarm Condition: DmdEnabled Properties: AlarmDescription: DMD Events Lambda Function Error > 0 Namespace: AWS/Lambda MetricName: Errors Dimensions: - Name: FunctionName Value: !Ref DmdEventsLambda - Name: Resource Value: !Sub ${DmdEventsLambda}:${AliasName} TreatMissingData: notBreaching Statistic: Sum Threshold: 0 ComparisonOperator: GreaterThanThreshold EvaluationPeriods: 1 Period: 60 ```
2023-04-28T15:07:08Z
[]
[]
aws-cloudformation/cfn-lint
2,757
aws-cloudformation__cfn-lint-2757
[ "2756" ]
431cf4fb9fefdfec25cb4cb69005f4dd064421ba
diff --git a/src/cfnlint/rules/custom/__init__.py b/src/cfnlint/rules/custom/__init__.py --- a/src/cfnlint/rules/custom/__init__.py +++ b/src/cfnlint/rules/custom/__init__.py @@ -42,73 +42,79 @@ def process_sets(raw_value): return raw_value line = line.rstrip() - rule_id = lineNumber + 9000 - line = line.split(" ", 3) - error_level = "E" - if len(line) == 4: - resourceType = line[0] - prop = line[1] - operator = line[2] - value = None - error_message = None - if "WARN" in line[3]: - error_level = "W" - value, error_message = set_arguments(line[3], "WARN") - elif "ERROR" in line[3]: - error_level = "E" - value, error_message = set_arguments(line[3], "ERROR") - else: - value = process_sets(line[3]) - value = get_value(line[3]) + # check line is not a comment or empty line + if not line.startswith("#") and line != "": + rule_id = lineNumber + 9000 + line = line.split(" ", 3) + error_level = "E" + if len(line) == 4: + resourceType = line[0] + prop = line[1] + operator = line[2] + value = None + error_message = None + if "WARN" in line[3]: + error_level = "W" + value, error_message = set_arguments(line[3], "WARN") + elif "ERROR" in line[3]: + error_level = "E" + value, error_message = set_arguments(line[3], "ERROR") + else: + value = process_sets(line[3]) + value = get_value(line[3]) - if isinstance(value, str): - value = value.strip().strip('"') + if isinstance(value, str): + value = value.strip().strip('"') - if operator in ["EQUALS", "=="]: - return cfnlint.rules.custom.Operators.CreateEqualsRule( - error_level + str(rule_id), resourceType, prop, value, error_message - ) - if operator in ["NOT_EQUALS", "!="]: - return cfnlint.rules.custom.Operators.CreateNotEqualsRule( - error_level + str(rule_id), resourceType, prop, value, error_message - ) - if operator == "REGEX_MATCH": - return cfnlint.rules.custom.Operators.CreateRegexMatchRule( - error_level + str(rule_id), resourceType, prop, value, error_message - ) - if operator == "IN": - return cfnlint.rules.custom.Operators.CreateInSetRule( - error_level + str(rule_id), resourceType, prop, value, error_message - ) - if operator == "NOT_IN": - return cfnlint.rules.custom.Operators.CreateNotInSetRule( - error_level + str(rule_id), resourceType, prop, value, error_message - ) - if operator == ">": - return cfnlint.rules.custom.Operators.CreateGreaterRule( - error_level + str(rule_id), resourceType, prop, value, error_message - ) - if operator == ">=": - return cfnlint.rules.custom.Operators.CreateGreaterEqualRule( - error_level + str(rule_id), resourceType, prop, value, error_message - ) - if operator == "<": - return cfnlint.rules.custom.Operators.CreateLesserRule( - error_level + str(rule_id), resourceType, prop, value, error_message - ) - if operator == "<=": - return cfnlint.rules.custom.Operators.CreateLesserEqualRule( - error_level + str(rule_id), resourceType, prop, value, error_message - ) - if operator == "IS": - if value in ["DEFINED", "NOT_DEFINED"]: - return cfnlint.rules.custom.Operators.CreateCustomIsDefinedRule( + if operator in ["EQUALS", "=="]: + return cfnlint.rules.custom.Operators.CreateEqualsRule( + error_level + str(rule_id), resourceType, prop, value, error_message + ) + if operator in ["NOT_EQUALS", "!="]: + return cfnlint.rules.custom.Operators.CreateNotEqualsRule( + error_level + str(rule_id), resourceType, prop, value, error_message + ) + if operator == "REGEX_MATCH": + return cfnlint.rules.custom.Operators.CreateRegexMatchRule( + error_level + str(rule_id), resourceType, prop, value, error_message + ) + if operator == "IN": + return cfnlint.rules.custom.Operators.CreateInSetRule( + error_level + str(rule_id), resourceType, prop, value, error_message + ) + if operator == "NOT_IN": + return cfnlint.rules.custom.Operators.CreateNotInSetRule( error_level + str(rule_id), resourceType, prop, value, error_message ) - return cfnlint.rules.custom.Operators.CreateInvalidRule( - "E" + str(rule_id), f"{operator} {value}" - ) + if operator == ">": + return cfnlint.rules.custom.Operators.CreateGreaterRule( + error_level + str(rule_id), resourceType, prop, value, error_message + ) + if operator == ">=": + return cfnlint.rules.custom.Operators.CreateGreaterEqualRule( + error_level + str(rule_id), resourceType, prop, value, error_message + ) + if operator == "<": + return cfnlint.rules.custom.Operators.CreateLesserRule( + error_level + str(rule_id), resourceType, prop, value, error_message + ) + if operator == "<=": + return cfnlint.rules.custom.Operators.CreateLesserEqualRule( + error_level + str(rule_id), resourceType, prop, value, error_message + ) + if operator == "IS": + if value in ["DEFINED", "NOT_DEFINED"]: + return cfnlint.rules.custom.Operators.CreateCustomIsDefinedRule( + error_level + str(rule_id), + resourceType, + prop, + value, + error_message, + ) + return cfnlint.rules.custom.Operators.CreateInvalidRule( + "E" + str(rule_id), f"{operator} {value}" + ) - return cfnlint.rules.custom.Operators.CreateInvalidRule( - "E" + str(rule_id), operator - ) + return cfnlint.rules.custom.Operators.CreateInvalidRule( + "E" + str(rule_id), operator + )
diff --git a/test/fixtures/custom_rules/good/custom_rule_perfect.txt b/test/fixtures/custom_rules/good/custom_rule_perfect.txt --- a/test/fixtures/custom_rules/good/custom_rule_perfect.txt +++ b/test/fixtures/custom_rules/good/custom_rule_perfect.txt @@ -1,3 +1,4 @@ +#This is a comment to ensure comments in custom rules work AWS::IAM::Role AssumeRolePolicyDocument.Version EQUALS "2012-10-17" AWS::IAM::Role AssumeRolePolicyDocument.Version IN [2012-10-16,2012-10-17,2012-10-18] AWS::IAM::Role AssumeRolePolicyDocument.Version NOT_EQUALS "2012-10-15" @@ -6,10 +7,12 @@ AWS::IAM::Policy PolicyName EQUALS "root" WARN ABC AWS::IAM::Policy PolicyName IN [2012-10-16,root,2012-10-18] ERROR ABC AWS::IAM::Policy PolicyName NOT_EQUALS "user" WARN ABC AWS::IAM::Policy PolicyName NOT_IN [2012-10-16,2012-11-20,2012-10-18] ERROR ABC +# Adding a comment in the middle of custom rules and new line for readability + AWS::EC2::Instance BlockDeviceMappings.Ebs.VolumeSize >= 20 WARN AWS::EC2::Instance BlockDeviceMappings.Ebs.VolumeSize > 10 ERROR ABC AWS::EC2::Instance BlockDeviceMappings.Ebs.VolumeSize <= 50 ERROR DEF AWS::EC2::Instance BlockDeviceMappings.Ebs.VolumeSize < 40 WARN ABC AWS::CloudFormation::Stack TemplateURL REGEX_MATCH "^https.*$" WARN ABC AWS::Lambda::Function Environment.Variables.NODE_ENV IS DEFINED -AWS::Lambda::Function Environment.Variables.PRIVATE_KEY IS NOT_DEFINED \ No newline at end of file +AWS::Lambda::Function Environment.Variables.PRIVATE_KEY IS NOT_DEFINED
New Lines in Custom Rules file causes failures ### CloudFormation Lint Version cfn-lint 0.77.6 ### What operating system are you using? Mac ### Describe the bug Similar to the issue reported in https://github.com/aws-cloudformation/cfn-lint/issues/2069, adding a new blank line in the custom rules file causes `cfn-lint` to fail My rules.txt file is the following. Note that `2` is an empty line (mostly just for readability) ``` 1 AWS::S3::Bucket AccessControl EQUALS Public ERROR 2 3 AWS::S3::Bucket WebsiteConfiguration.IndexDocument EQUALS Retains WARN ``` When i run the following command: `cfn-lint -t cft.yml -z rules.txt --format pretty --debug` - I get ``` 2023-06-02 17:20:25,429 - cfnlint - DEBUG - Begin linting of file: cft.yml 2023-06-02 17:20:25,799 - cfnlint.rules - DEBUG - Processing Custom Rule Line 1 2023-06-02 17:20:25,800 - cfnlint.rules - DEBUG - Processing Custom Rule Line 2 Traceback (most recent call last): File "/usr/local/bin/cfn-lint", line 8, in <module> sys.exit(main()) ^^^^^^ File "/usr/local/lib/python3.11/site-packages/cfnlint/__main__.py", line 39, in main matches = list(cfnlint.core.get_matches(filenames, args)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/cfnlint/core.py", line 169, in get_matches (template, rules, errors) = get_template_rules(filename, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/cfnlint/core.py", line 310, in get_template_rules _build_rule_cache(args) File "/usr/local/lib/python3.11/site-packages/cfnlint/core.py", line 270, in _build_rule_cache __CACHED_RULES = cfnlint.core.get_rules( ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/cfnlint/core.py", line 158, in get_rules rules.create_from_custom_rules_file(custom_rules) File "/usr/local/lib/python3.11/site-packages/cfnlint/rules/__init__.py", line 603, in create_from_custom_rules_file custom_rule = cfnlint.rules.custom.make_rule(line, line_number) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/cfnlint/rules/custom/__init__.py", line 113, in make_rule "E" + str(rule_id), operator ^^^^^^^^ UnboundLocalError: cannot access local variable 'operator' where it is not associated with a value ``` ### Expected behavior Expected for this to just skip the new line and not parse it and fail. I assume these `if` statement needs to be altered to check for `line == ""` https://github.com/aws-cloudformation/cfn-lint/blob/431cf4fb9fefdfec25cb4cb69005f4dd064421ba/src/cfnlint/rules/custom/__init__.py#L44-L48 I believe we can also fix #2069 a similar way by checking if the line starts with `#` ### Reproduction template ``` { 2 "AWSTemplateFormatVersion" : "2010-09-09", 3 4 "Description" : "AWS CloudFormation Sample Template S3_Website_Bucket_With_Retain_On_Delete: Sample template showing how to create a publicly accessible S3 bucket config ured for website access with a deletion policy of retain on delete. **WARNING** This template creates an S3 bucket that will NOT be deleted when the stack is deleted. You will be billed for the AWS resources used if you create a stack from this template.", 5 6 "Resources" : { 7 "S3Bucket" : { 8 "Type" : "AWS::S3::Bucket", 9 "Properties" : { 10 "AccessControl" : "PublicRead", 11 "WebsiteConfiguration" : { 12 "IndexDocument" : "index.html", 13 "ErrorDocument" : "error.html" 14 } 15 }, 16 "DeletionPolicy" : "Retain" 17 } 18 }, 19 20 "Outputs" : { 21 "WebsiteURL" : { 22 "Value" : { "Fn::GetAtt" : [ "S3Bucket", "WebsiteURL" ] }, 23 "Description" : "URL for website hosted on S3" 24 }, 25 "S3BucketSecureURL" : { 26 "Value" : { "Fn::Join" : [ "", [ "https://", { "Fn::GetAtt" : [ "S3Bucket", "DomainName" ] } ] ] }, 27 "Description" : "Name of S3 bucket to hold website content" 28 } 29 } ```
2023-06-04T18:29:09Z
[]
[]
aws-cloudformation/cfn-lint
2,780
aws-cloudformation__cfn-lint-2780
[ "2778" ]
582258aaea531dc8c9a242248cd5b23eb95c7f92
diff --git a/src/cfnlint/rules/functions/Cidr.py b/src/cfnlint/rules/functions/Cidr.py --- a/src/cfnlint/rules/functions/Cidr.py +++ b/src/cfnlint/rules/functions/Cidr.py @@ -49,7 +49,10 @@ def check_ip_block(self, value, path): ) ) else: - message = "Cidr ipBlock should be Cidr Range, Ref, GetAtt, Sub or Select for {0}" + message = ( + "Cidr ipBlock should be Cidr Range, Ref, GetAtt, Sub or" + " Select for {0}" + ) matches.append( RuleMatch( path, message.format("/".join(map(str, value))) @@ -78,18 +81,16 @@ def check_count(self, value, path): if len(value.get("Fn::If")) == 3 and isinstance( value.get("Fn::If"), list ): - matches.extend( - self.check_count( - value.get("Fn::If")[1], - path=path[:] + [index_key, 1], - ) - ) - matches.extend( - self.check_count( - value.get("Fn::If")[2], - path=path[:] + [index_key, 2], + for i in [1, 2]: + ( + new_count_parameters, + new_matches, + ) = self.check_count( + value.get("Fn::If")[i], + path=path[:] + [index_key, i], ) - ) + count_parameters.extend(new_count_parameters) + matches.extend(new_matches) else: message = "Cidr count should be Int, Ref, or Select for {0}" matches.append( @@ -168,7 +169,10 @@ def check_parameter_count(self, cfn, parameter_name): max_value = parameter_obj.get("MaxValue") min_value = parameter_obj.get("MinValue") if (not min_value) or min_value < 1 or min_value > 256: - message = "Parameter for Cidr count have MinValue between 1 and 256 at {0}" + message = ( + "Parameter for Cidr count have MinValue between 1 and 256" + " at {0}" + ) matches.append( RuleMatch( tree + ["MinValue"], @@ -176,7 +180,10 @@ def check_parameter_count(self, cfn, parameter_name): ) ) if (not max_value) or max_value < 1 or max_value > 256: - message = "Parameter for Cidr count have MaxValue between 1 and 256 at {0}" + message = ( + "Parameter for Cidr count have MaxValue between 1 and 256" + " at {0}" + ) matches.append( RuleMatch( tree + ["MaxValue"], @@ -258,7 +265,6 @@ def match(self, cfn): ) count_parameters.extend(new_count_parameters) matches.extend(new_matches) - new_size_mask_parameters, new_matches = self.check_size_mask( size_mask_obj, tree[:] + [2] )
diff --git a/test/fixtures/templates/good/functions/cidr.yaml b/test/fixtures/templates/good/functions/cidr.yaml --- a/test/fixtures/templates/good/functions/cidr.yaml +++ b/test/fixtures/templates/good/functions/cidr.yaml @@ -13,6 +13,8 @@ Parameters: MaxValue: 6 Size: Type: String + FirstTierSubnet1CIDR: + Type: String Mappings: CidrBitsMap: "2": @@ -55,7 +57,7 @@ Resources: - 8 - Fn::Select: - 15 - - Fn::Cidr: + - Fn::Cidr: - Fn::GetAtt: MyVPC.CidrBlock - 16 - 8 @@ -64,3 +66,17 @@ Resources: - 2 - 4 VpcId: 'vpc-123456' + PublicSubnet1: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref MyVPC + AvailabilityZone: !Select [0, !GetAZs ""] + CidrBlock: !If + - IsProd + - !Ref FirstTierSubnet1CIDR + - !Select + - 0 + - !Cidr + - 10.0.0.0/24 + - !If [IsProd, 16, 8] + - 4
E0002: Unknown exception while processing rule E1024: 'list' object has no attribute 'path' ### CloudFormation Lint Version cfn-lint 0.77.10 ### What operating system are you using? Mac ### Describe the bug When validation checks run on a the Cidr function `!Cidr [ ipBlock, count, cidrBits ]`, the count and cidrBits doesn't validate more complex functions like the `!If` in the example. ### Expected behavior Doesn't throw unknown exception ### Reproduction template ```yaml PublicSubnet1: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC AvailabilityZone: !Select [0, !GetAZs ""] CidrBlock: !If - defineYourOwnSubnetCIDR - !Ref FirstTierSubnet1CIDR - !Select - 0 - !Cidr - 10.0.0.0/24 - !If [3AZ, 16, 8] - 4 ```
Found the issue and working to correct it.
2023-06-30T17:34:19Z
[]
[]
aws-cloudformation/cfn-lint
2,786
aws-cloudformation__cfn-lint-2786
[ "2181" ]
b7bc622d556d4b98fa97226700174e05bc9cd669
diff --git a/src/cfnlint/helpers.py b/src/cfnlint/helpers.py --- a/src/cfnlint/helpers.py +++ b/src/cfnlint/helpers.py @@ -77,9 +77,9 @@ re.I | re.S, ) REGEX_DYN_REF = re.compile(r"^.*{{resolve:.+}}.*$") -REGEX_DYN_REF_SSM = re.compile(r"^.*{{resolve:ssm:[a-zA-Z0-9_\.\-/]+:\d+}}.*$") +REGEX_DYN_REF_SSM = re.compile(r"^.*{{resolve:ssm:[a-zA-Z0-9_\.\-/]+(:\d+)?}}.*$") REGEX_DYN_REF_SSM_SECURE = re.compile( - r"^.*{{resolve:ssm-secure:[a-zA-Z0-9_\.\-/]+:\d+}}.*$" + r"^.*{{resolve:ssm-secure:[a-zA-Z0-9_\.\-/]+(:\d+)?}}.*$" ) diff --git a/src/cfnlint/rules/functions/Split.py b/src/cfnlint/rules/functions/Split.py --- a/src/cfnlint/rules/functions/Split.py +++ b/src/cfnlint/rules/functions/Split.py @@ -2,6 +2,11 @@ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ +import json + +import regex as re + +from cfnlint.helpers import REGEX_DYN_REF_SSM from cfnlint.rules import CloudFormationLintRule, RuleMatch @@ -34,8 +39,19 @@ def _test_delimiter(self, delimiter, path): matches.append(RuleMatch(path, message.format("/".join(map(str, path))))) return matches + def _check_dyn_ref_value(self, value, path): + """Chec item type""" + matches = [] + if isinstance(value, str): + if re.match(REGEX_DYN_REF_SSM, value): + message = f'Fn::Split does not support dynamic references at {"/".join(map(str, path[:]))}' + matches.append(RuleMatch(path[:], message)) + + return matches + def _test_string(self, s, path): matches = [] + matches.extend(self._check_dyn_ref_value(json.dumps(s), path[:])) if isinstance(s, dict): if len(s) == 1: for key, _ in s.items():
diff --git a/test/fixtures/templates/bad/functions_split.yaml b/test/fixtures/templates/bad/functions_split.yaml --- a/test/fixtures/templates/bad/functions_split.yaml +++ b/test/fixtures/templates/bad/functions_split.yaml @@ -31,3 +31,10 @@ Resources: AvailabilityZone: !Select - 0 - Fn::Split: {Ref: AWS::Region} + myInstance4: + Type: AWS::EC2::Instance + Properties: + ImageId: String + AvailabilityZone: !Select + - 0 + - !Split [":", "{{resolve:ssm:/vpc/subnets/private}}"] diff --git a/test/unit/rules/functions/test_split.py b/test/unit/rules/functions/test_split.py --- a/test/unit/rules/functions/test_split.py +++ b/test/unit/rules/functions/test_split.py @@ -21,7 +21,7 @@ def test_file_positive(self): def test_file_negative(self): """Test failure""" - self.helper_file_negative("test/fixtures/templates/bad/functions_split.yaml", 3) + self.helper_file_negative("test/fixtures/templates/bad/functions_split.yaml", 4) def test_split_parts(self): rule = Split()
Alert when doing a split on a dynamic reference You can dynamic reference a `StringList` but it is read in as a comma delimited singular string. [Docs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#dynamic-references-ssm) You cannot put it back into a list by doing `!Split [',', '{{resolve:ssm:/vpc/subnets/private}}']` because the split is done prior to the dynamic reference. This will result in a singular string that is comma delimited. As a reference `!Split [':', '{{resolve:ssm:/vpc/subnets/private}}']` will split this string into a list of 3 strings.
2023-07-03T22:53:02Z
[]
[]
aws-cloudformation/cfn-lint
2,891
aws-cloudformation__cfn-lint-2891
[ "2890" ]
60714ec0be0126f33b9f9b60b860f359b184ed2d
diff --git a/src/cfnlint/rules/resources/properties/Exclusive.py b/src/cfnlint/rules/resources/properties/Exclusive.py --- a/src/cfnlint/rules/resources/properties/Exclusive.py +++ b/src/cfnlint/rules/resources/properties/Exclusive.py @@ -40,7 +40,7 @@ def check(self, properties, exclusions, path, cfn): for prop in obj: if prop == k: for excl_property in exclusions[prop]: - if excl_property in obj: + if obj.get(excl_property): if property_set["Scenario"] is None: message = "Property {0} should NOT exist with {1} for {2}" matches.append(
diff --git a/test/fixtures/templates/good/resources/properties/exclusive.yaml b/test/fixtures/templates/good/resources/properties/exclusive.yaml --- a/test/fixtures/templates/good/resources/properties/exclusive.yaml +++ b/test/fixtures/templates/good/resources/properties/exclusive.yaml @@ -5,4 +5,47 @@ Resources: SourceSecurityGroupId: sg-abc12345 CidrIp: !Ref AWS::NoValue IpProtocol: "-1" - GroupId: sg-abc1234567 \ No newline at end of file + GroupId: sg-abc1234567 + Alarm: + Type: AWS::CloudWatch::Alarm + Properties: + AlarmName: !Sub "${AWS::StackName}-ALB-5XX-Percentage" + ActionsEnabled: true + OKActions: [] + AlarmActions: [] + InsufficientDataActions: [] + Dimensions: [] + EvaluationPeriods: 15 + DatapointsToAlarm: 3 + Threshold: 5 + ComparisonOperator: GreaterThanOrEqualToThreshold + TreatMissingData: notBreaching + Metrics: + - Id: e1 + Label: ALB 5XX Percentage + ReturnData: true + Expression: (m2/(m1+m2+m3+0.001))*100 + - Id: m1 + ReturnData: false + MetricStat: + Metric: + Namespace: AWS/ApplicationELB + MetricName: RequestCount + Period: 60 + Stat: Sum + - Id: m2 + ReturnData: false + MetricStat: + Metric: + Namespace: AWS/ApplicationELB + MetricName: HTTPCode_ELB_5XX_Count + Period: 60 + Stat: Sum + - Id: m3 + ReturnData: false + MetricStat: + Metric: + Namespace: AWS/ApplicationELB + MetricName: HTTPCode_ELB_4XX_Count + Period: 60 + Stat: Sum diff --git a/test/unit/rules/resources/properties/test_exclusive.py b/test/unit/rules/resources/properties/test_exclusive.py --- a/test/unit/rules/resources/properties/test_exclusive.py +++ b/test/unit/rules/resources/properties/test_exclusive.py @@ -16,6 +16,9 @@ def setUp(self): """Setup""" super(TestPropertyExclusive, self).setUp() self.collection.register(Exclusive()) + self.success_templates = [ + "test/fixtures/templates/good/resources/properties/exclusive.yaml" + ] def test_file_positive(self): """Test Positive"""
E2520 false positive for CloudWatch Alarm with expression ### CloudFormation Lint Version 0.80.3 ### What operating system are you using? MacOS ### Describe the bug A valid CloudWatch alarm that uses a metrics expression is resulting in an E2520 false positive. The alarm was defined in the CloudWatch console and exported via the "View Source | CloudFormation YAML" capability, so it's definitionally a valid CloudWatch alarm. To confirm that the bug isn't in the console, created a copy of the alarm using the generated definition and neither CloudFormation nor CloudWatch have any complaints. ### Expected behavior E2520 should not be raised when `Dimensions` is present under `MetricStat.Metric`. ### Reproduction template ```yaml AWSTemplateFormatVersion: "2010-09-09" Description: AXIS ALB alarms Parameters: pLoadBalancerId: Type: String Default: app/private-api-proxy/ced2a65499b104e7 pAlarmPrefix: Type: String Default: MySampleApp Resources: rAlb5xxPercentage: Type: AWS::CloudWatch::Alarm Properties: AlarmName: !Sub "${pAlarmPrefix}-ALB-5XX-Percentage" AlarmDescription: >- This alarm fires when the ALB is returning HTTP 5XX errors. It is usually due to a misconfiguration of the ALB or not having any associated targets. See [runbook](https://google.com) for more details. ActionsEnabled: true OKActions: [] AlarmActions: [] InsufficientDataActions: [] Dimensions: [] EvaluationPeriods: 15 DatapointsToAlarm: 3 Threshold: 5 ComparisonOperator: GreaterThanOrEqualToThreshold TreatMissingData: notBreaching Metrics: - Id: e1 Label: ALB 5XX Percentage ReturnData: true Expression: (m2/(m1+m2+m3+0.001))*100 - Id: m1 ReturnData: false MetricStat: Metric: Namespace: AWS/ApplicationELB MetricName: RequestCount Dimensions: - Name: LoadBalancer Value: !Ref pLoadBalancerId Period: 60 Stat: Sum - Id: m2 ReturnData: false MetricStat: Metric: Namespace: AWS/ApplicationELB MetricName: HTTPCode_ELB_5XX_Count Dimensions: - Name: LoadBalancer Value: !Ref pLoadBalancerId Period: 60 Stat: Sum - Id: m3 ReturnData: false MetricStat: Metric: Namespace: AWS/ApplicationELB MetricName: HTTPCode_ELB_4XX_Count Dimensions: - Name: LoadBalancer Value: !Ref pLoadBalancerId Period: 60 Stat: Sum ```
2023-09-27T22:54:04Z
[]
[]
aws-cloudformation/cfn-lint
2,905
aws-cloudformation__cfn-lint-2905
[ "2903" ]
ae09aed9effc999188cde057529be23dafc87a7d
diff --git a/src/cfnlint/rules/resources/lmbd/SnapStart.py b/src/cfnlint/rules/resources/lmbd/SnapStart.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/resources/lmbd/SnapStart.py @@ -0,0 +1,77 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from cfnlint.rules import CloudFormationLintRule, RuleMatch + + +class SnapStart(CloudFormationLintRule): + """Check if Lambda SnapStart is properly configured""" + + id = "W2530" + shortdesc = "Validate that SnapStart is properly configured" + description = ( + "To properly leverage SnapStart, you must configure both the lambda function " + "and attach a Lambda version resource" + ) + source_url = "https://docs.aws.amazon.com/lambda/latest/dg/snapstart.html" + tags = ["resources", "lambda"] + + def __init__(self): + super().__init__() + self.resource_property_types.append("AWS::Lambda::Function") + + def _check_value(self, value, path, **kwargs): + lambda_versions = kwargs["lambda_versions"] + cfn = kwargs["cfn"] + + if value != "PublishedVersions": + return [] + + # SnapStart is enabled, validate if version is attached + matches = [ + v + for v in lambda_versions + if any(edge == path[1] for edge in cfn.graph.graph.neighbors(v)) + ] + + if len(matches) < 1: + return [ + RuleMatch( + path, + "SnapStart is enabled but Lambda version is not attached", + ) + ] + + return [] + + def match_resource_properties(self, properties, _, path, cfn): + """Check CloudFormation Properties""" + matches = [] + + # if there is no graph we can't validate + if not cfn.graph: + return matches + + lambda_versions = cfn.get_resources(["AWS::Lambda::Version"]) + + for scenario in cfn.get_object_without_conditions(properties, ["SnapStart"]): + props = scenario.get("Object") + + snap_start = props.get("SnapStart") + if not snap_start: + continue + + matches.extend( + cfn.check_value( + snap_start, + "ApplyOn", + path, + check_value=self._check_value, + lambda_versions=lambda_versions, + cfn=cfn, + ) + ) + + return matches diff --git a/src/cfnlint/rules/resources/lmbd/SnapStartEnabled.py b/src/cfnlint/rules/resources/lmbd/SnapStartEnabled.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/resources/lmbd/SnapStartEnabled.py @@ -0,0 +1,38 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from cfnlint.rules import CloudFormationLintRule, RuleMatch + + +class SnapStartEnabled(CloudFormationLintRule): + """Check if the SnapStart is enabled for certain java runtimes""" + + id = "I2530" + shortdesc = "Validate that SnapStart is configured for >= Java11 runtimes" + description = ( + "SnapStart is a no-cost feature that can increase performance up to 10x. " + "Enable SnapStart for Java 11 and greater runtimes" + ) + source_url = "https://docs.aws.amazon.com/lambda/latest/dg/snapstart.html" + tags = ["resources", "lambda"] + + def __init__(self): + super().__init__() + self.resource_property_types.append("AWS::Lambda::Function") + + def validate(self, runtime, path): + if not runtime: + return [] + + if not (runtime.startswith("java")) and runtime not in ["java8.al2", "java8"]: + return [] + + return [ + RuleMatch( + path, + f"When using {runtime} configure SnapStart", + rule=self, + ) + ] diff --git a/src/cfnlint/rules/resources/lmbd/SnapStartSupported.py b/src/cfnlint/rules/resources/lmbd/SnapStartSupported.py new file mode 100644 --- /dev/null +++ b/src/cfnlint/rules/resources/lmbd/SnapStartSupported.py @@ -0,0 +1,54 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" + +from cfnlint.rules import CloudFormationLintRule, RuleMatch + + +class SnapStartSupported(CloudFormationLintRule): + """Check if Lambda function using SnapStart has the correct runtimes""" + + id = "E2530" + shortdesc = "SnapStart supports the configured runtime" + description = ( + "To properly leverage SnapStart, you must have a runtime of Java11 or greater" + ) + source_url = "https://docs.aws.amazon.com/lambda/latest/dg/snapstart.html" + tags = ["resources", "lambda"] + + def __init__(self): + super().__init__() + self.resource_property_types.append("AWS::Lambda::Function") + self.child_rules = {"I2530": None} + + def match_resource_properties(self, properties, _, path, cfn): + """Check CloudFormation Properties""" + matches = [] + + for scenario in cfn.get_object_without_nested_conditions(properties, path): + props = scenario.get("Object") + + runtime = props.get("Runtime") + snap_start = props.get("SnapStart") + if not snap_start: + if self.child_rules["I2530"]: + matches.extend(self.child_rules["I2530"].validate(runtime, path)) + continue + + if snap_start.get("ApplyOn") != "PublishedVersions": + continue + + if ( + runtime + and (not runtime.startswith("java")) + and runtime not in ["java8.al2", "java8"] + ): + matches.append( + RuleMatch( + path + ["SnapStart", "ApplyOn"], + f"{runtime} is not supported for SnapStart enabled functions", + ) + ) + + return matches
diff --git a/test/fixtures/templates/bad/resources/lambda/snapstart-enabled.yaml b/test/fixtures/templates/bad/resources/lambda/snapstart-enabled.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources/lambda/snapstart-enabled.yaml @@ -0,0 +1,24 @@ +Resources: + LambdaRole: + Type: AWS::IAM::Role + Properties: + RoleName: LambdaRole + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: sts:AssumeRole + + FunctionJava17: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !GetAtt LambdaRole.Arn + ReservedConcurrentExecutions: 20 + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: java17 + TracingConfig: + Mode: Active diff --git a/test/fixtures/templates/bad/resources/lambda/snapstart-supported.yaml b/test/fixtures/templates/bad/resources/lambda/snapstart-supported.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources/lambda/snapstart-supported.yaml @@ -0,0 +1,26 @@ +Resources: + LambdaRole: + Type: AWS::IAM::Role + Properties: + RoleName: LambdaRole + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: sts:AssumeRole + + FunctionJava17: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !GetAtt LambdaRole.Arn + ReservedConcurrentExecutions: 20 + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: python3.10 + SnapStart: + ApplyOn: PublishedVersions + TracingConfig: + Mode: Active diff --git a/test/fixtures/templates/bad/resources/lambda/snapstart.yaml b/test/fixtures/templates/bad/resources/lambda/snapstart.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/resources/lambda/snapstart.yaml @@ -0,0 +1,41 @@ +Resources: + LambdaRole: + Type: AWS::IAM::Role + Properties: + RoleName: LambdaRole + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: sts:AssumeRole + + FunctionJava17: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !GetAtt LambdaRole.Arn + ReservedConcurrentExecutions: 20 + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: java17 + SnapStart: + ApplyOn: PublishedVersions + TracingConfig: + Mode: Active + + FunctionJava11: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !GetAtt LambdaRole.Arn + ReservedConcurrentExecutions: 20 + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: java17 + SnapStart: + ApplyOn: PublishedVersions + TracingConfig: + Mode: Active diff --git a/test/fixtures/templates/good/resources/lambda/snapstart-enabled.yaml b/test/fixtures/templates/good/resources/lambda/snapstart-enabled.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/lambda/snapstart-enabled.yaml @@ -0,0 +1,41 @@ +Resources: + LambdaRole: + Type: AWS::IAM::Role + Properties: + RoleName: LambdaRole + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: sts:AssumeRole + + FunctionJava17: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !GetAtt LambdaRole.Arn + ReservedConcurrentExecutions: 20 + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: java17 + SnapStart: + ApplyOn: PublishedVersions + TracingConfig: + Mode: Active + + FunctionJava11: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !GetAtt LambdaRole.Arn + ReservedConcurrentExecutions: 20 + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: java11 + SnapStart: + ApplyOn: None + TracingConfig: + Mode: Active diff --git a/test/fixtures/templates/good/resources/lambda/snapstart-supported.yaml b/test/fixtures/templates/good/resources/lambda/snapstart-supported.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/lambda/snapstart-supported.yaml @@ -0,0 +1,26 @@ +Resources: + LambdaRole: + Type: AWS::IAM::Role + Properties: + RoleName: LambdaRole + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: sts:AssumeRole + + FunctionJava17: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !GetAtt LambdaRole.Arn + ReservedConcurrentExecutions: 20 + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: java17 + SnapStart: + ApplyOn: PublishedVersions + TracingConfig: + Mode: Active \ No newline at end of file diff --git a/test/fixtures/templates/good/resources/lambda/snapstart.yaml b/test/fixtures/templates/good/resources/lambda/snapstart.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/lambda/snapstart.yaml @@ -0,0 +1,97 @@ +Conditions: + IsUsEast1: !Equals [!Ref AWS::Region, "us-east-1"] + +Resources: + LambdaRole: + Type: AWS::IAM::Role + Properties: + RoleName: LambdaRole + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: sts:AssumeRole + + FunctionJava17: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !GetAtt LambdaRole.Arn + ReservedConcurrentExecutions: 20 + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: java17 + SnapStart: + ApplyOn: !If [IsUsEast1, PublishedVersions, None] + + TracingConfig: + Mode: Active + + VersionJava17: + Type: AWS::Lambda::Version + Properties: + FunctionName: !Ref FunctionJava17 + Description: v1 + ProvisionedConcurrencyConfig: + ProvisionedConcurrentExecutions: 20 + + FunctionJava11: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !GetAtt LambdaRole.Arn + ReservedConcurrentExecutions: 20 + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: java17 + SnapStart: + ApplyOn: PublishedVersions + TracingConfig: + Mode: Active + + VersionJava11: + Type: AWS::Lambda::Version + Properties: + FunctionName: !Ref FunctionJava11 + Description: v1 + ProvisionedConcurrencyConfig: + ProvisionedConcurrentExecutions: 20 + + FunctionPython: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !GetAtt LambdaRole.Arn + ReservedConcurrentExecutions: 20 + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: python3.10 + TracingConfig: + Mode: Active + + FunctionJava17NoSnapStart: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !GetAtt LambdaRole.Arn + ReservedConcurrentExecutions: 20 + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: java17 + SnapStart: + ApplyOn: None + TracingConfig: + Mode: Active + + VersionJava17NoSnapStart: + Type: AWS::Lambda::Version + Properties: + FunctionName: !Ref FunctionJava17NoSnapStart + Description: v1 + ProvisionedConcurrencyConfig: + ProvisionedConcurrentExecutions: 20 diff --git a/test/unit/rules/resources/lmbd/test_snapstart.py b/test/unit/rules/resources/lmbd/test_snapstart.py new file mode 100644 --- /dev/null +++ b/test/unit/rules/resources/lmbd/test_snapstart.py @@ -0,0 +1,29 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.lmbd.SnapStart import SnapStart + + +class TestSnapStart(BaseRuleTestCase): + """Test Lambda SnapStarts""" + + def setUp(self): + """Setup""" + super(TestSnapStart, self).setUp() + self.collection.register(SnapStart()) + self.success_templates = [ + "test/fixtures/templates/good/resources/lambda/snapstart.yaml" + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative(self): + """Test failure""" + self.helper_file_negative( + "test/fixtures/templates/bad/resources/lambda/snapstart.yaml", 2 + ) diff --git a/test/unit/rules/resources/lmbd/test_snapstart_enabled.py b/test/unit/rules/resources/lmbd/test_snapstart_enabled.py new file mode 100644 --- /dev/null +++ b/test/unit/rules/resources/lmbd/test_snapstart_enabled.py @@ -0,0 +1,31 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.lmbd.SnapStartEnabled import SnapStartEnabled +from cfnlint.rules.resources.lmbd.SnapStartSupported import SnapStartSupported + + +class TestSnapStartEnabled(BaseRuleTestCase): + """Test Lambda SnapStart enabled""" + + def setUp(self): + """Setup""" + super(TestSnapStartEnabled, self).setUp() + self.collection.register(SnapStartEnabled()) + self.collection.register(SnapStartSupported()) + self.success_templates = [ + "test/fixtures/templates/good/resources/lambda/snapstart-enabled.yaml" + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative(self): + """Test failure""" + self.helper_file_negative( + "test/fixtures/templates/bad/resources/lambda/snapstart-enabled.yaml", 1 + ) diff --git a/test/unit/rules/resources/lmbd/test_snapstart_supported.py b/test/unit/rules/resources/lmbd/test_snapstart_supported.py new file mode 100644 --- /dev/null +++ b/test/unit/rules/resources/lmbd/test_snapstart_supported.py @@ -0,0 +1,29 @@ +""" +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: MIT-0 +""" +from test.unit.rules import BaseRuleTestCase + +from cfnlint.rules.resources.lmbd.SnapStartSupported import SnapStartSupported + + +class TestSnapStartSupported(BaseRuleTestCase): + """Test Lambda SnapStart supported""" + + def setUp(self): + """Setup""" + super(TestSnapStartSupported, self).setUp() + self.collection.register(SnapStartSupported()) + self.success_templates = [ + "test/fixtures/templates/good/resources/lambda/snapstart-supported.yaml" + ] + + def test_file_positive(self): + """Test Positive""" + self.helper_file_positive() + + def test_file_negative(self): + """Test failure""" + self.helper_file_negative( + "test/fixtures/templates/bad/resources/lambda/snapstart-supported.yaml", 1 + )
New rule to validate lambda SnapStart configuration ### Is this feature request related to a new rule or cfn-lint capabilities? rules ### Describe the feature you'd like to request When configuring SnapStart you also need to configure a version. A warning level rule will validate that when SnapStart is configured that there is associated `AWS::Lambda::Version` resource. ``` Resources: Function: Type: AWS::Lambda::Function Properties: Code: S3Key: Test S3Bucket: Test Role: !Ref Role Handler: index.main Runtime: java17 SnapStart: ApplyOn: PublishedVersions Version: Type: AWS::Lambda::Version Properties: FunctionName: !Ref Function ``` ### Describe the solution you'd like When configuring SnapStart you also need to configure a version. A warning level rule will validate that when SnapStart is configured that there is associated `AWS::Lambda::Version` resource. ### Additional context https://docs.aws.amazon.com/lambda/latest/dg/snapstart.html ### Is this something that you'd be interested in working on? - [x] 👋 I may be able to implement this feature request ### Would this feature include a breaking change? - [x] ⚠️ This feature might incur a breaking change
2023-10-12T17:17:06Z
[]
[]
aws-cloudformation/cfn-lint
2,912
aws-cloudformation__cfn-lint-2912
[ "2911" ]
00ee90b24a6b380d8abaa886eaf3a23f0d545282
diff --git a/src/cfnlint/rules/resources/lmbd/SnapStartEnabled.py b/src/cfnlint/rules/resources/lmbd/SnapStartEnabled.py --- a/src/cfnlint/rules/resources/lmbd/SnapStartEnabled.py +++ b/src/cfnlint/rules/resources/lmbd/SnapStartEnabled.py @@ -23,7 +23,7 @@ def __init__(self): self.resource_property_types.append("AWS::Lambda::Function") def validate(self, runtime, path): - if not runtime: + if not isinstance(runtime, str): return [] if not (runtime.startswith("java")) and runtime not in ["java8.al2", "java8"]: diff --git a/src/cfnlint/rules/resources/lmbd/SnapStartSupported.py b/src/cfnlint/rules/resources/lmbd/SnapStartSupported.py --- a/src/cfnlint/rules/resources/lmbd/SnapStartSupported.py +++ b/src/cfnlint/rules/resources/lmbd/SnapStartSupported.py @@ -39,6 +39,10 @@ def match_resource_properties(self, properties, _, path, cfn): if snap_start.get("ApplyOn") != "PublishedVersions": continue + # Validate runtime is a string before using startswith + if not isinstance(runtime, str): + continue + if ( runtime and (not runtime.startswith("java"))
diff --git a/test/fixtures/templates/good/resources/lambda/snapstart-supported.yaml b/test/fixtures/templates/good/resources/lambda/snapstart-supported.yaml --- a/test/fixtures/templates/good/resources/lambda/snapstart-supported.yaml +++ b/test/fixtures/templates/good/resources/lambda/snapstart-supported.yaml @@ -1,3 +1,6 @@ +Parameters: + Runtime: + Type: String Resources: LambdaRole: Type: AWS::IAM::Role @@ -23,4 +26,19 @@ Resources: SnapStart: ApplyOn: PublishedVersions TracingConfig: - Mode: Active \ No newline at end of file + Mode: Active + + FunctionParameter: + Type: AWS::Lambda::Function + Properties: + Handler: index.handler + Role: !GetAtt LambdaRole.Arn + ReservedConcurrentExecutions: 20 + Code: + S3Bucket: my-bucket + S3Key: function.zip + Runtime: !Ref Runtime + SnapStart: + ApplyOn: PublishedVersions + TracingConfig: + Mode: Active
E0002: Unknown exception while processing rule E2530: 'dict' object has no attribute 'startswith' ### CloudFormation Lint Version 0.82.0 ### What operating system are you using? windows 11 ### Describe the bug receive the E2530 error even though i dont have SnapStart in my lambda resource ### Expected behavior no error ### Reproduction template if i remove this lambda resource, it doesnt throw the error ``` Lambda: Type: AWS::Lambda::Function DependsOn: - LambdaLogGroup Properties: Architectures: - !If - ConditionLambdaArmSupport - !Ref OSArchitechture - x86_64 Code: S3Bucket: Fn::ImportValue: !Sub '${Region}-${BusinessUnit}-${Environment}-${AppName}-artifact-s3-bucket' S3Key: !Ref LambdaS3Key S3ObjectVersion: !Ref LambdaS3ObjectVersion Description: !Sub 'Lambda Function - ${LambdaPurpose}' FunctionName: !Sub '${Region}-${BusinessUnit}-${Environment}-${AppName}-lambda-${LambdaPurpose}' Handler: !Ref LambdaHandler Layers: - !Ref LambdaLayer MemorySize: !Ref LambdaMemory Role: !GetAtt LambdaRole.Arn Runtime: !Ref LambdaRuntime Timeout: !Ref LambdaTimeout VpcConfig: !If - ConditionVpcAttachment - SecurityGroupIds: - Fn::ImportValue: !Sub '${Region}-${BusinessUnit}-${Environment}-${AppName}-sg-${LambdaPurpose}' SubnetIds: - Fn::ImportValue: !Sub '${Region}-${BusinessUnit}-${Environment}-${VpcAttachment}-subnet-1-id' - Fn::ImportValue: !Sub '${Region}-${BusinessUnit}-${Environment}-${VpcAttachment}-subnet-2-id' - !If - ConditionThirdAZ - Fn::ImportValue: !Sub '${Region}-${BusinessUnit}-${Environment}-${VpcAttachment}-subnet-3-id' - !Ref AWS::NoValue - !Ref AWS::NoValue Tags: - Key: Name Value: !Sub '${Region}-${BusinessUnit}-${Environment}-${AppName}-lambda-${LambdaPurpose}' - Key: region-abbreviation Value: !Ref Region - Key: business-unit Value: !Ref BusinessUnit - Key: environment-type Value: !Ref Environment - Key: app-name Value: !Ref AppName - Key: service-type Value: !Ref Service - Key: cost-center Value: !Ref CostCenter - Key: compliance-type Value: !Ref Compliance - Key: owner-name Value: !Ref OwnerName - Key: owner-email-id Value: !Ref OwnerEmail - Key: patch-group Value: !Ref PatchGroup - Key: criticality-level Value: !Ref CriticalityLevel - Key: map-migrated Value: !Ref MapMigrated ```
Should have a fix out shortly.
2023-10-17T20:42:07Z
[]
[]
aws-cloudformation/cfn-lint
2,927
aws-cloudformation__cfn-lint-2927
[ "2925" ]
72de42964f8187ac58df755219e516e570d5a52c
diff --git a/src/cfnlint/rules/resources/properties/ListDuplicatesAllowed.py b/src/cfnlint/rules/resources/properties/ListDuplicatesAllowed.py --- a/src/cfnlint/rules/resources/properties/ListDuplicatesAllowed.py +++ b/src/cfnlint/rules/resources/properties/ListDuplicatesAllowed.py @@ -21,6 +21,10 @@ class ListDuplicatesAllowed(CloudFormationLintRule): source_url = "https://github.com/aws-cloudformation/cfn-python-lint/blob/main/docs/rules.md#rules-1" tags = ["resources", "property", "list"] + def __init__(self): + super().__init__() + self.exceptions = ["Command"] + def initialize(self, cfn): """Initialize the rule""" for resource_type_spec in RESOURCE_SPECS.get(cfn.regions[0]).get( @@ -71,11 +75,15 @@ def check_duplicates(self, values, path, cfn): """Check for duplicates""" matches = [] + if path[-1] in self.exceptions: + return matches if isinstance(values, list): matches.extend(self._check_duplicates(values, path)) elif isinstance(values, dict): props = cfn.get_object_without_conditions(values) for prop in props: + if prop in self.exceptions: + continue matches.extend( self._check_duplicates( prop.get("Object"), path, prop.get("Scenario")
diff --git a/test/fixtures/templates/good/resources/properties/list_duplicates_allowed.yaml b/test/fixtures/templates/good/resources/properties/list_duplicates_allowed.yaml --- a/test/fixtures/templates/good/resources/properties/list_duplicates_allowed.yaml +++ b/test/fixtures/templates/good/resources/properties/list_duplicates_allowed.yaml @@ -4,7 +4,7 @@ Metadata: cfn-lint: config: include_checks: - - I + - I Parameters: PrimaryRegion: Type: String @@ -13,7 +13,7 @@ Parameters: PrivateSubnetTwo: Type: String Conditions: - isPrimaryRegion: !Equals [!Ref PrimaryRegion, 'us-east-1'] + isPrimaryRegion: !Equals [!Ref PrimaryRegion, "us-east-1"] Resources: MyASG: Type: AWS::AutoScaling::AutoScalingGroup @@ -32,11 +32,11 @@ Resources: MinSize: "1" VPCZoneIdentifier: Fn::If: - - isPrimaryRegion - - - !Ref PrivateSubnetOne - - !Ref PrivateSubnetTwo - - - !Ref PrivateSubnetOne - - !Ref PrivateSubnetTwo + - isPrimaryRegion + - - !Ref PrivateSubnetOne + - !Ref PrivateSubnetTwo + - - !Ref PrivateSubnetOne + - !Ref PrivateSubnetTwo MyASG3: Type: AWS::AutoScaling::AutoScalingGroup Properties: @@ -44,5 +44,17 @@ Resources: MaxSize: "1" MinSize: "1" VPCZoneIdentifier: - - !If ['isPrimaryRegion', !Ref PrivateSubnetTwo, !Ref PrivateSubnetOne] + - !If ["isPrimaryRegion", !Ref PrivateSubnetTwo, !Ref PrivateSubnetOne] - "subnet-123456" + MyECSTaskDefinition: + Type: AWS::ECS::TaskDefinition + Properties: + ContainerDefinitions: + - Command: + - do_something + - --foo + - "1" + - --bar + - "1" + Image: my-image + Name: my-task
`I3037` false positives in `AWS::ECS::TaskDefinition.ContainerDefinitions.Command` ### CloudFormation Lint Version 0.83.0 ### What operating system are you using? Mac ### Describe the bug `I3037` issues (*List has a duplicate value*) are reported if the command specified in `AWS::ECS::TaskDefinition.ContainerDefinitions.Command` has repeating entries, e.g. the values of several command arguments are the same. ### Expected behavior No issue is detected. ### Reproduction template ```json { "AWSTemplateFormatVersion": "2010-09-09", "Description": "This template deploys an ECS task definition.", "Resources": { "MyECSTaskDefinition": { "Type": "AWS::ECS::TaskDefinition", "Properties": { "ContainerDefinitions": [ { "Command": [ "do_something", "--foo", "1", "--bar", "1" ], "Image": "my-image", "Name": "my-task" } ] } } } } ```
2023-10-24T16:56:22Z
[]
[]
aws-cloudformation/cfn-lint
2,967
aws-cloudformation__cfn-lint-2967
[ "2964" ]
d874e5899bef1cd8bb6330b4cff9f160f5d823fb
diff --git a/src/cfnlint/rules/resources/cloudfront/Aliases.py b/src/cfnlint/rules/resources/cloudfront/Aliases.py --- a/src/cfnlint/rules/resources/cloudfront/Aliases.py +++ b/src/cfnlint/rules/resources/cloudfront/Aliases.py @@ -4,7 +4,7 @@ """ import regex as re -from cfnlint.helpers import FUNCTIONS +from cfnlint.helpers import FUNCTIONS, REGEX_DYN_REF from cfnlint.rules import CloudFormationLintRule, RuleMatch @@ -35,6 +35,8 @@ def match(self, cfn): for alias in aliases: if isinstance(alias, str) and alias not in FUNCTIONS: wildcard = alias.split(".") + if re.match(REGEX_DYN_REF, alias): + continue if "*" in wildcard[1:]: path = result["Path"] + ["Aliases"] message = f'Invalid use of wildcards: {alias} at {"/".join(result["Path"])}'
diff --git a/test/fixtures/templates/good/resources/cloudfront/aliases.yaml b/test/fixtures/templates/good/resources/cloudfront/aliases.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/cloudfront/aliases.yaml @@ -0,0 +1,23 @@ +AWSTemplateFormatVersion: 2010-09-09 +Resources: + CloudFrontDistribution: + Type: "AWS::CloudFront::Distribution" + Properties: + DistributionConfig: + Aliases: + - "{{resolve:ssm:/env/fqdns/certifier}}" + DefaultCacheBehavior: + AllowedMethods: + - "GET" + - "HEAD" + CachedMethods: + - "GET" + - "HEAD" + ForwardedValues: + QueryString: true + TargetOriginId: "s3" + ViewerProtocolPolicy: "https-only" + Enabled: true + Origins: + - Id: "s3" + DomainName: www.example.com.s3.amazonaws.com" diff --git a/test/unit/rules/resources/cloudfront/test_aliases.py b/test/unit/rules/resources/cloudfront/test_aliases.py --- a/test/unit/rules/resources/cloudfront/test_aliases.py +++ b/test/unit/rules/resources/cloudfront/test_aliases.py @@ -4,7 +4,7 @@ """ from test.unit.rules import BaseRuleTestCase -from cfnlint.rules.resources.cloudfront.Aliases import Aliases # pylint: disable=E0401 +from cfnlint.rules.resources.cloudfront.Aliases import Aliases class TestCloudFrontAliases(BaseRuleTestCase): @@ -14,6 +14,9 @@ def setUp(self): """Setup""" super(TestCloudFrontAliases, self).setUp() self.collection.register(Aliases()) + self.success_templates = [ + "test/fixtures/templates/good/resources/cloudfront/aliases.yaml" + ] def test_file_positive(self): """Test Positive"""
Invalid Aliases when using SSM dynamic references ### CloudFormation Lint Version 0.83.0 ### What operating system are you using? Mac ### Describe the bug When using a dynamic reference to resolve the Alias domain, cfn-lint fails indicating it's an invalid alias. Shouldn't the code check if this is a `REGEX_DYN_REF` in https://github.com/aws-cloudformation/cfn-lint/blob/main/src/cfnlint/rules/resources/cloudfront/Aliases.py and ignore if so? A workaround would be to use "!Sub" which apparently is ignored already (`FUNCTIONS`). Shouldn't we also ignore when `REGEX_DYN_REF`? ### Expected behavior E3013 shouldn't be informed, since there's no way to validate the dynamic-reference value from cfn-lint perspective (?) ### Reproduction template ``` CloudFront: Type: AWS::CloudFront::Distribution Properties: DistributionConfig: Enabled: true Aliases: - "{{resolve:ssm:/env/fqdns/certifier}}" DefaultRootObject: index.html ```
2023-12-07T18:43:08Z
[]
[]
aws-cloudformation/cfn-lint
3,001
aws-cloudformation__cfn-lint-3001
[ "3000" ]
6e39e8cf67d0c6fe5769d56ab4a8d8152e491354
diff --git a/src/cfnlint/rules/resources/ectwo/SecurityGroupIngress.py b/src/cfnlint/rules/resources/ectwo/SecurityGroupIngress.py deleted file mode 100644 --- a/src/cfnlint/rules/resources/ectwo/SecurityGroupIngress.py +++ /dev/null @@ -1,85 +0,0 @@ -""" -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: MIT-0 -""" -from cfnlint.rules import CloudFormationLintRule, RuleMatch - - -class SecurityGroupIngress(CloudFormationLintRule): - """Check if EC2 Security Group Ingress Properties""" - - id = "E2506" - shortdesc = "Resource EC2 Security Group Ingress Properties" - description = ( - "See if EC2 Security Group Ingress Properties are set correctly. " - 'Check that "SourceSecurityGroupId" or "SourceSecurityGroupName" are ' - " are exclusive and using the type of Ref or GetAtt " - ) - source_url = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html" - tags = ["resources", "ec2", "securitygroup"] - - def check_ingress_rule(self, vpc_id, properties, path): - """Check ingress rule""" - - matches = [] - if vpc_id: - # Check that SourceSecurityGroupName isn't specified - if properties.get("SourceSecurityGroupName", None): - path_error = path[:] + ["SourceSecurityGroupName"] - message = ( - "SourceSecurityGroupName shouldn't be specified for " - "Vpc Security Group at {0}" - ) - matches.append( - RuleMatch( - path_error, message.format("/".join(map(str, path_error))) - ) - ) - - return matches - - def match(self, cfn): - """Check EC2 Security Group Ingress Resource Parameters""" - - matches = [] - - resources = cfn.get_resources(resource_type="AWS::EC2::SecurityGroup") - for resource_name, resource_object in resources.items(): - properties = resource_object.get("Properties", {}) - if properties: - vpc_id = properties.get("VpcId", None) - ingress_rules = properties.get("SecurityGroupIngress") - if isinstance(ingress_rules, list): - for index, ingress_rule in enumerate(ingress_rules): - path = [ - "Resources", - resource_name, - "Properties", - "SecurityGroupIngress", - index, - ] - matches.extend( - self.check_ingress_rule( - vpc_id=vpc_id, properties=ingress_rule, path=path - ) - ) - - resources = None - resources = cfn.get_resources(resource_type="AWS::EC2::SecurityGroupIngress") - for resource_name, resource_object in resources.items(): - properties = resource_object.get("Properties", {}) - group_id = properties.get("GroupId", None) - path = ["Resources", resource_name, "Properties"] - if group_id: - vpc_id = "vpc-1234567" - else: - vpc_id = None - - if properties: - path = ["Resources", resource_name, "Properties"] - matches.extend( - self.check_ingress_rule( - vpc_id=vpc_id, properties=properties, path=path - ) - ) - return matches
diff --git a/test/unit/rules/resources/ec2/test_sg_ingress.py b/test/unit/rules/resources/ec2/test_sg_ingress.py deleted file mode 100644 --- a/test/unit/rules/resources/ec2/test_sg_ingress.py +++ /dev/null @@ -1,31 +0,0 @@ -""" -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: MIT-0 -""" -from test.unit.rules import BaseRuleTestCase - -from cfnlint.rules.resources.ectwo.SecurityGroupIngress import ( - SecurityGroupIngress, # pylint: disable=E0401 -) - - -class TestPropertySgIngress(BaseRuleTestCase): - """Test Ec2 Security Group Ingress Rules""" - - def setUp(self): - """Setup""" - super(TestPropertySgIngress, self).setUp() - self.collection.register(SecurityGroupIngress()) - self.success_templates = [ - "test/fixtures/templates/good/properties_ec2_vpc.yaml", - ] - - def test_file_positive(self): - """Test Positive""" - self.helper_file_positive() - - def test_file_negative(self): - """Test failure""" - self.helper_file_negative( - "test/fixtures/templates/bad/properties_sg_ingress.yaml", 1 - )
E2506 will fail when using default vpc ### CloudFormation Lint Version latest ### What operating system are you using? Mac ### Describe the bug False positive for rule E2506 when using security group names with a default vpc ### Expected behavior We should be able to specify a default security group name with a default vpc ### Reproduction template ```yaml Resources: IngressRule: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: 'Security Group Vpc' VpcId: "vpc-default-id" SecurityGroupIngress: - IpProtocol: 1 SourceSecurityGroupName: default FromPort: 0 ToPort: 0 ```
2024-01-05T21:35:28Z
[]
[]
aws-cloudformation/cfn-lint
3,017
aws-cloudformation__cfn-lint-3017
[ "2141" ]
2660e6cf0a6e22a12efdff30f6fb412ad82c2aef
diff --git a/src/cfnlint/rules/resources/events/RuleScheduleExpression.py b/src/cfnlint/rules/resources/events/RuleScheduleExpression.py --- a/src/cfnlint/rules/resources/events/RuleScheduleExpression.py +++ b/src/cfnlint/rules/resources/events/RuleScheduleExpression.py @@ -25,29 +25,43 @@ def check_rate(self, value, path): rate_expression = value[value.find("(") + 1 : value.find(")")] if not rate_expression: - matches.append( - RuleMatch(path, "Rate value of ScheduleExpression cannot be empty") - ) - else: - # Rate format: rate(Value Unit) - items = rate_expression.split(" ") - - if len(items) != 2: - message = "Rate expression must contain 2 elements (Value Unit), rate contains {} elements" - matches.append(RuleMatch(path, message.format(len(items)))) - else: - # Check the Value - if not items[0].isdigit(): - message = "Rate Value ({}) should be of type Integer." - extra_args = { - "actual_type": type(items[0]).__name__, - "expected_type": int.__name__, - } - matches.append( - RuleMatch(path, message.format(items[0]), **extra_args) - ) + return [RuleMatch(path, "Rate value of ScheduleExpression cannot be empty")] + + # Rate format: rate(Value Unit) + items = rate_expression.split(" ") + + if len(items) != 2: + message = "Rate expression must contain 2 elements (Value Unit), rate contains {} elements" + matches.append(RuleMatch(path, message.format(len(items)))) + return [RuleMatch(path, message.format(len(items)))] + + # Check the Value + if not items[0].isdigit(): + message = "Rate Value ({}) should be of type Integer." + extra_args = { + "actual_type": type(items[0]).__name__, + "expected_type": int.__name__, + } + return [RuleMatch(path, message.format(items[0]), **extra_args)] + + if float(items[0]) <= 0: + return [ + RuleMatch(path, f"Rate Value {items[0]!r} should be greater than 0.") + ] + + if float(items[0]) <= 1: + valid_periods = ["minute", "hour", "day"] + elif float(items[0]) > 1: + valid_periods = ["minutes", "hours", "days"] + # Check the Unit + if items[1] not in valid_periods: + return [ + RuleMatch( + path, f"Rate Unit {items[1]!r} should be one of {valid_periods!r}." + ) + ] - return matches + return [] def check_cron(self, value, path): """Check Cron configuration"""
diff --git a/test/fixtures/templates/bad/resources/events/rule_schedule_expression.yaml b/test/fixtures/templates/bad/resources/events/rule_schedule_expression.yaml --- a/test/fixtures/templates/bad/resources/events/rule_schedule_expression.yaml +++ b/test/fixtures/templates/bad/resources/events/rule_schedule_expression.yaml @@ -33,3 +33,15 @@ Resources: Type: AWS::Events::Rule Properties: ScheduleExpression: "cron(* 1 * * * *)" # specify the Day-of-month and Day-of-week fields in the same cron expression + MyScheduledRule9: + Type: AWS::Events::Rule + Properties: + ScheduleExpression: "rate(1 minutes)" # Value of 1 should be singular. 'minute' not 'minutes' + MyScheduledRule10: + Type: AWS::Events::Rule + Properties: + ScheduleExpression: "rate(2 hour)" # Value of 2 should be plural. 'hours' not `hour` + MyScheduledRule11: + Type: AWS::Events::Rule + Properties: + ScheduleExpression: "rate(0 hour)" # Value has to be greater than 0 diff --git a/test/unit/rules/resources/events/test_rule_schedule_expression.py b/test/unit/rules/resources/events/test_rule_schedule_expression.py --- a/test/unit/rules/resources/events/test_rule_schedule_expression.py +++ b/test/unit/rules/resources/events/test_rule_schedule_expression.py @@ -28,5 +28,5 @@ def test_file_negative_alias(self): """Test failure""" self.helper_file_negative( "test/fixtures/templates/bad/resources/events/rule_schedule_expression.yaml", - 8, + 11, )
Doesn't catch invalid `rate(1 hours)` *cfn-lint version: (`cfn-lint --version`)* 0.44.7 *Description of issue.* cfn-lint doesn't recognize that this ScheduledExpression is invalid (should be `rate(1 hour)`) ```yaml ExampleRule: Type: AWS::Events::Rule Properties: Description: desc Name: name ScheduleExpression: rate(1 hours) State: ENABLED ``` But when building the cloudformation, I get the following error: ``` Parameter ScheduleExpression is not valid. (Service: AmazonCloudWatchEvents; Status Code: 400; Error Code: ValidationException; Request ID: ...; Proxy: null) ``` I saw #816, but since this is a `rate` issue, not a `cron` issue, I thought I should open a new ticket
2024-01-18T18:47:57Z
[]
[]
aws-cloudformation/cfn-lint
3,060
aws-cloudformation__cfn-lint-3060
[ "3047" ]
7cabf206313e8b1b0e46eaa0e1d1af1b1b6ad318
diff --git a/src/cfnlint/rules/resources/properties/PropertiesTemplated.py b/src/cfnlint/rules/resources/properties/PropertiesTemplated.py --- a/src/cfnlint/rules/resources/properties/PropertiesTemplated.py +++ b/src/cfnlint/rules/resources/properties/PropertiesTemplated.py @@ -60,6 +60,9 @@ def match_resource_properties(self, properties, resourcetype, path, cfn): """Check CloudFormation Properties""" matches = [] + if cfn.has_serverless_transform(): + return [] + for key in self.templated_exceptions.get(resourcetype, []): matches.extend( cfn.check_value( diff --git a/src/cfnlint/template/template.py b/src/cfnlint/template/template.py --- a/src/cfnlint/template/template.py +++ b/src/cfnlint/template/template.py @@ -94,9 +94,6 @@ def build_graph(self): def has_language_extensions_transform(self): """Check if the template has language extensions transform declared""" - LOGGER.debug( - "Check if the template has language extensions transform declaration" - ) lang_extensions_transform = "AWS::LanguageExtensions" transform_declaration = self.transform_pre["Transform"] transform_type = ( @@ -106,6 +103,17 @@ def has_language_extensions_transform(self): ) return bool(lang_extensions_transform in transform_type) + def has_serverless_transform(self): + """Check if the template has SAM transform declared""" + lang_extensions_transform = "AWS::Serverless-2016-10-31" + transform_declaration = self.transform_pre["Transform"] + transform_type = ( + transform_declaration + if isinstance(transform_declaration, list) + else [transform_declaration] + ) + return bool(lang_extensions_transform in transform_type) + def get_resources(self, resource_type=[]): """ Get Resources
diff --git a/test/fixtures/templates/good/resources/properties/templated_code_sam.yaml b/test/fixtures/templates/good/resources/properties/templated_code_sam.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/resources/properties/templated_code_sam.yaml @@ -0,0 +1,6 @@ +Transform: AWS::Serverless-2016-10-31 +Resources: + Function: + Type: AWS::Serverless::Application + Properties: + Location: path/ diff --git a/test/unit/rules/resources/properties/test_properties_templated.py b/test/unit/rules/resources/properties/test_properties_templated.py --- a/test/unit/rules/resources/properties/test_properties_templated.py +++ b/test/unit/rules/resources/properties/test_properties_templated.py @@ -18,7 +18,8 @@ def setUp(self): super(TestPropertiesTemplated, self).setUp() self.collection.register(PropertiesTemplated()) self.success_templates = [ - "test/fixtures/templates/good/resources/properties/templated_code.yaml" + "test/fixtures/templates/good/resources/properties/templated_code.yaml", + "test/fixtures/templates/good/resources/properties/templated_code_sam.yaml", ] def test_file_positive(self):
Support SAM `AWS::Serverless::Application` without triggering W3002 ### Is this feature request related to a new rule or cfn-lint capabilities? rules, New capability ### Describe the feature you'd like to request This is similar to https://github.com/aws-cloudformation/cfn-lint/issues/2297. When using a SAM template and creating a resource of type `AWS::Serverless::Application`, the string placed in the [location](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-application.html#sam-application-location) property is allowed to be a local file. This _does_ necessitate the use of `sam deploy` or `sam package` (documented in the SAM spec), but that is the intended workflow. Is there a way to get cfn-lint to natively (without ignores) support this workflow? Or is this working as intended and the correct solution is to just ignore that check (W3002) on that resource? ### Describe the solution you'd like cfn-lint should fully validate resources of type `AWS::Serverless::Application` with a local file in the `Location` property without ignores. ### Additional context _No response_ ### Is this something that you'd be interested in working on? - [X] 👋 I may be able to implement this feature request ### Would this feature include a breaking change? - [ ] ⚠️ This feature might incur a breaking change
2024-02-16T16:18:53Z
[]
[]
aws-cloudformation/cfn-lint
3,061
aws-cloudformation__cfn-lint-3061
[ "2622" ]
33983345c7eee06dd04e945ceac6112ae9cc5279
diff --git a/src/cfnlint/template/template.py b/src/cfnlint/template/template.py --- a/src/cfnlint/template/template.py +++ b/src/cfnlint/template/template.py @@ -7,7 +7,7 @@ import logging from copy import deepcopy -from typing import List, Union +from typing import Any, Dict, List, Union import regex as re @@ -20,6 +20,94 @@ LOGGER = logging.getLogger(__name__) +def resolve_pointer(obj, pointer) -> Dict: + """Find the elements at the end of a Cfn pointer + + Args: + obj (dict): the root schema used for searching for the pointer + pointer (str): the pointer using / to separate levels + Returns: + Dict: returns the object from the pointer + """ + json_pointer = _SchemaPointer(obj, pointer) + return json_pointer.resolve() + + +class _SchemaPointer: + def __init__(self, obj: dict, pointer: str) -> None: + self.obj = obj + self.parts = pointer.split("/")[1:] + + def resolve(self) -> Dict: + """Find the elements at the end of a Cfn pointer + + Args: + Returns: + Dict: returns the object from the pointer + """ + obj = self.obj + for part in self.parts: + try: + obj = self.walk(obj, part) + except KeyError as e: + raise e + + if "*" in self.parts: + return {"type": "array", "items": obj} + + return obj + + # pylint: disable=too-many-return-statements + def walk(self, obj: Dict, part: str) -> Any: + """Walks one step in doc and returns the referenced part + + Args: + obj (dict): the object to evaluate for the part + part (str): the string representation of the part + Returns: + Dict: returns the object at the part + """ + assert hasattr(obj, "__getitem__"), f"invalid document type {type(obj)}" + + try: + # using a test for typeName as that is a root schema property + if part == "properties" and obj.get("typeName"): + return obj[part] + if ( + obj.get("properties") + and part != "definitions" + and not obj.get("typeName") + ): + return obj["properties"][part] + # arrays have a * in the path + if part == "*" and obj.get("type") == "array": + return obj.get("items") + return obj[part] + + except KeyError as e: + # CFN JSON pointers can go down $ref paths so lets do that if we can + if obj.get("$ref"): + try: + return resolve_pointer(self.obj, f"{obj.get('$ref')}/{part}") + except KeyError as ke: + raise ke + if obj.get("items", {}).get("$ref"): + ref = obj.get("items", {}).get("$ref") + try: + return resolve_pointer(self.obj, f"{ref}/{part}") + except KeyError as ke: + raise ke + if obj.get("oneOf"): + for oneOf in obj.get("oneOf"): # type: ignore + try: + return self.walk(oneOf, part) + except KeyError: + pass + + raise KeyError(f"No oneOf matches for {part}") from e + raise e + + class Template: # pylint: disable=R0904,too-many-lines,too-many-instance-attributes """Class for a CloudFormation template""" @@ -246,6 +334,7 @@ def get_valid_refs(self): results[pseudoparam] = element return results + # pylint: disable=too-many-locals def get_valid_getatts(self): resourcetypes = cfnlint.helpers.RESOURCE_SPECS["us-east-1"].get("ResourceTypes") propertytypes = cfnlint.helpers.RESOURCE_SPECS["us-east-1"].get("PropertyTypes") @@ -314,6 +403,44 @@ def build_output_string(resource_type, property_name): element = {} element.update(attvalue) results[name][attname] = element + for schema in cfnlint.helpers.REGISTRY_SCHEMAS: + if value["Type"] == schema["typeName"]: + results[name] = {} + for ro_property in schema["readOnlyProperties"]: + try: + item = resolve_pointer(schema, ro_property) + except KeyError: + continue + item_type = item["type"] + _type = None + primitive_type = None + if item_type == "string": + primitive_type = "String" + elif item_type == "number": + primitive_type = "Double" + elif item_type == "integer": + primitive_type = "Integer" + elif item_type == "boolean": + primitive_type = "Boolean" + elif item_type == "array": + _type = "List" + primitive_type = "String" + + ro_property = ro_property.replace( + "/properties/", "" + ) + results[name][".".join(ro_property.split("/"))] = {} + if _type: + results[name][".".join(ro_property.split("/"))][ + "Type" + ] = _type + results[name][".".join(ro_property.split("/"))][ + "PrimitiveItemType" + ] = primitive_type + elif primitive_type: + results[name][".".join(ro_property.split("/"))][ + "PrimitiveType" + ] = primitive_type return results
diff --git a/test/fixtures/registry/custom/resource.json b/test/fixtures/registry/custom/resource.json new file mode 100644 --- /dev/null +++ b/test/fixtures/registry/custom/resource.json @@ -0,0 +1,138 @@ +{ + "typeName": "Initech::TPS::Report", + "description": "An example resource schema demonstrating some basic constructs and validation rules.", + "sourceUrl": "https://github.com/aws-cloudformation/aws-cloudformation-rpdk.git", + "definitions": { + "InitechDateFormat": { + "$comment": "Use the `definitions` block to provide shared resource property schemas", + "type": "string", + "format": "date-time" + }, + "Memo": { + "type": "object", + "properties": { + "Heading": { + "type": "string" + }, + "Body": { + "type": "string" + } + }, + "additionalProperties": false + }, + "Tag": { + "description": "A key-value pair to associate with a resource.", + "type": "object", + "properties": { + "Key": { + "type": "string", + "description": "The key name of the tag. You can specify a value that is 1 to 128 Unicode characters in length and cannot be prefixed with aws:. You can use any of the following characters: the set of Unicode letters, digits, whitespace, _, ., /, =, +, and -.", + "minLength": 1, + "maxLength": 128 + }, + "Value": { + "type": "string", + "description": "The value for the tag. You can specify a value that is 0 to 256 Unicode characters in length and cannot be prefixed with aws:. You can use any of the following characters: the set of Unicode letters, digits, whitespace, _, ., /, =, +, and -.", + "minLength": 0, + "maxLength": 256 + } + }, + "required": [ + "Key", + "Value" + ], + "additionalProperties": false + } + }, + "properties": { + "TPSCode": { + "description": "A TPS Code is automatically generated on creation and assigned as the unique identifier.", + "type": "string", + "pattern": "^[A-Z]{3,5}[0-9]{8}-[0-9]{4}$" + }, + "Title": { + "description": "The title of the TPS report is a mandatory element.", + "type": "string", + "minLength": 20, + "maxLength": 250 + }, + "CoverSheetIncluded": { + "description": "Required for all TPS Reports submitted after 2/19/1999", + "type": "boolean" + }, + "DueDate": { + "$ref": "#/definitions/InitechDateFormat" + }, + "ApprovalDate": { + "$ref": "#/definitions/InitechDateFormat" + }, + "Memo": { + "$ref": "#/definitions/Memo" + }, + "SecondCopyOfMemo": { + "description": "In case you didn't get the first one.", + "$ref": "#/definitions/Memo" + }, + "TestCode": { + "type": "string", + "enum": [ + "NOT_STARTED", + "CANCELLED" + ] + }, + "Authors": { + "type": "array", + "items": { + "type": "string" + } + }, + "Tags": { + "description": "An array of key-value pairs to apply to this resource.", + "type": "array", + "uniqueItems": true, + "insertionOrder": false, + "items": { + "$ref": "#/definitions/Tag" + } + } + }, + "additionalProperties": false, + "required": [ + "TestCode", + "Title" + ], + "readOnlyProperties": [ + "/properties/TPSCode", + "/properties/Authors" + ], + "primaryIdentifier": [ + "/properties/TPSCode" + ], + "handlers": { + "create": { + "permissions": [ + "initech:CreateReport" + ] + }, + "read": { + "permissions": [ + "initech:DescribeReport" + ] + }, + "update": { + "permissions": [ + "initech:UpdateReport" + ] + }, + "delete": { + "permissions": [ + "initech:DeleteReport" + ] + }, + "list": { + "permissions": [ + "initech:ListReports" + ] + } + } +} diff --git a/test/fixtures/templates/good/schema_resource.yaml b/test/fixtures/templates/good/schema_resource.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/good/schema_resource.yaml @@ -0,0 +1,9 @@ +Resources: + MyReport: + Type: Initech::TPS::Report + Properties: + TestCode: NOT_STARTED + Title: My report has to be longer +Outputs: + TpsCode: + Value: !GetAtt MyReport.TPSCode diff --git a/test/unit/module/test_template.py b/test/unit/module/test_template.py --- a/test/unit/module/test_template.py +++ b/test/unit/module/test_template.py @@ -6,8 +6,10 @@ import json import os from test.testlib.testcase import BaseTestCase +from unittest.mock import patch from cfnlint.decode import cfn_yaml, convert_dict +from cfnlint.helpers import REGISTRY_SCHEMAS from cfnlint.template import Template # pylint: disable=E0401 @@ -1233,3 +1235,22 @@ def test_get_directives(self): "I1001": ["myBucket1"], } self.assertDictEqual(directives, expected_result) + + def test_schemas(self): + """Validate getAtt when using a registry schema""" + schema = self.load_template("test/fixtures/registry/custom/resource.json") + + filename = "test/fixtures/templates/good/schema_resource.yaml" + template = self.load_template(filename) + self.template = Template(filename, template) + + with patch("cfnlint.helpers.REGISTRY_SCHEMAS", [schema]): + self.assertDictEqual( + { + "MyReport": { + "TPSCode": {"PrimitiveType": "String"}, + "Authors": {"PrimitiveItemType": "String", "Type": "List"}, + } + }, + self.template.get_valid_getatts(), + )
CloudFormation Registry resource support - GetAtt rules broken ### CloudFormation Lint Version cfn-lint 0.73.1 ### What operating system are you using? Mac ### Describe the bug Currently the `-s` switch brings in the schemas for custom resource extensions. This allow some cfn-lint rules to work but not all. As soon as `!GetAtt` rules are evaluated they start breaking. For example, [E1010](https://github.com/aws-cloudformation/cfn-lint/blob/1d5c4de28c18a6d2a4d5d72f48d28434f1b0bc8e/src/cfnlint/rules/functions/GetAtt.py), breaks with a custom resource. I have added logging locally and diagnosed it down to [this line](https://github.com/aws-cloudformation/cfn-lint/blob/1d5c4de28c18a6d2a4d5d72f48d28434f1b0bc8e/src/cfnlint/template.py#L225) being the issue causing GetAtt to fail. Furthermore, the real issue is `cfnlint.helpers.RESOURCE_SPECS` is using [these](https://d1uauaxba7bl26.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json) to determine which parameters are valid. Realistically, if we want to support this in pre-v1, the right answer is to find a way to combine the schemas and `CloudFormationResourceSpecification` as a source of truth for specifications so the rules get the right models. However in practice this might be difficult. @kddejong asked me to open via discord ### Expected behavior All cfn-lint rules work with CloudFormation Registry resource custom extensions. ### Reproduction template I dont have any public extensions I can share. So cannot easily provide a YAML here that is usable by someone else. With that said, this snippit here shows the problem: ```yaml IDPGroup: Type: xxxxx::AzureAD::Group Properties: GroupName: "mycustomgroup" GroupType: SECURITY Owners: - OwnerType: USER Name: !Ref OwnerEmail CredentialAppClientId: !Ref IDPAutoAppClientId CredentialAppAPIToken: !Ref IDPAutoAppAPIToken CredentialTenantId: !Ref IDPTenantId GroupAssignment: Type: xxxxx::AzureAD::GroupAssignment Properties: GroupId: !GetAtt IDPGroup.GroupId AppName: !Ref IDPAppName CredentialAppClientId: !Ref IDPAutoAppClientId CredentialAppAPIToken: !Ref IDPAutoAppAPIToken CredentialTenantId: !Ref IDPTenantId AppRoleName: "User" ```
Is there any update on this issue? Having similar issues with GetAtt.
2024-02-16T19:01:44Z
[]
[]
aws-cloudformation/cfn-lint
3,073
aws-cloudformation__cfn-lint-3073
[ "3067" ]
4a3dd987bdbd5c35113ab5b88f48fbfd9cd506dd
diff --git a/src/cfnlint/decode/cfn_yaml.py b/src/cfnlint/decode/cfn_yaml.py --- a/src/cfnlint/decode/cfn_yaml.py +++ b/src/cfnlint/decode/cfn_yaml.py @@ -88,6 +88,19 @@ def construct_yaml_map(self, node): key = self.construct_object(key_node, False) value = self.construct_object(value_node, False) + if key is None: + raise CfnParseError( + self.filename, + [ + build_match( + filename=self.filename, + message=f"Null key {key_node.value!r} not supported (line {key_node.start_mark.line + 1})", + line_number=key_node.start_mark.line, + column_number=key_node.start_mark.column, + key=key_node.value, + ), + ], + ) for key_dup in mapping: if key_dup == key: if not matches:
diff --git a/test/unit/module/decode/test_decode.py b/test/unit/module/decode/test_decode.py --- a/test/unit/module/decode/test_decode.py +++ b/test/unit/module/decode/test_decode.py @@ -11,7 +11,9 @@ import yaml from yaml.scanner import ScannerError -import cfnlint.decode.decode # pylint: disable=E0401 +import cfnlint.decode.cfn_json +import cfnlint.decode.cfn_yaml +import cfnlint.decode.decode class TestDecode(BaseTestCase): @@ -125,3 +127,14 @@ def test_decode_yaml_error(self, mock_cfn_yaml): self.assertEqual(len(matches), 1) self.assertEqual(matches[0].rule.id, "E0000") self.assertEqual(matches[0].message, err_msg) + + def test_decode_yaml_null_key(self): + err_msg = "Null key 'null' not supported (line 3)" + with self.assertRaises(cfnlint.decode.cfn_yaml.CfnParseError) as e: + cfnlint.decode.cfn_yaml.loads( + """ + Parameters: + null: test + """ + ) + self.assertEqual(str(e.exception), err_msg) diff --git a/test/unit/module/decode/test_nod_sub.py b/test/unit/module/decode/test_node_sub.py similarity index 100% rename from test/unit/module/decode/test_nod_sub.py rename to test/unit/module/decode/test_node_sub.py
"null" as Parameter Name Throws Incorrect Error ### CloudFormation Lint Version 0.85.2_1 ### What operating system are you using? Mac ### Describe the bug Setting a Parameter name to "null" produces incorrect or misleading errors: "E0002 Unknown exception while processing rule E2011: object of type 'NoneType' has no len()" "E0002 Unknown exception while processing rule E2003: expected string or buffer" (further, the document line reference is 1:1; which is not correct) The Cloudformation service itself returns the following more specific error message: "Template format error: [/Parameters] encountered malformed key" ### Expected behavior cfn-lint returns correct line number and a more accurate error message, such as: "E000X Parameters encountered malformed key" ### Reproduction template ```yaml AWSTemplateFormatVersion: 2010-09-09 Parameters: null: Description: anything Type: String #... ```
2024-02-23T22:10:28Z
[]
[]
aws-cloudformation/cfn-lint
3,131
aws-cloudformation__cfn-lint-3131
[ "3130" ]
8d1343be8303e65d42d51841c5c7071eb6d4cc54
diff --git a/src/cfnlint/template/transforms/_language_extensions.py b/src/cfnlint/template/transforms/_language_extensions.py --- a/src/cfnlint/template/transforms/_language_extensions.py +++ b/src/cfnlint/template/transforms/_language_extensions.py @@ -156,7 +156,7 @@ def _walk(self, item: Any, params: MutableMapping[str, Any], cfn: Any): elif k == "Fn::FindInMap": try: mapping = _ForEachValueFnFindInMap(get_hash(v), v) - map_value = mapping.value(cfn, params, True) + map_value = mapping.value(cfn, params, True, False) # if we get None this means its all strings but couldn't be resolved # we will pass this forward if map_value is None: @@ -298,6 +298,7 @@ def value( cfn: Any, params: Optional[Mapping[str, Any]] = None, only_params: bool = False, + default_on_resolver_failure: bool = True, ) -> Any: if params is None: params = {} @@ -361,11 +362,11 @@ def value( t_map[2].value(cfn, params, only_params) ) except _ResolveError as e: - if len(self._map) == 4: + if len(self._map) == 4 and default_on_resolver_failure: return self._map[3].value(cfn, params, only_params) raise _ResolveError("Can't resolve Fn::FindInMap", self._obj) from e - if len(self._map) == 4: + if len(self._map) == 4 and default_on_resolver_failure: return self._map[3].value(cfn, params, only_params) raise _ResolveError("Can't resolve Fn::FindInMap", self._obj)
diff --git a/test/unit/module/template/transforms/test_language_extensions.py b/test/unit/module/template/transforms/test_language_extensions.py --- a/test/unit/module/template/transforms/test_language_extensions.py +++ b/test/unit/module/template/transforms/test_language_extensions.py @@ -182,6 +182,32 @@ def test_bad_mappings(self): with self.assertRaises(_ValueError): _ForEachValueFnFindInMap("", ["foo"]) + def test_find_in_map_values_with_default(self): + map = _ForEachValueFnFindInMap( + "a", ["Bucket", {"Ref": "Foo"}, "Key", {"DefaultValue": "bar"}] + ) + + self.assertEqual(map.value(self.cfn, None, False, True), "bar") + with self.assertRaises(_ResolveError): + map.value(self.cfn, None, False, False) + + def test_find_in_map_values_without_default(self): + map = _ForEachValueFnFindInMap("a", ["Bucket", {"Ref": "Foo"}, "Key"]) + + with self.assertRaises(_ResolveError): + self.assertEqual(map.value(self.cfn, None, False, True), "bar") + with self.assertRaises(_ResolveError): + map.value(self.cfn, None, False, False) + + def test_mapping_not_found(self): + map = _ForEachValueFnFindInMap( + "a", ["Foo", {"Ref": "Foo"}, "Key", {"DefaultValue": "bar"}] + ) + + self.assertEqual(map.value(self.cfn, None, False, True), "bar") + with self.assertRaises(_ResolveError): + map.value(self.cfn, None, False, False) + def test_two_mappings(self): template_obj = deepcopy(self.template_obj) template_obj["Mappings"]["Foo"] = {"Bar": {"Key": ["a", "b"]}}
W8003 False positive ### CloudFormation Lint Version 0.86.0 ### What operating system are you using? mac ### Describe the bug lint raises a W8003 for the below template, but I don't think it's true that it will always return True or False. It checks whether the value obtained from the mapping for the specified environment (!Ref Env) matches the string "No retention". If it does, then the condition evaluates to false, and if it doesn't, it evaluates to true. ### Expected behavior W8003 isn't raised ### Reproduction template ``` Mappings: dwS3BucketEnvironmentConfigMap: # Create an entry for each environment prod: BucketName: 'digital-workspace-v2-prod' DeletionPolicy: Delete hotfix: BucketName: 'digital-workspace-v2-hotfix' DeletionPolicy: Delete staging: BucketName: 'digital-workspace-v2-staging' DeletionPolicy: Delete training: BucketName: 'digital-workspace-v2-training' DeletionPolicy: Delete dev: BucketName: 'digital-workspace-v2-dev' DeletionPolicy: Delete Conditions: dwS3BucketApplyRetentionPolicy: !Not - !Equals - !FindInMap - dwS3BucketEnvironmentConfigMap - !Ref Env - RetentionMode - DefaultValue: No retention - No retention dwS3BucketRetentionPolicyDurationIsInDays: !Equals - !FindInMap - dwS3BucketEnvironmentConfigMap - !Ref Env - RetentionDurationType - DefaultValue: Days - Days ```
2024-04-03T17:37:12Z
[]
[]
aws-cloudformation/cfn-lint
3,169
aws-cloudformation__cfn-lint-3169
[ "3168" ]
fb55eeee02581aaaf40c9a7b87880c6db4a97aaa
diff --git a/src/cfnlint/rules/conditions/Configuration.py b/src/cfnlint/rules/conditions/Configuration.py --- a/src/cfnlint/rules/conditions/Configuration.py +++ b/src/cfnlint/rules/conditions/Configuration.py @@ -26,8 +26,10 @@ class Configuration(CloudFormationLintRule): def match(self, cfn): matches = [] - conditions = cfn.template.get("Conditions", {}) - if conditions: + if "Conditions" not in cfn.template: + return matches + conditions = cfn.template.get("Conditions", None) + if isinstance(conditions, dict): for condname, condobj in conditions.items(): if not isinstance(condobj, dict): message = "Condition {0} has invalid property" @@ -52,5 +54,12 @@ def match(self, cfn): message.format(condname, k), ) ) + else: + matches.append( + RuleMatch( + ["Conditions"], + "Condition must be an object", + ) + ) return matches
diff --git a/test/fixtures/templates/bad/conditions_type.yaml b/test/fixtures/templates/bad/conditions_type.yaml new file mode 100644 --- /dev/null +++ b/test/fixtures/templates/bad/conditions_type.yaml @@ -0,0 +1,8 @@ +AWSTemplateFormatVersion: "2010-09-09" +Conditions: +Resources: + myTopic: + Type: AWS::SNS::Topic + Properties: + DisplayName: mytopic + TopicName: mytopic diff --git a/test/unit/rules/conditions/test_configuration.py b/test/unit/rules/conditions/test_configuration.py --- a/test/unit/rules/conditions/test_configuration.py +++ b/test/unit/rules/conditions/test_configuration.py @@ -22,6 +22,10 @@ def test_file_positive(self): """Test Positive""" self.helper_file_positive() + def test_file_negative_type(self): + """Test failure""" + self.helper_file_negative("test/fixtures/templates/bad/conditions_type.yaml", 1) + def test_file_negative(self): """Test failure""" self.helper_file_negative("test/fixtures/templates/bad/conditions.yaml", 4)
Condition Specified but with no condition passes linting but fails deploy ### CloudFormation Lint Version 0.83.1 ### What operating system are you using? mac/ubuntu ### Describe the bug in a cfn template if you specify root level item `Conditions` but have no conditions this passes cfn-lint but always fails on deploy ### Expected behavior cfn-lint should fail if there is a Conditions root level object but no array entries under it. ### Reproduction template ``` AWSTemplateFormatVersion: "2010-09-09" Parameters: myParam Conditions: Resources: myTopic: Type: AWS::SNS::Topic Properties: DisplayName: mytopic TopicName: mytopic ```
This breaks pretty hard in v1 but yea we are missing some extra logic here in v0. Probably an unfortunate change to allowing null values and not building up some of the other logic.
2024-04-24T22:09:25Z
[]
[]
aws-cloudformation/cfn-lint
3,176
aws-cloudformation__cfn-lint-3176
[ "3174" ]
691836389149bc0047b4216c0022d17356321239
diff --git a/src/cfnlint/decode/node.py b/src/cfnlint/decode/node.py --- a/src/cfnlint/decode/node.py +++ b/src/cfnlint/decode/node.py @@ -76,7 +76,6 @@ class node_class(cls): def __init__( self, x, start_mark: Mark | None = None, end_mark: Mark | None = None ): - LOGGER.debug(type(start_mark)) try: cls.__init__(self, x) except TypeError: diff --git a/src/cfnlint/template/transforms/_language_extensions.py b/src/cfnlint/template/transforms/_language_extensions.py --- a/src/cfnlint/template/transforms/_language_extensions.py +++ b/src/cfnlint/template/transforms/_language_extensions.py @@ -5,6 +5,8 @@ from __future__ import annotations +import hashlib +import json import logging import random import string @@ -193,7 +195,9 @@ def _walk(self, item: Any, params: MutableMapping[str, Any], cfn: Any): return obj def _replace_string_params( - self, s: str, params: Mapping[str, Any] + self, + s: str, + params: Mapping[str, Any], ) -> Tuple[bool, str]: pattern = r"(\$|&){[a-zA-Z0-9\.:]+}" if not re.search(pattern, s): @@ -201,6 +205,8 @@ def _replace_string_params( new_s = deepcopy(s) for k, v in params.items(): + if isinstance(v, dict): + v = hashlib.md5(json.dumps(v).encode("utf-8")).digest().hex()[0:4] new_s = re.sub(rf"\$\{{{k}\}}", v, new_s) new_s = re.sub(rf"\&\{{{k}\}}", re.sub("[^0-9a-zA-Z]+", "", v), new_s) @@ -453,6 +459,9 @@ def value( return [x.strip() for x in allowed_values[0].split(",")] return allowed_values[0] + if "List" in t: + return [{"Fn::Select": [0, {"Ref": v}]}, {"Fn::Select": [1, {"Ref": v}]}] + raise _ResolveError("Can't resolve Fn::Ref", self._obj) @@ -490,7 +499,7 @@ def values( if values: if isinstance(values, list): for value in values: - if isinstance(value, str): + if isinstance(value, (str, dict)): yield value else: raise _ValueError(
diff --git a/test/unit/module/template/transforms/test_language_extensions.py b/test/unit/module/template/transforms/test_language_extensions.py --- a/test/unit/module/template/transforms/test_language_extensions.py +++ b/test/unit/module/template/transforms/test_language_extensions.py @@ -10,9 +10,9 @@ from cfnlint.template import Template from cfnlint.template.transforms._language_extensions import ( _ForEach, + _ForEachCollection, _ForEachValue, _ForEachValueFnFindInMap, - _ForEachValueRef, _ResolveError, _Transform, _TypeError, @@ -27,6 +27,7 @@ def test_valid(self): _ForEach( "key", [{"Ref": "Parameter"}, {"Ref": "AWS::NotificationArns"}, {}], {} ) + _ForEach("key", ["AccountId", {"Ref": "AccountIds"}, {}], {}) def test_wrong_type(self): with self.assertRaises(_TypeError): @@ -54,6 +55,32 @@ def test_output_type(self): _ForEach("key", ["foo", ["bar"], []], {}) +class TestForEach(TestCase): + def setUp(self) -> None: + super().setUp() + self.cfn = Template( + "", + { + "Parameters": { + "AccountIds": { + "Type": "CommaDelimitedList", + }, + }, + }, + regions=["us-west-2"], + ) + + def test_valid(self): + fec = _ForEachCollection({"Ref": "AccountIds"}) + self.assertListEqual( + list(fec.values(self.cfn, {})), + [ + {"Fn::Select": [0, {"Ref": "AccountIds"}]}, + {"Fn::Select": [1, {"Ref": "AccountIds"}]}, + ], + ) + + class TestRef(TestCase): def setUp(self) -> None: self.template_obj = convert_dict( @@ -75,6 +102,9 @@ def setUp(self) -> None: "Type": "List<AWS::EC2::Subnet::Id>", "AllowedValues": ["sg-12345678, sg-87654321"], }, + "AccountIds": { + "Type": "CommaDelimitedList", + }, }, } ) @@ -115,6 +145,15 @@ def test_ref(self): fe = _ForEachValue.create({"Ref": "SecurityGroups"}) self.assertEqual(fe.value(self.cfn), ["sg-12345678", "sg-87654321"]) + fe = _ForEachValue.create({"Ref": "AccountIds"}) + self.assertEqual( + fe.value(self.cfn), + [ + {"Fn::Select": [0, {"Ref": "AccountIds"}]}, + {"Fn::Select": [1, {"Ref": "AccountIds"}]}, + ], + ) + class TestFindInMap(TestCase): def setUp(self) -> None: @@ -416,6 +455,76 @@ def test_transform_findinmap_function(self): result, ) + def test_transform_list_parameter(self): + template_obj = deepcopy(self.template_obj) + parameters = {"AccountIds": {"Type": "CommaDelimitedList"}} + template_obj["Parameters"] = parameters + + nested_set( + template_obj, + [ + "Resources", + "Fn::ForEach::SpecialCharacters", + 1, + ], + {"Ref": "AccountIds"}, + ) + nested_set( + template_obj, + [ + "Resources", + "Fn::ForEach::SpecialCharacters", + 2, + ], + { + "S3Bucket&{Identifier}": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": {"Ref": "Identifier"}, + "Tags": [ + {"Key": "Name", "Value": {"Fn::Sub": "Name-${Identifier}"}}, + ], + }, + } + }, + ) + cfn = Template(filename="", template=template_obj, regions=["us-east-1"]) + matches, template = language_extension(cfn) + self.assertListEqual(matches, []) + + result = deepcopy(self.result) + result["Parameters"] = parameters + result["Resources"]["S3Bucket5096"] = { + "Properties": { + "BucketName": {"Fn::Select": [1, {"Ref": "AccountIds"}]}, + "Tags": [ + { + "Key": "Name", + "Value": "Name-5096", + }, + ], + }, + "Type": "AWS::S3::Bucket", + } + result["Resources"]["S3Bucketa72a"] = { + "Properties": { + "BucketName": {"Fn::Select": [0, {"Ref": "AccountIds"}]}, + "Tags": [ + { + "Key": "Name", + "Value": "Name-a72a", + }, + ], + }, + "Type": "AWS::S3::Bucket", + } + del result["Resources"]["S3Bucketab"] + del result["Resources"]["S3Bucketcd"] + self.assertDictEqual( + template, + result, + ) + def test_bad_collection_ref(self): template_obj = deepcopy(self.template_obj) nested_set(
Validaton error for `Fn::ForEach` - `contains invalid characters` ### CloudFormation Lint Version cfn-lint 0.86.4 ### What operating system are you using? Ubuntu ### Describe the bug I am getting false validation errors when using `Fn::ForEach` : ``` E3031 TargetId contains invalid characters (Pattern: \d{12}) at Resources/SystemAdminAssignmentCFcfhIH/Properties/TargetId ``` I am not 100% this is a bug since I am not able (at least not that I am aware of) set a type for the values. I wasn't able to locate how to define values for this test. This would explain the issue as I am seeing it using `CFcfhIH` as the value when this should be an id. Perhaps I am missing something? ### Expected behavior I expected this to not throw a validation error. I have this same issue in all templates that use `Fn::ForEach`. ### Reproduction template ```yaml AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::LanguageExtensions' Description: Configures IAM Identity Center. IAM Identity Center must be enabled before you create this stack. Parameters: IamIdentityCenterInstanceArn: Type: String Description: 'The ARN for the IAM Identity Center Instance. Found in the settings of IAM Identity Center.' IdentityStoreId: Type: String Description: 'The id for the identity store. Found in the settings of IAM Identity Center.' AccountIds: Description: Comma separated list of account ids Type: CommaDelimitedList Resources: SystemAdminPermissionSet: Type: AWS::SSO::PermissionSet Properties: InstanceArn: !Ref IamIdentityCenterInstanceArn Name: 'SystemAdmin' Description: 'System Admin Permissions' SessionDuration: 'PT8H' InlinePolicy: Version: '2012-10-17' Statement: - Effect: Allow Action: '*' Resource: '*' SystemAdminGroup: Type: AWS::IdentityStore::Group Properties: DisplayName: SystemAdmin Description: 'System Admin Group' IdentityStoreId: !Ref IdentityStoreId # Testing Account Assignments 'Fn::ForEach::TestingAssignments': - AccountId - !Ref AccountIds - 'SystemAdminAssignment${AccountId}': Type: 'AWS::SSO::Assignment' Properties: InstanceArn: !Ref IamIdentityCenterInstanceArn PermissionSetArn: !GetAtt SystemAdminPermissionSet.PermissionSetArn TargetId: !Ref AccountId TargetType: AWS_ACCOUNT PrincipalId: !GetAtt SystemAdminGroup.GroupId PrincipalType: GROUP ``` Note: I was able to bypass this by using: ```yaml 'Fn::ForEach::TestingAssignments': - AccountId - !Ref AccountIds - 'SystemAdminAssignment${AccountId}': Type: 'AWS::SSO::Assignment' Metadata: cfn-lint: config: ignore_checks: - E3031 Properties: InstanceArn: !Ref IamIdentityCenterInstanceArn PermissionSetArn: !GetAtt SystemAdminPermissionSet.PermissionSetArn TargetId: !Ref AccountId TargetType: AWS_ACCOUNT PrincipalId: !GetAtt SystemAdminGroup.GroupId PrincipalType: GROUP ``` This will work for now but ideally, I would like to be able to pass values for the parameters to be used for the linting.
I need to evaluate some options to resolve this. Thanks for reporting it.
2024-04-29T20:13:12Z
[]
[]
aws-cloudformation/cfn-lint
3,224
aws-cloudformation__cfn-lint-3224
[ "3223" ]
10b6a8b517c0e90ed825fc207982c67506fe8bf6
diff --git a/src/cfnlint/rules/resources/properties/Properties.py b/src/cfnlint/rules/resources/properties/Properties.py --- a/src/cfnlint/rules/resources/properties/Properties.py +++ b/src/cfnlint/rules/resources/properties/Properties.py @@ -493,6 +493,26 @@ def propertycheck(self, text, proptype, parenttype, resourcename, path, root): message.format(prop, resourcename), ) ) + elif "Fn::GetAtt" in text[prop]: + getatt = text[prop]["Fn::GetAtt"] + if isinstance(getatt, str): + getatt = getatt.split(".", 1) + valid_getatts = self.cfn.get_valid_getatts() + if getatt[0] in valid_getatts: + if getatt[1] in valid_getatts[getatt[0]]: + getatt_prop = valid_getatts[getatt[0]][ + getatt[1] + ] + if getatt_prop.get("Type") != "List": + message = "Property {0} should be of type List for resource {1}" + matches.append( + RuleMatch( + proppath, + message.format( + prop, resourcename + ), + ) + ) else: if len(text[prop]) == 1: for k in text[prop].keys(): diff --git a/src/cfnlint/template/template.py b/src/cfnlint/template/template.py --- a/src/cfnlint/template/template.py +++ b/src/cfnlint/template/template.py @@ -423,16 +423,10 @@ def build_output_string(resource_type, property_name): valtype = value["Type"] if isinstance(valtype, str): if valtype.startswith(astrik_string_types): - LOGGER.debug( - "Cant build an appropriate getatt list from %s", valtype - ) results[name] = {"*": {"PrimitiveItemType": "String"}} elif valtype.startswith(astrik_unknown_types) or valtype.endswith( "::MODULE" ): - LOGGER.debug( - "Cant build an appropriate getatt list from %s", valtype - ) results[name] = {"*": {}} else: if value["Type"] in resourcetypes:
diff --git a/test/fixtures/templates/bad/object_should_be_list.yaml b/test/fixtures/templates/bad/object_should_be_list.yaml --- a/test/fixtures/templates/bad/object_should_be_list.yaml +++ b/test/fixtures/templates/bad/object_should_be_list.yaml @@ -677,3 +677,19 @@ Resources: - - AttributeName: !Ref PartitionKeyName KeyType: HASH - "String2" + EC2Instance: + Type: AWS::EC2::Instance + Properties: + InstanceType: t2.micro + ImageId: XXXXXXXXXXXXXXXXXXXXX + Tags: + - Key: Name + Value: !Ref AWS::StackName + SSMAssociation: + Type: AWS::SSM::Association + Properties: + Name: "SSM Document Name" + ScheduleExpression: rate(2 days) + Targets: + - Key: InstanceIds + Values: !GetAtt EC2Instance.InstanceId diff --git a/test/unit/rules/resources/properties/test_properties.py b/test/unit/rules/resources/properties/test_properties.py --- a/test/unit/rules/resources/properties/test_properties.py +++ b/test/unit/rules/resources/properties/test_properties.py @@ -37,7 +37,7 @@ def test_file_negative(self): def test_file_negative_2(self): """Failure test""" self.helper_file_negative( - "test/fixtures/templates/bad/object_should_be_list.yaml", 4 + "test/fixtures/templates/bad/object_should_be_list.yaml", 5 ) def test_file_negative_3(self):
[AWS::SSM::Association] - [BUG] - cfn-lint doesn't recognize `Values: expected type: JSONArray, found: String` ### CloudFormation Lint Version cfn-lint 0.87.1 ### What operating system are you using? Windows 11 ### Describe the bug cfn-lint doesn't recognize the following error message: ``` Resource handler returned message: "Model validation failed (#/Targets/0/Values: expected type: JSONArray, found: String)" (RequestToken: REQUESTTOKEN, HandlerErrorCode: InvalidRequest) ``` for the following example: ```yaml SSMAssociation: Type: AWS::SSM::Association Properties: Name: "SSM Document Name" ScheduleExpression: rate(2 days) Targets: - Key: InstanceIds Values: !GetAtt EC2Instance.InstanceId ``` This is how it should look like: ```yaml SSMAssociation: Type: AWS::SSM::Association Properties: Name: "SSM Document Name" ScheduleExpression: rate(2 days) Targets: - Key: InstanceIds Values: - !GetAtt EC2Instance.InstanceId ``` ### Expected behavior cfn-lint finds this error. ### Reproduction template See above.
Hmm, should be able to find this one. I wonder if we aren't handling JSON values well. I'll look into this. Already fixed in v1 but is a bug in v0.
2024-05-09T01:16:44Z
[]
[]