diff --git a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandler.java b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandler.java index a4cebd15cd..8e51649baa 100644 --- a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandler.java +++ b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandler.java @@ -490,12 +490,19 @@ public class ElastiCacheQueryHandler { boolean showNodeInfo = "true".equalsIgnoreCase(params.getFirst("ShowCacheNodeInfo")); boolean filtered = filterId != null && !filterId.isBlank(); try { + // Cache clusters are stored per account; like AWS, only the request's Region's are listed. List members = service.listMemberCacheClusters(filterId); - List clusterList = new ArrayList<>(service.findCacheClusters(filterId)); + List clusterList = new ArrayList<>(service.findCacheClusters(filterId).stream() + .filter(c -> service.inRequestRegion(c.getArn())).toList()); // The Memcached lookup is the one that raises CacheClusterNotFound for an unknown id, // which is the right answer only once no other source has answered. if (!filtered || (members.isEmpty() && clusterList.isEmpty())) { - clusterList.addAll(memcachedService.listCacheClusters(filterId)); + memcachedService.listCacheClusters(filterId).stream() + .filter(c -> service.inRequestRegion(c.getArn())) + .forEach(clusterList::add); + if (filtered && clusterList.isEmpty()) { + throw new AwsException("CacheClusterNotFound", "Cache cluster " + filterId + " not found.", 404); + } } XmlBuilder xml = new XmlBuilder().start("CacheClusters"); for (CacheCluster c : clusterList) { 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 f2993917e3..ecd6dcc6dd 100644 --- a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java +++ b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java @@ -899,6 +899,16 @@ public class ElastiCacheService implements ResourceProvider { return AwsArnUtils.regionOrDefault(arn, regionResolver.getDefaultRegion()); } + /** + * Whether a resource belongs to the request's Region. Replication groups, cache clusters (including + * Memcached ones, which DescribeCacheClusters lists too), users and user groups are stored per account; + * like AWS, the Describe* listings only show the requesting Region's. + * The getters stay unscoped: credential lookups, restore and validation run outside a request. + */ + boolean inRequestRegion(String arn) { + return regionResolver.getRegion().equals(regionOf(arn)); + } + /** * Restarts the container and auth proxy behind a standalone Redis or Valkey cache cluster, * the same pair {@link #provisionCacheCluster} creates. The cache comes back empty, as it @@ -1298,12 +1308,12 @@ public class ElastiCacheService implements ResourceProvider { public Collection listReplicationGroups(String filterGroupId) { if (filterGroupId != null && !filterGroupId.isBlank()) { - return groups.get(filterGroupId) + return groups.get(filterGroupId).filter(g -> inRequestRegion(g.getArn())) .map(List::of) .orElseThrow(() -> new AwsException("ReplicationGroupNotFoundFault", "Replication group " + filterGroupId + " not found.", 404)); } - return groups.scan(k -> true); + return groups.scan(k -> true).stream().filter(g -> inRequestRegion(g.getArn())).toList(); } public void deleteReplicationGroup(String groupId) { @@ -2094,6 +2104,9 @@ public class ElastiCacheService implements ResourceProvider { public List listMemberCacheClusters(String filterClusterId) { List members = new ArrayList<>(); for (ReplicationGroup group : groups.scan(k -> true)) { + if (!inRequestRegion(group.getArn())) { + continue; + } for (MemberCacheCluster member : memberCacheClusters(group)) { if (filterClusterId == null || filterClusterId.isBlank() || filterClusterId.equals(member.cacheClusterId())) { @@ -2554,7 +2567,7 @@ public class ElastiCacheService implements ResourceProvider { public Collection listUsers(String filterUserId, String filterEngine) { // UserId wins when both filters are sent; AWS documents no interaction between them. if (filterUserId != null && !filterUserId.isBlank()) { - return findUser(filterUserId) + return findUser(filterUserId).flatMap(this::inRequestRegion) .map(List::of) .orElseThrow(() -> new AwsException("UserNotFound", "User " + filterUserId + " not found.", 404)); @@ -2562,10 +2575,31 @@ public class ElastiCacheService implements ResourceProvider { ensureDefaultUser(); if (filterEngine != null && !filterEngine.isBlank()) { return users.scan(k -> true).stream() + .map(this::inRequestRegion).flatMap(Optional::stream) .filter(u -> filterEngine.equalsIgnoreCase(u.getEngine())) .toList(); } - return users.scan(k -> true); + return users.scan(k -> true).stream().map(this::inRequestRegion).flatMap(Optional::stream).toList(); + } + + /** + * {@code user} as the request's Region lists it, or empty when it is another Region's. AWS has the built-in + * default user in every Region; Floci seeds one per account, so it is listed in every Region, with that + * Region's ARN. + */ + private Optional inRequestRegion(ElastiCacheUser user) { + if (!DEFAULT_USER_ID.equals(user.getUserId())) { + return inRequestRegion(user.getArn()) ? Optional.of(user) : Optional.empty(); + } + String arn = regionResolver.buildArn("elasticache", regionResolver.getRegion(), "user:" + DEFAULT_USER_ID); + if (arn.equals(user.getArn())) { + return Optional.of(user); + } + ElastiCacheUser regional = new ElastiCacheUser(user.getUserId(), user.getUserName(), user.getAuthMode(), + user.getPasswords(), user.getAccessString(), user.getEngine(), user.getStatus(), user.getCreatedAt()); + regional.setTags(user.getTags()); + regional.setArn(arn); + return Optional.of(regional); } /** @@ -2724,9 +2758,13 @@ public class ElastiCacheService implements ResourceProvider { public Collection listUserGroups(String filterUserGroupId) { if (filterUserGroupId != null && !filterUserGroupId.isBlank()) { - return List.of(getUserGroup(filterUserGroupId)); + ElastiCacheUserGroup userGroup = getUserGroup(filterUserGroupId); + if (!inRequestRegion(userGroup.getArn())) { + throw userGroupNotFound(filterUserGroupId); + } + return List.of(userGroup); } - return userGroups.scan(k -> true); + return userGroups.scan(k -> true).stream().filter(g -> inRequestRegion(g.getArn())).toList(); } public ElastiCacheUserGroup modifyUserGroup(String userGroupId, List userIdsToAdd, @@ -2833,8 +2871,10 @@ public class ElastiCacheService implements ResourceProvider { .toList(); } + /** The request Region's user groups the user is a member of, as DescribeUserGroups lists them there. */ public List userGroupIdsContaining(String userId) { return userGroups.scan(k -> true).stream() + .filter(g -> inRequestRegion(g.getArn())) .filter(g -> g.getUserIds().contains(userId)) .map(ElastiCacheUserGroup::getUserGroupId) .toList(); diff --git a/src/test/java/io/floci/aws/core/common/RequestRegionArnIntegrationTest.java b/src/test/java/io/floci/aws/core/common/RequestRegionArnIntegrationTest.java index 09b8d6a672..a26463ea33 100644 --- a/src/test/java/io/floci/aws/core/common/RequestRegionArnIntegrationTest.java +++ b/src/test/java/io/floci/aws/core/common/RequestRegionArnIntegrationTest.java @@ -161,13 +161,21 @@ class RequestRegionArnIntegrationTest { .statusCode(200) .body("CreateUserResponse.CreateUserResult.ARN", startsWith("arn:aws:elasticache:" + REGION + ":")); - // Users are not stored per region, so another region can read this one; its ARN must not change. + // A user is Regional: another Region does not find it, and its own Region reads it with the ARN minted there. given() .header("Authorization", auth(OTHER_REGION, "elasticache")) .formParam("Action", "DescribeUsers") .formParam("UserId", "region-arn-user") .when() .post("/") + .then() + .statusCode(404); + given() + .header("Authorization", auth("elasticache")) + .formParam("Action", "DescribeUsers") + .formParam("UserId", "region-arn-user") + .when() + .post("/") .then() .statusCode(200) .body("DescribeUsersResponse.DescribeUsersResult.Users.member.ARN", diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandlerTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandlerTest.java index e4979ff495..f64cbea8dc 100644 --- a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandlerTest.java @@ -44,6 +44,8 @@ class ElastiCacheQueryHandlerTest { void setUp() { SigV4Validator sigV4Validator = mock(SigV4Validator.class); service = mock(ElastiCacheService.class); + // Every record these tests describe belongs to the request's Region. + when(service.inRequestRegion(any())).thenReturn(true); memcachedService = mock(ElastiCacheMemcachedService.class); RegionResolver regionResolver = mock(RegionResolver.class); when(regionResolver.getRegion()).thenReturn("us-east-1"); diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheRegionScopingIntegrationTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheRegionScopingIntegrationTest.java new file mode 100644 index 0000000000..c6fe086e75 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheRegionScopingIntegrationTest.java @@ -0,0 +1,149 @@ +package io.floci.aws.services.elasticache; + +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.QueryRequests; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +/** + * Replication groups, cache clusters, users and user groups are Regional on AWS: one created in a Region of an + * account is listed, and found by its id, only from that Region of that account. Each case creates the resource + * in {@link #HOME} of {@link #ACCOUNT} and checks the unfiltered listing and the id filter from there, from + * {@link #OTHER_REGION} of the same account, and from {@link #HOME} of {@link #OTHER_ACCOUNT}. + */ +@QuarkusTest +class ElastiCacheRegionScopingIntegrationTest { + + private static final String ACCOUNT = "975318642097"; + private static final String OTHER_ACCOUNT = "864207531986"; + private static final String HOME = "eu-west-1"; + private static final String OTHER_REGION = "eu-central-1"; + + @Test + void userIsOnlyVisibleInItsRegionAndAccount() { + String user = "region-scoped-user"; + createUser(user, user); + try { + // Each Region also holds the built-in "default" user, so look for this user's element. + assertRegional("DescribeUsers", "UserId", user, "" + user + ""); + } finally { + send(ACCOUNT, HOME, "DeleteUser", "UserId", user).then().statusCode(200); + } + } + + @Test + void builtInDefaultUserIsListedAndFoundInEveryRegionWithThatRegionsArn() { + for (String region : new String[] {HOME, OTHER_REGION}) { + String arn = "arn:aws:elasticache:" + region + ":" + ACCOUNT + ":user:default"; + send(ACCOUNT, region, "DescribeUsers").then().statusCode(200) + .body(containsString("default")).body(containsString(arn)); + send(ACCOUNT, region, "DescribeUsers", "UserId", "default").then().statusCode(200) + .body(containsString(arn)); + } + // A user group holding it is one of its groups in the group's Region alone. + String group = "region-scoped-default-group"; + send(ACCOUNT, HOME, "CreateUserGroup", "UserGroupId", group, "Engine", "redis", + "UserIds.member.1", "default").then().statusCode(200); + try { + send(ACCOUNT, HOME, "DescribeUsers", "UserId", "default").then().statusCode(200) + .body(containsString("" + group + "")); + send(ACCOUNT, OTHER_REGION, "DescribeUsers", "UserId", "default").then().statusCode(200) + .body(not(containsString(group))); + } finally { + send(ACCOUNT, HOME, "DeleteUserGroup", "UserGroupId", group).then().statusCode(200); + } + } + + @Test + void userGroupIsOnlyVisibleInItsRegionAndAccount() { + String member = "region-scoped-default"; + String group = "region-scoped-group"; + createUser(member, "default"); + try { + send(ACCOUNT, HOME, "CreateUserGroup", "UserGroupId", group, "Engine", "redis", + "UserIds.member.1", member).then().statusCode(200); + try { + assertRegional("DescribeUserGroups", "UserGroupId", group, "" + group + ""); + } finally { + send(ACCOUNT, HOME, "DeleteUserGroup", "UserGroupId", group).then().statusCode(200); + } + } finally { + send(ACCOUNT, HOME, "DeleteUser", "UserId", member).then().statusCode(200); + } + } + + @Test + void replicationGroupAndItsMembersAreOnlyVisibleInTheirRegionAndAccount() throws InterruptedException { + requireDocker(); + String group = "region-scoped-rg"; + send(ACCOUNT, HOME, "CreateReplicationGroup", "ReplicationGroupId", group, + "ReplicationGroupDescription", "Region scoping").then().statusCode(200); + try { + assertRegional("DescribeReplicationGroups", "ReplicationGroupId", group, + "" + group + ""); + String member = group + "-001"; + assertRegional("DescribeCacheClusters", "CacheClusterId", member, + "" + member + ""); + } finally { + send(ACCOUNT, HOME, "DeleteReplicationGroup", "ReplicationGroupId", group).then().statusCode(200); + } + } + + @Test + void redisCacheClusterIsOnlyVisibleInItsRegionAndAccount() throws InterruptedException { + requireDocker(); + assertCacheClusterIsRegional("region-scoped-redis", "redis"); + } + + @Test + void memcachedCacheClusterIsOnlyVisibleInItsRegionAndAccount() throws InterruptedException { + requireDocker(); + assertCacheClusterIsRegional("region-scoped-memcached", "memcached"); + } + + private static void assertCacheClusterIsRegional(String cluster, String engine) { + send(ACCOUNT, HOME, "CreateCacheCluster", "CacheClusterId", cluster, "Engine", engine, + "NumCacheNodes", "1", "CacheNodeType", "cache.t3.micro").then().statusCode(200); + try { + assertRegional("DescribeCacheClusters", "CacheClusterId", cluster, + "" + cluster + ""); + } finally { + send(ACCOUNT, HOME, "DeleteCacheCluster", "CacheClusterId", cluster).then().statusCode(200); + } + } + + /** + * {@code action} lists {@code id} and finds it by {@code idParam} in its own Region and account, and neither + * lists it nor finds it (404) from another Region of the account or from the same Region of another account. + */ + private static void assertRegional(String action, String idParam, String id, String element) { + send(ACCOUNT, HOME, action).then().statusCode(200).body(containsString(element)); + send(ACCOUNT, HOME, action, idParam, id).then().statusCode(200).body(containsString(element)); + + for (String[] elsewhere : new String[][] {{ACCOUNT, OTHER_REGION}, {OTHER_ACCOUNT, HOME}}) { + send(elsewhere[0], elsewhere[1], action).then().statusCode(200).body(not(containsString(element))); + send(elsewhere[0], elsewhere[1], action, idParam, id).then().statusCode(404); + } + } + + private static void createUser(String userId, String userName) { + send(ACCOUNT, HOME, "CreateUser", "UserId", userId, "UserName", userName, "Engine", "redis", + "AccessString", "on ~* +@all", "AuthenticationMode.Type", "no-password-required") + .then().statusCode(200); + } + + /** An ElastiCache Query request from {@code region} of {@code account}, with {@code params} as name/value pairs. */ + private static Response send(String account, String region, String action, String... params) { + return QueryRequests.request(account, region, "elasticache", action, params).when().post("/"); + } + + private static void requireDocker() throws InterruptedException { + Assumptions.assumeTrue(DockerAvailability.isAvailable(), + "Docker daemon must be available for ElastiCache container tests"); + } +} diff --git a/src/test/java/io/floci/aws/testing/QueryRequests.java b/src/test/java/io/floci/aws/testing/QueryRequests.java index 30ab0158ea..13cea21aed 100644 --- a/src/test/java/io/floci/aws/testing/QueryRequests.java +++ b/src/test/java/io/floci/aws/testing/QueryRequests.java @@ -8,9 +8,15 @@ public final class QueryRequests { private QueryRequests() {} public static RequestSpecification request(String account, String service, String action, String... params) { + return request(account, "us-east-1", service, action, params); + } + + /** A Query request signed for {@code region}. */ + public static RequestSpecification request(String account, String region, String service, String action, + String... params) { RequestSpecification request = given() .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + account - + "/20261022/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc") + + "/20261022/" + region + "/" + service + "/aws4_request, SignedHeaders=host, Signature=abc") .formParam("Action", action); for (int i = 0; i < params.length; i += 2) { request = request.formParam(params[i], params[i + 1]);