Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix: mint ARNs in the request region for Amazon MQ, MSK, EKS Fargate, AppSync and ElastiCache users (#5053)

Hector Ventura1b138812fa81
diff --git a/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqService.java b/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqService.java
index 44e3436905..9f771401be 100644
--- a/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqService.java
@@ -120,7 +120,7 @@ public class AmazonMqService implements ResourceProvider {
String brokerId = "b-" + UUID.randomUUID();
String accountId = regionResolver.getAccountId();
- String brokerArn = AwsArnUtils.Arn.of("mq", config.defaultRegion(), accountId,
+ String brokerArn = AwsArnUtils.Arn.of("mq", regionResolver.getRegion(), accountId,
"broker:" + name + ":" + brokerId).toString();
String engineVersion = (params.engineVersion() == null || params.engineVersion().isBlank())
? DEFAULT_ENGINE_VERSION : params.engineVersion();
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java
index 042e39c068..ab235d449f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java
@@ -736,9 +736,9 @@ public class AppSyncService {
dn.setDescription((String) request.get("description"));
dn.setCertificateArn((String) request.get("certificateArn"));
String shortId = generateShortId();
- dn.setAppsyncDomainName(shortId + "." + AwsEndpoints.host("appsync-api", regionResolver.getDefaultRegion()));
+ dn.setAppsyncDomainName(shortId + "." + AwsEndpoints.host("appsync-api", regionResolver.getRegion()));
dn.setHostedZoneId("Z" + generateShortId());
- dn.setDomainNameArn(regionResolver.buildArn("appsync", regionResolver.getDefaultRegion(),
+ dn.setDomainNameArn(regionResolver.buildArn("appsync", regionResolver.getRegion(),
"domainnames/" + domainName));
Object tagsObj = request.get("tags");
@@ -814,7 +814,7 @@ public class AppSyncService {
public ChannelNamespace createChannelNamespace(String apiId, Map<String, Object> request) {
assertSchemaNotBusy(apiId);
- getGraphqlApi(apiId);
+ GraphqlApi api = getGraphqlApi(apiId);
String name = (String) request.get("name");
if (name == null || name.isBlank()) {
throw new AwsException("BadRequestException", "A channel namespace name is required", 400);
@@ -828,7 +828,7 @@ public class AppSyncService {
ns.setName(name);
ns.setApiId(apiId);
ns.setDescription((String) request.get("description"));
- ns.setChannelNamespaceArn(regionResolver.buildArn("appsync", regionResolver.getDefaultRegion(),
+ ns.setChannelNamespaceArn(regionResolver.buildArn("appsync", apiRegion(api),
"apis/" + apiId + "/channelNamespaces/" + name));
ns.setCodeHandlers((String) request.get("codeHandlers"));
ns.setCreated(System.currentTimeMillis());
@@ -1153,6 +1153,14 @@ public class AppSyncService {
return apiId + "::" + typeName + "::" + fieldName;
}
+ /** The region of an API's ARN, where its child resources live; the request region if it has none. */
+ private String apiRegion(GraphqlApi api) {
+ if (api.getArn() != null && AwsArnUtils.isArn(api.getArn())) {
+ return AwsArnUtils.parse(api.getArn()).region();
+ }
+ return regionResolver.getRegion();
+ }
+
private String buildApiArn(String apiId, String region) {
return regionResolver.buildArn("appsync", region, "apis/" + apiId);
}
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 82c1954049..3afce2eabb 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
@@ -961,7 +961,7 @@ public class EksService implements TagHandler, ResourceProvider {
}
public FargateProfile createFargateProfile(String clusterName, CreateFargateProfileRequest request) {
- describeCluster(clusterName);
+ Cluster cluster = describeCluster(clusterName);
String fargateProfileName = request.getFargateProfileName();
if (fargateProfileName == null || fargateProfileName.isBlank()) {
@@ -977,7 +977,7 @@ public class EksService implements TagHandler, ResourceProvider {
"Fargate profile already exists: " + fargateProfileName, 409);
}
- String region = config.defaultRegion();
+ String region = resolveClusterRegion(cluster);
String accountId = regionResolver.getAccountId();
String id = UUID.randomUUID().toString();
String arn = AwsArnUtils.Arn.of("eks", region, accountId,
diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java
index 5c1ae848f2..e1b28803a7 100644
--- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java
@@ -1049,10 +1049,22 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String>
// MinimumEngineVersion: the only value AWS documents; no valkey-specific one is published.
.elem("MinimumEngineVersion", "6.0")
.start("UserGroupIds").end("UserGroupIds")
- .elem("ARN", AwsArnUtils.Arn.of("elasticache", regionResolver.getDefaultRegion(), regionResolver.getAccountId(), "user:" + u.getUserId()).toString())
+ .elem("ARN", userArn(u))
.build();
}
+ /**
+ * The ARN stored at CreateUser. Users persisted before it was stored keep the default-region ARN
+ * they were always reported with, so their identity stays stable.
+ */
+ private String userArn(ElastiCacheUser u) {
+ if (u.getArn() != null) {
+ return u.getArn();
+ }
+ return AwsArnUtils.Arn.of("elasticache", regionResolver.getDefaultRegion(),
+ regionResolver.getAccountId(), "user:" + u.getUserId()).toString();
+ }
+
private record UserAuthentication(AuthMode mode, List<String> passwords) {}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java
index 3e48190b7e..ac8d8708de 100644
--- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java
@@ -1538,6 +1538,7 @@ public class ElastiCacheService implements ResourceProvider {
passwords != null ? passwords : List.of(),
accessString != null ? accessString : "on ~* +@all",
normalizedEngine, "active", Instant.now());
+ user.setArn(regionResolver.buildArn("elasticache", regionResolver.getRegion(), "user:" + userId));
users.put(userId, user);
LOG.infov("ElastiCache user {0} created with authMode={1}", userId, authMode);
diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/model/ElastiCacheUser.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/model/ElastiCacheUser.java
index 82f4284754..8f39f1593c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/elasticache/model/ElastiCacheUser.java
+++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/model/ElastiCacheUser.java
@@ -18,6 +18,8 @@ public class ElastiCacheUser {
private String engine = "redis";
private String status;
private Instant createdAt;
+ // Minted once in the region of the CreateUser request; null for users persisted before it was stored.
+ private String arn;
public ElastiCacheUser() {}
@@ -58,6 +60,9 @@ public class ElastiCacheUser {
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
+ public String getArn() { return arn; }
+ public void setArn(String arn) { this.arn = arn; }
+
@JsonIgnore
public boolean isEnabled() {
return isAccessStringOn(accessString);
diff --git a/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java b/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java
index 0d6aebdd38..b2256a51ba 100644
--- a/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java
@@ -440,7 +440,7 @@ public class MskService implements ResourceProvider {
}
String accountId = regionResolver.getAccountId();
- String arn = AwsArnUtils.Arn.of("kafka", config.defaultRegion(), accountId,
+ String arn = AwsArnUtils.Arn.of("kafka", regionResolver.getRegion(), accountId,
"configuration/" + name + "/" + UUID.randomUUID()).toString();
MskConfiguration configuration = new MskConfiguration(arn, name, description, kafkaVersions, serverProperties);
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RequestRegionArnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RequestRegionArnIntegrationTest.java
new file mode 100644
index 0000000000..962bfae73b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/RequestRegionArnIntegrationTest.java
@@ -0,0 +1,185 @@
+package io.github.hectorvent.floci.core.common;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.startsWith;
+
+/**
+ * Resources created by a request signed for a non-default region carry that region in their ARN,
+ * not the emulator's default region.
+ */
+@QuarkusTest
+class RequestRegionArnIntegrationTest {
+
+ private static final String REGION = "eu-west-1";
+
+ private static final String OTHER_REGION = "us-west-2";
+
+ private static String auth(String service) {
+ return auth(REGION, service);
+ }
+
+ private static String auth(String region, String service) {
+ return "AWS4-HMAC-SHA256 Credential=AKID/20260215/" + region + "/" + service
+ + "/aws4_request, SignedHeaders=host, Signature=abc";
+ }
+
+ @Test
+ void amazonMqBrokerArnUsesTheRequestRegion() {
+ String brokerId = given()
+ .header("Authorization", auth("mq"))
+ .contentType("application/json")
+ .body("""
+ {"brokerName": "region-arn-broker", "engineType": "RABBITMQ",
+ "deploymentMode": "SINGLE_INSTANCE", "hostInstanceType": "mq.t3.micro",
+ "publiclyAccessible": false,
+ "users": [{"username": "admin", "password": "AdminPass123", "consoleAccess": true}]}
+ """)
+ .when()
+ .post("/v1/brokers")
+ .then()
+ .statusCode(200)
+ .body("brokerArn", startsWith("arn:aws:mq:" + REGION + ":"))
+ .extract().path("brokerId");
+
+ given().header("Authorization", auth("mq")).delete("/v1/brokers/{id}", brokerId)
+ .then().statusCode(200);
+ }
+
+ @Test
+ void mskConfigurationArnUsesTheRequestRegion() {
+ String properties = Base64.getEncoder()
+ .encodeToString("auto.create.topics.enable=true".getBytes(StandardCharsets.UTF_8));
+ String arn = given()
+ .header("Authorization", auth("kafka"))
+ .contentType("application/json")
+ .body("""
+ {"name": "region-arn-config", "kafkaVersions": ["3.6.0"], "serverProperties": "%s"}
+ """.formatted(properties))
+ .when()
+ .post("/v1/configurations")
+ .then()
+ .statusCode(200)
+ .body("arn", startsWith("arn:aws:kafka:" + REGION + ":"))
+ .extract().path("arn");
+
+ given().header("Authorization", auth("kafka")).delete("/v1/configurations/{arn}", arn)
+ .then().statusCode(200);
+ }
+
+ @Test
+ void eksFargateProfileArnUsesTheClusterRegion() {
+ String cluster = "region-arn-cluster";
+ given()
+ .header("Authorization", auth("eks"))
+ .contentType("application/json")
+ .body("{\"name\":\"" + cluster + "\",\"roleArn\":\"arn:aws:iam::000000000000:role/eks-role\","
+ + "\"version\":\"1.29\"}")
+ .when()
+ .post("/clusters")
+ .then()
+ .statusCode(200)
+ .body("cluster.arn", startsWith("arn:aws:eks:" + REGION + ":"));
+
+ given()
+ .header("Authorization", auth("eks"))
+ .contentType("application/json")
+ .body("{\"fargateProfileName\":\"fp\",\"podExecutionRoleArn\":\"arn:aws:iam::000000000000:role/fp\"}")
+ .when()
+ .post("/clusters/{name}/fargate-profiles", cluster)
+ .then()
+ .statusCode(200)
+ .body("fargateProfile.fargateProfileArn", startsWith("arn:aws:eks:" + REGION + ":"));
+
+ given().header("Authorization", auth("eks"))
+ .delete("/clusters/{name}/fargate-profiles/{fp}", cluster, "fp").then().statusCode(200);
+ given().header("Authorization", auth("eks"))
+ .delete("/clusters/{name}", cluster).then().statusCode(200);
+ }
+
+ @Test
+ void appSyncDomainNameUsesTheRequestRegionAndChannelNamespaceItsApisRegion() {
+ String domain = "region-arn-" + System.nanoTime() + ".example.com";
+ given()
+ .header("Authorization", auth("appsync"))
+ .contentType("application/json")
+ .body("""
+ {"domainName": "%s", "certificateArn": "arn:aws:acm:%s:000000000000:certificate/1"}
+ """.formatted(domain, REGION))
+ .when()
+ .post("/v1/domainnames")
+ .then()
+ .statusCode(200)
+ .body("domainNameConfig.domainNameArn", startsWith("arn:aws:appsync:" + REGION + ":"))
+ .body("domainNameConfig.appsyncDomainName", containsString(REGION));
+ given().header("Authorization", auth("appsync")).delete("/v1/domainnames/" + domain)
+ .then().statusCode(204);
+
+ String apiId = given()
+ .header("Authorization", auth("appsync"))
+ .contentType("application/json")
+ .body("{\"name\": \"region-arn-api\", \"authenticationType\": \"API_KEY\"}")
+ .when()
+ .post("/v1/apis")
+ .then()
+ .statusCode(200)
+ .extract().path("graphqlApi.apiId");
+ // A namespace lives in its API's region, even when the request is signed for another one.
+ given()
+ .header("Authorization", auth(OTHER_REGION, "appsync"))
+ .contentType("application/json")
+ .body("{\"name\": \"region-arn-ns\"}")
+ .when()
+ .post("/v2/apis/" + apiId + "/channelNamespaces")
+ .then()
+ .statusCode(200)
+ .body("channelNamespace.channelNamespaceArn", startsWith("arn:aws:appsync:" + REGION + ":"));
+ given().header("Authorization", auth("appsync"))
+ .delete("/v2/apis/" + apiId + "/channelNamespaces/region-arn-ns").then().statusCode(204);
+ given().header("Authorization", auth("appsync")).delete("/v1/apis/" + apiId).then().statusCode(204);
+ }
+
+ @Test
+ void elastiCacheUserArnIsMintedOnceInTheCreateRegion() {
+ given()
+ .header("Authorization", auth("elasticache"))
+ .formParam("Action", "CreateUser")
+ .formParam("UserId", "region-arn-user")
+ .formParam("UserName", "region-arn-user")
+ .formParam("Engine", "valkey")
+ .formParam("AuthenticationMode.Type", "no-password-required")
+ .formParam("AccessString", "on ~* +@all")
+ .when()
+ .post("/")
+ .then()
+ .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.
+ given()
+ .header("Authorization", auth(OTHER_REGION, "elasticache"))
+ .formParam("Action", "DescribeUsers")
+ .formParam("UserId", "region-arn-user")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeUsersResponse.DescribeUsersResult.Users.member.ARN",
+ startsWith("arn:aws:elasticache:" + REGION + ":"));
+
+ given()
+ .header("Authorization", auth("elasticache"))
+ .formParam("Action", "DeleteUser")
+ .formParam("UserId", "region-arn-user")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+}