From 1b5c862c2f5b2227736ca2a0959600dc0a98cb6a Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:30:23 -0400 Subject: [PATCH] fix(iam): read the stored tags of ElastiCache resources (#9839) The request-resources table gives resource-tag keys to ElastiCache's user, user group, replication group, cluster, snapshot, subnet group, parameter group and serverless cache types, but ElastiCache gave IAM none of the tags it stores, so an aws:ResourceTag condition on one of its actions never matched: an Allow scoped to a tag never applied and a Deny scoped to one never refused. ElastiCacheStoredResourceArns reads ElastiCacheService.storedTags, and ElastiCacheServerlessService.storedTags for a serverless cache. A resource stored with its ARN is matched on its kind and id, as the handlers find it: those that change or delete a user, user group, replication group, cluster or snapshot find it by its id whatever Region a request is signed for, so IAM checks the one they act on; a subnet group, stored by name alone, only in the request's Region, where ListTagsForResource reads it; a parameter group in the ARN's Region. A user group's id and a serverless cache's name are read in lower case, as the handlers find them, so a request spelling one in another case is checked with its tags. Each is read in place (AccountAwareStorageBackend.readInAccount): the handlers' lookups move a pre-multi-account entry into the caller's account, which a read made before the request is allowed must not do. Each kind's tags change in place under its own lock, so the read copies them under that lock, taken only once the resource is found (an ARN naming nothing leaves no lock behind) and finding it again under it. A serverless cache's tags are replaced whole on each change, so its copy needs no lock. ElastiCacheResourceTagIamIntegrationTest checks a caller allowed elasticache:DeleteUser and elasticache:DeleteCacheParameterGroup only on resources tagged team=blue deletes the blue one and is refused the red one, and the same for elasticache:DeleteUserGroup with the group's id in upper case, and that a Deny on team=red refuses a delete of the red user signed for another Region; ElastiCacheServiceTest and ElastiCacheServerlessServiceTest check the reads, their copies, the ARNs that name nothing, that reading those leaves the lock count as it was, and that a legacy user is read where it is. --- docs/services/iam.md | 5 +- .../ElastiCacheServerlessService.java | 36 +++- .../elasticache/ElastiCacheService.java | 94 ++++++++++ .../ElastiCacheStoredResourceArns.java | 49 ++++++ ...stiCacheResourceTagIamIntegrationTest.java | 163 ++++++++++++++++++ .../ElastiCacheServerlessServiceTest.java | 20 +++ .../elasticache/ElastiCacheServiceTest.java | 59 +++++++ 7 files changed, 423 insertions(+), 3 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/elasticache/ElastiCacheStoredResourceArns.java create mode 100644 src/test/java/io/floci/aws/services/elasticache/ElastiCacheResourceTagIamIntegrationTest.java diff --git a/docs/services/iam.md b/docs/services/iam.md index 9592e0f885..270000b89b 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -4035,8 +4035,9 @@ floci populates: holds; tags it keeps on an ARN of another kind, with no resource behind it, satisfy no condition), EFS for its file systems and access points, Route 53 Resolver for its endpoints, rules and firewall domain lists, Transfer Family for its servers and users, SES for its identities, configuration sets, templates, contact lists, custom - verification email templates, dedicated IP pools and tenants, and Amazon Managed Service for Prometheus for its - workspaces and rule groups namespaces. Tag keys + verification email templates, dedicated IP pools and tenants, ElastiCache for its users, user groups, replication + groups, cache clusters, snapshots, subnet groups, parameter groups and serverless caches, and Amazon Managed Service + for Prometheus for its workspaces and rule groups namespaces. Tag keys differing only in case are one condition key holding every value. - EC2 resource keys such as a network interface's `ec2:Vpc`, `ec2:Subnet`, `ec2:AvailabilityZone` and `ec2:NetworkInterfaceID`: for every action on a resource EC2 holds, the members of the resource the diff --git a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheServerlessService.java b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheServerlessService.java index a062bfce91..3234e94b4c 100644 --- a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheServerlessService.java +++ b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheServerlessService.java @@ -1,6 +1,7 @@ package io.floci.aws.services.elasticache; import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.Resettable; @@ -244,6 +245,35 @@ public class ElastiCacheServerlessService implements Resettable { } } + /** + * The tags of the serverless cache the ARN names, in the caller's account and the ARN's Region, as + * {@code ListTagsForResource} reads them; empty for an ARN of another account or kind, or naming no serverless + * cache this service holds as that ARN. The cache is the one the handlers find under the name, which they read in + * lower case, so a request spelling it in another case is checked with its tags. Read in place, never moving a + * pre-multi-account entry into the caller's + * account as the handlers' lookup does. A tag change stores a new map, so the copy read is of one whole set. + */ + public Map storedTags(String arn) { + AwsArnUtils.Arn parsed; + try { + parsed = AwsArnUtils.parse(arn); + } catch (IllegalArgumentException expected) { + // Not an ARN: it names no serverless cache. + return Map.of(); + } + String resource = parsed.resource(); + if (!"elasticache".equals(parsed.service()) || !resource.startsWith("serverlesscache:") + || !resolver.getAccountId().equals(parsed.accountId())) { + return Map.of(); + } + // The handlers find a cache by its name in lower case, whatever case a request spells it in. + String name = resource.substring("serverlesscache:".length()).toLowerCase(Locale.ROOT); + return AccountAwareStorageBackend.readInAccount(caches, parsed.accountId(), key(parsed.region(), name)) + .filter(cache -> arn.equalsIgnoreCase(cache.getArn())) + .map(ServerlessCache::getTags) + .orElse(Map.of()); + } + public Map addTagsToResource(String resourceArn, Map tags, String region) { TagResourceRef ref = parseTagResourceArn(resourceArn, region); synchronized (lockFor(ref.id())) { @@ -352,7 +382,11 @@ public class ElastiCacheServerlessService implements Resettable { } private String key(String name) { - return resolver.getRegion() + "/" + name; + return key(resolver.getRegion(), name); + } + + private static String key(String region, String name) { + return region + "/" + name; } private Object lockFor(String name) { diff --git a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java index f4578051fe..99c10b03c2 100644 --- a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java +++ b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java @@ -69,10 +69,13 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; import java.util.function.Supplier; import java.util.function.UnaryOperator; import java.util.regex.Pattern; +import static io.floci.aws.core.storage.AccountAwareStorageBackend.readInAccount; + /** * Core ElastiCache business logic — replication groups and users. * Creates Valkey containers and auth proxies on group creation. @@ -2480,6 +2483,97 @@ public class ElastiCacheService implements ResourceProvider { return user; } + /** + * The tags of the user, user group, replication group, cache cluster, snapshot, subnet group or parameter group the + * ARN names, in the caller's account, the ones {@code ListTagsForResource} reads, copied under the lock their tag + * changes hold; empty for an ARN of another account, of another kind (a serverless cache is {@link + * ElastiCacheServerlessService#storedTags}), or naming no resource this service holds. A resource stored with its + * ARN is matched on its kind and id ({@link #sameResource}), as the handlers find it; a subnet group, stored by + * name alone, only in the request's Region, where {@code ListTagsForResource} reads it; a parameter group in the + * ARN's Region. Read in place: the lookups the handlers make move a pre-multi-account entry into the caller's + * account, which a read made before the request is allowed must not do. The resource is found before its lock is + * taken, so an ARN naming nothing leaves no lock behind, and found again under it, so a delete in between is seen. + */ + public Map storedTags(String arn) { + AwsArnUtils.Arn parsed; + try { + parsed = AwsArnUtils.parse(arn); + } catch (IllegalArgumentException expected) { + // Not an ARN: it names no resource. + return Map.of(); + } + String[] resource = parsed.resource().split(":", 2); + if (!"elasticache".equals(parsed.service()) || resource.length != 2 + || !regionResolver.getAccountId().equals(parsed.accountId())) { + return Map.of(); + } + String account = parsed.accountId(); + String region = parsed.region(); + String id = resource[1]; + return switch (resource[0]) { + case "user" -> heldTags(arn, () -> readInAccount(users, account, id), ElastiCacheUser::getArn, + ElastiCacheUser::getTags, () -> userGroupLock); + case "usergroup" -> heldTags(arn, () -> readInAccount(userGroups, account, id.toLowerCase(Locale.ROOT)), + ElastiCacheUserGroup::getArn, ElastiCacheUserGroup::getTags, () -> userGroupLock); + case "replicationgroup" -> heldTags(arn, () -> readInAccount(groups, account, id), ReplicationGroup::getArn, + ReplicationGroup::getTags, () -> lockFor("rg:" + id)); + case "cluster" -> heldTags(arn, () -> readInAccount(cacheClusters, account, id) + .or(() -> readInAccount(memcachedClusters, account, id)) + .filter(cluster -> cluster.getServerlessCacheName() == null), + CacheCluster::getArn, CacheCluster::getTags, () -> lockFor("cc:" + id)); + case "snapshot" -> heldTags(arn, () -> readInAccount(snapshots, account, id), ElastiCacheSnapshot::getArn, + ElastiCacheSnapshot::getTags, () -> lockFor("snapshot:" + id)); + case "subnetgroup" -> region.equals(regionResolver.getRegion()) + ? heldTags(arn, () -> readInAccount(subnetGroups, account, id), group -> arn, + CacheSubnetGroup::getTags, () -> lockFor("sng:" + id)) + : Map.of(); + case "parametergroup" -> heldTags(arn, + () -> readInAccount(parameterGroups, account, parameterGroupKey(region, id)), group -> arn, + CacheParameterGroup::getTags, () -> lockFor(parameterGroupKey(region, id))); + default -> Map.of(); + }; + } + + /** + * Whether {@code stored}, the ARN a resource is stored with, names the resource {@code arn} does as the handlers + * find it: by its kind and id, in any case, whatever Region either names. The handlers that change or delete a + * user, a user group, a replication group, a cluster or a snapshot find it by its id alone, whatever Region a + * request is signed for, so IAM checks the one they act on with its tags. + */ + private static boolean sameResource(String arn, String stored) { + if (stored == null) { + return false; + } + try { + return AwsArnUtils.parse(arn).resource().equalsIgnoreCase(AwsArnUtils.parse(stored).resource()); + } catch (IllegalArgumentException expected) { + // A stored ARN that is not one names no resource a request can. + return false; + } + } + + /** The locks this service keeps; tests read this to see that a read of a resource it does not hold leaves none. */ + int heldLocks() { + return parameterGroupLocks.size(); + } + + /** + * A copy of the tags of the resource {@code find} gives when its ARN ({@code arnOf}) names the resource {@code arn} + * does ({@link #sameResource}), taken under {@code lock}, which is asked for only once the resource is found. + */ + private static Map heldTags(String arn, Supplier> find, Function arnOf, + Function> tagsOf, Supplier lock) { + if (find.get().filter(resource -> sameResource(arn, arnOf.apply(resource))).isEmpty()) { + return Map.of(); + } + synchronized (lock.get()) { + return find.get().filter(resource -> sameResource(arn, arnOf.apply(resource))) + .map(tagsOf) + .>map(LinkedHashMap::new) + .orElse(Map.of()); + } + } + public Map addTagsToResource(String resourceArn, Map tags, String region) { TagResourceRef ref = ElastiCacheTagResourceArn.parse(resourceArn, region, regionResolver); diff --git a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheStoredResourceArns.java b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheStoredResourceArns.java new file mode 100644 index 0000000000..0e8510b791 --- /dev/null +++ b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheStoredResourceArns.java @@ -0,0 +1,49 @@ +package io.floci.aws.services.elasticache; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.StoredResourceArns; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * What IAM asks ElastiCache of the resources a request names: the tags it keeps on a user, a user group, a replication + * group, a cache cluster, a snapshot, a subnet group, a parameter group or a serverless cache, which the + * request-resources table's resource-tag keys for those types take as their values ({@code aws:ResourceTag/}). + */ +@ApplicationScoped +public class ElastiCacheStoredResourceArns implements StoredResourceArns { + + private final ElastiCacheService elastiCache; + private final ElastiCacheServerlessService serverless; + + @Inject + public ElastiCacheStoredResourceArns(ElastiCacheService elastiCache, ElastiCacheServerlessService serverless) { + this.elastiCache = elastiCache; + this.serverless = serverless; + } + + @Override + public String namespace() { + return "elasticache"; + } + + /** A request names an ElastiCache resource by the name or ID its ARN ends in: nothing to find. */ + @Override + public Optional find(String type, List names, String region) { + return Optional.empty(); + } + + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "elasticache")) { + return Map.of(); + } + Map tags = AwsArnUtils.parse(arn).resource().startsWith("serverlesscache:") + ? serverless.storedTags(arn) : elastiCache.storedTags(arn); + return StoredResourceArns.withEmptyValues(tags); + } +} diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheResourceTagIamIntegrationTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheResourceTagIamIntegrationTest.java new file mode 100644 index 0000000000..c7792295eb --- /dev/null +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheResourceTagIamIntegrationTest.java @@ -0,0 +1,163 @@ +package io.floci.aws.services.elasticache; + +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.EnforcementFixtures.UserCredentials; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.util.Locale; +import java.util.UUID; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; + +/** + * A condition on {@code aws:ResourceTag} reads the tags ElastiCache keeps on a user and a parameter group, types the + * request-resources table gives resource-tag keys: a caller allowed {@code elasticache:DeleteUser} and + * {@code elasticache:DeleteCacheParameterGroup} only on resources tagged {@code team=blue} deletes the blue one and is + * refused the red one. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class ElastiCacheResourceTagIamIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + + @TestHTTPResource("/") + URI endpoint; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void aUserIsCheckedWithItsTags() { + String admin = auth(ACCOUNT, REGION, "elasticache"); + String[] ids = new String[2]; + for (int i = 0; i < 2; i++) { + String team = i == 0 ? "blue" : "red"; + String id = team + "-" + suffix(); + query("CreateUser", admin).formParam("UserId", id).formParam("UserName", id) + .formParam("Engine", "redis").formParam("AccessString", "on ~* +@all") + .formParam("AuthenticationMode.Type", "password") + .formParam("AuthenticationMode.Passwords.member.1", "password-0123456789") + .formParam("Tags.Tag.1.Key", "team").formParam("Tags.Tag.1.Value", team) + .when().post("/").then().statusCode(200); + cleanup.register(() -> query("DeleteUser", admin).formParam("UserId", id).when().post("/")); + ids[i] = id; + } + String caller = auth(blueOnly("elasticache:DeleteUser").accessKeyId(), REGION, "elasticache"); + query("DeleteUser", caller).formParam("UserId", ids[1]).when().post("/").then() + .statusCode(403).body(containsString("AccessDenied")) + .body(containsString("not authorized to perform: elasticache:DeleteUser")); + query("DeleteUser", caller).formParam("UserId", ids[0]).when().post("/").then().statusCode(200); + } + + @Test + void aParameterGroupIsCheckedWithItsTags() { + String admin = auth(ACCOUNT, REGION, "elasticache"); + String[] names = new String[2]; + for (int i = 0; i < 2; i++) { + String team = i == 0 ? "blue" : "red"; + String name = team + "-" + suffix(); + query("CreateCacheParameterGroup", admin).formParam("CacheParameterGroupName", name) + .formParam("CacheParameterGroupFamily", "redis7").formParam("Description", "tags") + .formParam("Tags.Tag.1.Key", "team").formParam("Tags.Tag.1.Value", team) + .when().post("/").then().statusCode(200); + cleanup.register(() -> query("DeleteCacheParameterGroup", admin) + .formParam("CacheParameterGroupName", name).when().post("/")); + names[i] = name; + } + String caller = auth(blueOnly("elasticache:DeleteCacheParameterGroup").accessKeyId(), REGION, "elasticache"); + query("DeleteCacheParameterGroup", caller).formParam("CacheParameterGroupName", names[1]).when().post("/") + .then().statusCode(403).body(containsString("AccessDenied")) + .body(containsString("not authorized to perform: elasticache:DeleteCacheParameterGroup")); + query("DeleteCacheParameterGroup", caller).formParam("CacheParameterGroupName", names[0]).when().post("/") + .then().statusCode(200); + } + + /** + * ElastiCache's handlers find a user by its id whatever Region a request is signed for, so IAM checks that user + * with its tags: a Deny on {@code team=red} refuses a delete of the red user signed for another Region. + */ + @Test + void aUserNamedFromAnotherRegionIsCheckedWithItsTags() { + String admin = auth(ACCOUNT, REGION, "elasticache"); + String id = "red-" + suffix(); + query("CreateUser", admin).formParam("UserId", id).formParam("UserName", id) + .formParam("Engine", "redis").formParam("AccessString", "on ~* +@all") + .formParam("AuthenticationMode.Type", "password") + .formParam("AuthenticationMode.Passwords.member.1", "password-0123456789") + .formParam("Tags.Tag.1.Key", "team").formParam("Tags.Tag.1.Value", "red") + .when().post("/").then().statusCode(200); + cleanup.register(() -> query("DeleteUser", admin).formParam("UserId", id).when().post("/")); + String name = "tags-" + suffix(); + String iam = auth(ACCOUNT, REGION, "iam"); + UserCredentials user = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), iam, name); + EnforcementFixtures.putUserPolicy(endpoint.getPort(), iam, name, "not-red", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"elasticache:DeleteUser","Resource":"*"}, + {"Effect":"Deny","Action":"elasticache:DeleteUser","Resource":"*", + "Condition":{"StringEquals":{"aws:ResourceTag/team":"red"}}}]}"""); + + query("DeleteUser", auth(user.accessKeyId(), "eu-west-1", "elasticache")).formParam("UserId", id) + .when().post("/").then() + .statusCode(403).body(containsString("not authorized to perform: elasticache:DeleteUser")); + } + + /** + * ElastiCache reads a user group's id in lower case, whatever case a request spells it in, and IAM checks the group + * it finds: a caller allowed {@code elasticache:DeleteUserGroup} only on groups tagged {@code team=blue} deletes + * the blue one named in upper case and is refused the red one. + */ + @Test + void aUserGroupSpelledInAnotherCaseIsCheckedWithItsTags() { + String admin = auth(ACCOUNT, REGION, "elasticache"); + String[] ids = new String[2]; + for (int i = 0; i < 2; i++) { + String team = i == 0 ? "blue" : "red"; + String id = team + "-" + suffix(); + query("CreateUserGroup", admin).formParam("UserGroupId", id).formParam("Engine", "redis") + .formParam("UserIds.member.1", "default") + .formParam("Tags.Tag.1.Key", "team").formParam("Tags.Tag.1.Value", team) + .when().post("/").then().statusCode(200); + cleanup.register(() -> query("DeleteUserGroup", admin).formParam("UserGroupId", id).when().post("/")); + ids[i] = id; + } + String caller = auth(blueOnly("elasticache:DeleteUserGroup").accessKeyId(), REGION, "elasticache"); + query("DeleteUserGroup", caller).formParam("UserGroupId", ids[1].toUpperCase(Locale.ROOT)).when().post("/") + .then().statusCode(403).body(containsString("not authorized to perform: elasticache:DeleteUserGroup")); + query("DeleteUserGroup", caller).formParam("UserGroupId", ids[0].toUpperCase(Locale.ROOT)).when().post("/") + .then().statusCode(200); + } + + private UserCredentials blueOnly(String action) { + String name = "tags-" + suffix(); + String authorization = auth(ACCOUNT, REGION, "iam"); + UserCredentials user = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), authorization, name); + EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, name, "blue", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"%s","Resource":"*", + "Condition":{"StringEquals":{"aws:ResourceTag/team":"blue"}}}]}""".formatted(action)); + return user; + } + + /** + * A Query call on the test's port: a cleanup runs after the test method, once Quarkus has reset RestAssured's port, + * so every call names it. + */ + private RequestSpecification query(String action, String authorization) { + return given().port(endpoint.getPort()).formParam("Action", action).header("Authorization", authorization); + } + + private static String suffix() { + return UUID.randomUUID().toString().substring(0, 8); + } +} diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheServerlessServiceTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheServerlessServiceTest.java index 3963b5904e..8884594003 100644 --- a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheServerlessServiceTest.java +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheServerlessServiceTest.java @@ -131,6 +131,26 @@ class ElastiCacheServerlessServiceTest { assertEquals(code, assertThrows(AwsException.class, action::run).getErrorCode()); } + /** + * IAM reads the tags of the serverless cache an ARN names, in the ARN's Region and whatever case it spells the name + * in, as the handlers find it, as a copy; an ARN of another Region, account or kind, or naming no serverless + * cache, has none. + */ + @Test + void storedTagsReadTheServerlessCacheTheArnNames() { + String arn = service.createServerlessCache(create("tagged", "valkey", null)).getArn(); + + assertEquals(Map.of("team", "local"), service.storedTags(arn)); + assertEquals(Map.of("team", "local"), service.storedTags(arn.replace(":tagged", ":TaGgEd"))); + service.storedTags(arn).put("forged", "yes"); + assertEquals(Map.of("team", "local"), service.storedTags(arn)); + assertEquals(Map.of(), service.storedTags(arn.replace(":us-east-1:", ":eu-west-1:"))); + assertEquals(Map.of(), service.storedTags(arn.replace(":000000000000:", ":111122223333:"))); + assertEquals(Map.of(), service.storedTags(arn.replace(":serverlesscache:", ":cluster:"))); + assertEquals(Map.of(), service.storedTags(arn + "-missing")); + assertEquals(Map.of(), service.storedTags("not-an-arn")); + } + @Test void createsHiddenRuntimeMutatesMetadataAndReleasesPortOnDelete() { ServerlessCache cache = service.createServerlessCache(create("cache", "valkey", "team")); diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheServiceTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheServiceTest.java index 9a45ebea02..c2d1768cca 100644 --- a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheServiceTest.java +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheServiceTest.java @@ -40,6 +40,7 @@ import java.lang.management.ThreadInfo; import java.lang.reflect.Field; import java.time.Duration; import java.time.Instant; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -186,6 +187,64 @@ class ElastiCacheServiceTest { service.getUserGroup("tagged-group").getTags()); } + /** + * IAM reads the tags ElastiCache keeps on a resource by its ARN, as a copy, from the resource the handlers act on: + * a user by its id whatever Region the ARN names, a parameter group in the ARN's Region. An ARN of another account, + * or naming nothing it holds, has none, and reading one leaves no lock. + */ + @Test + void storedTagsReadTheResourceTheArnNames() { + ElastiCacheUser user = service.createUser("iam-user", "iam", AuthMode.PASSWORD, + List.of("password"), "on ~* +@all", "redis", Map.of("team", "blue")); + service.createCacheParameterGroup("iam-params", "redis7", "tags", Map.of("team", "red")); + String group = "arn:aws:elasticache:us-east-1:000000000000:parametergroup:iam-params"; + + assertEquals(Map.of("team", "blue"), service.storedTags(user.getArn())); + assertEquals(Map.of("team", "red"), service.storedTags(group)); + service.storedTags(user.getArn()).put("forged", "yes"); + assertEquals(Map.of("team", "blue"), service.storedTags(user.getArn())); + + // The handlers find a user by its id whatever Region a request names, so IAM reads the one they act on. + assertEquals(Map.of("team", "blue"), service.storedTags(user.getArn().replace(":us-east-1:", ":eu-west-1:"))); + + int locks = service.heldLocks(); + assertEquals(Map.of(), service.storedTags(user.getArn().replace(":000000000000:", ":111122223333:"))); + assertEquals(Map.of(), service.storedTags(group.replace(":us-east-1:", ":eu-west-1:"))); + for (String kind : List.of("replicationgroup", "cluster", "snapshot", "subnetgroup", "parametergroup", + "usergroup", "user", "reserved-instance")) { + assertEquals(Map.of(), service.storedTags("arn:aws:elasticache:us-east-1:000000000000:" + kind + ":none")); + } + assertEquals(Map.of(), service.storedTags("not-an-arn")); + assertEquals(locks, service.heldLocks()); + } + + /** + * A user stored before keys carried the account is the default account's: IAM reads its tags in place, for that + * account alone, so a request naming it, allowed or not, leaves it under its key. + */ + @Test + void storedTagsReadALegacyUserInPlace() { + InMemoryStorage raw = new InMemoryStorage<>(); + ElastiCacheUser legacy = new ElastiCacheUser("legacy-user", "legacy", AuthMode.PASSWORD, List.of("password"), + "on ~* +@all", "redis", "active", Instant.now()); + legacy.setArn("arn:aws:elasticache:us-east-1:000000000000:user:legacy-user"); + legacy.setTags(new LinkedHashMap<>(Map.of("team", "blue"))); + raw.put("legacy-user", legacy); + StorageFactory legacyStorage = mock(StorageFactory.class); + when(legacyStorage.create(anyString(), anyString(), any())) + .thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000")); + AccountAwareStorageBackend legacyUsers = new AccountAwareStorageBackend<>(raw, null, + "000000000000"); + when(legacyStorage.create(anyString(), eq("elasticache-users.json"), any())) + .thenAnswer(inv -> legacyUsers); + ElastiCacheService withLegacy = new ElastiCacheService(containerManager, proxyManager, clusterFormation, + legacyStorage, config, ec2Service, new RegionResolver("us-east-1", "000000000000"), + kmsService, mock(CloudWatchLogsService.class), provisioningIds); + + assertEquals(Map.of("team", "blue"), withLegacy.storedTags(legacy.getArn())); + assertEquals(Set.of("legacy-user"), raw.keys()); + } + @Test void tagResourceRejectsSameIdResourceFromAnotherRegion() { ElastiCacheUser user = service.createUser("regional-user", "regional", AuthMode.PASSWORD,