From d173d65eb4593b2f6fea84a76b3b8981f9fbf1b7 Mon Sep 17 00:00:00 2001 From: Jackson Price <59149601+jprice8@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:02:38 -0500 Subject: [PATCH] fix(ec2): honor CopyImageTags on CopyImage (#7097) * fix(ec2): tag an AMI with the tags RegisterImage is given RegisterImage never read TagSpecification, so an AMI registered with image tags came back from DescribeImages untagged: its tag filters matched nothing and DescribeTags listed nothing for it. A tag specification for another resource type was accepted as well, although AWS fails that request. RegisterImage now reads its image tag specifications and refuses any other resource type with InvalidParameterValue. It checks the tags as CreateTags does (no aws: prefix, the key and value lengths, at most 50 tags) before registering anything, so a refused request leaves no AMI behind. The tags are stored before the AMI is, so DescribeImages never lists it without them, and a key given twice keeps its last value, as Floci's CreateTags keeps it. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): copy an AMI's tags when CopyImage sets CopyImageTags CopyImage never read CopyImageTags, so a copy asked to carry its source's tags came out untagged, and DescribeImages could not find it by them. With CopyImageTags=true the copy now gets the caller's tags on the source, read in the source region, less the aws: system tags, which AWS does not copy either. Without it, or with false, no tags are copied, which is AWS's default. The source keeps its tags, and the copy's are stored in the destination region only. The tags are read under the source AMI's own id, so a catalog AMI's tags on that id are copied too, while tags put on one of its aliases are not. Floci keeps each account's tags apart, so another account's tags never reach the copy. CopyImage still neither checks nor applies TagSpecification, and the docs now say so. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): stub the CopyImage overload the handler calls Upstream's handler test for CopyImage tag specifications stubbed the five-argument copyImage. On this branch the handler passes CopyImageTags as well, so the stub never matched, the mock returned null and the test failed with a NullPointerException. It now stubs the six-argument call with CopyImageTags false, which is what a request without it sends. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * refactor(ec2): leave RegisterImage tag specifications to upstream's handling Upstream now reads RegisterImage's TagSpecification in the Query handler, refuses other resource types and checks the tags before the AMI is registered, so this branch's own path for the same thing is a duplicate. The seven-argument registerImage overload and the tag code in registerImageLocked are removed, and RegisterImage goes back to upstream's code. CopyImage stores the tags it copies straight after it registers the copy instead. The branch's RegisterImage tests go too: upstream's Ec2CreateTagSpecificationIntegrationTest and Ec2QueryHandlerTest cover the same behaviour. What the branch adds is CopyImageTags alone. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): pin a TagSpecification tag over a copied tag of the same key With CopyImageTags=true and an image TagSpecification on the same request, the copy carries both sets. When both name the same key, the TagSpecification value is the one the copy keeps, since the handler applies the specification after the service copies the source's tags. The docs row says so; this test holds it. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): refuse a CopyImage over the tag limit before creating the copy With CopyImageTags=true and an image TagSpecification, the copied and the specified tags were each checked against the 50-tag limit on their own. The service then created the AMI and its snapshots and stored the copied tags, and only the handler's CreateTags of the specification saw the combined set: past 50 it answered TagLimitExceeded while the copy it had just made stayed behind, so a retry under the same Name failed with InvalidAMIName.Duplicate. The handler now passes the requested image tags to the service, which checks the union of copied and requested keys before it registers anything. The upstream handler test stubs the new signature. The docs and the test of a key given both ways now say that the TagSpecification value winning is Floci's behaviour: the public CopyImage reference does not say how AWS settles that. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * refactor(ec2): keep one CopyImage service signature --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --- .../java/com/floci/test/Ec2ImageTagsTest.java | 47 ++++++ docs/services/ec2.md | 2 +- .../floci/services/ec2/Ec2QueryHandler.java | 4 +- .../floci/services/ec2/Ec2Service.java | 35 +++- ...c2CapturedImageReclaimIntegrationTest.java | 4 +- ...DeregisterAndCopyImageIntegrationTest.java | 155 +++++++++++++++++- .../services/ec2/Ec2QueryHandlerTest.java | 4 +- .../ec2/Ec2ServicePersistenceTest.java | 6 +- .../floci/services/ec2/Ec2ServiceTest.java | 4 +- 9 files changed, 243 insertions(+), 18 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2ImageTagsTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2ImageTagsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2ImageTagsTest.java new file mode 100644 index 0000000000..fd031d9631 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2ImageTagsTest.java @@ -0,0 +1,47 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.Tag; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("EC2 CopyImage tags") +class Ec2ImageTagsTest { + + @Test + @DisplayName("CopyImage copies the source image's tags only when CopyImageTags is true") + void copyImageCopiesTagsOnlyWhenAsked() { + String region = TestFixtures.region().id(); + Tag team = Tag.builder().key("Team").value("images").build(); + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + String sourceId = ec2.registerImage(r -> r.name(TestFixtures.uniqueName("image-tags-copy-source"))) + .imageId(); + try { + ec2.createTags(r -> r.resources(sourceId).tags(team)); + String untaggedId = ec2.copyImage(r -> r.sourceImageId(sourceId).sourceRegion(region) + .name(TestFixtures.uniqueName("image-tags-copy-default"))).imageId(); + try { + String taggedId = ec2.copyImage(r -> r.sourceImageId(sourceId).sourceRegion(region) + .name(TestFixtures.uniqueName("image-tags-copy-tags")).copyImageTags(true)).imageId(); + try { + assertThat(ec2.describeImages(r -> r.imageIds(untaggedId)).images().get(0).tags()) + .isEmpty(); + assertThat(ec2.describeImages(r -> r.imageIds(taggedId)).images().get(0).tags()) + .containsExactly(team); + assertThat(ec2.describeImages(r -> r.imageIds(sourceId)).images().get(0).tags()) + .containsExactly(team); + } finally { + // Each copy gets its own root snapshot, which deregistering alone would leave behind. + ec2.deregisterImage(r -> r.imageId(taggedId).deleteAssociatedSnapshots(true)); + } + } finally { + ec2.deregisterImage(r -> r.imageId(untaggedId).deleteAssociatedSnapshots(true)); + } + } finally { + ec2.deregisterImage(r -> r.imageId(sourceId)); + } + } + } +} diff --git a/docs/services/ec2.md b/docs/services/ec2.md index d71b0fb879..8fa998db6e 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -403,7 +403,7 @@ with `DryRunOperation` before any of these checks, and creates nothing either. | DescribeImages | Returns AMI metadata known to the local EC2 service. | | CreateImage | Captures an instance as a new AMI. Reboots the source unless `NoReboot=true`. Applies `image` and `snapshot` tags from `TagSpecification` to the AMI and its new snapshots. | | RegisterImage | Registers an AMI from supplied metadata and block device mappings, with `image` tags from `TagSpecification`. | -| CopyImage | Copies an AMI from `SourceRegion` into the request's region as a new AMI the caller owns, applying `image` and `snapshot` tags from `TagSpecification` to the copy and its new snapshots. | +| CopyImage | Copies an AMI from `SourceRegion` into the request's region as a new AMI the caller owns, applying `image` and `snapshot` tags from `TagSpecification` to the copy and its new snapshots. By default the source's tags are not copied. With `CopyImageTags=true` the copy also gets the caller's tags on the source AMI's own id, without its `aws:` system tags; tags put on a catalog alias such as `ami-amazonlinux2` stay behind. When a `TagSpecification` tag has the same key as a copied one, Floci keeps the `TagSpecification` value, and the copied and specified tags together may not exceed 50 (`TagLimitExceeded`, and nothing is created). | | DeregisterImage | Deregisters an AMI. Its snapshots are kept unless `DeleteAssociatedSnapshots=true`, and a snapshot another AMI still uses is kept either way. | Every resource EC2 creates is owned by the account the request resolves to, the same account 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 85d030d9ab..3b651cb625 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 @@ -4014,7 +4014,9 @@ public class Ec2QueryHandler { p.getFirst("SourceRegion"), p.getFirst("SourceImageId"), p.getFirst("Name"), - p.getFirst("Description")); + p.getFirst("Description"), + Boolean.parseBoolean(p.getFirst("CopyImageTags")), + imageTags); applyResourceTags(imageTags, region, image.getImageId()); applyImageSnapshotTags(snapshotTags, region, image); XmlBuilder xml = new XmlBuilder() 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 5f0ea6215d..258274f9e3 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 @@ -9254,10 +9254,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab * {@code available} immediately, consistent with what CreateImage and RegisterImage already * report. A caller that waits for {@code available} therefore returns on its first poll. * + *

Tags: "Default: Your user-defined AMI tags are not copied." With {@code copyImageTags} + * the copy gets the caller's tags on the source, less the {@code aws:} system tags, which AWS + * does not copy either. Floci keeps each account's tags apart and does not model shared + * ({@code ec2:SharedTag/}) tags, so no other account's tag is visible to the caller or copied. + * {@code requestedImageTags} are the image tags the request's TagSpecification will add after + * the copy; with the copied ones they must stay within the per-resource limit, which is + * checked before anything is created so a refused copy leaves no AMI or snapshot behind. + * * @see CopyImage */ public Image copyImage(String destinationRegion, String sourceRegion, String sourceImageId, - String name, String description) { + String name, String description, boolean copyImageTags, + List requestedImageTags) { if (sourceImageId == null || sourceImageId.isBlank()) { throw new AwsException("MissingParameter", "The request must contain the parameter SourceImageId", 400); } @@ -9290,11 +9299,21 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab "The image id '[" + sourceImageId + "]' does not exist in region " + sourceRegion, 400); } + List copiedTags = copyImageTags ? copiedImageTags(sourceRegion, source) : List.of(); + if (!copiedTags.isEmpty() && requestedImageTags != null && !requestedImageTags.isEmpty()) { + Set userKeys = userTagKeys(copiedTags); + userKeys.addAll(userTagKeys(requestedImageTags)); + requireWithinTagLimit(userKeys); + } // Fresh snapshot ids: two AMIs sharing one snapshot would make deleting either appear // to take the other's backing with it, and the copy's snapshots live in the // destination region anyway. Image copy = registerImage(destinationRegion, name, description, source.getArchitecture(), source.getRootDeviceName(), sourceImageMappings(source)); + if (!copiedTags.isEmpty()) { + copy.setTags(new ArrayList<>(copiedTags)); + putTags(destinationRegion, copy.getImageId(), new ArrayList<>(copiedTags)); + } copy.setVirtualizationType(source.getVirtualizationType()); copy.setRootDeviceType(source.getRootDeviceType()); copy.setPlatform(source.getPlatform()); @@ -9317,6 +9336,20 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } } + /** + * The caller's tags on the source in its own region, as CreateTags and DeleteTags keep them, + * less the system tags. Looked up by the source's own id: tags that CreateTags filed under a + * catalog alias stay with the alias. + */ + private List copiedImageTags(String sourceRegion, Image source) { + List sourceTags = tagsOf(sourceRegion, source.getImageId()) + .orElseGet(() -> source.getTags() == null ? List.of() : source.getTags()); + return sourceTags.stream() + .filter(tag -> !isAwsTagKey(tag.getKey())) + .map(tag -> new Tag(tag.getKey(), tag.getValue())) + .toList(); + } + /** Rejects an AMI id that has been deregistered; unknown ids fall through to the resolver. */ private void requireNotDeregistered(String region, String imageId) { Image image = registeredImages.get(key(region, imageId)).orElse(null); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CapturedImageReclaimIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CapturedImageReclaimIntegrationTest.java index ca43e90b8e..24a9624fb4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CapturedImageReclaimIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CapturedImageReclaimIntegrationTest.java @@ -201,7 +201,7 @@ class Ec2CapturedImageReclaimIntegrationTest { Image source = captureAmi("copy-carries-capture", tag); Image copy = service.copyImage(WEST, REGION, source.getImageId(), - uniqueName("copy-carries-capture-west"), "copied"); + uniqueName("copy-carries-capture-west"), "copied", false, List.of()); Instance fromCopy = launch(WEST, copy.getImageId()); assertEquals(tag, launchedImageOf(fromCopy).dockerImage()); @@ -214,7 +214,7 @@ class Ec2CapturedImageReclaimIntegrationTest { String tag = "floci-ami/ami-copy-shared:latest"; Image source = captureAmi("copy-shared-capture", tag); service.copyImage(WEST, REGION, source.getImageId(), - uniqueName("copy-shared-capture-west"), "copied"); + uniqueName("copy-shared-capture-west"), "copied", false, List.of()); service.deregisterImage(REGION, source.getImageId(), false); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DeregisterAndCopyImageIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DeregisterAndCopyImageIntegrationTest.java index f5be069bb3..2d12e5840b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DeregisterAndCopyImageIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DeregisterAndCopyImageIntegrationTest.java @@ -14,6 +14,7 @@ import jakarta.inject.Inject; import org.junit.jupiter.api.Test; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -62,6 +63,9 @@ class Ec2DeregisterAndCopyImageIntegrationTest { "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request"; private static final String WEST_AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-west-2/ec2/aws4_request"; + /** A 12-digit access key is taken as the account id, so this signs as a second account. */ + private static final String OTHER_ACCOUNT_EAST_AUTH = + "AWS4-HMAC-SHA256 Credential=111111111111/20260205/us-east-1/ec2/aws4_request"; private String ec2(String auth, String action, String... formParams) { RequestSpecification req = given().formParam("Action", action).header("Authorization", auth); @@ -297,7 +301,7 @@ class Ec2DeregisterAndCopyImageIntegrationTest { Image source = service.registerImage(EAST, uniqueName("floci-copy-state-src"), null, "arm64", "/dev/xvda", List.of(mapping("/dev/xvda", "snap-" + hex()))); Image copy = service.copyImage(WEST, EAST, source.getImageId(), - uniqueName("floci-copy-state-dst"), "promoted"); + uniqueName("floci-copy-state-dst"), "promoted", false, List.of()); assertEquals("available", copy.getState()); assertEquals(source.getOwnerId(), copy.getOwnerId()); @@ -315,7 +319,7 @@ class Ec2DeregisterAndCopyImageIntegrationTest { Image source = service.registerImage(EAST, uniqueName("floci-copy-snap-src"), null, "x86_64", "/dev/xvda", List.of(mapping("/dev/xvda", "snap-" + hex()))); Image copy = service.copyImage(WEST, EAST, source.getImageId(), - uniqueName("floci-copy-snap-dst"), null); + uniqueName("floci-copy-snap-dst"), null, false, List.of()); assertNotEquals(snapshotIdOf(source), snapshotIdOf(copy)); assertEquals(1, service.describeSnapshots(WEST, List.of(snapshotIdOf(copy)), null, Map.of()).size()); @@ -328,7 +332,7 @@ class Ec2DeregisterAndCopyImageIntegrationTest { Image source = service.registerImage(EAST, uniqueName("floci-copy-launch-src"), null, "x86_64", "/dev/xvda", null); Image copy = service.copyImage(WEST, EAST, source.getImageId(), - uniqueName("floci-copy-launch-dst"), null); + uniqueName("floci-copy-launch-dst"), null, false, List.of()); String instanceId = service.runInstances(WEST, copy.getImageId(), "t3.micro", 1, 1, null, List.of(), null, null, List.of(), null, null, null) @@ -379,11 +383,146 @@ class Ec2DeregisterAndCopyImageIntegrationTest { // All three are documented as required; SourceRegion in particular has no useful default, // since a missing one would silently mean "the destination region". assertEquals("MissingParameter", assertThrows(AwsException.class, - () -> service.copyImage(WEST, EAST, null, "n", null)).getErrorCode()); + () -> service.copyImage(WEST, EAST, null, "n", null, false, List.of())).getErrorCode()); assertEquals("MissingParameter", assertThrows(AwsException.class, - () -> service.copyImage(WEST, null, "ami-0abcdef1234567890", "n", null)).getErrorCode()); + () -> service.copyImage(WEST, null, "ami-0abcdef1234567890", "n", null, false, List.of())).getErrorCode()); assertEquals("MissingParameter", assertThrows(AwsException.class, - () -> service.copyImage(WEST, EAST, "ami-0abcdef1234567890", null, null)).getErrorCode()); + () -> service.copyImage(WEST, EAST, "ami-0abcdef1234567890", null, null, false, List.of())).getErrorCode()); + } + + @Test + void copyImageCopiesTheSourceTagsOnlyWhenCopyImageTagsIsTrue() { + // "Default: Your user-defined AMI tags are not copied." + String sourceId = registerViaHttp(EAST_AUTH, uniqueName("floci-copy-tags-src")); + ec2(EAST_AUTH, "CreateTags", "ResourceId.1", sourceId, + "Tag.1.Key", "Team", "Tag.1.Value", "images", "Tag.2.Key", "Stage", "Tag.2.Value", ""); + + String byDefault = copyToWest(sourceId, uniqueName("floci-copy-tags-default")); + String declined = copyToWest(sourceId, uniqueName("floci-copy-tags-declined"), "CopyImageTags", "false"); + String copied = copyToWest(sourceId, uniqueName("floci-copy-tags-copied"), "CopyImageTags", "true"); + + assertEquals(Map.of(), tagsOf(WEST_AUTH, byDefault)); + assertEquals(Map.of(), tagsOf(WEST_AUTH, declined)); + assertEquals(Map.of("Team", "images", "Stage", ""), tagsOf(WEST_AUTH, copied)); + List taggedInWest = XmlParser.extractAll(ec2(WEST_AUTH, "DescribeImages", + "Filter.1.Name", "tag:Team", "Filter.1.Value.1", "images"), "imageId"); + assertTrue(taggedInWest.contains(copied), "DescribeImages filters on the copied tags"); + assertFalse(taggedInWest.contains(byDefault)); + // The source keeps its tags, and the copy's are only in the destination region. + assertEquals(Map.of("Team", "images", "Stage", ""), tagsOf(EAST_AUTH, sourceId)); + assertEquals(Map.of(), tagsOf(EAST_AUTH, copied)); + } + + @Test + void copyImageTagsLeaveTheSourcesSystemTagsBehind() { + // "The following tags are not be copied: System tags (prefixed with aws:)". CreateTags + // refuses that prefix, so the system tag is written the way Floci writes its own. + String sourceId = registerViaHttp(EAST_AUTH, uniqueName("floci-copy-system-tags-src")); + ec2(EAST_AUTH, "CreateTags", "ResourceId.1", sourceId, "Tag.1.Key", "Team", "Tag.1.Value", "images"); + service.createSystemTags(EAST, List.of(sourceId), List.of(new Tag("aws:cloudformation:stack-name", "images"))); + + String copied = copyToWest(sourceId, uniqueName("floci-copy-system-tags-dst"), "CopyImageTags", "true"); + + assertEquals(Map.of("Team", "images"), tagsOf(WEST_AUTH, copied)); + } + + @Test + void copyImageTagsCopiesTheCallersTagsOnACatalogImageAndNoOtherAccounts() { + // The caller's own tags on a public AMI are user-defined tags AWS copies. Another + // account's tags on it are not, and Floci models no shared tags that would be. + String catalogId = "ami-0abcdef1234567890"; + String key = "Copied-" + UUID.randomUUID(); + String otherKey = "OtherAccount-" + UUID.randomUUID(); + ec2(EAST_AUTH, "CreateTags", "ResourceId.1", catalogId, "Tag.1.Key", key, "Tag.1.Value", "catalog"); + ec2(OTHER_ACCOUNT_EAST_AUTH, "CreateTags", "ResourceId.1", catalogId, + "Tag.1.Key", otherKey, "Tag.1.Value", "not-yours"); + try { + String copied = copyToWest(catalogId, uniqueName("floci-copy-catalog-tags"), "CopyImageTags", "true"); + + Map copiedTags = tagsOf(WEST_AUTH, copied); + assertEquals("catalog", copiedTags.get(key)); + assertFalse(copiedTags.containsKey(otherKey), "another account's tag must not reach the copy"); + } finally { + ec2(EAST_AUTH, "DeleteTags", "ResourceId.1", catalogId, "Tag.1.Key", key); + ec2(OTHER_ACCOUNT_EAST_AUTH, "DeleteTags", "ResourceId.1", catalogId, "Tag.1.Key", otherKey); + } + } + + @Test + void copyImageTagsReadACatalogImageNamedByItsAliasUnderItsOwnId() { + // A catalog alias names the same AMI as its id, so the copy takes the tags on that id. + String key = "ByAlias-" + UUID.randomUUID(); + ec2(EAST_AUTH, "CreateTags", "ResourceId.1", "ami-0abcdef1234567890", + "Tag.1.Key", key, "Tag.1.Value", "canonical"); + try { + String copied = copyToWest("ami-amazonlinux2", uniqueName("floci-copy-alias-tags"), "CopyImageTags", "true"); + + assertEquals("canonical", tagsOf(WEST_AUTH, copied).get(key)); + } finally { + ec2(EAST_AUTH, "DeleteTags", "ResourceId.1", "ami-0abcdef1234567890", "Tag.1.Key", key); + } + } + + @Test + void aTagSpecificationTagWinsOverACopiedTagOfTheSameKey() { + // Both reach the copy; Floci keeps the value the request names explicitly. The public + // CopyImage reference does not say how AWS settles a key given both ways. + String sourceId = registerViaHttp(EAST_AUTH, uniqueName("floci-copy-tags-and-spec-src")); + ec2(EAST_AUTH, "CreateTags", "ResourceId.1", sourceId, + "Tag.1.Key", "Team", "Tag.1.Value", "images", "Tag.2.Key", "Stage", "Tag.2.Value", "dev"); + + String copied = copyToWest(sourceId, uniqueName("floci-copy-tags-and-spec-dst"), "CopyImageTags", "true", + "TagSpecification.1.ResourceType", "image", + "TagSpecification.1.Tag.1.Key", "Stage", "TagSpecification.1.Tag.1.Value", "prod"); + + assertEquals(Map.of("Team", "images", "Stage", "prod"), tagsOf(WEST_AUTH, copied)); + } + + @Test + void copiedAndSpecifiedTagsOverTheLimitRefuseTheCopyAndLeaveNothingBehind() { + // The copy's tags are the copied ones plus the TagSpecification's; past 50 the request + // fails, and it must fail before the AMI and its snapshot exist. + Image source = service.registerImage(EAST, uniqueName("floci-copy-tag-limit-src"), null, + "x86_64", "/dev/xvda", List.of(mapping("/dev/xvda", "snap-" + hex()))); + List sourceTags = new ArrayList<>(List.of("ResourceId.1", source.getImageId())); + for (int i = 1; i <= 30; i++) { + sourceTags.addAll(List.of("Tag." + i + ".Key", "copied-" + i, "Tag." + i + ".Value", "v")); + } + ec2(EAST_AUTH, "CreateTags", sourceTags.toArray(String[]::new)); + String name = uniqueName("floci-copy-tag-limit-dst"); + int snapshotsBefore = service.describeSnapshots(WEST, List.of(), null, Map.of()).size(); + RequestSpecification copy = given().formParam("Action", "CopyImage").header("Authorization", WEST_AUTH) + .formParam("SourceRegion", EAST).formParam("SourceImageId", source.getImageId()) + .formParam("Name", name).formParam("CopyImageTags", "true") + .formParam("TagSpecification.1.ResourceType", "image"); + for (int i = 1; i <= 30; i++) { + copy = copy.formParam("TagSpecification.1.Tag." + i + ".Key", "specified-" + i); + } + + copy.when().post("/").then().statusCode(400) + .body(hasXPath("//*[local-name()='Code']", equalTo("TagLimitExceeded"))); + + assertFalse(ec2(WEST_AUTH, "DescribeImages", "Owner.1", "self").contains(name), + "a refused copy must not be registered"); + assertEquals(snapshotsBefore, service.describeSnapshots(WEST, List.of(), null, Map.of()).size()); + } + + private String copyToWest(String sourceId, String name, String... extraParams) { + List params = new ArrayList<>(List.of("SourceRegion", EAST, "SourceImageId", sourceId, "Name", name)); + params.addAll(List.of(extraParams)); + return xmlValue(ec2(WEST_AUTH, "CopyImage", params.toArray(String[]::new)), "imageId"); + } + + /** The tags DescribeTags lists for one resource in the caller's region, by key. */ + private Map tagsOf(String auth, String resourceId) { + String xml = ec2(auth, "DescribeTags", "Filter.1.Name", "resource-id", "Filter.1.Value.1", resourceId); + List keys = XmlParser.extractAll(xml, "key"); + List values = XmlParser.extractAll(xml, "value"); + Map tags = new LinkedHashMap<>(); + for (int i = 0; i < keys.size(); i++) { + tags.put(keys.get(i), values.get(i)); + } + return tags; } // ─── Concurrency ────────────────────────────────────────────────────────── @@ -411,7 +550,7 @@ class Ec2DeregisterAndCopyImageIntegrationTest { AtomicInteger duplicates = new AtomicInteger(); List created = runConcurrently(RACE_THREADS, () -> { try { - return service.copyImage(WEST, EAST, source.getImageId(), name, null); + return service.copyImage(WEST, EAST, source.getImageId(), name, null, false, List.of()); } catch (AwsException e) { assertEquals("InvalidAMIName.Duplicate", e.getErrorCode()); duplicates.incrementAndGet(); @@ -470,7 +609,7 @@ class Ec2DeregisterAndCopyImageIntegrationTest { AtomicInteger seq = new AtomicInteger(); List copies = runConcurrently(24, () -> service.copyImage(WEST, EAST, source.getImageId(), - prefix + "-" + seq.getAndIncrement(), null)); + prefix + "-" + seq.getAndIncrement(), null, false, List.of())); Set ids = copies.stream().map(Image::getImageId).collect(Collectors.toSet()); assertEquals(24, ids.size(), "every concurrent copy must get a distinct id"); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandlerTest.java index 359ce3b562..779f8114a5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandlerTest.java @@ -43,6 +43,7 @@ import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -410,7 +411,8 @@ class Ec2QueryHandlerTest { Image image = new Image(); image.setImageId("ami-0123456789abcdef2"); image.setBlockDeviceMappings(List.of(deviceMapping("/dev/sda1", "snap-0123456789abcdef3"))); - when(service.copyImage("us-east-1", "us-west-2", "ami-source", "name", null)).thenReturn(image); + when(service.copyImage(eq("us-east-1"), eq("us-west-2"), eq("ami-source"), eq("name"), isNull(), eq(false), + anyList())).thenReturn(image); MultivaluedMap params = new MultivaluedHashMap<>(); params.putSingle("SourceRegion", "us-west-2"); params.putSingle("SourceImageId", "ami-source"); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java index 15684b8296..977f7b51aa 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java @@ -278,7 +278,8 @@ class Ec2ServicePersistenceTest { String instanceId = first.runInstances(REGION, "ami-0abcdef1234567890", "t3.micro", 1, 1, null, List.of(), null, null, List.of(), null, null).getInstances().getFirst().getInstanceId(); Image captured = first.createImage(REGION, instanceId, "provenance-capture", null, true); - Image copied = first.copyImage("us-west-2", REGION, captured.getImageId(), "provenance-copy", null); + Image copied = first.copyImage("us-west-2", REGION, captured.getImageId(), + "provenance-copy", null, false, List.of()); Ec2Service restarted = newService(dir); @@ -385,7 +386,8 @@ class Ec2ServicePersistenceTest { assertTrue(restarted.describeImages("us-west-2", List.of(), List.of(), Map.of("source-image-id", List.of("*"))).isEmpty()); - Image copiedNow = restarted.copyImage("us-west-2", REGION, capture, "copied-after-upgrade", null); + Image copiedNow = restarted.copyImage("us-west-2", REGION, capture, + "copied-after-upgrade", null, false, List.of()); assertEquals(capture, copiedNow.getCreationSourceImageId()); assertEquals(REGION, copiedNow.getCreationSourceImageRegion()); assertEquals("ami-0abcdef1234567890", copiedNow.getSourceImageId()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index 0d791bd756..8ff15b2f77 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -3490,7 +3490,7 @@ class Ec2ServiceTest { Map.of("block-device-mapping.volume-type", List.of("gp2"))).get(0); assertEquals("gp2", found.getBlockDeviceMappings().get(0).getEbs().getVolumeType()); - Image copy = service.copyImage("us-east-1", "us-east-1", found.getImageId(), "copy", null); + Image copy = service.copyImage("us-east-1", "us-east-1", found.getImageId(), "copy", null, false, List.of()); assertEquals("gp2", copy.getBlockDeviceMappings().get(0).getEbs().getVolumeType()); } @@ -3513,7 +3513,7 @@ class Ec2ServiceTest { } // A copy's root is still backed by a real snapshot record. - Image copy = service.copyImage("us-east-1", "us-east-1", catalog.getImageId(), "copy", null); + Image copy = service.copyImage("us-east-1", "us-east-1", catalog.getImageId(), "copy", null, false, List.of()); String copySnapshot = copy.getBlockDeviceMappings().getFirst().getEbs().getSnapshotId(); assertEquals(1, service.describeSnapshots("us-east-1", List.of(copySnapshot), null, Map.of()).size()); }