From 1761be46e33d84465362ef5ade074a3e7f44db7c Mon Sep 17 00:00:00 2001 From: Brian Pandola Date: Fri, 26 Mar 2021 06:00:51 -0700 Subject: [PATCH] Return error when trying to add rules to a non-existent security group (#3802) Behavior and error code/message confirmed against real AWS backend. --- moto/ec2/models.py | 4 ++++ tests/test_ec2/test_security_groups.py | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/moto/ec2/models.py b/moto/ec2/models.py index 3aba5f892..32b0ad053 100644 --- a/moto/ec2/models.py +++ b/moto/ec2/models.py @@ -2265,6 +2265,8 @@ class SecurityGroupBackend(object): vpc_id=None, ): group = self.get_security_group_by_name_or_id(group_name_or_id, vpc_id) + if group is None: + raise InvalidSecurityGroupNotFoundError(group_name_or_id) if ip_ranges: if isinstance(ip_ranges, str) or ( six.PY2 and isinstance(ip_ranges, unicode) # noqa @@ -2353,6 +2355,8 @@ class SecurityGroupBackend(object): ): group = self.get_security_group_by_name_or_id(group_name_or_id, vpc_id) + if group is None: + raise InvalidSecurityGroupNotFoundError(group_name_or_id) if ip_ranges and not isinstance(ip_ranges, list): if isinstance(ip_ranges, str) and "CidrIp" not in ip_ranges: diff --git a/tests/test_ec2/test_security_groups.py b/tests/test_ec2/test_security_groups.py index 2a7111f92..ae4c97589 100644 --- a/tests/test_ec2/test_security_groups.py +++ b/tests/test_ec2/test_security_groups.py @@ -969,3 +969,19 @@ def test_revoke_security_group_egress(): sg.reload() sg.ip_permissions_egress.should.have.length_of(0) + + +@mock_ec2 +def test_non_existent_security_group_raises_error_on_authorize(): + client = boto3.client("ec2", "us-east-1") + non_existent_sg = "sg-123abc" + expected_error = "The security group '{}' does not exist".format(non_existent_sg) + authorize_funcs = [ + client.authorize_security_group_egress, + client.authorize_security_group_ingress, + ] + for authorize_func in authorize_funcs: + with pytest.raises(ClientError) as ex: + authorize_func(GroupId=non_existent_sg, IpPermissions=[{}]) + ex.value.response["Error"]["Code"].should.equal("InvalidGroup.NotFound") + ex.value.response["Error"]["Message"].should.equal(expected_error)