From 73da37b90e24e5133350d308e8406a2298669e76 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Mon, 19 Oct 2026 22:39:29 -0500 Subject: [PATCH] fix(ec2): reject tag writes on missing, malformed or absent resources (#5996) * fix(ec2): reject tag writes on missing, malformed or absent resources CreateTags and DeleteTags stored tags for any id. Both now answer MissingParameter when no resource is named and InvalidID for an id that is not a known EC2 prefix followed by hex digits. CreateTags also checks each resource exists in the request region and answers with that type's own NotFound error, as moto does; a well-formed id of a type Floci does not model is still tagged. CreateTags enforces the documented limits: at most 50 user tags per resource (aws: tags do not count) with TagLimitExceeded, and keys up to 128 and values up to 256 Unicode characters with InvalidParameterValue. Every resource and limit is checked before any tag is written. Signed-off-by: Hector Ventura * fix(ec2): match tag targets in full and resolve them by their prefix A tag target id is now matched in full with an 8 or 17 hex suffix, and an id Floci seeds without hex digits (a default VPC resource, a catalog AMI alias) passes only when the region holds it. The resource type comes from the matched prefix, so eni-attach-, vpce-svc- and the cidr-assoc ids reach the unmodelled arm, and an AMI is checked against the catalog and the region's registered images instead of DescribeImages, which answers an unknown id with a launchable fallback. Signed-off-by: Hector Ventura * fix(ec2): accept fleet and IPAM tag targets and check the tag limit under the write's locks EC2 Fleet and Spot Fleet request ids are UUIDs and an IPAM pool allocation id has 33 hex digits, so a tag target id now takes 8 or more hex digits or a UUID, and the ipam, ipam-scope, ipam-pool and ipam-pool-alloc prefixes are known. The 50-tag check ran before the write took its resource locks, so concurrent CreateTags requests at 49 tags could all pass it; the check and the write now run holding every named resource's lock, taken in stripe order after the topology lock. Signed-off-by: Hector Ventura --------- Signed-off-by: Hector Ventura --- docs/services/ec2.md | 9 + .../floci/services/ec2/Ec2Service.java | 195 ++++++++++++++++- .../ec2/Ec2ServiceConcurrencyTest.java | 28 +++ .../floci/services/ec2/Ec2ServiceTest.java | 205 ++++++++++++++---- .../ec2/Ec2TagValidationIntegrationTest.java | 46 ++++ 5 files changed, 441 insertions(+), 42 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TagValidationIntegrationTest.java diff --git a/docs/services/ec2.md b/docs/services/ec2.md index d32a7244d4..5372586c04 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -327,6 +327,15 @@ version are moved under their resource's region at startup. Tags on a catalog AM default region, and tags on an EKS node instance move to the node's region once the node is restored; any other tag whose resource no longer exists is dropped. +`CreateTags` and `DeleteTags` require at least one resource id (`MissingParameter`) and reject an +id that is not a known EC2 resource prefix followed by 8 or more hex digits or, for fleets, a UUID +(`InvalidID`). `CreateTags` also +checks each resource exists in the request's region and answers with that type's own error +(`InvalidVpcID.NotFound`, `InvalidInstanceID.NotFound`, ...); a well-formed id of a type Floci does +not model is tagged as given. A resource takes at most 50 user tags (`TagLimitExceeded`; tags with +the `aws:` prefix do not count), keys up to 128 and values up to 256 Unicode characters +(`InvalidParameterValue`). A request that fails changes no resource's tags. + Public tag mutations reject keys beginning with `aws:` regardless of ASCII case. An empty `DeleteTags` tag list removes user tags and preserves AWS-managed tags. CloudFormation tag updates and rollbacks likewise leave AWS-managed tags intact. 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 be2255d797..232d070a04 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 @@ -137,6 +137,7 @@ import java.util.function.BiPredicate; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; +import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -155,6 +156,20 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab private static final DateTimeFormatter ISO_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .withZone(ZoneOffset.UTC); private static final int DEFAULT_ROOT_VOLUME_SIZE_GIB = 8; + // An EC2 id is a known resource prefix, a hyphen and either 8 or more hex digits (8, 17, or 33 + // for an IPAM pool allocation) or a UUID (EC2 Fleet and Spot Fleet requests). Longer prefixes + // come first so that eni-attach- is read as one type, not as eni-. + private static final String TAGGABLE_RESOURCE_TYPES = "(subnet-cidr-assoc|vpc-cidr-assoc" + + "|ipam-pool-alloc|ipam-scope|ipam-pool|ipam" + + "|traf-mir-fil|traf-mir-tar|iip-assoc|eni-attach|tgw-attach|tgw-rtb|vpce-svc|aclassoc|eipassoc" + + "|eipalloc|rtbassoc|subnet|fleet|cagw|dopt|eigw|snap|vpce|acl|ami|cgw|eni|igw|key|nat|pcx|rtb|scr" + + "|sfr|sgr|sir|tgw|tms|vgw|vol|vpc|vpn|cr|fl|lt|pl|sg|h|i|r)-"; + private static final Pattern TAGGABLE_RESOURCE_ID = Pattern.compile(TAGGABLE_RESOURCE_TYPES + + "(?:[0-9a-f]{8,}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"); + private static final Pattern TAGGABLE_RESOURCE_PREFIX = Pattern.compile(TAGGABLE_RESOURCE_TYPES); + private static final int MAX_USER_TAGS_PER_RESOURCE = 50; + private static final int MAX_TAG_KEY_LENGTH = 128; + private static final int MAX_TAG_VALUE_LENGTH = 256; private static final long SYNTHETIC_FIRST_OFFSET = 10; /** AWS reserves the first four addresses of every subnet, so offset 4 is the first assignable one. */ private static final long ENDPOINT_FIRST_USABLE_OFFSET = 4; @@ -8618,8 +8633,185 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab // ─── Tags ────────────────────────────────────────────────────────────────── public void createTags(String region, List resourceIds, List tagList) { + validateTagTargets(region, resourceIds); validateUserTagKeys(tagList); - createSystemTags(region, resourceIds, tagList); + validateTagLengths(tagList); + ensureDefaultResources(region); + for (String resourceId : resourceIds) { + requireTaggableResource(region, resourceId); + } + // The limit is checked under the same locks as the write, so two requests cannot both pass + // it and then together exceed it, and a rejected request writes nothing. + withTagWriteLocks(region, resourceIds, () -> { + for (String resourceId : resourceIds) { + requireWithinTagLimit(region, resourceId, tagList); + } + createSystemTags(region, resourceIds, tagList); + }); + } + + /** + * Runs a tag write holding the lock of every resource it names, in the order the deletes and + * {@link #withTopologyLockIfNeeded} use: the topology lock first when a transit gateway + * resource is among them, then the stripes in ascending index order, the total order every + * multi-stripe caller agrees on. + */ + private void withTagWriteLocks(String region, List resourceIds, Runnable change) { + int[] stripes = resourceIds.stream().mapToInt(id -> stripeOf(key(region, id))).distinct().sorted().toArray(); + if (resourceIds.stream().anyMatch(id -> id.startsWith("tgw-"))) { + synchronized (attachmentTopologyLock(region)) { + runHoldingStripes(stripes, 0, change); + } + return; + } + runHoldingStripes(stripes, 0, change); + } + + private void runHoldingStripes(int[] stripes, int next, Runnable change) { + if (next == stripes.length) { + change.run(); + return; + } + synchronized (resourceLocks[stripes[next]]) { + runHoldingStripes(stripes, next + 1, change); + } + } + + /** + * CreateTags and DeleteTags name at least one resource, each a well-formed EC2 id. An id Floci + * seeds without hex digits (the default VPC's, a catalog AMI's) passes only when this region + * holds that resource. + */ + private void validateTagTargets(String region, List resourceIds) { + if (resourceIds == null || resourceIds.isEmpty()) { + throw new AwsException("MissingParameter", "The request must contain the parameter resourceIdSet", 400); + } + for (String resourceId : resourceIds) { + if (resourceId == null || !TAGGABLE_RESOURCE_ID.matcher(resourceId).matches() + && !holdsSeededResource(region, resourceId)) { + throw new AwsException("InvalidID", "The ID '" + resourceId + "' is not valid", 400); + } + } + } + + private boolean holdsSeededResource(String region, String resourceId) { + if (!TAGGABLE_RESOURCE_PREFIX.matcher(resourceId).lookingAt()) { + return false; + } + ensureDefaultResources(region); + try { + return requireTaggableResource(region, resourceId); + } catch (AwsException notHeld) { + // A non-hex id that names nothing here is malformed rather than missing. + return false; + } + } + + private static void validateTagLengths(List tagList) { + for (Tag tag : tagList) { + if (tag.getKey().codePointCount(0, tag.getKey().length()) > MAX_TAG_KEY_LENGTH) { + throw new AwsException("InvalidParameterValue", + "Tag key exceeds the maximum length of " + MAX_TAG_KEY_LENGTH + " characters", 400); + } + String value = tag.getValue(); + if (value != null && value.codePointCount(0, value.length()) > MAX_TAG_VALUE_LENGTH) { + throw new AwsException("InvalidParameterValue", + "Tag value exceeds the maximum length of " + MAX_TAG_VALUE_LENGTH + " characters", 400); + } + } + } + + /** + * CreateTags fails for a resource this region does not hold, with the error that resource's own + * Describe call gives. A well-formed id of a type Floci does not model is accepted. + * + * @return whether Floci models the resource's type, and so found it + */ + private boolean requireTaggableResource(String region, String resourceId) { + Matcher prefix = TAGGABLE_RESOURCE_PREFIX.matcher(resourceId); + if (!prefix.lookingAt()) { + throw new AwsException("InvalidID", "The ID '" + resourceId + "' is not valid", 400); + } + switch (prefix.group(1)) { + case "i" -> getRequiredInstance(region, resourceId); + case "vpc" -> getRequiredVpc(region, resourceId); + case "subnet" -> requireSubnet(region, resourceId); + case "sg" -> getRequiredSecurityGroup(region, resourceId); + case "sgr" -> requireFound(!describeSecurityGroupRules(region, List.of(), List.of(resourceId)).isEmpty(), + "InvalidSecurityGroupRuleId.NotFound", "The security group rule ID '" + resourceId + "' does not exist"); + case "igw" -> getRequiredInternetGateway(region, resourceId); + case "eigw" -> requireFound(egressOnlyInternetGateways.get(key(region, resourceId)).isPresent(), + "InvalidGatewayID.NotFound", "The eigw ID '" + resourceId + "' does not exist"); + case "rtb" -> getRequiredRouteTable(region, resourceId); + case "acl" -> getRequiredNetworkAcl(region, resourceId); + case "nat" -> getRequiredNatGateway(region, resourceId); + case "eipalloc" -> getRequiredAddress(region, resourceId); + case "vpce" -> getRequiredVpcEndpoint(region, resourceId); + case "pl" -> getRequiredManagedPrefixList(region, resourceId); + case "tgw" -> getRequiredTransitGateway(region, resourceId); + case "tgw-rtb" -> getRequiredTransitGatewayRouteTable(region, resourceId); + case "tgw-attach" -> { + if (transitGatewayVpcAttachments.get(key(region, resourceId)).isEmpty()) { + getRequiredPeeringAttachment(region, resourceId); + } + } + case "cr" -> getRequiredCapacityReservation(region, resourceId); + case "h" -> getRequiredHost(region, resourceId); + case "vol" -> getRequiredVolume(region, resourceId); + // Not describeImages: it answers an unknown ami- id with a launchable fallback image. + case "ami" -> requireFound(imageCatalog.findByIdOrAlias(resourceId).isPresent() + || registeredImages.get(key(region, resourceId)) + .filter(image -> !DEREGISTERED_STATE.equals(image.getState())).isPresent(), + "InvalidAMIID.NotFound", "The image id '[" + resourceId + "]' does not exist"); + case "snap" -> requireFound(!describeSnapshots(region, List.of(resourceId), List.of(), Map.of()).isEmpty(), + "InvalidSnapshot.NotFound", "The snapshot '" + resourceId + "' does not exist."); + case "key" -> requireFound(!describeKeyPairs(region, List.of(), List.of(resourceId)).isEmpty(), + "InvalidKeyPair.NotFound", "The key pair '" + resourceId + "' does not exist"); + case "lt" -> requireFound(!describeLaunchTemplates(region, List.of(resourceId), List.of(), Map.of()).isEmpty(), + "InvalidLaunchTemplateId.NotFound", "The specified launch template, with template ID " + + resourceId + ", does not exist."); + case "eni" -> requireFound(!describeNetworkInterfaces(region, List.of(resourceId), Map.of()) + .networkInterfaces().isEmpty(), + "InvalidNetworkInterfaceID.NotFound", "The networkInterface ID '" + resourceId + "' does not exist"); + case "sir" -> requireFound(!describeSpotInstanceRequests(region, List.of(resourceId), Map.of()).isEmpty(), + "InvalidSpotInstanceRequestID.NotFound", "The spot instance request ID '" + resourceId + + "' does not exist"); + case "pcx" -> { + if (describeVpcPeeringConnections(region, List.of(resourceId), Map.of()).isEmpty()) { + throw vpcPeeringConnectionNotFound(resourceId); + } + } + default -> { + // A valid EC2 id of a type Floci does not model: tagged as given. + return false; + } + } + return true; + } + + private static void requireFound(boolean found, String code, String message) { + if (!found) { + throw new AwsException(code, message, 400); + } + } + + /** At most 50 user tags on a resource after the change; tags with the aws: prefix do not count. */ + private void requireWithinTagLimit(String region, String resourceId, List tagList) { + Set userKeys = new HashSet<>(); + for (Tag tag : tagsOf(region, resourceId).orElse(List.of())) { + if (!isAwsTagKey(tag.getKey())) { + userKeys.add(tag.getKey()); + } + } + for (Tag tag : tagList) { + if (!isAwsTagKey(tag.getKey())) { + userKeys.add(tag.getKey()); + } + } + if (userKeys.size() > MAX_USER_TAGS_PER_RESOURCE) { + throw new AwsException("TagLimitExceeded", + "The maximum number of Tags for a resource has been reached.", 400); + } } /** Service-owned tags, separate from the public EC2 CreateTags operation. */ @@ -8661,6 +8853,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public void deleteTags(String region, List resourceIds, List tagList) { + validateTagTargets(region, resourceIds); validateUserTagKeys(tagList); ensureDefaultResources(region); for (String resourceId : resourceIds) { diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceConcurrencyTest.java index 0bc343cdcf..bca33faf58 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceConcurrencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceConcurrencyTest.java @@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager; import org.junit.jupiter.api.Test; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; @@ -229,6 +230,33 @@ class Ec2ServiceConcurrencyTest { } } + @Test + void concurrentCreateTagsNeverPassTheFiftyTagLimit() throws Exception { + for (int trial = 0; trial < TRIALS; trial++) { + String region = "race-tag-limit-" + trial; + Ec2Service service = newService(); + String vpcId = service.createVpc(region, "10.0.0.0/16", false).getVpcId(); + List fortyNine = new ArrayList<>(); + for (int i = 0; i < 49; i++) { + fortyNine.add(new Tag("k" + i, "v")); + } + service.createTags(region, List.of(vpcId), fortyNine); + AtomicInteger accepted = new AtomicInteger(); + + runRaceAllowing(i -> { + try { + service.createTags(region, List.of(vpcId), List.of(new Tag("race" + i, "v"))); + accepted.incrementAndGet(); + } catch (AwsException e) { + assertEquals("TagLimitExceeded", e.getErrorCode()); + } + }); + + assertEquals(1, accepted.get(), "trial " + trial + ": only one writer takes the fiftieth tag"); + assertEquals(50, service.resourceTags(region, vpcId).size(), "trial " + trial + ": tags stored"); + } + } + /** Runs N concurrent invocations of the same op; the op absorbs its own expected failures. */ private static void runRaceAllowing(java.util.function.IntConsumer op) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(THREADS); 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 07f9958df8..983448419b 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 @@ -881,6 +881,129 @@ class Ec2ServiceTest { assertFalse(tagStore.keys().contains("null::" + nodeId)); } + @Test + void createTagsOnAnotherRegionsVpcIsNotFoundAndWritesNothing() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + String east = service.createVpc("us-east-1", "10.85.0.0/16", false).getVpcId(); + String west = service.createVpc("eu-west-1", "10.86.0.0/16", false).getVpcId(); + + AwsException missing = assertThrows(AwsException.class, () -> service.createTags("eu-west-1", + List.of(west, east), List.of(new Tag("Team", "x")))); + + assertEquals("InvalidVpcID.NotFound", missing.getErrorCode()); + assertTrue(service.describeTags("eu-west-1", Map.of("key", List.of("Team"))).isEmpty()); + assertTrue(service.describeTags("us-east-1", Map.of("key", List.of("Team"))).isEmpty()); + } + + @Test + void tagWritesRejectMissingAndMalformedIds() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + List tag = List.of(new Tag("Team", "x")); + + assertEquals("MissingParameter", assertThrows(AwsException.class, + () -> service.createTags("us-east-1", List.of(), tag)).getErrorCode()); + assertEquals("MissingParameter", assertThrows(AwsException.class, + () -> service.deleteTags("us-east-1", List.of(), tag)).getErrorCode()); + for (String id : List.of("not-an-id", "vpc-xyz", "i-123", "foo-0123456789abcdef0", "vgw-12345678-not-an-id", + "vgw-0123456", "vgw-0123456789ABCDEF0", "fleet-73fbd2ce-aa30-494c-8788", "vpc-default-nowhere")) { + assertEquals("InvalidID", assertThrows(AwsException.class, + () -> service.createTags("us-east-1", List.of(id), tag)).getErrorCode(), id); + assertEquals("InvalidID", assertThrows(AwsException.class, + () -> service.deleteTags("us-east-1", List.of(id), tag)).getErrorCode(), id); + } + } + + @Test + void aWellFormedIdOfAnUnmodelledTypeIsTagged() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + + List ids = List.of("vgw-0123456789abcdef0", "vgw-01234567", "vpce-svc-0123456789abcdef0", + "eni-attach-0123456789abcdef0", "vpc-cidr-assoc-01234567", "subnet-cidr-assoc-0123456789abcdef0", + "fleet-73fbd2ce-aa30-494c-8788-1cee4a1b2c3d", "fleet-0123456789abcdef0123456789abcdef", + "sfr-306341ed-9739-402e-881b-ce47b0123456", "ipam-0123456789abcdef0", + "ipam-scope-0123456789abcdef0", "ipam-pool-0123456789abcdef0", + "ipam-pool-alloc-018ecc28043b54ba38e2cd99943cebfbd"); + service.createTags("us-east-1", ids, List.of(new Tag("Team", "x"))); + + for (String id : ids) { + assertEquals("x", service.resourceTags("us-east-1", id).getFirst().getValue(), id); + } + } + + @Test + void theDefaultVpcsSeededResourcesTakeTags() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + Map> isDefault = Map.of("is-default", List.of("true")); + String vpcId = service.describeVpcs("us-east-1", List.of(), isDefault).getFirst().getVpcId(); + Map> inVpc = Map.of("vpc-id", List.of(vpcId)); + List ids = new ArrayList<>(List.of(vpcId, + service.describeSubnets("us-east-1", List.of(), inVpc).getFirst().getSubnetId(), + service.describeSecurityGroups("us-east-1", List.of(), List.of(), inVpc).getFirst().getGroupId(), + service.describeInternetGateways("us-east-1", List.of(), Map.of()).getFirst().getInternetGatewayId(), + service.describeRouteTables("us-east-1", List.of(), inVpc).getFirst().getRouteTableId(), + service.describeNetworkAcls("us-east-1", List.of(), inVpc).getFirst().getNetworkAclId())); + + service.createTags("us-east-1", ids, List.of(new Tag("Team", "x"))); + for (String id : ids) { + assertEquals("x", service.resourceTags("us-east-1", id).getFirst().getValue(), id); + } + service.deleteTags("us-east-1", ids, List.of(new Tag("Team", null))); + for (String id : ids) { + assertTrue(service.resourceTags("us-east-1", id).isEmpty(), id); + } + } + + @Test + void catalogImagesTakeTagsButAnAbsentImageIsNotFound() { + Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog(); + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), new AmiImageResolver(imageCatalog), imageCatalog, + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + Ec2ImageCatalog.CatalogImage catalogImage = imageCatalog.images().stream() + .filter(image -> !image.aliases().isEmpty()).findFirst().orElseThrow(); + List ids = List.of(catalogImage.imageId, catalogImage.aliases().getFirst()); + + service.createTags("us-east-1", ids, List.of(new Tag("Team", "x"))); + AwsException absent = assertThrows(AwsException.class, () -> service.createTags("us-east-1", + List.of("ami-0123456789abcdef0"), List.of(new Tag("Team", "x")))); + + assertEquals("InvalidAMIID.NotFound", absent.getErrorCode()); + assertTrue(service.resourceTags("us-east-1", "ami-0123456789abcdef0").isEmpty()); + } + + @Test + void aResourceTakesFiftyUserTagsAndAwsTagsDoNotCount() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + String vpcId = service.createVpc("us-east-1", "10.87.0.0/16", false).getVpcId(); + service.createSystemTags("us-east-1", List.of(vpcId), List.of(new Tag("aws:cloudformation:stack-name", "s"))); + List fifty = new ArrayList<>(); + for (int i = 0; i < 50; i++) { + fifty.add(new Tag("k" + i, "v")); + } + + service.createTags("us-east-1", List.of(vpcId), fifty); + service.createTags("us-east-1", List.of(vpcId), List.of(new Tag("k0", "overwritten"))); + AwsException limit = assertThrows(AwsException.class, + () -> service.createTags("us-east-1", List.of(vpcId), List.of(new Tag("k50", "v")))); + + assertEquals("TagLimitExceeded", limit.getErrorCode()); + assertEquals(51, service.resourceTags("us-east-1", vpcId).size()); + } + + @Test + void tagKeysAndValuesAreLimitedTo128And256Characters() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + String vpcId = service.createVpc("us-east-1", "10.88.0.0/16", false).getVpcId(); + + service.createTags("us-east-1", List.of(vpcId), List.of(new Tag("k".repeat(128), "v".repeat(256)))); + assertEquals("InvalidParameterValue", assertThrows(AwsException.class, () -> service.createTags("us-east-1", + List.of(vpcId), List.of(new Tag("k".repeat(129), "v")))).getErrorCode()); + assertEquals("InvalidParameterValue", assertThrows(AwsException.class, () -> service.createTags("us-east-1", + List.of(vpcId), List.of(new Tag("k", "v".repeat(257))))).getErrorCode()); + // Unicode characters, not UTF-16 units: 128 emoji are a valid key. + service.createTags("us-east-1", List.of(vpcId), List.of(new Tag("\uD83D\uDE00".repeat(128), "v"))); + } + private static Ec2Service tagTestService(StorageFactory storageFactory) { return new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), storageFactory); @@ -3158,13 +3281,13 @@ class Ec2ServiceTest { new InMemoryStorageFactory(Map.of("ec2-registered-images.json", imageStorage))); Image stored = new Image(); - stored.setImageId("ami-detached-tags"); + stored.setImageId("ami-0de7ac4ed7a95"); stored.setName("detached-tags"); stored.setOwnerId("000000000000"); stored.setPublic(false); stored.setImageOwnerAlias(null); stored.setRegion("us-east-1"); - imageStorage.put("us-east-1::ami-detached-tags", stored); + imageStorage.put("us-east-1::ami-0de7ac4ed7a95", stored); int putsBeforeDescribe = imageStorage.putCount(); Tag tag = new Tag(); @@ -7094,7 +7217,7 @@ class Ec2ServiceTest { } private Image storedImage() { - return copy(values.get("us-east-1::ami-detached-tags")); + return copy(values.get("us-east-1::ami-0de7ac4ed7a95")); } private static Image copy(Image source) { @@ -7129,7 +7252,7 @@ class Ec2ServiceTest { mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); Instance nodeInstance = new Instance(); - nodeInstance.setInstanceId("i-node1234567890abc"); + nodeInstance.setInstanceId("i-0de1234567890abc"); nodeInstance.setRegion("us-east-1"); nodeInstance.setPlacement(new Placement("us-east-1a")); nodeInstance.setState(InstanceState.running()); @@ -7139,7 +7262,7 @@ class Ec2ServiceTest { service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() { @Override public Optional findInstance(String accountId, String region, String instanceId) { - return "i-node1234567890abc".equals(instanceId) && ("us-east-1".equals(region) || region == null) + return "i-0de1234567890abc".equals(instanceId) && ("us-east-1".equals(region) || region == null) ? Optional.of(nodeInstance) : Optional.empty(); } @@ -7165,7 +7288,7 @@ class Ec2ServiceTest { mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); Instance nodeInstance = new Instance(); - nodeInstance.setInstanceId("i-node1234567890abc"); + nodeInstance.setInstanceId("i-0de1234567890abc"); nodeInstance.setRegion("us-east-1"); nodeInstance.setPlacement(new Placement("us-east-1a")); nodeInstance.setState(InstanceState.running()); @@ -7175,7 +7298,7 @@ class Ec2ServiceTest { service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() { @Override public Optional findInstance(String accountId, String region, String instanceId) { - return "i-node1234567890abc".equals(instanceId) && ("us-east-1".equals(region) || region == null) + return "i-0de1234567890abc".equals(instanceId) && ("us-east-1".equals(region) || region == null) ? Optional.of(nodeInstance) : Optional.empty(); } @@ -7188,11 +7311,11 @@ class Ec2ServiceTest { List reservations = service.describeInstances("us-east-1", List.of(), Map.of()); assertEquals(1, reservations.size()); Instance inst = reservations.getFirst().getInstances().getFirst(); - assertEquals("i-node1234567890abc", inst.getInstanceId()); + assertEquals("i-0de1234567890abc", inst.getInstanceId()); assertEquals("m5.large", inst.getInstanceType()); assertEquals("us-east-1a", inst.getPlacement().getAvailabilityZone()); - List byId = service.describeInstances("us-east-1", List.of("i-node1234567890abc"), Map.of()); + List byId = service.describeInstances("us-east-1", List.of("i-0de1234567890abc"), Map.of()); assertEquals(1, byId.size()); List filtered = service.describeInstances("us-east-1", List.of(), Map.of("instance-type", List.of("m5.large"))); @@ -7203,11 +7326,11 @@ class Ec2ServiceTest { List statuses = service.describeInstanceStatus("us-east-1", List.of()); assertEquals(1, statuses.size()); - assertEquals("i-node1234567890abc", statuses.getFirst().getInstanceId()); + assertEquals("i-0de1234567890abc", statuses.getFirst().getInstanceId()); - Instance foundById = service.findInstanceById("i-node1234567890abc"); + Instance foundById = service.findInstanceById("i-0de1234567890abc"); assertNotNull(foundById); - assertEquals("i-node1234567890abc", foundById.getInstanceId()); + assertEquals("i-0de1234567890abc", foundById.getInstanceId()); } @Test @@ -7216,7 +7339,7 @@ class Ec2ServiceTest { mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); Instance nodeInstance = new Instance(); - nodeInstance.setInstanceId("i-node1234567890abc"); + nodeInstance.setInstanceId("i-0de1234567890abc"); nodeInstance.setRegion("us-east-1"); nodeInstance.setPlacement(new Placement("us-east-1a")); nodeInstance.setState(InstanceState.running()); @@ -7225,7 +7348,7 @@ class Ec2ServiceTest { service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() { @Override public Optional findInstance(String accountId, String region, String instanceId) { - return "i-node1234567890abc".equals(instanceId) && ("us-east-1".equals(region) || region == null) + return "i-0de1234567890abc".equals(instanceId) && ("us-east-1".equals(region) || region == null) ? Optional.of(nodeInstance) : Optional.empty(); } @@ -7236,22 +7359,22 @@ class Ec2ServiceTest { }); AwsException terminateEx = assertThrows(AwsException.class, () -> - service.terminateInstances("us-east-1", List.of("i-node1234567890abc"))); + service.terminateInstances("us-east-1", List.of("i-0de1234567890abc"))); assertEquals("OperationNotPermitted", terminateEx.getErrorCode()); assertEquals(400, terminateEx.getHttpStatus()); AwsException stopEx = assertThrows(AwsException.class, () -> - service.stopInstances("us-east-1", List.of("i-node1234567890abc"))); + service.stopInstances("us-east-1", List.of("i-0de1234567890abc"))); assertEquals("OperationNotPermitted", stopEx.getErrorCode()); assertEquals(400, stopEx.getHttpStatus()); AwsException startEx = assertThrows(AwsException.class, () -> - service.startInstances("us-east-1", List.of("i-node1234567890abc"))); + service.startInstances("us-east-1", List.of("i-0de1234567890abc"))); assertEquals("OperationNotPermitted", startEx.getErrorCode()); assertEquals(400, startEx.getHttpStatus()); AwsException rebootEx = assertThrows(AwsException.class, () -> - service.rebootInstances("us-east-1", List.of("i-node1234567890abc"))); + service.rebootInstances("us-east-1", List.of("i-0de1234567890abc"))); assertEquals("OperationNotPermitted", rebootEx.getErrorCode()); assertEquals(400, rebootEx.getHttpStatus()); } @@ -7342,7 +7465,7 @@ class Ec2ServiceTest { mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); Instance nodeInstance = new Instance(); - nodeInstance.setInstanceId("i-node1234567890abc"); + nodeInstance.setInstanceId("i-0de1234567890abc"); nodeInstance.setRegion("us-east-1"); nodeInstance.setPlacement(new Placement("us-east-1a")); nodeInstance.setState(InstanceState.running()); @@ -7350,7 +7473,7 @@ class Ec2ServiceTest { service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() { @Override public Optional findInstance(String accountId, String region, String instanceId) { - return "i-node1234567890abc".equals(instanceId) ? Optional.of(nodeInstance) : Optional.empty(); + return "i-0de1234567890abc".equals(instanceId) ? Optional.of(nodeInstance) : Optional.empty(); } @Override @@ -7379,7 +7502,7 @@ class Ec2ServiceTest { mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); Instance nodeInstance = new Instance(); - nodeInstance.setInstanceId("i-node1234567890abc"); + nodeInstance.setInstanceId("i-0de1234567890abc"); nodeInstance.setRegion("us-east-1"); nodeInstance.setPlacement(new Placement("us-east-1a")); nodeInstance.setState(InstanceState.running()); @@ -7387,7 +7510,7 @@ class Ec2ServiceTest { service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() { @Override public Optional findInstance(String accountId, String region, String instanceId) { - return "i-node1234567890abc".equals(instanceId) ? Optional.of(nodeInstance) : Optional.empty(); + return "i-0de1234567890abc".equals(instanceId) ? Optional.of(nodeInstance) : Optional.empty(); } @Override @@ -7402,7 +7525,7 @@ class Ec2ServiceTest { assertTrue(service.describeInstances("us-east-1", List.of(), Map.of()).isEmpty()); AwsException error = assertThrows(AwsException.class, () -> - service.describeInstances("us-east-1", List.of("i-node1234567890abc"), Map.of())); + service.describeInstances("us-east-1", List.of("i-0de1234567890abc"), Map.of())); assertEquals("InvalidInstanceID.NotFound", error.getErrorCode()); } @@ -7412,7 +7535,7 @@ class Ec2ServiceTest { String accountB = "444455556666"; Instance nodeInstance = new Instance(); - nodeInstance.setInstanceId("i-node1234567890abc"); + nodeInstance.setInstanceId("i-0de1234567890abc"); nodeInstance.setRegion("us-east-1"); nodeInstance.setPlacement(new Placement("us-east-1a")); nodeInstance.setState(InstanceState.running()); @@ -7421,7 +7544,7 @@ class Ec2ServiceTest { ClusterNodeInstanceProvider provider = new ClusterNodeInstanceProvider() { @Override public Optional findInstance(String accountId, String region, String instanceId) { - if (accountA.equals(accountId) && "i-node1234567890abc".equals(instanceId)) { + if (accountA.equals(accountId) && "i-0de1234567890abc".equals(instanceId)) { return Optional.of(nodeInstance); } return Optional.empty(); @@ -7452,7 +7575,7 @@ class Ec2ServiceTest { reqCtx.setAccountId(accountA); List resA = service.describeInstances("us-east-1", List.of(), Map.of()); assertEquals(1, resA.size()); - assertEquals("i-node1234567890abc", resA.getFirst().getInstances().getFirst().getInstanceId()); + assertEquals("i-0de1234567890abc", resA.getFirst().getInstances().getFirst().getInstanceId()); // Under account B, instance is not visible reqCtx.setAccountId(accountB); @@ -7460,27 +7583,27 @@ class Ec2ServiceTest { assertTrue(resB.isEmpty()); AwsException notFoundB = assertThrows(AwsException.class, () -> - service.describeInstances("us-east-1", List.of("i-node1234567890abc"), Map.of())); + service.describeInstances("us-east-1", List.of("i-0de1234567890abc"), Map.of())); assertEquals("InvalidInstanceID.NotFound", notFoundB.getErrorCode()); // findInstanceForAccount respects account argument - assertTrue(service.findInstanceForAccount(accountA, "us-east-1", "i-node1234567890abc").isPresent()); - assertTrue(service.findInstanceForAccount(accountB, "us-east-1", "i-node1234567890abc").isEmpty()); + assertTrue(service.findInstanceForAccount(accountA, "us-east-1", "i-0de1234567890abc").isPresent()); + assertTrue(service.findInstanceForAccount(accountB, "us-east-1", "i-0de1234567890abc").isEmpty()); // findInstanceById respects callerAccountId and explicit account argument - assertNull(service.findInstanceById("i-node1234567890abc")); - assertNull(service.findInstanceById(accountB, "i-node1234567890abc")); - assertNotNull(service.findInstanceById(accountA, "i-node1234567890abc")); + assertNull(service.findInstanceById("i-0de1234567890abc")); + assertNull(service.findInstanceById(accountB, "i-0de1234567890abc")); + assertNotNull(service.findInstanceById(accountA, "i-0de1234567890abc")); reqCtx.setAccountId(accountA); - assertNotNull(service.findInstanceById("i-node1234567890abc")); + assertNotNull(service.findInstanceById("i-0de1234567890abc")); } @Test void clusterNodeInstanceTaggingIsolatedAndDoesNotMutateProvider() { String accountA = "111122223333"; Instance nodeInstance = new Instance(); - nodeInstance.setInstanceId("i-node1234567890abc"); + nodeInstance.setInstanceId("i-0de1234567890abc"); nodeInstance.setRegion("us-east-1"); nodeInstance.setPlacement(new Placement("us-east-1a")); nodeInstance.setState(InstanceState.running()); @@ -7491,7 +7614,7 @@ class Ec2ServiceTest { ClusterNodeInstanceProvider provider = new ClusterNodeInstanceProvider() { @Override public Optional findInstance(String accountId, String region, String instanceId) { - if (accountA.equals(accountId) && "i-node1234567890abc".equals(instanceId)) { + if (accountA.equals(accountId) && "i-0de1234567890abc".equals(instanceId)) { return Optional.of(nodeInstance); } return Optional.empty(); @@ -7520,31 +7643,31 @@ class Ec2ServiceTest { service.setClusterNodeInstanceProvider(provider); // Before any custom tags are added, describeTags includes default tags - List> initialTags = service.describeTags("us-east-1", Map.of("resource-id", List.of("i-node1234567890abc"))); + List> initialTags = service.describeTags("us-east-1", Map.of("resource-id", List.of("i-0de1234567890abc"))); assertEquals(1, initialTags.size()); assertEquals("Name", initialTags.getFirst().get("key")); assertEquals("test-cluster-node", initialTags.getFirst().get("value")); // Create tags on the node instance - service.createTags("us-east-1", List.of("i-node1234567890abc"), List.of(new Tag("Environment", "production"))); + service.createTags("us-east-1", List.of("i-0de1234567890abc"), List.of(new Tag("Environment", "production"))); // Provider's underlying object must NOT be mutated assertEquals(1, nodeInstance.getTags().size()); assertEquals("Name", nodeInstance.getTags().getFirst().getKey()); // EC2 service returns defensive copy with new tag merged - List reservations = service.describeInstances("us-east-1", List.of("i-node1234567890abc"), Map.of()); + List reservations = service.describeInstances("us-east-1", List.of("i-0de1234567890abc"), Map.of()); Instance queried = reservations.getFirst().getInstances().getFirst(); assertTrue(queried.getTags().stream().anyMatch(t -> "Environment".equals(t.getKey()) && "production".equals(t.getValue()))); assertTrue(queried.getTags().stream().anyMatch(t -> "Name".equals(t.getKey()) && "test-cluster-node".equals(t.getValue()))); // DescribeTags now returns both tags - List> updatedTags = service.describeTags("us-east-1", Map.of("resource-id", List.of("i-node1234567890abc"))); + List> updatedTags = service.describeTags("us-east-1", Map.of("resource-id", List.of("i-0de1234567890abc"))); assertEquals(2, updatedTags.size()); // Delete tag - service.deleteTags("us-east-1", List.of("i-node1234567890abc"), List.of(new Tag("Environment", "production"))); - List> finalTags = service.describeTags("us-east-1", Map.of("resource-id", List.of("i-node1234567890abc"))); + service.deleteTags("us-east-1", List.of("i-0de1234567890abc"), List.of(new Tag("Environment", "production"))); + List> finalTags = service.describeTags("us-east-1", Map.of("resource-id", List.of("i-0de1234567890abc"))); assertEquals(1, finalTags.size()); assertEquals("Name", finalTags.getFirst().get("key")); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TagValidationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TagValidationIntegrationTest.java new file mode 100644 index 0000000000..7d54cfc7f2 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TagValidationIntegrationTest.java @@ -0,0 +1,46 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** CreateTags and DeleteTags reject what AWS rejects, with the EC2 Query error shape. */ +@QuarkusTest +class Ec2TagValidationIntegrationTest { + + private static final String EAST_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request"; + private static final String WEST_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/eu-west-1/ec2/aws4_request"; + + private RequestSpecification ec2(String auth, String action, String... formParams) { + RequestSpecification req = given().formParam("Action", action).header("Authorization", auth); + for (int i = 0; i < formParams.length; i += 2) { + req = req.formParam(formParams[i], formParams[i + 1]); + } + return req; + } + + @Test + void createTagsAnswersEachRejectionWithItsCode() { + String vpcId = ec2(EAST_AUTH, "CreateVpc", "CidrBlock", "10.94.0.0/16") + .when().post("/").then().statusCode(200).extract().xmlPath().getString("CreateVpcResponse.vpc.vpcId"); + try { + ec2(WEST_AUTH, "CreateTags", "ResourceId.1", vpcId, "Tag.1.Key", "Team", "Tag.1.Value", "x") + .when().post("/").then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidVpcID.NotFound")); + ec2(EAST_AUTH, "CreateTags", "ResourceId.1", "not-an-id", "Tag.1.Key", "Team", "Tag.1.Value", "x") + .when().post("/").then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidID")) + .body("Response.Errors.Error.Message", equalTo("The ID 'not-an-id' is not valid")); + ec2(EAST_AUTH, "DeleteTags", "Tag.1.Key", "Team") + .when().post("/").then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("MissingParameter")); + } finally { + ec2(EAST_AUTH, "DeleteVpc", "VpcId", vpcId).when().post("/").then().statusCode(200); + } + } +}