From 0a4cd51acb7ba519cd63d403e510a532d3f8fe83 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 31 Oct 2026 15:46:44 -0500 Subject: [PATCH] fix(eks): tag node groups, Fargate profiles, add-ons, pod identity associations and access entries by ARN (#7113) * fix(eks): tag node groups, Fargate profiles, add-ons, pod identity associations and access entries by ARN TagResource, UntagResource and ListTagsForResource read the text after an ARN's last '/' as a cluster name, so a node group, Fargate profile, add-on, pod identity association or access entry ARN looked up a cluster named after its id and answered ResourceNotFoundException. The ARN is now parsed and routed by its resource type to the store that holds that resource, and a child ARN reaches the resource only when it matches the stored ARN. Signed-off-by: Hector Ventura * fix(eks): answer TagResource and UntagResource with 200 The EKS model declares no responseCode on either tag write, so both answer 200, but EksService kept the shared tag route's 204 default. Signed-off-by: Hector Ventura * fix(eks): lock tag writes and keep tags within the TagMap limits The child retag methods now share their service's lock, so a tag write racing a delete or disassociate can no longer restore the record it read. TagResource checks the merged tags against the TagMap limits for every resource type, and the tag operations answer the BadRequestException and NotFoundException the model declares. A resource ARN with an empty cluster or child segment is a bad request instead of a server error. Signed-off-by: Hector Ventura --------- Signed-off-by: Hector Ventura --- .../services/eks/EksAccessEntryService.java | 33 +++++ .../floci/services/eks/EksAddonService.java | 26 ++++ .../eks/EksPodIdentityAssociationService.java | 26 ++++ .../floci/services/eks/EksService.java | 131 ++++++++++++---- .../EksResourceTaggingIntegrationTest.java | 140 ++++++++++++++++++ 5 files changed, 324 insertions(+), 32 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/eks/EksResourceTaggingIntegrationTest.java diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksAccessEntryService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksAccessEntryService.java index a7fed8ce9b..9987d311f2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksAccessEntryService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksAccessEntryService.java @@ -31,6 +31,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.function.UnaryOperator; /** Access-entry and access-policy management metadata; Kubernetes authorization is handled separately. */ @ApplicationScoped @@ -271,6 +272,38 @@ public class EksAccessEntryService { } } + /** + * Applies {@code change} to the tags of the access entry {@code accessEntryArn} names on + * {@code cluster} and returns them, or empty when the cluster has no entry with that ARN. Entries + * are stored by principal, which the ARN does not carry whole, so the cluster's entries are + * searched. This is how TagResource, UntagResource and ListTagsForResource reach an entry. + */ + public synchronized Optional> retag(Cluster cluster, String accessEntryArn, + UnaryOperator> change) { + String prefix = prefix(cluster); + for (String key : entries.keys()) { + if (!key.startsWith(prefix)) { + continue; + } + Optional found = entries.get(key) + .filter(stored -> accessEntryArn.equals(stored.entry().accessEntryArn())); + if (found.isPresent()) { + StoredEntry stored = found.get(); + AccessEntry current = stored.entry(); + Map tags = Map.copyOf(change.apply(current.tags() == null ? Map.of() : current.tags())); + if (!tags.equals(current.tags())) { + AccessEntry retagged = new AccessEntry(current.accessEntryArn(), current.clusterName(), + current.principalArn(), current.type(), current.username(), current.kubernetesGroups(), + tags, current.createdAt(), current.modifiedAt()); + entries.put(key, new StoredEntry(retagged, stored.principalId(), stored.clientRequestToken(), + stored.accessPolicies())); + } + return Optional.of(tags); + } + } + return Optional.empty(); + } + private static String prefix(Cluster cluster) { // A recreated cluster must not inherit access entries or pagination tokens from its predecessor. return cluster.getArn() + "/" + Objects.toString(cluster.getCreatedAt()) + "/"; diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksAddonService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksAddonService.java index bd5c0f6b82..203431edaa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksAddonService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksAddonService.java @@ -36,6 +36,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.function.Function; +import java.util.function.UnaryOperator; @ApplicationScoped public class EksAddonService { @@ -459,6 +460,31 @@ public class EksAddonService { return "kube-system"; } + /** + * Applies {@code change} to the tags of the add-on {@code addonArn} names on {@code cluster} and + * returns them, or empty when the cluster has no add-on with that ARN. This is how TagResource, + * UntagResource and ListTagsForResource reach an add-on. + */ + public synchronized Optional> retag(Cluster cluster, String addonName, String addonArn, + UnaryOperator> change) { + String storageKey = prefix(cluster) + addonName.toLowerCase(Locale.ROOT); + Optional found = storage.get(storageKey) + .filter(stored -> addonArn.equals(stored.addon().addonArn())); + if (found.isEmpty()) { + return Optional.empty(); + } + Addon current = found.get().addon(); + Map tags = Map.copyOf(change.apply(current.tags() == null ? Map.of() : current.tags())); + if (!tags.equals(current.tags())) { + Addon retagged = new Addon(current.addonArn(), current.addonName(), current.addonVersion(), + current.clusterName(), current.status(), current.health(), current.createdAt(), + current.modifiedAt(), current.serviceAccountRoleArn(), current.configurationValues(), tags, + current.podIdentityAssociations(), current.owner(), current.publisher()); + storage.put(storageKey, new StoredAddon(retagged, found.get().clientRequestToken())); + } + return Optional.of(tags); + } + private static String prefix(Cluster cluster) { return cluster.getArn() + "/" + Objects.toString(cluster.getCreatedAt()) + "/"; } diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java index 7d31d27680..3409e25b21 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java @@ -26,6 +26,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.function.UnaryOperator; /** * Manages EKS Pod Identity association metadata. @@ -297,6 +298,31 @@ public class EksPodIdentityAssociationService { .findFirst(); } + /** + * Applies {@code change} to the tags of the association {@code associationArn} names on + * {@code cluster} and returns them, or empty when the cluster has no association with that ARN. + * This is how TagResource, UntagResource and ListTagsForResource reach an association. + */ + public synchronized Optional> retag(Cluster cluster, String associationId, String associationArn, + UnaryOperator> change) { + String key = prefix(cluster) + associationId; + Optional found = associations.get(key) + .filter(stored -> associationArn.equals(stored.association().associationArn())); + if (found.isEmpty()) { + return Optional.empty(); + } + PodIdentityAssociation current = found.get().association(); + Map tags = Map.copyOf(change.apply(current.tags() == null ? Map.of() : current.tags())); + if (!tags.equals(current.tags())) { + PodIdentityAssociation retagged = new PodIdentityAssociation(current.clusterName(), current.namespace(), + current.serviceAccount(), current.roleArn(), current.associationArn(), current.associationId(), + tags, current.createdAt(), current.modifiedAt(), current.ownerArn(), current.targetRoleArn(), + current.disableSessionTags(), current.externalId(), current.policy()); + associations.put(key, new StoredAssociation(retagged, found.get().clientRequestToken())); + } + return Optional.of(tags); + } + private static String prefix(Cluster cluster) { String base = cluster.getArn() != null ? cluster.getArn() : cluster.getName(); return base + "/" + Objects.toString(cluster.getCreatedAt()) + "/"; diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java index 57b50e76be..de00f960c3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java @@ -72,6 +72,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; +import java.util.function.UnaryOperator; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -1269,42 +1270,41 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun return "eks"; } + /** EKS models no {@code responseCode} on either tag write, so both answer 200. */ + @Override + public int tagResourceSuccessStatus() { + return 200; + } + + @Override + public int untagResourceSuccessStatus() { + return 200; + } + @Override public void tagResource(String region, String resourceArn, Map tags) { ReservedTags.rejectReservedTagsOnUpdate(tags); - String clusterName = extractClusterName(resourceArn); - Cluster cluster = storage.get(clusterName) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Resource not found: " + resourceArn, 404)); - - if (cluster.getTags() == null) { - cluster.setTags(new HashMap<>()); - } - cluster.getTags().putAll(tags); - storage.put(clusterName, cluster); + retag(resourceArn, current -> { + Map next = new HashMap<>(current); + next.putAll(tags); + return next; + }); } @Override public void untagResource(String region, String resourceArn, List tagKeys) { - String clusterName = extractClusterName(resourceArn); - Cluster cluster = storage.get(clusterName) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Resource not found: " + resourceArn, 404)); - - if (cluster.getTags() != null && tagKeys != null) { - tagKeys.forEach(cluster.getTags()::remove); - } - storage.put(clusterName, cluster); + retag(resourceArn, current -> { + Map next = new HashMap<>(current); + if (tagKeys != null) { + tagKeys.forEach(next::remove); + } + return next; + }); } @Override public Map listTags(String region, String resourceArn) { - String clusterName = extractClusterName(resourceArn); - Cluster cluster = storage.get(clusterName) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Resource not found: " + resourceArn, 404)); - - return cluster.getTags() != null ? cluster.getTags() : Map.of(); + return retag(resourceArn, UnaryOperator.identity()); } public void tagResource(String resourceArn, Map tags) { @@ -1319,14 +1319,81 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun return listTags(null, resourceArn); } - private String extractClusterName(String resourceArn) { - // arn:aws:eks:us-east-1:000000000000:cluster/my-cluster - int idx = resourceArn.lastIndexOf('/'); - if (idx < 0 || idx == resourceArn.length() - 1) { - throw new AwsException("InvalidParameterException", - "Invalid resource ARN: " + resourceArn, 400); + /** + * Applies {@code edit} to the tags of the resource {@code resourceArn} names and returns them. + * TagResource takes a cluster, node group, Fargate profile, add-on, pod identity association or + * access entry ARN; each child ARN names its cluster as the segment after the resource type. + */ + private Map retag(String resourceArn, UnaryOperator> edit) { + String resource = AwsArnUtils.isArnFor(resourceArn, "eks") ? AwsArnUtils.parse(resourceArn).resource() : ""; + String[] parts = resource.split("/", -1); + boolean child = !"cluster".equals(parts[0]); + if (parts.length < (child ? 3 : 2) || parts[1].isEmpty() || (child && parts[2].isEmpty())) { + throw new AwsException("BadRequestException", "Invalid resource ARN: " + resourceArn, 400); } - return resourceArn.substring(idx + 1); + String clusterName = parts[1]; + String childName = child ? parts[2] : ""; + UnaryOperator> change = current -> { + Map next = edit.apply(current); + if (!next.equals(current)) { + checkTagLimits(next); + } + return next; + }; + Optional> tags = switch (parts[0]) { + case "cluster" -> storage.get(clusterName).map(cluster -> applyTags(cluster.getTags(), change, next -> { + cluster.setTags(new HashMap<>(next)); + storage.put(clusterName, cluster); + })); + case "nodegroup" -> nodeGroupStorage.get(nodeGroupKey(clusterName, childName)) + .filter(nodegroup -> resourceArn.equals(nodegroup.getNodegroupArn())) + .map(nodegroup -> applyTags(nodegroup.getTags(), change, next -> { + nodegroup.setTags(new HashMap<>(next)); + nodeGroupStorage.put(nodeGroupKey(clusterName, childName), nodegroup); + })); + case "fargateprofile" -> fargateProfileStorage.get(fargateProfileKey(clusterName, childName)) + .filter(profile -> resourceArn.equals(profile.getFargateProfileArn())) + .map(profile -> applyTags(profile.getTags(), change, next -> { + profile.setTags(new HashMap<>(next)); + fargateProfileStorage.put(fargateProfileKey(clusterName, childName), profile); + })); + case "addon" -> addons == null ? Optional.empty() : storage.get(clusterName) + .flatMap(cluster -> addons.retag(cluster, childName, resourceArn, change)); + case "podidentityassociation" -> podIdentityAssociations == null ? Optional.empty() + : storage.get(clusterName) + .flatMap(cluster -> podIdentityAssociations.retag(cluster, childName, resourceArn, change)); + case "access-entry" -> accessEntries == null ? Optional.empty() : storage.get(clusterName) + .flatMap(cluster -> accessEntries.retag(cluster, resourceArn, change)); + default -> Optional.empty(); + }; + return tags.orElseThrow(() -> new AwsException("NotFoundException", + "Resource not found: " + resourceArn, 404)); + } + + /** The TagMap limits: at most 50 tags, keys of 1 to 128 characters and values of at most 256. */ + private static void checkTagLimits(Map tags) { + if (tags.size() > 50) { + throw new AwsException("BadRequestException", "Too many tags: maximum is 50", 400); + } + for (Map.Entry tag : tags.entrySet()) { + if (tag.getKey() == null || tag.getKey().isEmpty() || tag.getKey().length() > 128) { + throw new AwsException("BadRequestException", "Invalid tag key: " + tag.getKey(), 400); + } + if (tag.getValue() == null || tag.getValue().length() > 256) { + throw new AwsException("BadRequestException", "Invalid tag value for key: " + tag.getKey(), 400); + } + } + } + + /** The tags {@code change} makes of {@code current}, handed to {@code store} only when they differ. */ + private static Map applyTags(Map current, + UnaryOperator> change, + Consumer> store) { + Map next = Map.copyOf(change.apply(current != null ? current : Map.of())); + if (!next.equals(current)) { + store.accept(next); + } + return next; } /** diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksResourceTaggingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksResourceTaggingIntegrationTest.java new file mode 100644 index 0000000000..13aea1ddd8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksResourceTaggingIntegrationTest.java @@ -0,0 +1,140 @@ +package io.github.hectorvent.floci.services.eks; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.anEmptyMap; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; + +/** + * TagResource, UntagResource and ListTagsForResource take the ARN of any taggable EKS resource, not + * only a cluster's. A child ARN such as {@code nodegroup///} used to be read as a + * cluster named after its last segment, so every child answered as not found. + */ +@QuarkusTest +class EksResourceTaggingIntegrationTest { + + private static final String ACCOUNT = "112233445566"; + + @Test + void everyTaggableResourceIsTaggedUntaggedAndListedByItsArn() { + String name = "tags-" + UUID.randomUUID().toString().substring(0, 8); + String role = "role-" + name; + String roleArn = "arn:aws:iam::" + ACCOUNT + ":role/" + role; + createRole(role); + createCluster(name, roleArn); + try { + String base = "/clusters/" + name; + Map arns = new LinkedHashMap<>(); + arns.put("cluster", eks().get(base).then().statusCode(200).extract().path("cluster.arn")); + arns.put("nodegroup", eks().contentType("application/json") + .body(Map.of("nodegroupName", "ng1", "subnets", new String[] {"subnet-abc"}, "nodeRole", roleArn, + "scalingConfig", Map.of("minSize", 1, "maxSize", 1, "desiredSize", 1))) + .post(base + "/node-groups").then().statusCode(200).extract().path("nodegroup.nodegroupArn")); + arns.put("fargateprofile", eks().contentType("application/json") + .body(Map.of("fargateProfileName", "fp1", "podExecutionRoleArn", roleArn, + "selectors", new Object[] {Map.of("namespace", "default")})) + .post(base + "/fargate-profiles").then().statusCode(200) + .extract().path("fargateProfile.fargateProfileArn")); + arns.put("addon", eks().contentType("application/json").body(Map.of("addonName", "vpc-cni")) + .post(base + "/addons").then().statusCode(200).extract().path("addon.addonArn")); + arns.put("podidentityassociation", eks().contentType("application/json") + .body(Map.of("namespace", "default", "serviceAccount", "sa", "roleArn", roleArn)) + .post(base + "/pod-identity-associations").then().statusCode(200) + .extract().path("association.associationArn")); + arns.put("access-entry", eks().contentType("application/json").body(Map.of("principalArn", roleArn)) + .post(base + "/access-entries").then().statusCode(200) + .extract().path("accessEntry.accessEntryArn")); + + for (Map.Entry resource : arns.entrySet()) { + String arn = resource.getValue(); + eks().contentType("application/json").body(Map.of("tags", Map.of("team", resource.getKey(), "env", "dev"))) + .post("/tags/" + arn).then().statusCode(200); + eks().get("/tags/" + arn).then().statusCode(200) + .body("tags.team", equalTo(resource.getKey())) + .body("tags.env", equalTo("dev")); + eks().queryParam("tagKeys", "env").delete("/tags/" + arn).then().statusCode(200); + eks().get("/tags/" + arn).then().statusCode(200) + .body("tags", not(hasKey("env"))) + .body("tags.team", equalTo(resource.getKey())); + } + + // Tags written through TagResource are the ones each resource's own describe returns. + eks().get(base + "/node-groups/ng1").then().statusCode(200).body("nodegroup.tags.team", equalTo("nodegroup")); + eks().get(base + "/addons/vpc-cni").then().statusCode(200).body("addon.tags.team", equalTo("addon")); + + // A child ARN whose id is not the stored resource's, or whose cluster does not exist, names nothing. + String staleNodegroup = arns.get("nodegroup").substring(0, arns.get("nodegroup").lastIndexOf('/') + 1) + + UUID.randomUUID(); + eks().get("/tags/" + staleNodegroup).then().statusCode(404) + .body("__type", equalTo("NotFoundException")); + eks().get("/tags/" + arns.get("addon").replace("/" + name + "/", "/no-such-cluster/")).then() + .statusCode(404).body("__type", equalTo("NotFoundException")); + eks().get("/tags/arn:aws:eks:us-east-1:" + ACCOUNT + ":identityproviderconfig/" + name + "/oidc/x/y") + .then().statusCode(404).body("__type", equalTo("NotFoundException")); + eks().get("/tags/" + arns.get("cluster")).then().statusCode(200).body("tags", not(anEmptyMap())); + + // An ARN that names a resource type but no cluster is a bad request, not a server error. + String noCluster = "arn:aws:eks:us-east-1:" + ACCOUNT + ":cluster/"; + eks().get("/tags/" + noCluster).then().statusCode(400).body("__type", equalTo("BadRequestException")); + eks().queryParam("tagKeys", "team").delete("/tags/" + noCluster).then().statusCode(400) + .body("__type", equalTo("BadRequestException")); + eks().get("/tags/" + arns.get("addon").substring(0, arns.get("addon").indexOf(name)) + name + "/") + .then().statusCode(400).body("__type", equalTo("BadRequestException")); + + // TagResource keeps every resource within the TagMap limits, counting the tags it already has. + Map fortyNine = new LinkedHashMap<>(); + for (int i = 0; i < 49; i++) { + fortyNine.put("k" + i, "v"); + } + eks().contentType("application/json").body(Map.of("tags", fortyNine)) + .post("/tags/" + arns.get("addon")).then().statusCode(200); + eks().contentType("application/json").body(Map.of("tags", Map.of("one-too-many", "v"))) + .post("/tags/" + arns.get("addon")).then().statusCode(400) + .body("__type", equalTo("BadRequestException")); + eks().get("/tags/" + arns.get("addon")).then().statusCode(200) + .body("tags", not(hasKey("one-too-many"))) + .body("tags.team", equalTo("addon")); + eks().contentType("application/json").body(Map.of("tags", Map.of("k", "v".repeat(257)))) + .post("/tags/" + arns.get("access-entry")).then().statusCode(400) + .body("__type", equalTo("BadRequestException")); + } finally { + eks().delete("/clusters/" + name + "/addons/vpc-cni"); + eks().delete("/clusters/" + name + "/node-groups/ng1"); + eks().delete("/clusters/" + name + "/fargate-profiles/fp1"); + eks().delete("/clusters/" + name).then().statusCode(200); + given().header("Authorization", auth("iam")).contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteRole").formParam("RoleName", role).post("/"); + } + } + + private static RequestSpecification eks() { + return given().header("Authorization", auth("eks")); + } + + private static void createRole(String role) { + given().header("Authorization", auth("iam")).contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateRole").formParam("RoleName", role).formParam("Path", "/") + .formParam("AssumeRolePolicyDocument", "{}").post("/").then().statusCode(200); + } + + private static void createCluster(String name, String roleArn) { + eks().contentType("application/json") + .body(Map.of("name", name, "roleArn", roleArn, + "accessConfig", Map.of("authenticationMode", "API", "bootstrapClusterCreatorAdminPermissions", false))) + .post("/clusters").then().statusCode(200); + } + + private static String auth(String service) { + return "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + + "/20260916/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc"; + } +}