From c68cd650e77f801da4a10fcec3ec616378e5fb72 Mon Sep 17 00:00:00 2001 From: Nuwan Goonasekera Date: Fri, 22 Dec 2017 18:50:18 +0530 Subject: [PATCH] Make sure invalid or malformed AMIs raise an exception Closes: https://github.com/spulec/moto/issues/1408 --- moto/ec2/models.py | 10 ++++++++++ tests/test_ec2/test_amis.py | 14 ++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/moto/ec2/models.py b/moto/ec2/models.py index 80bbf8439..932f535a1 100755 --- a/moto/ec2/models.py +++ b/moto/ec2/models.py @@ -48,6 +48,7 @@ from .exceptions import ( InvalidRouteError, InvalidInstanceIdError, InvalidAMIIdError, + MalformedAMIIdError, InvalidAMIAttributeItemValueError, InvalidSnapshotIdError, InvalidVolumeIdError, @@ -1122,6 +1123,9 @@ class Ami(TaggedEC2Resource): class AmiBackend(object): + + AMI_REGEX = re.compile("ami-[a-z0-9]+") + def __init__(self): self.amis = {} @@ -1170,6 +1174,12 @@ class AmiBackend(object): if ami_ids: images = [ami for ami in images if ami.id in ami_ids] + if len(ami_ids) > len(images): + unknown_ids = set(ami_ids) - set(images) + for id in unknown_ids: + if not self.AMI_REGEX.match(id): + raise MalformedAMIIdError(id) + raise InvalidAMIIdError(unknown_ids) # Generic filters if filters: diff --git a/tests/test_ec2/test_amis.py b/tests/test_ec2/test_amis.py index 1029ba39e..9ba782414 100755 --- a/tests/test_ec2/test_amis.py +++ b/tests/test_ec2/test_amis.py @@ -8,6 +8,7 @@ import boto3 import boto.ec2 import boto3 from boto.exception import EC2ResponseError, EC2ResponseError +from botocore.exceptions import ClientError import sure # noqa @@ -666,6 +667,19 @@ def test_ami_attribute_error_cases(): cm.exception.request_id.should_not.be.none +@mock_ec2 +def test_ami_describe_non_existent(): + ec2 = boto3.resource('ec2', region_name='us-west-1') + # Valid pattern but non-existent id + img = ec2.Image('ami-abcd1234') + with assert_raises(ClientError): + img.load() + # Invalid ami pattern + img = ec2.Image('not_an_ami_id') + with assert_raises(ClientError): + img.load() + + @mock_ec2 def test_ami_filter_wildcard(): ec2 = boto3.resource('ec2', region_name='us-west-1')