Repository: aws-cloudformation/cfn-lint

Issue:
W2507 "Security Group Id Parameter should of type" invalid for cross-account references
*cfn-lint version: (`cfn-lint --version`)*

cfn-lint 0.21.4

*Description of issue.*

The warning W2507 "Security Group Id Parameter should be of type [AWS::SSM::Parameter::Value<AWS::EC2::SecurityGroup::Id>, AWS::EC2::SecurityGroup::Id]" is appearing against my template, where I use parameters to take the IDs of Security Groups in other accounts.

These cross-account SG ID references work perfectly well in the SourceSecurityGroupId property of SecurityGroupIngress, when paired with a SourceSecurityGroupOwnerId.

The suggestion from the cfn-lint warning is to use the special parameter type for SG IDs, but this won't work as it will validate the input against the list of security groups in the *same* account.  Cross-account references will be rejected as invalid, even though they are completely valid when used in the actual resource properties.

I'm not sure what the proper solution is here, but in the worst case maybe we just have to concede the reality that "String" is a possible valid data type for security group IDs.




Discussion:
So this was an early rule.  I'm proposing we remove this rule, make it more lenient (accepting strings) with the spec patching definitions we have.  

The other part of this rule is it was written before we had `Info` level errors and I don't think we would have written this as a `Warning`.  Giving more credibility to just removing it.

Resolving patch:
diff --git a/src/cfnlint/rules/parameters/SecurityGroup.py b/src/cfnlint/rules/parameters/SecurityGroup.py
deleted file mode 100644
--- a/src/cfnlint/rules/parameters/SecurityGroup.py
+++ /dev/null
@@ -1,136 +0,0 @@
-"""
-  Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
-
-  Permission is hereby granted, free of charge, to any person obtaining a copy of this
-  software and associated documentation files (the "Software"), to deal in the Software
-  without restriction, including without limitation the rights to use, copy, modify,
-  merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
-  permit persons to whom the Software is furnished to do so.
-
-  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
-  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-"""
-from cfnlint import CloudFormationLintRule
-from cfnlint import RuleMatch
-
-
-class SecurityGroup(CloudFormationLintRule):
-
-    """Check if EC2 Security Group Ingress Properties"""
-    id = 'W2507'
-    shortdesc = 'Security Group Parameters are of correct type AWS::EC2::SecurityGroup::Id'
-    description = 'Check if a parameter is being used in a resource for Security ' \
-                  'Group.  If it is make sure it is of type AWS::EC2::SecurityGroup::Id'
-    source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html#parmtypes'
-    tags = ['parameters', 'securitygroup']
-
-    def __init__(self):
-        """Init"""
-        super(SecurityGroup, self).__init__()
-        resource_type_specs = [
-            'AWS::ElasticLoadBalancingV2::LoadBalancer',
-            'AWS::AutoScaling::LaunchConfiguration',
-            'AWS::ElasticLoadBalancingV2::LoadBalancer',
-            'AWS::EC2::Instance',
-            'AWS::ElastiCache::ReplicationGroup',
-            'AWS::DAX::Cluster',
-            'AWS::ElastiCache::ReplicationGroup',
-            'AWS::Glue::DevEndpoint',
-            'AWS::EC2::SecurityGroupIngress',
-        ]
-        property_type_specs = [
-            'AWS::EC2::LaunchTemplate.LaunchTemplateData',
-            'AWS::Elasticsearch::Domain.VPCOptions',
-            'AWS::Lambda::Function.VpcConfig',
-            'AWS::Batch::ComputeEnvironment.ComputeResources',
-            'AWS::CodeBuild::Project.VpcConfig',
-            'AWS::EC2::SecurityGroup.Ingress',
-        ]
-
-        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_sgid_ref(self, value, path, parameters, resources):
-        """Check ref for VPC"""
-        matches = []
-        if 'SourceSecurityGroupId' in path:
-            allowed_types = [
-                'AWS::SSM::Parameter::Value<AWS::EC2::SecurityGroup::Id>',
-                'AWS::EC2::SecurityGroup::Id'
-            ]
-        elif isinstance(path[-2], int):
-            allowed_types = [
-                'AWS::SSM::Parameter::Value<AWS::EC2::SecurityGroup::Id>',
-                'AWS::EC2::SecurityGroup::Id'
-            ]
-        else:
-            allowed_types = [
-                'AWS::SSM::Parameter::Value<List<AWS::EC2::SecurityGroup::Id>>',
-                'List<AWS::EC2::SecurityGroup::Id>'
-            ]
-
-        if value in parameters:
-            parameter_properties = parameters.get(value)
-            parameter_type = parameter_properties.get('Type')
-            if parameter_type not in allowed_types:
-                path_error = ['Parameters', value, 'Type']
-                message = 'Security Group Id 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 check(self, properties, resource_type, path, cfn):
-        """Check itself"""
-        matches = []
-
-        matches.extend(
-            cfn.check_value(
-                properties, 'SecurityGroupIds', path,
-                check_value=None, check_ref=self.check_sgid_ref,
-                check_find_in_map=None, check_split=None, check_join=None
-            )
-        )
-        matches.extend(
-            cfn.check_value(
-                properties, 'SecurityGroups', path,
-                check_value=None, check_ref=self.check_sgid_ref,
-                check_find_in_map=None, check_split=None, check_join=None
-            )
-        )
-        matches.extend(
-            cfn.check_value(
-                properties, 'SourceSecurityGroupId', path,
-                check_value=None, check_ref=self.check_sgid_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/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
@@ -28,64 +28,7 @@ class SecurityGroupIngress(CloudFormationLintRule):
     source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html'
     tags = ['resources', 'securitygroup']
 
-    def check_sgid_value(self, value, path):
-        """Check VPC Values"""
-        matches = []
-        if not value.startswith('sg-'):
-            message = 'Security Group Id must have a valid Identifier {0}'
-            matches.append(
-                RuleMatch(path, message.format('/'.join(map(str, path)))))
-        return matches
-
-    def check_sgid_ref(self, value, path, parameters, resources):
-        """Check ref for VPC"""
-        matches = []
-
-        allowed_types = [
-            'AWS::SSM::Parameter::Value<AWS::EC2::SecurityGroup::Id>',
-            'AWS::EC2::SecurityGroup::Id',
-            'String'
-        ]
-        if value in parameters:
-            parameter_properties = parameters.get(value)
-            parameter_type = parameter_properties.get('Type')
-            if parameter_type not in allowed_types:
-                path_error = ['Parameters', value, 'Type']
-                message = 'Security Group Id 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)))))
-        if value in resources:
-            resource = resources.get(value, {})
-            resource_type = resource.get('Type', '')
-            if resource_type != 'AWS::EC2::SecurityGroup':
-                message = 'Security Group Id resources should be of type AWS::EC2::SecurityGroup for {0}'
-                matches.append(
-                    RuleMatch(path, message.format('/'.join(map(str, path)))))
-            else:
-                resource_properties = resource.get('Properties', {})
-                vpc_property = resource_properties.get('VpcId', None)
-                if not vpc_property:
-                    message = 'Security Group Id should reference a VPC based AWS::EC2::SecurityGroup for {0}'
-                    matches.append(
-                        RuleMatch(path, message.format('/'.join(map(str, path)))))
-
-        return matches
-
-    # pylint: disable=W0613
-    def check_sgid_fail(self, value, path, **kwargs):
-        """Automatic failure for certain functions"""
-
-        matches = []
-        message = 'Use Ref, FindInMap, or string values for {0}'
-        matches.append(
-            RuleMatch(path, message.format('/'.join(map(str, path)))))
-        return matches
-
-    def check_ingress_rule(self, vpc_id, properties, path, cfn):
+    def check_ingress_rule(self, vpc_id, properties, path):
         """Check ingress rule"""
 
         matches = []
@@ -99,16 +42,6 @@ def check_ingress_rule(self, vpc_id, properties, path, cfn):
                 matches.append(
                     RuleMatch(path_error, message.format('/'.join(map(str, path_error)))))
 
-            matches.extend(
-                cfn.check_value(
-                    obj=properties, key='SourceSecurityGroupId',
-                    path=path[:],
-                    check_value=self.check_sgid_value, check_ref=self.check_sgid_ref,
-                    check_find_in_map=None, check_split=self.check_sgid_fail,
-                    check_join=self.check_sgid_fail
-                )
-            )
-
         else:
 
             if properties.get('SourceSecurityGroupId', None):
@@ -141,8 +74,7 @@ def match(self, cfn):
                             self.check_ingress_rule(
                                 vpc_id=vpc_id,
                                 properties=ingress_rule,
-                                path=path,
-                                cfn=cfn
+                                path=path
                             )
                         )
 
@@ -163,8 +95,7 @@ def match(self, cfn):
                     self.check_ingress_rule(
                         vpc_id=vpc_id,
                         properties=properties,
-                        path=path,
-                        cfn=cfn
+                        path=path
                     )
                 )
         return matches


Test patch:
diff --git a/test/rules/parameters/test_security_group.py b/test/rules/parameters/test_security_group.py
deleted file mode 100644
--- a/test/rules/parameters/test_security_group.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""
-  Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
-
-  Permission is hereby granted, free of charge, to any person obtaining a copy of this
-  software and associated documentation files (the "Software"), to deal in the Software
-  without restriction, including without limitation the rights to use, copy, modify,
-  merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
-  permit persons to whom the Software is furnished to do so.
-
-  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
-  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-"""
-from cfnlint.rules.parameters.SecurityGroup import SecurityGroup  # pylint: disable=E0401
-from .. import BaseRuleTestCase
-
-
-class TestParameterSecurityGroup(BaseRuleTestCase):
-    """Test template parameter configurations"""
-    def setUp(self):
-        """Setup"""
-        super(TestParameterSecurityGroup, self).setUp()
-        self.collection.register(SecurityGroup())
-
-    def atest_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', 4)
diff --git a/test/rules/resources/ec2/test_sg_ingress.py b/test/rules/resources/ec2/test_sg_ingress.py
--- a/test/rules/resources/ec2/test_sg_ingress.py
+++ b/test/rules/resources/ec2/test_sg_ingress.py
@@ -34,4 +34,4 @@ def test_file_positive(self):
 
     def test_file_negative(self):
         """Test failure"""
-        self.helper_file_negative('test/fixtures/templates/bad/properties_sg_ingress.yaml', 5)
+        self.helper_file_negative('test/fixtures/templates/bad/properties_sg_ingress.yaml', 2)