From a29215008723668848968e399b12fb46771fcf61 Mon Sep 17 00:00:00 2001 From: Steve Pulec Date: Wed, 11 Jan 2017 22:35:27 -0500 Subject: [PATCH] Throw exception if same security group rule added twice. Closes #737. --- moto/ec2/models.py | 13 +++++++++++-- tests/test_ec2/test_security_groups.py | 25 +++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/moto/ec2/models.py b/moto/ec2/models.py index 9146b283d..a3e333dc7 100755 --- a/moto/ec2/models.py +++ b/moto/ec2/models.py @@ -1255,6 +1255,15 @@ class SecurityGroup(TaggedEC2Resource): return self.id raise UnformattedGetAttTemplateException() + def add_ingress_rule(self, rule): + if rule in self.ingress_rules: + raise InvalidParameterValueError('security_group') + else: + self.ingress_rules.append(rule) + + def add_egress_rule(self, rule): + self.egress_rules.append(rule) + class SecurityGroupBackend(object): @@ -1367,7 +1376,7 @@ class SecurityGroupBackend(object): source_groups.append(source_group) security_rule = SecurityRule(ip_protocol, from_port, to_port, ip_ranges, source_groups) - group.ingress_rules.append(security_rule) + group.add_ingress_rule(security_rule) def revoke_security_group_ingress(self, group_name_or_id, @@ -1432,7 +1441,7 @@ class SecurityGroupBackend(object): source_groups.append(source_group) security_rule = SecurityRule(ip_protocol, from_port, to_port, ip_ranges, source_groups) - group.egress_rules.append(security_rule) + group.add_egress_rule(security_rule) def revoke_security_group_egress(self, group_name_or_id, diff --git a/tests/test_ec2/test_security_groups.py b/tests/test_ec2/test_security_groups.py index 585f97eeb..204380562 100644 --- a/tests/test_ec2/test_security_groups.py +++ b/tests/test_ec2/test_security_groups.py @@ -8,6 +8,7 @@ from nose.tools import assert_raises import boto3 import boto +from botocore.exceptions import ClientError from boto.exception import EC2ResponseError, JSONResponseError import sure # noqa @@ -382,6 +383,26 @@ def test_authorize_all_protocols_with_no_port_specification(): Boto3 ''' +@mock_ec2 +def test_add_same_rule_twice_throws_error(): + ec2 = boto3.resource('ec2', region_name='us-west-1') + + vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16') + sg = ec2.create_security_group(GroupName='sg1', Description='Test security group sg1', VpcId=vpc.id) + + ip_permissions = [ + { + 'IpProtocol': 'tcp', + 'FromPort': 27017, + 'ToPort': 27017, + 'IpRanges': [{"CidrIp": "1.2.3.4/32"}] + }, + ] + sg.authorize_ingress(IpPermissions=ip_permissions) + + with assert_raises(ClientError) as ex: + sg.authorize_ingress(IpPermissions=ip_permissions) + @mock_ec2 def test_security_group_tagging_boto3(): @@ -423,8 +444,8 @@ def test_authorize_and_revoke_in_bulk(): }, { 'IpProtocol': 'tcp', - 'FromPort': 27017, - 'ToPort': 27017, + 'FromPort': 27018, + 'ToPort': 27018, 'UserIdGroupPairs': [{'GroupId': sg02.id, 'UserId': sg02.owner_id}], 'IpRanges': [] },