fix(core): accept ARNs from every AWS partition (#3376)

* fix(core): accept ARNs from every AWS partition

Now that ARNs are minted with the region's real partition, the code that reads
them back has to accept them, or Floci emits names it then refuses. Fifteen
sites across eleven services anchored a pattern, a prefix check or a store scan
on a literal arn:aws:.

Two shapes, and the second is the serious one.

Client-supplied ARNs that were rejected as malformed: the KMS key-ARN branch in
resolveKey, the four service probes in ResourceArnBuilder, DynamoDB's
TagResource validation, and SsoAdminService, which now takes the model's
ManagedPolicyArn pattern. That fixes the pinned partition and tightens a .+ tail
that accepted policy names AWS rejects, while still refusing customer-managed
policies, which is correct for that operation.

Values written partition-aware and read back with a literal. These are not
rejections of foreign input, they are the emulator failing to find its own
resources, so in GovCloud or China they are live functional breaks:

  - ListStateMachines and ListActivities returned empty. Step Functions is the
    only service keying its stores by the full ARN, so its list prefix has to
    carry the partition. The prefix deliberately stops before the account
    segment, because the store holds more than one account.
  - SQS DLQ redrive stopped silently. queueUrlFromArn resolved a
    deadLetterTargetArn read back from GetQueueAttributes to null, the move
    block was skipped, and nothing was logged.
  - An EventBridge bus ARN was taken as a literal bus name, so DescribeEventBus
    reported not-found for a bus it had just created.
  - A Secrets Manager partial ARN, which AWS lets clients write without the
    random suffix, resolved to nothing.
  - An ECS task could not read its own configuration: a Secrets Manager
    valueFrom fell through to the SSM branch and a parameter ARN was passed
    along whole as a parameter name, killing the task at launch.
  - AppSync IAM authorisation built its policy resource with a pinned
    partition, so a policy naming its own API never matched and the request was
    denied.

The IAM trust-policy path failed the same way and needed the regex and the
construction changed together: resolving an STS assumed-role ARN back to its
IAM role rebuilt the role ARN with a hardcoded partition, so widening the
pattern alone would have denied AssumeRole to a caller who is entitled.

Two spellings are deliberate rather than an oversight. EventBridge matches an
ARN prefix instead of a whole ARN, so a truncated arn:aws:events: is still
reported as malformed rather than taken as a bus name. Secrets Manager reads
the name off the parsed resource without splitting it again, because a secret
name may contain colons.

API Gateway is not a widening. ACTION_URI_PATTERN and PATH_URI_PATTERN were
declared and referenced nowhere, so the real gate was a startsWith inside
parseIntegrationUri. The dead patterns are removed and the guard fixed.

Left alone, and not fixable here: IAM SAML providers and the SSO instance ARN
build a region-less arn:aws: ARN by concatenation, store under it, then look it
up by the string given. Widening those turns one miss into a different miss.
They need a deployment-level partition, which nothing in a request supplies.
The Amazon States Language service-integration ids are arn:aws:states::: in
every partition and stay as they are.

Each behavioural fix was checked by reverting its source file and confirming
the new tests fail without it.

* chore(stepfunctions): drop the duplicate AwsArnUtils import

StepFunctionsService imported AwsArnUtils twice. The duplicate arrived with
#2485 and javac accepts it silently, so nothing surfaced it until this branch
added an AwsRegions import above it and a diff view made it look new.

It is the only duplicate import in src/main/java, so there is nothing else of
this shape to sweep up.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-10 23:10:55 -04:00
1 parent cb6b4d8a88
commit 1726c6a8a3
26 files changed
+876 -43

No files matched your search

@@ -6,7 +6,9 @@ import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link AwsArnUtils} is the emulator's shared ARN helper and had no test of its own, despite
@@ -161,6 +163,43 @@ class AwsArnUtilsTest {
"secret:s").toString());
}
@ParameterizedTest
@ValueSource(strings = {
"arn:aws:sqs:us-east-1:000000000000:my-queue",
"arn:aws-us-gov:sqs:us-gov-west-1:000000000000:my-queue",
"arn:aws-cn:s3:::bucket",
"arn:aws:lambda:us-east-1:000000000000:function:f:PROD"})
void isArnAcceptsAnyPartition(String value) {
assertTrue(AwsArnUtils.isArn(value));
}
@ParameterizedTest
@ValueSource(strings = {"my-queue", "arn:aws:sqs:us-east-1:000000000000", "arn:", "", " "})
void isArnRejectsNonArns(String value) {
assertFalse(AwsArnUtils.isArn(value));
}
@Test
void isArnRejectsNullRatherThanThrowing() {
assertFalse(AwsArnUtils.isArn(null));
}
/**
* The shape the {@code startsWith("arn:aws:dynamodb:")} probes were reaching for: is this
* identifier an ARN for my service, whatever partition it came from.
*/
@Test
void isArnForMatchesTheServiceInAnyPartition() {
assertTrue(AwsArnUtils.isArnFor("arn:aws:dynamodb:us-east-1:000000000000:table/t",
"dynamodb"));
assertTrue(AwsArnUtils.isArnFor("arn:aws-cn:dynamodb:cn-north-1:000000000000:table/t",
"dynamodb"));
assertFalse(AwsArnUtils.isArnFor("arn:aws:kinesis:us-east-1:000000000000:stream/s",
"dynamodb"));
assertFalse(AwsArnUtils.isArnFor("my-table", "dynamodb"));
assertFalse(AwsArnUtils.isArnFor(null, "dynamodb"));
}
@Test
void queueUrlIsAccountThenQueueName() {
assertEquals("http://localhost:4566/000000000000/my-queue",
@@ -0,0 +1,83 @@
package io.github.hectorvent.floci.services.apigateway;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Parsing of an AWS integration URI, which is the ARN a customer writes into their integration
* config: {@code arn:<partition>:apigateway:<region>:<service>:action/<Action>}. The parse needs
* none of the router's handlers, so they are left null.
*/
class AwsServiceRouterIntegrationUriTest {
private final AwsServiceRouter router = new AwsServiceRouter(
null, null, null, null, null, null, null, null, null, null, null, null, null, null);
@Test
void parsesAnActionUri() {
AwsServiceRouter.IntegrationTarget target =
router.parseIntegrationUri("arn:aws:apigateway:us-east-1:sqs:action/SendMessage");
assertEquals("us-east-1", target.region());
assertEquals("sqs", target.service());
assertEquals("SendMessage", target.action());
assertNull(target.path());
}
@Test
void parsesAPathUri() {
AwsServiceRouter.IntegrationTarget target = router.parseIntegrationUri(
"arn:aws:apigateway:us-east-1:s3:path/my-bucket/my-key");
assertEquals("s3", target.service());
assertNull(target.action());
assertEquals("my-bucket/my-key", target.path());
}
/**
* The guard was a literal {@code startsWith("arn:aws:apigateway:")}, so a customer running
* against GovCloud or China wrote a legal integration URI and the router returned null, which
* reads downstream as "this is not an AWS integration" rather than as an error.
*/
@ParameterizedTest
@ValueSource(strings = {
"arn:aws-us-gov:apigateway:us-gov-west-1:sqs:action/SendMessage",
"arn:aws-cn:apigateway:cn-north-1:sqs:action/SendMessage",
"arn:aws-iso-b:apigateway:us-isob-east-1:sqs:action/SendMessage"})
void parsesAnActionUriFromAnyPartition(String uri) {
AwsServiceRouter.IntegrationTarget target = router.parseIntegrationUri(uri);
assertNotNull(target, uri + " was not recognised as an AWS integration URI");
assertEquals("sqs", target.service());
assertEquals("SendMessage", target.action());
}
/** A path segment may itself contain a colon, and the remainder is re-joined to keep it. */
@Test
void keepsColonsInsideAPath() {
AwsServiceRouter.IntegrationTarget target = router.parseIntegrationUri(
"arn:aws:apigateway:us-east-1:s3:path/bucket/a:b");
assertEquals("bucket/a:b", target.path());
}
@ParameterizedTest
@ValueSource(strings = {
"arn:aws:lambda:us-east-1:000000000000:function:f",
"arn:aws:apigateway:us-east-1:sqs",
"http://example.com",
"arn:aws:apigateway:us-east-1:sqs:unknown/Thing"})
void rejectsWhatIsNotAnAwsIntegrationUri(String uri) {
assertNull(router.parseIntegrationUri(uri));
}
@Test
void rejectsNull() {
assertNull(router.parseIntegrationUri(null));
}
}
@@ -90,6 +90,33 @@ class IamAuthValidatorTest {
assertEquals("test", identity.get("user"));
}
/**
* These two build the resource the policy evaluator matches against, and the ARN a customer
* writes their policy from is the one AppSync minted, which carries the region's partition.
* A pinned {@code aws} here meant a GovCloud policy naming its own API never matched and the
* request was denied with nothing saying why.
*/
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.CsvSource({
"us-east-1, arn:aws:appsync:",
"us-gov-west-1, arn:aws-us-gov:appsync:",
"cn-north-1, arn:aws-cn:appsync:",
"us-isob-east-1, arn:aws-iso-b:appsync:"})
void resourceArnsCarryTheRegionsPartition(String region, String expectedPrefix) {
assertTrue(IamAuthValidator.requestArn(region, "000000000000", "api-1").startsWith(expectedPrefix),
IamAuthValidator.requestArn(region, "000000000000", "api-1"));
assertTrue(IamAuthValidator.fieldArn(region, "000000000000", "api-1", "Query", "hello")
.startsWith(expectedPrefix),
IamAuthValidator.fieldArn(region, "000000000000", "api-1", "Query", "hello"));
}
/** A null or blank region keeps the commercial partition, as every global ARN does. */
@Test
void aBlankRegionStaysCommercial() {
assertEquals("arn:aws:appsync::000000000000:apis/api-1/*",
IamAuthValidator.requestArn(null, "000000000000", "api-1"));
}
@Test
void fieldArnDenyDetected() {
when(iamService.resolveCallerContext("AKIAGOOD")).thenReturn(CallerContext.of(List.of(FIELD_DENY)));
@@ -0,0 +1,147 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.startsWith;
/**
* TagResource validates its ResourceArn against a pattern the emulator owns: botocore gives
* DynamoDB's {@code ResourceArnString} no pattern at all, only a length range. That pattern pinned
* the commercial partition, so a Floci deployed against a GovCloud or China region minted table
* ARNs it then refused to accept back, and tagging a table by its own ARN failed as malformed.
*
* <p>The region drives the partition, and it comes from the request's SigV4 credential scope.
*/
@QuarkusTest
class DynamoDbTagResourcePartitionIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
/**
* Tables created here live in the emulator's shared state for the rest of the suite, and the
* non-commercial ones carry a non-commercial ARN. ResourceExplorer2's cross-service scan
* asserts that every resource it can see is in the commercial partition, so leaving these
* behind fails an unrelated test. Every table this class creates is removed again.
*/
private final List<Map.Entry<String, String>> createdTables = new ArrayList<>();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@AfterEach
void deleteCreatedTables() {
for (Map.Entry<String, String> table : createdTables) {
given()
.header("Authorization", auth(table.getKey()))
.header("X-Amz-Target", "DynamoDB_20120810.DeleteTable")
.contentType(CONTENT_TYPE)
.body("{\"TableName\": \"%s\"}".formatted(table.getValue()))
.when()
.post("/");
}
createdTables.clear();
}
private static String auth(String region) {
return "AWS4-HMAC-SHA256 Credential=AKID/20260215/" + region + "/dynamodb/aws4_request, "
+ "SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=abc";
}
private String createTable(String region, String tableName) {
createdTables.add(Map.entry(region, tableName));
return given()
.header("Authorization", auth(region))
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
.contentType(CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"BillingMode": "PAY_PER_REQUEST"
}
""".formatted(tableName))
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("TableDescription.TableArn");
}
private static Response tag(String region, String resourceArn) {
return given()
.header("Authorization", auth(region))
.header("X-Amz-Target", "DynamoDB_20120810.TagResource")
.contentType(CONTENT_TYPE)
.body("""
{"ResourceArn": "%s", "Tags": [{"Key": "env", "Value": "test"}]}
""".formatted(resourceArn))
.when()
.post("/");
}
/**
* The round trip: create a table in a region, then tag it by the ARN the emulator gave back.
* This has to hold in every partition, and it is the case that was broken.
*/
@ParameterizedTest
@CsvSource({
"us-east-1, arn:aws:dynamodb:",
"us-gov-west-1, arn:aws-us-gov:dynamodb:",
"cn-north-1, arn:aws-cn:dynamodb:",
"us-isob-east-1, arn:aws-iso-b:dynamodb:"})
void tagsATableByItsOwnArnInEveryPartition(String region, String expectedArnPrefix) {
String tableName = "tag-partition-" + UUID.randomUUID().toString().substring(0, 8);
String tableArn = createTable(region, tableName);
org.hamcrest.MatcherAssert.assertThat(tableArn, startsWith(expectedArnPrefix));
tag(region, tableArn).then().statusCode(200);
}
/**
* A table ARN from another partition is well formed, so it is no longer a ValidationException.
* It is simply not a resource this region holds, which is what AWS reports too.
*/
@Test
void aTableArnFromAnotherPartitionIsNotFoundRatherThanMalformed() {
String tableName = "tag-foreign-" + UUID.randomUUID().toString().substring(0, 8);
createTable("us-east-1", tableName);
tag("us-east-1", "arn:aws-cn:dynamodb:cn-north-1:000000000000:table/" + tableName)
.then()
.statusCode(400)
.body(containsString("ResourceNotFoundException"));
}
/** Widening the partition must not loosen the rest of the shape. */
@ParameterizedTest
@ValueSource(strings = {
"arn:aws:sqs:us-east-1:000000000000:table/Some",
"arn:aws:dynamodb:us-east-1:0:table/Some",
"arn:aws:dynamodb:us-east-1:000000000000:stream/Some",
"arn:notaws:dynamodb:us-east-1:000000000000:table/Some",
"not-an-arn"})
void stillRejectsAMalformedArnAsAValidationException(String resourceArn) {
tag("us-east-1", resourceArn)
.then()
.statusCode(400)
.body(containsString("ValidationException"));
}
}
@@ -113,6 +113,40 @@ class EcsContainerManagerSecretsTest {
verify(ssmService).getParameter("/foo/bar", "us-east-1");
}
/**
* Both {@code valueFrom} guards required a literal {@code arn:aws:}. Outside the commercial
* partition a Secrets Manager ARN fell through to the SSM branch and a parameter ARN was
* passed along whole as a parameter name, so the task died at launch with ParameterNotFound
* rather than reading its own configuration.
*/
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.CsvSource({
"us-gov-west-1, aws-us-gov",
"cn-north-1, aws-cn",
"us-isob-east-1, aws-iso-b"})
void resolvesSecretsAndParametersInAnyPartition(String region, String partition) {
String ssmArn = "arn:" + partition + ":ssm:" + region + ":000000000000:parameter/app/token";
String secretArn = "arn:" + partition + ":secretsmanager:" + region + ":000000000000:secret:db-AbCdEf";
when(ssmService.getParameter("/app/token", region))
.thenReturn(new Parameter("/app/token", "ssm-value", "String"));
when(secretsManagerService.getSecretValue(secretArn, null, null, region))
.thenReturn(secretVersion("sm-value"));
manager.startTask(task(), taskDef(containerDef("app", List.of(
new Secret("TOKEN", ssmArn),
new Secret("PASSWORD", secretArn)))),
List.of(), region);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> envCaptor = ArgumentCaptor.forClass(List.class);
verify(builder).withEnv(envCaptor.capture());
List<String> env = envCaptor.getValue();
assertTrue(env.contains("TOKEN=ssm-value"), "SSM ARN in " + partition + " did not resolve: " + env);
assertTrue(env.contains("PASSWORD=sm-value"),
"Secrets Manager ARN in " + partition + " did not resolve: " + env);
}
@Test
void crossRegionArnResolvesAgainstArnRegionNotTaskRegion() {
String ssmArn = "arn:aws:ssm:eu-west-1:000000000000:parameter/app/token";
@@ -226,6 +226,77 @@ class EventBridgeArnIntegrationTest {
.statusCode(200);
}
/**
* The bus ARN EventBridge mints carries the region's own partition, and DescribeEventBus
* accepts an ARN in place of a name. The gate that recognised an ARN required a literal
* {@code arn:aws:events:}, so outside the commercial partition the emulator handed back an ARN
* it then read as a literal bus name and reported ResourceNotFound for a bus it had created.
*
* <p>Region comes from the SigV4 credential scope. The bus is deleted again: @QuarkusTest
* classes share one emulator, and a non-commercial ARN left behind fails the cross-service
* scan in ResourceExplorer2IntegrationTest.
*/
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.CsvSource({
"us-east-1, arn:aws:events:",
"us-gov-west-1, arn:aws-us-gov:events:",
"cn-north-1, arn:aws-cn:events:"})
@Order(10)
void describeEventBus_withArn_inAnyPartition(String region, String expectedArnPrefix) {
String busName = "partition-bus-" + region;
String auth = "AWS4-HMAC-SHA256 Credential=AKID/20260215/" + region
+ "/events/aws4_request, SignedHeaders=host, Signature=abc";
String busArn = given()
.header("Authorization", auth)
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", "AWSEvents.CreateEventBus")
.body("{\"Name\":\"" + busName + "\"}")
.when().post("/")
.then().statusCode(200)
.extract().jsonPath().getString("EventBusArn");
org.hamcrest.MatcherAssert.assertThat(busArn, org.hamcrest.Matchers.startsWith(expectedArnPrefix));
try {
given()
.header("Authorization", auth)
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", "AWSEvents.DescribeEventBus")
.body("{\"Name\":\"" + busArn + "\"}")
.when().post("/")
.then()
.statusCode(200)
.body("Name", equalTo(busName))
.body("Arn", equalTo(busArn));
} finally {
given()
.header("Authorization", auth)
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", "AWSEvents.DeleteEventBus")
.body("{\"Name\":\"" + busName + "\"}")
.when().post("/");
}
}
/**
* A truncated ARN must still be reported as a malformed ARN rather than quietly taken as a
* literal bus name. This is why the gate matches an ARN <em>prefix</em> instead of asking
* whether the whole string is a well-formed EventBridge ARN.
*/
@Test
@Order(10)
void describeEventBus_withTruncatedArn_isRejected() {
given()
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
.header("X-Amz-Target", "AWSEvents.DescribeEventBus")
.body("{\"Name\":\"arn:aws:events:\"}")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("ValidationException"));
}
@Test
@Order(11)
void describeEventBus_withArn() {
@@ -151,6 +151,45 @@ class AssumeRolePolicyEvaluatorTest {
assumedRoleArn, CALLER_ACCOUNT));
}
@Test
void allowsAssumedRoleCallerAgainstRolePrincipalArnInGovCloud() {
// The silent-denial case. Resolving the session back to its role used to rebuild the role
// ARN with a hardcoded "aws" partition, so a GovCloud caller was compared against
// arn:aws:iam::... and never matched the arn:aws-us-gov:iam::... principal its own trust
// policy names. AssumeRole was refused with nothing in the response explaining why.
String assumedRoleArn = "arn:aws-us-gov:sts::111111111111:assumed-role/AppRole/session-abc";
assertTrue(evaluator.allows(
trust("{\"AWS\":\"arn:aws-us-gov:iam::111111111111:role/AppRole\"}"),
assumedRoleArn, CALLER_ACCOUNT));
}
@Test
void allowsAssumedRoleCallerAgainstRolePrincipalArnInChina() {
String assumedRoleArn = "arn:aws-cn:sts::111111111111:assumed-role/AppRole/session-abc";
assertTrue(evaluator.allows(
trust("{\"AWS\":\"arn:aws-cn:iam::111111111111:role/AppRole\"}"),
assumedRoleArn, CALLER_ACCOUNT));
}
/**
* The guard against over-widening. Partitions are isolated, so a session in one must not
* satisfy a trust policy written for another even when account, role and session all match.
*/
@Test
void deniesAssumedRoleCallerFromAnotherPartition() {
String assumedRoleArn = "arn:aws-us-gov:sts::111111111111:assumed-role/AppRole/session-abc";
assertFalse(evaluator.allows(
trust("{\"AWS\":\"arn:aws:iam::111111111111:role/AppRole\"}"),
assumedRoleArn, CALLER_ACCOUNT));
}
@Test
void allowsAccountRootPrincipalInGovCloud() {
assertTrue(evaluator.allows(
trust("{\"AWS\":\"arn:aws-us-gov:iam::111111111111:root\"}"),
"arn:aws-us-gov:iam::111111111111:user/alice", CALLER_ACCOUNT));
}
@Test
void deniesServiceOnlyPrincipal() {
assertFalse(evaluator.allows(
@@ -71,6 +71,29 @@ class ResourceArnBuilderTest {
assertEquals("arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable", arn);
}
/**
* Pass-through used to be a {@code startsWith("arn:aws:dynamodb:")} probe, so a table ARN from
* any other partition was not recognised as an ARN at all and got rebuilt as
* {@code table/arn:aws-cn:dynamodb:...}, a resource name that matches no policy.
*/
@Test
void dynamoDbReturnsExactArnForAnyPartition() {
for (String fullArn : List.of(
"arn:aws-us-gov:dynamodb:us-gov-west-1:000000000000:table/FgacTable",
"arn:aws-cn:dynamodb:cn-north-1:000000000000:table/FgacTable")) {
setJsonBody("{\"TableName\":\"" + fullArn + "\"}");
assertEquals(fullArn, builder.build("dynamodb", ctx, "us-east-1", "000000000000"));
}
}
/** A bare name that merely looks ARN-ish is still a name, not an ARN. */
@Test
void dynamoDbTreatsAnIncompleteArnAsATableName() {
setJsonBody("{\"TableName\":\"arn:aws:dynamodb:us-east-1\"}");
assertEquals("arn:aws:dynamodb:us-east-1:000000000000:table/arn:aws:dynamodb:us-east-1",
builder.build("dynamodb", ctx, "us-east-1", "000000000000"));
}
@Test
void dynamoDbReturnsExactArnIfTableNameIsAlreadyArn() {
String fullArn = "arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable";
@@ -67,6 +67,22 @@ class KmsServiceTest {
);
}
/**
* Round-trip in a non-commercial partition. The key ARN a GovCloud or China deployment mints
* carries that partition, and resolving a key by ARN used to test
* {@code startsWith("arn:aws:kms:")}, so the emulator refused to find a key it had just
* created and reported NotFound for a key that exists.
*/
@Test
void resolvesAKeyByItsOwnArnInAnyPartition() {
for (String region : List.of("us-gov-west-1", "cn-north-1", "us-east-1")) {
KmsKey created = kmsService.createKey("partition key", region);
assertEquals(created.getKeyId(), kmsService.describeKey(created.getArn(), region).getKeyId(),
"key in " + region + " was not resolvable by its own ARN " + created.getArn());
}
}
@Test
void createKeyAndDescribe() {
KmsKey key = kmsService.createKey("my test key", REGION);
@@ -678,6 +678,39 @@ class SecretsManagerServiceTest {
assertEquals("db-pass", version.getSecretString());
}
/**
* A secret name may contain colons, and the partial-ARN fallback used to preserve them by
* splitting the ARN tail with an explicit limit. Reading the name off the parsed resource has
* to keep that property: strip only the leading "secret:", never split again.
*/
@Test
void getSecretValueByPartialArnWithColonsInNameSucceeds() {
Secret secret = service.createSecret("team:app:db", "colon-pass", null, null, null, null, REGION);
String partialArn = secret.getArn().substring(0, secret.getArn().length() - 7);
SecretVersion version = service.getSecretValue(partialArn, null, null, REGION);
assertEquals("colon-pass", version.getSecretString());
}
/**
* The partial-ARN fallback matched a literal "arn:aws:secretsmanager:", so outside the
* commercial partition a secret's own ARN, minus the random suffix AWS lets clients omit,
* resolved to nothing. Round trip through the ARN the emulator itself minted.
*/
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.CsvSource({
"us-east-1, arn:aws:secretsmanager:",
"us-gov-west-1, arn:aws-us-gov:secretsmanager:",
"cn-north-1, arn:aws-cn:secretsmanager:"})
void getSecretValueByPartialArnSucceedsInAnyPartition(String region, String expectedArnPrefix) {
Secret secret = service.createSecret("p-secret", "value", null, null, null, null, region);
assertTrue(secret.getArn().startsWith(expectedArnPrefix), "minted ARN was " + secret.getArn());
String partialArn = secret.getArn().substring(0, secret.getArn().length() - 7);
assertEquals("value", service.getSecretValue(partialArn, null, null, region).getSecretString());
}
@Test
void getSecretValueByFullArnStillWorks() {
Secret secret = service.createSecret("my-secret", "value", null, null, null, null, REGION);
@@ -780,6 +780,73 @@ class SqsServiceTest {
assertEquals(25, task.maxNumberOfMessagesPerSecond());
}
/**
* The DLQ redrive path resolves a queue URL from the {@code deadLetterTargetArn} a client read
* back out of GetQueueAttributes, and SQS mints that ARN with the region's own partition. The
* resolver used to require a literal {@code arn:aws:sqs:}, so in GovCloud or China it returned
* null, the move block was skipped, and messages stayed on the source queue with nothing
* logged. A silent redrive failure is the worst shape this bug takes.
*/
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.CsvSource({
"us-east-1, arn:aws:sqs:us-east-1:000000000000:",
"us-gov-west-1, arn:aws-us-gov:sqs:us-gov-west-1:000000000000:",
"cn-north-1, arn:aws-cn:sqs:cn-north-1:000000000000:"})
void startMessageMoveTask_acceptsAQueueArnFromAnyPartition(String region, String arnPrefix) {
sqsService.createQueue("p-dlq", null, region);
String dlqArn = arnPrefix + "p-dlq";
sqsService.createQueue("p-src",
Map.of("RedrivePolicy",
"{\"deadLetterTargetArn\":\"" + dlqArn + "\",\"maxReceiveCount\":\"1\"}"), region);
sqsService.createQueue("p-dest", null, region);
String taskHandle = sqsService.startMessageMoveTask(dlqArn, arnPrefix + "p-dest", 5, region);
assertNotNull(taskHandle);
assertEquals(dlqArn, sqsService.listMessageMoveTasks(dlqArn, region).get(0).sourceArn());
}
/**
* The ARN the emulator itself hands back must be the one it accepts. This is the assertion
* that ties the two halves together rather than trusting a hand-written prefix.
*/
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = {"us-east-1", "us-gov-west-1", "cn-north-1"})
void startMessageMoveTask_acceptsTheQueueArnGetQueueAttributesReturned(String region) {
sqsService.createQueue("rt-dlq", null, region);
String dlqArn = sqsService.getQueueAttributes(
sqsService.getQueueUrl("rt-dlq", region), List.of("QueueArn"), region).get("QueueArn");
sqsService.createQueue("rt-src",
Map.of("RedrivePolicy",
"{\"deadLetterTargetArn\":\"" + dlqArn + "\",\"maxReceiveCount\":\"1\"}"), region);
sqsService.createQueue("rt-dest", null, region);
String destArn = sqsService.getQueueAttributes(
sqsService.getQueueUrl("rt-dest", region), List.of("QueueArn"), region).get("QueueArn");
assertNotNull(sqsService.startMessageMoveTask(dlqArn, destArn, 5, region));
}
/**
* Widening the partition must not turn "queue does not exist" into something softer: an ARN
* naming a queue nobody created is still ResourceNotFound, exactly as a commercial one is.
*
* <p>Note the resolver takes only the account and queue name out of the ARN and looks them up
* in the caller's region, so the ARN's own region is not enforced. That is pre-existing and
* already applied to a cross-region commercial ARN; this change does not alter it.
*/
@Test
void startMessageMoveTask_foreignPartitionQueueThatDoesNotExistIsNotFound() {
sqsService.createQueue("fp-dlq", null, "us-east-1");
String dlqArn = queueArn("fp-dlq");
sqsService.createQueue("fp-src",
Map.of("RedrivePolicy",
"{\"deadLetterTargetArn\":\"" + dlqArn + "\",\"maxReceiveCount\":\"1\"}"), "us-east-1");
AwsException ex = assertThrows(AwsException.class, () -> sqsService.startMessageMoveTask(
dlqArn, "arn:aws-cn:sqs:cn-north-1:000000000000:never-created", 0, "us-east-1"));
assertEquals("ResourceNotFoundException", ex.getErrorCode());
}
@Test
void startMessageMoveTask_destinationDoesNotExist_throwsResourceNotFound() {
sqsService.createQueue("a-dlq", null, "us-east-1");
@@ -1425,6 +1425,57 @@ class SsoAdminServiceTest {
"arn:aws:iam::aws:policy/OverQuotaPolicy"));
}
/**
* The model's ManagedPolicyArn pattern is partition-tolerant. Pinning it to the commercial
* partition refused a legal GovCloud or China managed-policy ARN.
*/
@Test
void attachAcceptsManagedPolicyArnsFromEveryPartition() {
PermissionSet permissionSet = createPermissionSet("PartitionAdmins");
service.attachPolicy(service.getInstanceArn(), permissionSet.arn(),
"arn:aws-us-gov:iam::aws:policy/ReadOnlyAccess");
service.attachPolicy(service.getInstanceArn(), permissionSet.arn(),
"arn:aws-cn:iam::aws:policy/SecurityAudit");
service.attachPolicy(service.getInstanceArn(), permissionSet.arn(),
"arn:aws-iso-b:iam::aws:policy/ViewOnlyAccess");
}
/** AWS-managed policies live under a path, which the previous {@code .+} tail also allowed. */
@Test
void attachAcceptsAServiceRolePath() {
PermissionSet permissionSet = createPermissionSet("PathAdmins");
service.attachPolicy(service.getInstanceArn(), permissionSet.arn(),
"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy");
}
/**
* Tightening the tail from {@code .+} to the model's charset. A space is not a legal policy
* name and used to be accepted.
*/
@Test
void attachRejectsAPolicyNameOutsideTheModelCharset() {
PermissionSet permissionSet = createPermissionSet("StrictAdmins");
assertThrows(AwsException.class, () -> service.attachPolicy(service.getInstanceArn(),
permissionSet.arn(), "arn:aws:iam::aws:policy/bad name"));
}
/**
* AttachManagedPolicyToPermissionSet takes AWS-managed policies only, which the model spells
* as the literal {@code ::aws:policy} account segment. Customer-managed policies go through
* the separate customer-managed-reference operations, so this rejection is correct AWS
* behaviour and must survive the widening above.
*/
@Test
void attachStillRejectsACustomerManagedPolicy() {
PermissionSet permissionSet = createPermissionSet("CustomerAdmins");
assertThrows(AwsException.class, () -> service.attachPolicy(service.getInstanceArn(),
permissionSet.arn(), "arn:aws:iam::" + ACCOUNT_ID + ":policy/MyOwnPolicy"));
}
@Test
void managedPolicyPaginationHonorsMaxResultsAndNextToken() {
PermissionSet permissionSet = createPermissionSet("PlatformAdmins");
@@ -0,0 +1,107 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.stepfunctions.model.Activity;
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
/**
* Step Functions is the only service that keys its stores by the full ARN; the others key by
* {@code region::name}. Once ARNs carried the region's real partition, the list operations still
* scanned for a {@code arn:aws:states:} prefix, so a state machine or activity created in GovCloud
* or China was stored under {@code arn:aws-us-gov:...} and listing returned nothing: the write path
* and the read path disagreed about the same resource.
*
* <p>A real {@link RegionResolver} is used deliberately, not a mock, because the whole point is
* that the list prefix agrees with what {@code buildArn} actually produced.
*/
class StepFunctionsListPartitionTest {
private static final String ACCOUNT = "000000000000";
private StepFunctionsService buildService() {
StorageFactory factory = mock(StorageFactory.class);
doReturn(AccountAwareStorageBackend.<StateMachine>inMemory(ACCOUNT))
.doReturn(AccountAwareStorageBackend.<Execution>inMemory(ACCOUNT))
.doReturn(AccountAwareStorageBackend.<Activity>inMemory(ACCOUNT))
.when(factory).create(anyString(), anyString(), any());
// aslExecutor stays null: neither CreateStateMachine nor CreateActivity reaches it, and
// AslExecutor cannot be class-loaded in this sandbox because it needs Vert.x.
return new StepFunctionsService(factory, new RegionResolver("us-east-1", ACCOUNT), null,
new ObjectMapper(), mock(SfnMockLoader.class));
}
private static final String DEFINITION =
"{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Pass\",\"End\":true}}}";
@ParameterizedTest
@CsvSource({
"us-east-1, arn:aws:states:",
"us-gov-west-1, arn:aws-us-gov:states:",
"cn-north-1, arn:aws-cn:states:",
"us-isob-east-1, arn:aws-iso-b:states:"})
void listsAStateMachineCreatedInThatPartition(String region, String expectedArnPrefix) {
StepFunctionsService service = buildService();
StateMachine created = service.createStateMachine("sm-" + region, DEFINITION,
"arn:aws:iam::" + ACCOUNT + ":role/r", "STANDARD", region, null);
assertTrue(created.getStateMachineArn().startsWith(expectedArnPrefix),
"created ARN was " + created.getStateMachineArn());
List<StateMachine> listed = service.listStateMachines(region);
assertEquals(1, listed.size(),
"ListStateMachines found nothing in " + region + " for " + created.getStateMachineArn());
assertEquals(created.getStateMachineArn(), listed.getFirst().getStateMachineArn());
}
@ParameterizedTest
@CsvSource({
"us-east-1, arn:aws:states:",
"us-gov-west-1, arn:aws-us-gov:states:",
"cn-north-1, arn:aws-cn:states:",
"us-isob-east-1, arn:aws-iso-b:states:"})
void listsAnActivityCreatedInThatPartition(String region, String expectedArnPrefix) {
StepFunctionsService service = buildService();
Activity created = service.createActivity("act-" + region, region, null);
assertTrue(created.getActivityArn().startsWith(expectedArnPrefix),
"created ARN was " + created.getActivityArn());
List<Activity> listed = service.listActivities(region);
assertEquals(1, listed.size(),
"ListActivities found nothing in " + region + " for " + created.getActivityArn());
assertEquals(created.getActivityArn(), listed.getFirst().getActivityArn());
}
/** A list must still be scoped to its own region, and now also to its own partition. */
@Test
void doesNotListAcrossRegions() {
StepFunctionsService service = buildService();
service.createActivity("gov", "us-gov-west-1", null);
service.createActivity("commercial", "us-east-1", null);
assertEquals(1, service.listActivities("us-gov-west-1").size());
assertEquals(1, service.listActivities("us-east-1").size());
assertEquals("gov", service.listActivities("us-gov-west-1").getFirst().getName());
}
}