From cdb6811bbf4f8a79df7cd155f723cbb077a298b5 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Sun, 16 Aug 2026 19:47:15 -0600 Subject: [PATCH] feat(ec2): DescribeImages synthesizes an AMI for an unmatched wildcard name lookup (#2009) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(ec2): DescribeImages synthesizes an AMI for an unmatched wildcard name lookup CDK MachineImage.lookup is a synth-time context provider that queries by a name wildcard and aborts cdk deploy on an empty response. When a wildcard name filter matches no seeded AMI, synthesize a deterministic one satisfying the name/owner/architecture filters so the lookup resolves — the exact id is a runtime detail. Fixes #2008 * fix(ec2): synthesized lookup AMI id must be 17 hex chars (was substring OOB) * fix(ec2): a synthesized lookup AMI must satisfy the request that produced it The synthesized name was built by truncating the pattern at its first wildcard, so an infix pattern like ubuntu-*-20.04-* produced "ubuntu-20260101", which does not satisfy it. Each wildcard is now substituted instead, and the scalar fields a request can filter on (architecture, owner alias, state, root device, virtualization type, hypervisor) take the requested value rather than a hardcoded one. Synthesis is also no longer unconditional: the result is checked against the full filter set before being returned, and withheld when it cannot satisfy it. An empty result is what the caller would otherwise have got, and it is better than an AMI that contradicts the request without the caller being able to tell. * fix(ec2): a name filter reads ? as the single-character wildcard AWS defines AWS filter values take two wildcards, * for any run of characters and ? for exactly one. wildcardMatches expanded only *, quoting everything else, so a pattern like ubuntu-? matched nothing. wildcardToRegex further down the same file already read both, so the two disagreed on the same syntax. That half is not specific to lookup synthesis and affects any name filter. Synthesis in turn substituted * and left ? in place, which handed back a name carrying a literal ? that the requesting filter no longer matches once the matcher reads ? properly. It now substitutes a single character for each one. * fix(ec2): a synthesized lookup image resolves its owner and faces the owner scope Owner.N takes aliases, and synthesizeLookupImage wrote the requested value through verbatim, so Owner.1=self with no owner-id filter produced an image owned by the literal "self". Ec2Service matches self by comparing the image owner against the account id, so nothing resolves that. It now maps self to the account id and passes anything else through. The guard below it only re-checked Filter.N, so the image never faced the owner scope that produced it and a foreign Owner.N still got an AMI back. matchesImageOwners already existed privately on Ec2Service and is now exposed next to imageMatchesFilters, rather than restating the rule in the handler. Two tests, neither of which passed before, since nothing in the suite sent Owner.N. * fix(ec2): DescribeImages owner aliases resolve to the accounts they name Resolving only self left amazon and aws-marketplace written through verbatim, so a synthesized lookup image came back owned by the literal alias. The owner check added alongside it then accepted that by string equality, which made the result self-consistently wrong rather than merely unmatched. Both aliases now resolve to their accounts in the synthesized image, and matchesImageOwners resolves them too, so Owner.1=amazon matches an Amazon-owned image rather than only one owned by the literal string. * fix(ec2): the seeded Amazon Linux images carry their owner matchesImageOwners learning the amazon alias only helped registered images. The catalog matches on its own owner metadata, and five of the ten seeded entries carry none, so Owner.1=amazon omitted Amazon Linux 2 and 2023 regardless. Both now carry ownerId 137112412989 and the amazon alias, matching how the Canonical entries are already seeded. Debian, Alpine and Windows Server are still without owner metadata, which is the same pre-existing gap and needs their real account ids rather than a guess. * fix(ec2): lookup synthesis reads the wildcard value, not the first one A filter's values are an OR, and the name pattern was taken with findFirst on the list, so an exact value ahead of a wildcard meant the wildcard check failed and synthesis never ran. The lookup then got an empty set that one of its own values could have been satisfied by. It now picks the first value carrying a wildcard. This predates the ? support, which only widened which values qualify. * fix(ec2): a synthesized image's owner id and alias agree with each other The alias defaulted to amazon whatever the owner resolved to, so Owner.1=self reported account 000000000000 beside imageOwnerAlias amazon. The alias is now derived from the resolved account, and an account with no alias emits no element at all, which is what AWS does. The mirror was wrong too and is fixed with it. An owner-alias filter names an account as much as Owner.N does, but was consulted by nothing, so filtering on owner-alias alone left the id at the Amazon default and reported that account beside someone else's alias. Owner resolution now reads the owner-id filter, then Owner.N, then the owner-alias filter, then the default. Asserted as a pair across all four owner scopes rather than per field. Each half was confirmed by reverting the source change with the test in place and watching it fail on the exact contradiction. --- .../floci/services/ec2/Ec2QueryHandler.java | 111 ++++++++ .../floci/services/ec2/Ec2Service.java | 51 +++- src/main/resources/ec2/image-catalog.yaml | 4 + .../services/ec2/Ec2IntegrationTest.java | 257 +++++++++++++++++- 4 files changed, 416 insertions(+), 7 deletions(-) diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index 16d8b9ccba..9c74d417d8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -1662,6 +1662,30 @@ public class Ec2QueryHandler { List owners = getList(p, "Owner"); Map> filters = getFilters(p); List images = service.describeImages(region, imageIds, owners, filters); + // CDK's MachineImage.lookup is a synth-time context provider that queries + // by a `name` wildcard and aborts `cdk deploy` if the response is empty. + // When a wildcard name filter matches no seeded AMI, synthesize one that + // satisfies it, so the lookup resolves — the exact id is a runtime detail. + if (images.isEmpty() && imageIds.isEmpty() && filters.containsKey("name")) { + // A filter's values are an OR, so the wildcard is whichever value carries one rather + // than whichever comes first. Taking the first outright meant an exact value ahead of + // a wildcard skipped synthesis and the lookup got nothing. + String namePattern = filters.get("name").stream() + .filter(v -> v != null && (v.contains("*") || v.contains("?"))) + .findFirst() + .orElse(null); + if (namePattern != null) { + Image synthesized = synthesizeLookupImage(namePattern, filters, owners); + // Only hand it back if it satisfies everything that was asked for. Returning an + // AMI that violates the request is worse than the empty result the lookup would + // otherwise get, and the caller cannot tell the difference. Owner.N is carried + // outside the filter set, so it has to be checked separately. + if (service.imageMatchesFilters(synthesized, filters) + && service.imageMatchesOwners(synthesized, owners)) { + images = List.of(synthesized); + } + } + } XmlBuilder xml = new XmlBuilder() .start("DescribeImagesResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()) @@ -1690,6 +1714,93 @@ public class Ec2QueryHandler { return xmlResponse(xml.build()); } + /** Stands in for a {@code *} when turning a lookup pattern into a concrete name. */ + private static final String SYNTH_WILDCARD_TOKEN = "20260101"; + + /** Stands in for a {@code ?}, which matches exactly one character. */ + private static final String SYNTH_SINGLE_CHAR_TOKEN = "0"; + + /** AWS's own account for the Amazon-owned AMIs, and the default when no owner is requested. */ + private static final String AMAZON_OWNER_ID = "137112412989"; + + /** The account behind the {@code aws-marketplace} owner alias. */ + private static final String AWS_MARKETPLACE_OWNER_ID = "679593333241"; + + /** + * The owner the synthesized image should carry. {@code Owner.N} takes the aliases {@code self}, + * {@code amazon} and {@code aws-marketplace} as well as bare account ids, and an alias written + * through verbatim produced an image owned by the literal string. AWS always reports an account + * id in {@code imageOwnerId}, so each alias resolves to the account it names. + */ + private String resolveSynthOwner(Map> filters, List owners) { + // An owner-alias filter names an account just as much as Owner.N does, so it is consulted + // before the default. Without that, filtering on owner-alias alone produced an image + // carrying that alias beside the default Amazon account id, contradicting itself the same + // way an unresolved alias did in the other direction. + String requested = filters.getOrDefault("owner-id", owners == null ? List.of() : owners) + .stream().findFirst() + .orElseGet(() -> firstFilterValue(filters, "owner-alias", AMAZON_OWNER_ID)); + return switch (requested) { + case "self" -> config.defaultAccountId(); + case "amazon" -> AMAZON_OWNER_ID; + case "aws-marketplace" -> AWS_MARKETPLACE_OWNER_ID; + default -> requested; + }; + } + + /** + * The alias that belongs to a resolved owner account, or null when the account has none. AWS + * only sets imageOwnerAlias for its own published images, so defaulting it to amazon reported + * ownership contradicting the owner id whenever the scope named anything else. + */ + private static String aliasForOwner(String ownerId) { + return switch (ownerId) { + case AMAZON_OWNER_ID -> "amazon"; + case AWS_MARKETPLACE_OWNER_ID -> "aws-marketplace"; + default -> null; + }; + } + + /** The requested value for a scalar filter, so the synthesized image satisfies it. */ + private static String firstFilterValue(Map> filters, String name, String fallback) { + return filters.getOrDefault(name, List.of()).stream() + .filter(v -> v != null && !v.contains("*") && !v.contains("?")) + .findFirst() + .orElse(fallback); + } + + /** + * Builds an AMI that satisfies a lookup's name wildcard and its owner and architecture filters. + * The id is a hash of the pattern, so repeated lookups resolve to the same image. + */ + private Image synthesizeLookupImage(String namePattern, Map> filters, List owners) { + Image img = new Image(); + // 17 hex chars after "ami-", deterministic from the pattern. + String hash = String.format("%08x", namePattern.hashCode() & 0x7fffffff); + String id17 = (hash + hash + hash).substring(0, 17); + img.setImageId("ami-" + id17); + // Substitute each wildcard rather than truncating at the first one, so an infix pattern + // like ubuntu-*-20.04-* yields a name that still satisfies it. Truncating produced + // "ubuntu-20260101", which does not. A ? takes exactly one character, so leaving it in + // place would hand back a name the requesting filter no longer matches. + img.setName(namePattern + .replace("*", SYNTH_WILDCARD_TOKEN) + .replace("?", SYNTH_SINGLE_CHAR_TOKEN)); + img.setState(firstFilterValue(filters, "state", "available")); + String ownerId = resolveSynthOwner(filters, owners); + img.setOwnerId(ownerId); + img.setImageOwnerAlias(firstFilterValue(filters, "owner-alias", aliasForOwner(ownerId))); + img.setPublic(true); + img.setArchitecture(firstFilterValue(filters, "architecture", "x86_64")); + img.setRootDeviceType(firstFilterValue(filters, "root-device-type", "ebs")); + img.setRootDeviceName(firstFilterValue(filters, "root-device-name", "/dev/xvda")); + img.setVirtualizationType(firstFilterValue(filters, "virtualization-type", "hvm")); + img.setHypervisor(firstFilterValue(filters, "hypervisor", "xen")); + img.setDescription("Synthesized AMI for MachineImage.lookup(" + namePattern + ")"); + img.setCreationDate("2026-01-01T00:00:00.000Z"); + return img; + } + private Response handleCreateImage(MultivaluedMap p, String region) { Image image = service.createImage( region, diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 7d74663a9f..f359e18304 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -96,6 +96,9 @@ public class Ec2Service implements ContainerTeardown { .withZone(ZoneOffset.UTC); private static final int DEFAULT_ROOT_VOLUME_SIZE_GIB = 8; private static final String DEFAULT_ROOT_VOLUME_TYPE = "gp3"; + /** The accounts behind the two non-self owner aliases DescribeImages accepts. */ + private static final String AMAZON_OWNER_ID = "137112412989"; + private static final String AWS_MARKETPLACE_OWNER_ID = "679593333241"; // The ASN AWS assigns when CreateTransitGateway omits Options.AmazonSideAsn. private static final long DEFAULT_AMAZON_SIDE_ASN = 64512L; private static final Pattern TRANSIT_GATEWAY_ID_PATTERN = Pattern.compile("^tgw-[0-9a-f]{8}([0-9a-f]{9})?$"); @@ -2993,10 +2996,38 @@ public class Ec2Service implements ContainerTeardown { return imageIds == null || imageIds.isEmpty() || imageIds.contains(image.getImageId()); } + /** + * {@code Owner.N} takes the aliases {@code self}, {@code amazon} and {@code aws-marketplace} + * beside bare account ids, while {@code imageOwnerId} is always an account id. Only + * {@code self} was translated, so an alias matched nothing unless an image happened to be + * owned by the literal string. + */ private boolean matchesImageOwners(Image image, List owners) { - return owners == null || owners.isEmpty() - || owners.contains(image.getOwnerId()) - || (owners.contains("self") && accountId.equals(image.getOwnerId())); + if (owners == null || owners.isEmpty()) { + return true; + } + String ownerId = image.getOwnerId(); + return owners.contains(ownerId) + || (owners.contains("self") && accountId.equals(ownerId)) + || (owners.contains("amazon") && AMAZON_OWNER_ID.equals(ownerId)) + || (owners.contains("aws-marketplace") && AWS_MARKETPLACE_OWNER_ID.equals(ownerId)); + } + + /** + * Whether an image satisfies a DescribeImages filter set. Exposed so a synthesized lookup image + * can be checked against the request that produced it before being returned. + */ + public boolean imageMatchesFilters(Image image, Map> filters) { + return matchesRegisteredImageFilters(image, filters); + } + + /** + * Whether an image satisfies a DescribeImages owner scope. Exposed alongside + * {@link #imageMatchesFilters} so a synthesized lookup image faces the whole request that + * produced it, since {@code Owner.N} is carried outside the filter set. + */ + public boolean imageMatchesOwners(Image image, List owners) { + return matchesImageOwners(image, owners); } private boolean matchesRegisteredImageFilters(Image image, Map> filters) { @@ -3093,15 +3124,25 @@ public class Ec2Service implements ContainerTeardown { return patterns.stream().anyMatch(pattern -> wildcardMatches(pattern, value)); } + /** + * AWS filter values take two wildcards, {@code *} for any run of characters and {@code ?} for + * exactly one. Only {@code *} was honoured here, so a {@code ?} was matched literally and a + * pattern like {@code ubuntu-?} found nothing, while {@link #wildcardToRegex} a few hundred + * lines down already treated both. + */ private boolean wildcardMatches(String pattern, String value) { if (pattern == null) { return false; } - if (!pattern.contains("*")) { + if (!pattern.contains("*") && !pattern.contains("?")) { return pattern.equals(value); } String regex = pattern.chars() - .mapToObj(ch -> ch == '*' ? ".*" : java.util.regex.Pattern.quote(String.valueOf((char) ch))) + .mapToObj(ch -> switch (ch) { + case '*' -> ".*"; + case '?' -> "."; + default -> java.util.regex.Pattern.quote(String.valueOf((char) ch)); + }) .collect(Collectors.joining()); return value.matches(regex); } diff --git a/src/main/resources/ec2/image-catalog.yaml b/src/main/resources/ec2/image-catalog.yaml index 8e2789aa46..b561e4a071 100644 --- a/src/main/resources/ec2/image-catalog.yaml +++ b/src/main/resources/ec2/image-catalog.yaml @@ -7,6 +7,8 @@ images: dockerImage: public.ecr.aws/amazonlinux/amazonlinux:2 name: amzn2-ami-hvm-2.0.20230404.0-x86_64-gp2 description: Amazon Linux 2 AMI + ownerId: "137112412989" + imageOwnerAlias: amazon architecture: x86_64 creationDate: "2023-04-04T00:00:00.000Z" @@ -16,6 +18,8 @@ images: dockerImage: public.ecr.aws/amazonlinux/amazonlinux:2023 name: al2023-ami-2023.0.20230315.0-kernel-6.1-x86_64 description: Amazon Linux 2023 AMI + ownerId: "137112412989" + imageOwnerAlias: amazon architecture: x86_64 creationDate: "2023-03-15T00:00:00.000Z" diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java index 9d3f5087be..cf8a6e736b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java @@ -2,16 +2,18 @@ package io.github.hectorvent.floci.services.ec2; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.emptyOrNullString; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.everyItem; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.Matchers.containsString; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -223,6 +225,257 @@ class Ec2IntegrationTest { .body("DescribeImagesResponse.imagesSet.item.architecture", equalTo("x86_64")); } + @Test + @Order(9) + void synthesizedLookupImageSatisfiesAnInfixWildcardName() { + // Truncating at the first wildcard produced "unmatched-vendor-20260101", which does not + // satisfy the pattern the caller asked for. + String name = given() + .formParam("Action", "DescribeImages") + .formParam("Filter.1.Name", "name") + .formParam("Filter.1.Value.1", "unmatched-vendor-*-20.04-*") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeImagesResponse.imagesSet.item.size()", equalTo(1)) + .extract().path("DescribeImagesResponse.imagesSet.item.name"); + + assertThat(name, startsWith("unmatched-vendor-")); + assertThat(name, containsString("-20.04-")); + } + + @Test + @Order(9) + void synthesizedLookupImageSatisfiesASingleCharacterWildcard() { + // ? matches exactly one character in an AWS filter. Leaving it in the synthesized name + // handed back "unmatched-vendor-?", which the requesting filter does not match once the + // matcher reads ? as a wildcard rather than a literal. + String name = given() + .formParam("Action", "DescribeImages") + .formParam("Filter.1.Name", "name") + .formParam("Filter.1.Value.1", "unmatched-vendor-?-single") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeImagesResponse.imagesSet.item.size()", equalTo(1)) + .extract().path("DescribeImagesResponse.imagesSet.item.name"); + + assertThat(name, not(containsString("?"))); + assertThat(name, startsWith("unmatched-vendor-")); + assertThat(name, endsWith("-single")); + assertEquals("unmatched-vendor-".length() + 1 + "-single".length(), name.length()); + } + + @Test + @Order(9) + void synthesizedLookupImageResolvesTheSelfOwnerAlias() { + // Owner.N takes aliases. Writing "self" through verbatim produced an image owned by the + // literal string, which no owner scope resolves to, and the guard never re-checked the + // owner because it only looked at Filter.N. + String owner = given() + .formParam("Action", "DescribeImages") + .formParam("Owner.1", "self") + .formParam("Filter.1.Name", "name") + .formParam("Filter.1.Value.1", "unmatched-self-owned-*") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeImagesResponse.imagesSet.item.size()", equalTo(1)) + .extract().path("DescribeImagesResponse.imagesSet.item.imageOwnerId"); + + assertEquals("000000000000", owner); + } + + /** + * Owner scope, then the id and alias the synthesized image must report together. A null + * expectedAlias means AWS reports no alias for that account, so the element is asserted + * absent from the body rather than compared as a value. + */ + private void assertSynthesizedOwnership(String ownerScope, String expectedId, String expectedAlias) { + var response = given() + .formParam("Action", "DescribeImages") + .formParam("Owner.1", ownerScope) + .formParam("Filter.1.Name", "name") + .formParam("Filter.1.Value.1", "unmatched-coherence-" + ownerScope + "-*") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeImagesResponse.imagesSet.item.size()", equalTo(1)) + .extract(); + + assertEquals(expectedId, response.path("DescribeImagesResponse.imagesSet.item.imageOwnerId"), + "imageOwnerId for Owner.1=" + ownerScope); + if (expectedAlias == null) { + assertThat("imageOwnerAlias for Owner.1=" + ownerScope, + response.asString(), not(containsString(""))); + } else { + assertEquals(expectedAlias, + response.path("DescribeImagesResponse.imagesSet.item.imageOwnerAlias").toString(), + "imageOwnerAlias for Owner.1=" + ownerScope); + } + } + + @Test + @Order(9) + void synthesizedOwnershipIsSelfConsistentAcrossOwnerScopes() { + // Every earlier round here fixed one field and left the one beside it, so this asserts the + // pair together. An id resolved from the scope with an alias defaulted to amazon reports + // ownership that contradicts itself. + assertSynthesizedOwnership("self", "000000000000", null); + assertSynthesizedOwnership("amazon", "137112412989", "amazon"); + assertSynthesizedOwnership("aws-marketplace", "679593333241", "aws-marketplace"); + assertSynthesizedOwnership("099720109477", "099720109477", null); + } + + @Test + @Order(9) + void anOwnerAliasFilterAloneStillAgreesWithTheOwnerId() { + // The mirror of the above. Filtering on the alias with no Owner.N left the id at the + // Amazon default, so the image reported aws-marketplace beside Amazon's account. + var response = given() + .formParam("Action", "DescribeImages") + .formParam("Filter.1.Name", "name") + .formParam("Filter.1.Value.1", "unmatched-alias-filter-only-*") + .formParam("Filter.2.Name", "owner-alias") + .formParam("Filter.2.Value.1", "aws-marketplace") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeImagesResponse.imagesSet.item.size()", equalTo(1)) + .extract(); + + assertEquals("679593333241", + response.path("DescribeImagesResponse.imagesSet.item.imageOwnerId")); + assertEquals("aws-marketplace", + response.path("DescribeImagesResponse.imagesSet.item.imageOwnerAlias").toString()); + } + + @Test + @Order(9) + void aWildcardBehindAnExactNameValueStillSynthesizes() { + // A filter's values are an OR. Taking the first value outright picked the exact one, the + // wildcard check failed, and the lookup got an empty set it could have satisfied. + String name = given() + .formParam("Action", "DescribeImages") + .formParam("Filter.1.Name", "name") + .formParam("Filter.1.Value.1", "unmatched-exact-name-no-wildcard") + .formParam("Filter.1.Value.2", "unmatched-second-value-*") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeImagesResponse.imagesSet.item.size()", equalTo(1)) + .extract().path("DescribeImagesResponse.imagesSet.item.name"); + + assertThat(name, startsWith("unmatched-second-value-")); + } + + @Test + @Order(9) + void amazonOwnerScopeFindsTheSeededAmazonLinuxImages() { + // The catalog matches on its own owner metadata, and the two Amazon Linux entries carried + // none, so Owner.1=amazon omitted them however the registered-image matcher read the alias. + given() + .formParam("Action", "DescribeImages") + .formParam("Owner.1", "amazon") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("amzn2-ami-hvm")) + .body(containsString("al2023-ami")); + } + + @Test + @Order(9) + void synthesizedLookupImageResolvesTheAmazonOwnerAlias() { + // imageOwnerId is always an account id in AWS. Writing the alias through left the image + // owned by the literal "amazon", and the owner check accepted it by string equality. + String owner = given() + .formParam("Action", "DescribeImages") + .formParam("Owner.1", "amazon") + .formParam("Filter.1.Name", "name") + .formParam("Filter.1.Value.1", "unmatched-amazon-owned-*") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeImagesResponse.imagesSet.item.size()", equalTo(1)) + .extract().path("DescribeImagesResponse.imagesSet.item.imageOwnerId"); + + assertEquals("137112412989", owner); + } + + @Test + @Order(9) + void synthesizedLookupImageIsWithheldFromAnOwnerScopeItCannotSatisfy() { + // A foreign owner scope cannot be satisfied by anything we synthesize, so the lookup gets + // the empty result rather than an AMI that contradicts the request. + given() + .formParam("Action", "DescribeImages") + .formParam("Owner.1", "999999999999") + .formParam("Filter.1.Name", "name") + .formParam("Filter.1.Value.1", "unmatched-foreign-owner-*") + .formParam("Filter.2.Name", "owner-id") + .formParam("Filter.2.Value.1", "137112412989") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body(not(containsString(""))); + } + + @Test + @Order(9) + void synthesizedLookupImageHonorsOtherRequestedFilters() { + given() + .formParam("Action", "DescribeImages") + .formParam("Filter.1.Name", "name") + .formParam("Filter.1.Value.1", "unmatched-vendor-arm-*") + .formParam("Filter.2.Name", "architecture") + .formParam("Filter.2.Value.1", "arm64") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeImagesResponse.imagesSet.item.size()", equalTo(1)) + .body("DescribeImagesResponse.imagesSet.item.architecture", equalTo("arm64")); + } + + @Test + @Order(9) + void synthesizedLookupImageIsWithheldWhenItCannotSatisfyTheRequest() { + // The synthesized description is fixed, so a description filter it cannot meet must yield + // an empty result rather than an AMI that violates the request. + given() + .formParam("Action", "DescribeImages") + .formParam("Filter.1.Name", "name") + .formParam("Filter.1.Value.1", "unmatched-vendor-none-*") + .formParam("Filter.2.Name", "description") + .formParam("Filter.2.Value.1", "a description no synthesized image carries") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body(not(containsString(""))); + } + @Test @Order(9) void describeImagesWithUbuntu2404Arm64Filters() {