EC2:run_instances() now validates the provided SecurityGroup (#5486)

This commit is contained in:
Bert Blommers 2022-09-19 21:34:06 +00:00 committed by GitHub
parent b0e78140f5
commit b9f5ecacde
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 3 deletions

View File

@ -21,6 +21,7 @@ from ..exceptions import (
InvalidInstanceIdError,
InvalidInstanceTypeError,
InvalidParameterValueErrorUnknownAttribute,
InvalidSecurityGroupNotFoundError,
OperationNotPermitted4,
)
from ..utils import (
@ -596,8 +597,6 @@ class InstanceBackend:
):
if settings.EC2_ENABLE_INSTANCE_TYPE_VALIDATION:
raise InvalidInstanceTypeError(kwargs["instance_type"])
new_reservation = Reservation()
new_reservation.id = random_reservation_id()
security_groups = [
self.get_security_group_by_name_or_id(name) for name in security_group_names
@ -605,10 +604,16 @@ class InstanceBackend:
for sg_id in kwargs.pop("security_group_ids", []):
if isinstance(sg_id, str):
security_groups.append(self.get_security_group_from_id(sg_id))
sg = self.get_security_group_from_id(sg_id)
if sg is None:
raise InvalidSecurityGroupNotFoundError(sg_id)
security_groups.append(sg)
else:
security_groups.append(sg_id)
new_reservation = Reservation()
new_reservation.id = random_reservation_id()
self.reservations[new_reservation.id] = new_reservation
tags = kwargs.pop("tags", {})

View File

@ -688,6 +688,19 @@ def test_get_instances_filtering_by_ni_private_dns():
reservations[0]["Instances"].should.have.length_of(1)
@mock_ec2
def test_run_instances_with_unknown_security_group():
client = boto3.client("ec2", region_name="us-east-1")
sg_id = f"sg-{str(uuid4())[0:6]}"
with pytest.raises(ClientError) as exc:
client.run_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1, SecurityGroupIds=[sg_id]
)
err = exc.value.response["Error"]
err["Code"].should.equal("InvalidGroup.NotFound")
err["Message"].should.equal(f"The security group '{sg_id}' does not exist")
@mock_ec2
def test_get_instances_filtering_by_instance_group_name():
client = boto3.client("ec2", region_name="us-east-1")