fix(core): read ARNs and Step Functions integration ids in every partition (#4358)

P2 of the multi-partition initiative (#4272), the parse side. StatesIntegration
replaces the literal arn:aws:states::: integration ids the ASL executor and the
definition validator compared against: the CDK builds them as
arn:${Aws.PARTITION}:states:::, so a China or GovCloud state machine never
matched (aws-cdk task-utils.ts:36). Only AWS's three suffixes (.sync, .sync:2,
.waitForTaskToken) parse, and a dispatch that does not read the suffix accepts
none, so sqs:sendMessage.bogus stays unsupported as it was. AwsArnUtils
.resourceIfArnFor replaces the 16 startsWith("arn:aws") probes, so bucket
policies, S3 resource paths, assumed-role principals, SAML role pairs, EKS
instance profiles, Security Hub, OAM and CloudTrail selectors recognise China,
GovCloud and ISO ARNs, and an assumed role's underlying role is rebuilt in the
session's own partition. Where a check used to pin arn:aws: and thereby the
commercial partition, it now pins the partition explicitly: a root principal
matches only a caller of the same partition and account, and a Security Hub
resource ARN must carry the request's partition. The 25 hand-rolled partition
alternations in regexes collapse onto AwsArnUtils.PARTITION_REGEX. The
partition-literal baseline drops from 270 to 195 gated occurrences.

Part of #4272
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-24 21:03:38 -04:00
1 parent 6ed4726f52
commit eb2872f578
36 files changed
+654 -153

No files matched your search

@@ -160,6 +160,22 @@ class AwsArnUtilsTest {
PartitionMatrix.assertGlobalArnIn(partitionCase, arn.toString());
}
@ParameterizedTest
@MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases")
void resourceIfArnForYieldsTheResourceTailInEveryPartition(PartitionCase partitionCase) {
String prefix = "arn:" + partitionCase.partition() + ":s3:::";
assertEquals("bucket/key", AwsArnUtils.resourceIfArnFor(prefix + "bucket/key", "s3").orElseThrow());
assertEquals("", AwsArnUtils.resourceIfArnFor(prefix, "s3").orElseThrow());
assertTrue(AwsArnUtils.resourceIfArnFor(prefix + "bucket", "sqs").isEmpty());
}
@Test
void resourceIfArnForIsEmptyForNonArns() {
assertTrue(AwsArnUtils.resourceIfArnFor(null, "s3").isEmpty());
assertTrue(AwsArnUtils.resourceIfArnFor("bucket", "s3").isEmpty());
assertTrue(AwsArnUtils.resourceIfArnFor("arn:aws:s3", "s3").isEmpty());
}
@Test
void aPseudoRegionResolvesToItsPartitionWhenMinting() {
assertEquals("arn:aws-cn:sqs:aws-cn-global:000000000000:q",
@@ -106,6 +106,16 @@ class IamEnforcementFilterUnitTest {
IamEnforcementFilter.parseS3Resource("arn:aws:s3:::b/a/b/c.txt"));
}
@Test
void parseObjectArn_acceptsEveryPartition() {
assertArrayEquals(new String[] { "audit-source", "documents/hello.txt" },
IamEnforcementFilter.parseS3Resource("arn:aws-cn:s3:::audit-source/documents/hello.txt"));
assertArrayEquals(new String[] { "audit-source", null },
IamEnforcementFilter.parseS3Resource("arn:aws-us-gov:s3:::audit-source"));
assertArrayEquals(new String[] { "b", "k" },
IamEnforcementFilter.parseS3Resource("arn:aws-iso-b:s3:::b/k"));
}
@Test
void parseStarArn_returnsNulls() {
assertArrayEquals(new String[] { null, null },
@@ -20,6 +20,15 @@ class CloudTrailSelectorMatchingTest {
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::", "any-bucket", null));
}
@Test
void chinaAndGovCloudArns_matchLikeCommercialOnes() {
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws-cn:s3", "any-bucket", "any/key.txt"));
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws-cn:s3:::", "any-bucket", null));
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws-cn:s3:::b/logs/", "b", "logs/1.txt"));
assertFalse(CloudTrailService.matchesS3DataResourceArn("arn:aws-us-gov:s3:::b/logs/", "b", "other/1.txt"));
assertFalse(CloudTrailService.matchesS3DataResourceArn("arn:aws-us-gov:s3:::other/", "b", "logs/1.txt"));
}
@Test
void allBucketsArnWithSlash_matchesEverything() {
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::/", "any-bucket", "any/key.txt"));
@@ -547,6 +547,29 @@ class IamPolicyEvaluatorTest {
assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(
List.of(rolePolicy), "arn:aws:sts::123456789012:assumed-role/other/sess", "s3:GetObject", "arn:aws:s3:::b/k", null));
// The same in the China partition: the session's role and the root principal are matched
// in the partition the ARNs carry, not a fixed arn:aws:
String chinaRolePolicy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws-cn:iam::123456789012:role/r"},"Action":"s3:*","Resource":"*"}]}""";
assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicy(
List.of(chinaRolePolicy), "arn:aws-cn:sts::123456789012:assumed-role/r/sess", "s3:GetObject", "arn:aws-cn:s3:::b/k", null));
assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(
List.of(rolePolicy), "arn:aws-cn:sts::123456789012:assumed-role/r/sess", "s3:GetObject", "arn:aws-cn:s3:::b/k", null));
String chinaRootPolicy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws-cn:iam::123456789012:root"},"Action":"s3:*","Resource":"*"}]}""";
assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicy(
List.of(chinaRootPolicy), "arn:aws-cn:iam::123456789012:user/alice", "s3:GetObject", "arn:aws-cn:s3:::b/k", null));
assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(
List.of(chinaRootPolicy), "arn:aws-cn:iam::999999999999:user/bob", "s3:GetObject", "arn:aws-cn:s3:::b/k", null));
// An account id is scoped to its partition: the China root grant does not reach the
// commercial account of the same number, nor the other way round.
assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(
List.of(chinaRootPolicy), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k", null));
String commercialRootPolicy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::123456789012:root"},"Action":"s3:*","Resource":"*"}]}""";
assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(
List.of(commercialRootPolicy), "arn:aws-cn:iam::123456789012:user/alice", "s3:GetObject", "arn:aws-cn:s3:::b/k", null));
// 12-digit account ID and root ARN match account principals
String acctPolicy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"123456789012"},"Action":"s3:*","Resource":"*"}]}""";
@@ -0,0 +1,33 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* The bucket-policy lookup is on the authorization path: a bucket ARN whose partition the
* provider does not recognise finds no policy, which silently flips an allow or a deny.
*/
class S3ResourcePolicyProviderTest {
@ParameterizedTest
@MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases")
void bucketIsExtractedFromAnS3ArnInEveryPartition(PartitionCase partitionCase) {
String prefix = "arn:" + partitionCase.partition() + ":s3:::";
assertEquals("audit-source", S3ResourcePolicyProvider.extractBucketName(prefix + "audit-source"));
assertEquals("audit-source", S3ResourcePolicyProvider.extractBucketName(prefix + "audit-source/documents/hello.txt"));
assertEquals("*", S3ResourcePolicyProvider.extractBucketName(prefix + "*"));
}
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {"arn:aws:lambda:us-east-1:000000000000:function:f", "audit-source", "arn:aws:s3"})
void nonS3ArnsYieldNoBucket(String value) {
assertNull(S3ResourcePolicyProvider.extractBucketName(value));
}
}
@@ -29,6 +29,7 @@ class SecurityHubServiceTest {
void setUp() {
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
when(regionResolver.getPartition()).thenReturn("aws");
service = new SecurityHubService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID), regionResolver,
mock(OrganizationsService.class));
}
@@ -48,6 +49,17 @@ class SecurityHubServiceTest {
assertEquals(Map.of("env", "test"), service.tagsForResource(REGION, service.hubArn(REGION)));
}
/** An account id is scoped to its partition: a China ARN of the same account names nothing here. */
@Test
void aResourceArnFromAnotherPartitionIsNotFound() throws Exception {
service.enableSecurityHub(REGION, objectMapper.readTree("{\"Tags\": {\"env\": \"test\"}}"));
String foreign = service.hubArn(REGION).replace("arn:aws:", "arn:aws-cn:");
AwsException notFound = assertThrows(AwsException.class, () -> service.tagsForResource(REGION, foreign));
assertEquals("ResourceNotFoundException", notFound.getErrorCode());
assertEquals(Map.of("env", "test"), service.tagsForResource(REGION, service.hubArn(REGION)));
}
@Test
void invalidReservedTagPrefixIsRejected() throws Exception {
AwsException error = assertThrows(AwsException.class, () -> service.enableSecurityHub(REGION,
@@ -0,0 +1,91 @@
package io.github.hectorvent.floci.services.stepfunctions;
import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase;
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.MethodSource;
import org.junit.jupiter.params.provider.NullAndEmptySource;
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.assertTrue;
/**
* Service-integration ids carry the state machine's partition, which the CDK builds as
* {@code arn:${Aws.PARTITION}:states:::service:api} ({@code task-utils.ts}); the executor used
* to compare against literal {@code arn:aws:} strings and silently failed to dispatch every
* Task of a China or GovCloud state machine.
*/
class StatesIntegrationTest {
@ParameterizedTest
@MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases")
void optimizedAndSdkIdsParseInEveryPartition(PartitionCase partitionCase) {
String prefix = "arn:" + partitionCase.partition() + ":states:::";
StatesIntegration lambda = StatesIntegration.parse(prefix + "lambda:invoke").orElseThrow();
assertEquals(partitionCase.partition(), lambda.partition());
assertTrue(lambda.is("lambda", "invoke"));
assertFalse(lambda.isSdk("lambda", "invoke"));
assertEquals("", lambda.suffix());
assertEquals(prefix + "lambda:invoke", lambda.toString());
StatesIntegration sdk = StatesIntegration.parse(prefix + "aws-sdk:dynamodb:putItem").orElseThrow();
assertTrue(sdk.sdk());
assertTrue(sdk.isSdk("dynamodb", "putItem"));
assertTrue(sdk.isSdkService("dynamodb"));
assertFalse(sdk.isOptimizedService("dynamodb"));
assertEquals("putItem", sdk.api());
assertEquals(prefix + "aws-sdk:dynamodb:putItem", sdk.withoutSuffix());
}
@ParameterizedTest
@CsvSource({
"arn:aws:states:::states:startExecution.sync, states, startExecution, .sync",
"arn:aws-cn:states:::ecs:runTask.sync:2, ecs, runTask, .sync:2",
"arn:aws-us-gov:states:::sqs:sendMessage.waitForTaskToken, sqs, sendMessage, .waitForTaskToken",
"arn:aws-iso:states:::s3:listObjectsV2, s3, listObjectsV2, ''"})
void suffixesArePreservedButNeverPartOfTheApi(String resource, String service, String api, String suffix) {
StatesIntegration integration = StatesIntegration.parse(resource).orElseThrow();
assertEquals(service, integration.service());
assertEquals(api, integration.api());
assertEquals(suffix, integration.suffix());
assertTrue(integration.isAnySuffix(service, api));
assertEquals(suffix.isEmpty(), integration.is(service, api), "is() is exact: a suffixed id is another integration");
assertEquals(resource, integration.toString());
}
/** Only AWS's three suffixes exist; anything else is not an integration id, as LocalStack refuses it too. */
@ParameterizedTest
@ValueSource(strings = {
"arn:aws:states:::sqs:sendMessage.bogus",
"arn:aws:states:::ecs:runTask.sync:3",
"arn:aws:states:::s3:getObject.waitForTaskToken.sync",
"arn:aws:states:::aws-sdk:sqs:sendMessage.Sync"})
void unknownSuffixesDoNotParse(String resource) {
assertTrue(StatesIntegration.parse(resource).isEmpty());
}
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {
"arn:aws:states:us-east-1:000000000000:activity:work",
"arn:aws:lambda:us-east-1:000000000000:function:f",
"arn:aws:states:::lambda",
"arn:aws:states:::Lambda:invoke",
"arn:aws:states:::lambda:invoke:extra",
"states:::lambda:invoke",
"arn:mars:states:::lambda:invoke"})
void activitiesPlainArnsAndMalformedIdsDoNotParse(String resource) {
assertTrue(StatesIntegration.parse(resource).isEmpty());
}
@Test
void tailIsEverythingAfterStatesInAnyPartition() {
assertEquals("aws-sdk:sfn:startExecution", StatesIntegration.tail("arn:aws-cn:states:::aws-sdk:sfn:startExecution").orElseThrow());
assertEquals("oddity", StatesIntegration.tail("arn:aws:states:::oddity").orElseThrow());
assertTrue(StatesIntegration.tail("arn:aws:states:us-east-1:000000000000:activity:work").isEmpty());
assertTrue(StatesIntegration.tail(null).isEmpty());
}
}
@@ -0,0 +1,163 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.PartitionMatrix;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.time.Duration;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A state machine created under a China signing scope carries {@code arn:aws-cn:states:...}
* and, as the CDK generates it, Task resources of the form {@code arn:aws-cn:states:::sqs:sendMessage}.
* Those must dispatch exactly like their commercial spelling.
*/
@QuarkusTest
class StepFunctionsPartitionIntegrationTest {
private static final String REGION = "cn-north-1";
private static final String JSON_1_0 = "application/x-amz-json-1.0";
private static final ObjectMapper MAPPER = new ObjectMapper();
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void chinaStateMachineDispatchesItsOwnPartitionsIntegrationIds() throws Exception {
String suffix = Long.toString(System.nanoTime(), 36);
String queueUrl = createQueue("sfn-partition-" + suffix);
for (String resource : new String[] {
"arn:aws-cn:states:::sqs:sendMessage",
"arn:aws-cn:states:::aws-sdk:sqs:sendMessage"}) {
String definition = """
{
"StartAt": "Send",
"States": {
"Send": {
"Type": "Task",
"Resource": "%s",
"Parameters": {"QueueUrl": "%s", "MessageBody": "from %s"},
"End": true
}
}
}
""".formatted(resource, queueUrl, resource);
String stateMachineArn = createStateMachine("partition-" + suffix + "-" + (resource.contains("aws-sdk") ? "sdk" : "opt"), definition);
assertTrue(stateMachineArn.startsWith("arn:aws-cn:states:" + REGION + ":"), stateMachineArn);
String executionArn = startExecution(stateMachineArn);
JsonNode execution = awaitTerminal(executionArn);
assertEquals("SUCCEEDED", execution.path("status").asText(),
resource + " -> " + execution.path("error").asText() + ": " + execution.path("cause").asText());
assertTrue(MAPPER.readTree(execution.path("output").asText()).has("MessageId"), execution.toString());
JsonNode message = receiveSingleMessage(queueUrl);
assertEquals("from " + resource, message.path("Body").asText());
}
}
private static String auth(String service) {
return PartitionMatrix.sigV4Auth(REGION, service);
}
private String createQueue(String name) {
Response response = given()
.header("Authorization", auth("sqs"))
.header("X-Amz-Target", "AmazonSQS.CreateQueue")
.contentType(JSON_1_0)
.body("{\"QueueName\":\"" + name + "\"}")
.when().post("/");
response.then().statusCode(200);
String queueUrl = response.jsonPath().getString("QueueUrl");
cleanup.register(() -> given()
.header("Authorization", auth("sqs"))
.header("X-Amz-Target", "AmazonSQS.DeleteQueue")
.contentType(JSON_1_0)
.body("{\"QueueUrl\":\"" + queueUrl + "\"}")
.when().post("/"));
return queueUrl;
}
private JsonNode receiveSingleMessage(String queueUrl) throws Exception {
Response response = given()
.header("Authorization", auth("sqs"))
.header("X-Amz-Target", "AmazonSQS.ReceiveMessage")
.contentType(JSON_1_0)
.body("{\"QueueUrl\":\"" + queueUrl + "\",\"MaxNumberOfMessages\":1,\"WaitTimeSeconds\":1}")
.when().post("/");
response.then().statusCode(200);
JsonNode messages = MAPPER.readTree(response.body().asString()).path("Messages");
assertEquals(1, messages.size(), "expected one message: " + messages);
given()
.header("Authorization", auth("sqs"))
.header("X-Amz-Target", "AmazonSQS.DeleteMessage")
.contentType(JSON_1_0)
.body("{\"QueueUrl\":\"" + queueUrl + "\",\"ReceiptHandle\":\""
+ messages.get(0).path("ReceiptHandle").asText() + "\"}")
.when().post("/").then().statusCode(200);
return messages.get(0);
}
private String createStateMachine(String name, String definition) throws Exception {
String body = MAPPER.writeValueAsString(MAPPER.createObjectNode()
.put("name", name)
.put("definition", definition)
.put("roleArn", "arn:aws-cn:iam::000000000000:role/test-role"));
Response response = given()
.header("Authorization", auth("states"))
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
.contentType(JSON_1_0)
.body(body)
.when().post("/");
response.then().statusCode(200);
String arn = response.jsonPath().getString("stateMachineArn");
cleanup.register(() -> given()
.header("Authorization", auth("states"))
.header("X-Amz-Target", "AWSStepFunctions.DeleteStateMachine")
.contentType(JSON_1_0)
.body("{\"stateMachineArn\":\"" + arn + "\"}")
.when().post("/"));
return arn;
}
private String startExecution(String stateMachineArn) {
Response response = given()
.header("Authorization", auth("states"))
.header("X-Amz-Target", "AWSStepFunctions.StartExecution")
.contentType(JSON_1_0)
.body("{\"stateMachineArn\":\"" + stateMachineArn + "\",\"input\":\"{}\"}")
.when().post("/");
response.then().statusCode(200);
return response.jsonPath().getString("executionArn");
}
private JsonNode awaitTerminal(String executionArn) {
return await().atMost(Duration.ofSeconds(20)).pollInterval(Duration.ofMillis(100)).until(() -> {
Response response = given()
.header("Authorization", auth("states"))
.header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
.contentType(JSON_1_0)
.body("{\"executionArn\":\"" + executionArn + "\"}")
.when().post("/");
response.then().statusCode(200);
return MAPPER.readTree(response.body().asString());
}, execution -> !"RUNNING".equals(execution.path("status").asText()));
}
}