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

@@ -91,6 +91,44 @@ public final class AwsArnUtils {
}
}
/**
* Regex fragment matching any AWS partition id: {@code aws}, {@code aws-cn},
* {@code aws-us-gov}, and the classified {@code aws-iso*} and {@code aws-eusc} partitions.
*
* <p>Transcribed from the shape AWS publishes in its own service models, where every
* partition-carrying ARN member is patterned {@code arn:aws(-[a-z]{1,5}){0,3}:...}. The group
* is non-capturing so it can be dropped into an existing pattern without shifting the
* numbering of the groups around it.
*
* <p>Exists because a literal {@code ^arn:aws:} anchors a pattern to the commercial partition
* and silently rejects every legal ARN outside it.
*/
public static final String PARTITION_REGEX = "aws(?:-[a-z]{1,5}){0,3}";
/**
* True when {@code value} is syntactically an ARN: six colon-delimited segments, the first
* of which is {@code arn}. Says nothing about whether the resource part is well formed for
* its service, which only that service can decide.
*
* <p>The partition-tolerant replacement for a {@code startsWith("arn:aws:")} probe.
*/
public static boolean isArn(String value) {
if (value == null || value.isBlank()) {
return false;
}
String[] parts = value.split(":", 6);
return parts.length == 6 && "arn".equals(parts[0]);
}
/**
* True when {@code value} is an ARN naming {@code service}, in any partition. The common use
* is telling an identifier that may be either a bare name or a full ARN apart, e.g. a
* DynamoDB {@code TableName} that clients are allowed to give either way.
*/
public static boolean isArnFor(String value, String service) {
return isArn(value) && value.split(":", 6)[2].equals(service);
}
/**
* Converts an SQS ARN to a queue URL using the given base URL.
* Example: arn:aws:sqs:us-east-1:000000000000:my-queue → http://localhost:4566/000000000000/my-queue
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.acm.AcmJsonHandler;
@@ -22,7 +23,6 @@ import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Routes API Gateway AWS integration requests to the correct internal service handler.
@@ -82,13 +82,6 @@ public class AwsServiceRouter {
this.acmHandler = acmHandler;
}
private static final Pattern ACTION_URI_PATTERN = Pattern.compile(
"^arn:aws:apigateway:([^:]+):([^:]+):action/(.+)$"
);
private static final Pattern PATH_URI_PATTERN = Pattern.compile(
"^arn:aws:apigateway:([^:]+):([^:]+):path/(.+)$"
);
/**
* Parsed components of an API Gateway AWS integration URI.
*/
@@ -113,7 +106,7 @@ public class AwsServiceRouter {
* @return parsed target, or null if the URI format is not recognized
*/
public IntegrationTarget parseIntegrationUri(String uri) {
if (uri == null || !uri.startsWith("arn:aws:apigateway:")) {
if (!AwsArnUtils.isArnFor(uri, "apigateway")) {
return null;
}
// arn:aws:apigateway:{region}:{service}:{action/{Action}|path/{resourcePath}}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamService;
@@ -63,13 +64,22 @@ public class IamAuthValidator {
return "test".equals(accessKeyId);
}
/**
* The resource these two build is matched against a policy the customer wrote using the ARN
* AppSync handed them, and that ARN carries the region's partition. Pinning {@code aws} here
* meant a GovCloud policy naming its own API never matched, and the request was denied.
*/
private static String appsyncArnPrefix(String region) {
return "arn:" + AwsRegions.partitionFor(region) + ":appsync:";
}
static String requestArn(String region, String accountId, String apiId) {
return "arn:aws:appsync:" + nullToEmpty(region) + ":" + nullToEmpty(accountId)
return appsyncArnPrefix(region) + nullToEmpty(region) + ":" + nullToEmpty(accountId)
+ ":apis/" + apiId + "/*";
}
static String fieldArn(String region, String accountId, String apiId, String typeName, String fieldName) {
return "arn:aws:appsync:" + nullToEmpty(region) + ":" + nullToEmpty(accountId)
return appsyncArnPrefix(region) + nullToEmpty(region) + ":" + nullToEmpty(accountId)
+ ":apis/" + apiId + "/types/" + typeName + "/fields/" + fieldName;
}
@@ -1802,9 +1802,14 @@ public class DynamoDbJsonHandler {
return Response.ok(response).build();
}
/**
* Botocore gives DynamoDB's {@code ResourceArnString} no pattern at all, only a length range,
* so this shape is the emulator's own. Widening the partition keeps it from rejecting a legal
* GovCloud or China table ARN.
*/
private static final java.util.regex.Pattern DYNAMODB_TABLE_ARN_PATTERN =
java.util.regex.Pattern.compile(
"^arn:aws:dynamodb:[a-z0-9-]+:\\d{12}:table/[a-zA-Z0-9._-]+$");
java.util.regex.Pattern.compile("^arn:" + AwsArnUtils.PARTITION_REGEX
+ ":dynamodb:[a-z0-9-]+:\\d{12}:table/[a-zA-Z0-9._-]+$");
private static boolean isValidDynamoDbTableArn(String arn) {
return arn != null && DYNAMODB_TABLE_ARN_PATTERN.matcher(arn).matches();
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.ecs.container;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -421,7 +422,7 @@ public class EcsContainerManager {
String value;
String jsonKey = null;
try {
if (valueFrom != null && valueFrom.startsWith("arn:aws:secretsmanager:")) {
if (AwsArnUtils.isArnFor(valueFrom, "secretsmanager")) {
// The valueFrom may carry the ECS selector suffix
// (:json-key:version-stage:version-id); the parser strips it so the base ARN
// reaches SecretsManagerService intact, keeping its partial-ARN fallback working.
@@ -479,7 +480,7 @@ public class EcsContainerManager {
}
private String ssmParameterName(String valueFrom) {
if (valueFrom != null && valueFrom.startsWith("arn:aws:ssm:")) {
if (AwsArnUtils.isArnFor(valueFrom, "ssm")) {
int parameterMarker = valueFrom.indexOf(":parameter");
if (parameterMarker >= 0) {
return valueFrom.substring(parameterMarker + ":parameter".length());
@@ -1096,8 +1096,8 @@ public class EventBridgeService implements ResourceProvider {
if (busName == null || busName.isBlank()) {
return "default";
}
// Handle ARN format: arn:aws:events:region:account-id:event-bus/bus-name
if (busName.startsWith("arn:aws:events:")) {
// Handle ARN format: arn:<partition>:events:region:account-id:event-bus/bus-name
if (EVENT_BUS_ARN_PREFIX.matcher(busName).lookingAt()) {
try {
return extractBusNameFromArn(busName);
} catch (IllegalArgumentException e) {
@@ -1107,6 +1107,14 @@ public class EventBridgeService implements ResourceProvider {
return busName;
}
/**
* The partition-tolerant form of {@code startsWith("arn:aws:events:")}: it matches a prefix,
* not a whole ARN, so a truncated {@code arn:aws:events:} still enters the branch below and is
* reported as a malformed ARN rather than silently taken as a literal bus name.
*/
private static final Pattern EVENT_BUS_ARN_PREFIX =
Pattern.compile("^arn:" + AwsArnUtils.PARTITION_REGEX + ":events:");
private static String extractBusNameFromArn(String arn) {
// ARN format: arn:aws:events:region:account-id:event-bus/bus-name
if (arn == null) return null;
@@ -29,9 +29,10 @@ public class AssumeRolePolicyEvaluator {
private static final Logger LOG = Logger.getLogger(AssumeRolePolicyEvaluator.class);
private static final String ASSUME_ROLE_ACTION = "sts:AssumeRole";
private static final Pattern ACCOUNT_ROOT_ARN = Pattern.compile("^arn:aws:iam::(\\d{12}):root$");
private static final Pattern ASSUMED_ROLE_ARN =
Pattern.compile("^arn:aws:sts::(\\d{12}):assumed-role/([^/]+)/.*$");
private static final Pattern ACCOUNT_ROOT_ARN =
Pattern.compile("^arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::(\\d{12}):root$");
private static final Pattern ASSUMED_ROLE_ARN = Pattern.compile(
"^arn:(" + AwsArnUtils.PARTITION_REGEX + "):sts::(\\d{12}):assumed-role/([^/]+)/.*$");
private final ObjectMapper objectMapper;
@@ -183,9 +184,17 @@ public class AssumeRolePolicyEvaluator {
* Maps an STS assumed-role ARN ({@code arn:aws:sts::ACCT:assumed-role/Role/session}) to the
* underlying IAM role ARN ({@code arn:aws:iam::ACCT:role/Role}), or {@code null} if {@code arn}
* is not an assumed-role ARN.
*
* <p>The caller's partition is carried across rather than assumed. IAM ARNs are regionless, so
* {@code Arn.of} cannot derive it, and hardcoding {@code aws} here would rewrite a GovCloud
* caller into a commercial role ARN that no GovCloud trust policy can match: the caller would
* be denied a role they are entitled to, with nothing in the response saying why.
*/
private static String assumedRoleToRoleArn(String arn) {
var m = ASSUMED_ROLE_ARN.matcher(arn);
return m.matches() ? AwsArnUtils.Arn.of("iam", "", m.group(1), "role/" + m.group(2)).toString() : null;
if (!m.matches()) {
return null;
}
return new AwsArnUtils.Arn(m.group(1), "iam", "", m.group(2), "role/" + m.group(3)).toString();
}
}
@@ -263,7 +263,7 @@ public class ResourceArnBuilder {
}
private String toDynamoDbTableArn(String tableName, String region, String accountId) {
if (tableName.startsWith("arn:aws:dynamodb:")) {
if (AwsArnUtils.isArnFor(tableName, "dynamodb")) {
return tableName;
}
return AwsArnUtils.Arn.of("dynamodb", region, accountId, "table/" + tableName).toString();
@@ -282,7 +282,7 @@ public class ResourceArnBuilder {
if (json.hasNonNull("StreamName")) {
String streamName = json.get("StreamName").asText().trim();
if (!streamName.isEmpty()) {
if (streamName.startsWith("arn:aws:kinesis:")) {
if (AwsArnUtils.isArnFor(streamName, "kinesis")) {
return streamName;
}
return AwsArnUtils.Arn.of("kinesis", region, accountId, "stream/" + streamName).toString();
@@ -305,7 +305,7 @@ public class ResourceArnBuilder {
if (json.hasNonNull("SecretId")) {
String secretId = json.get("SecretId").asText().trim();
if (!secretId.isEmpty()) {
if (secretId.startsWith("arn:aws:secretsmanager:")) {
if (AwsArnUtils.isArnFor(secretId, "secretsmanager")) {
return secretId;
}
return AwsArnUtils.Arn.of("secretsmanager", region, accountId, "secret:" + secretId).toString();
@@ -322,7 +322,7 @@ public class ResourceArnBuilder {
if (json.hasNonNull("Name")) {
String name = json.get("Name").asText().trim();
if (!name.isEmpty()) {
if (name.startsWith("arn:aws:ssm:")) {
if (AwsArnUtils.isArnFor(name, "ssm")) {
return name;
}
String paramResource = name.startsWith("/") ? "parameter" + name : "parameter/" + name;
@@ -2008,7 +2008,7 @@ public class KmsService implements ResourceProvider {
id = aliasStore.get(aliasKey)
.map(KmsAlias::getTargetKeyId)
.orElseThrow(() -> new AwsException("NotFoundException", "Alias not found: " + keyIdOrArn, 404));
} else if (id.startsWith("arn:aws:kms:")) {
} else if (AwsArnUtils.isArnFor(id, "kms")) {
// Key arn
id = id.substring(id.lastIndexOf("/") + 1);
} else if (id.startsWith("alias/")) {
@@ -998,17 +998,21 @@ public class SecretsManagerService implements ResourceProvider {
// 2. Partial-ARN fallback: extract region + name and do a name-based lookup.
// AWS supports ARNs without the trailing "-XXXXXX" random suffix.
// ARN format: arn:aws:secretsmanager:<region>:<account>:secret:<name>
String smPrefix = "arn:aws:secretsmanager:";
if (secretId.startsWith(smPrefix)) {
String[] parts = secretId.substring(smPrefix.length()).split(":", 4);
if (parts.length == 4 && "secret".equals(parts[2])) {
String arnRegion = parts[0];
String nameFromArn = parts[3];
Secret byName = store.get(regionKey(arnRegion, nameFromArn)).orElse(null);
if (byName != null) {
return byName;
}
// ARN format: arn:<partition>:secretsmanager:<region>:<account>:secret:<name>
// Parsed rather than matched against a literal prefix, because the ARN carries the
// region's own partition and a pinned "arn:aws:" refused a GovCloud or China
// secret its own ARN. The name comes off the parsed resource without a second
// split: a secret name may itself contain colons.
AwsArnUtils.Arn parsedArn = parseOrNull(secretId);
String secretResourcePrefix = "secret:";
if (parsedArn != null
&& "secretsmanager".equals(parsedArn.service())
&& parsedArn.resource().startsWith(secretResourcePrefix)) {
String arnRegion = parsedArn.region();
String nameFromArn = parsedArn.resource().substring(secretResourcePrefix.length());
Secret byName = store.get(regionKey(arnRegion, nameFromArn)).orElse(null);
if (byName != null) {
return byName;
}
}
@@ -1039,6 +1043,15 @@ public class SecretsManagerService implements ResourceProvider {
return regionResolver.buildArn("secretsmanager", region, "secret:" + name + "-" + suffix);
}
/** {@link AwsArnUtils#parse} result, or {@code null} when the value is not an ARN. */
private static AwsArnUtils.Arn parseOrNull(String value) {
try {
return AwsArnUtils.parse(value);
} catch (IllegalArgumentException e) {
return null;
}
}
private static String regionKey(String region, String name) {
return region + "::" + name;
}
@@ -870,7 +870,7 @@ public class SqsService implements Resettable, ResourceProvider {
}
private String queueUrlFromArn(String arn, String region) {
if (arn == null || !arn.startsWith("arn:aws:sqs:")) {
if (!AwsArnUtils.isArnFor(arn, "sqs")) {
return null;
}
try {
@@ -58,7 +58,14 @@ public class SsoAdminService implements Resettable {
private static final Pattern PERMISSION_SET_NAME = Pattern.compile("[\\w+=,.@-]+");
private static final Pattern PERMISSION_SET_ARN = Pattern.compile("arn:aws(?:-[a-z]{1,5}){0,3}:sso:::permissionSet/(?:sso)?ins-[a-zA-Z0-9-.]{16}/ps-[a-zA-Z0-9-./]{16}");
private static final Pattern PRINCIPAL_ID = Pattern.compile("([0-9a-f]{10}-|)[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}");
private static final Pattern MANAGED_POLICY_ARN = Pattern.compile("arn:aws:iam::aws:policy/.+");
/**
* The model's own {@code ManagedPolicyArn} pattern. The previous
* {@code arn:aws:iam::aws:policy/.+} was wrong in both directions: it pinned the commercial
* partition, and its {@code .+} tail accepted a policy name containing characters AWS rejects.
*/
private static final Pattern MANAGED_POLICY_ARN = Pattern.compile(
"arn:aws(?:-[a-z]{1,5}){0,3}:iam::aws:policy((?:/[A-Za-z0-9\\.,\\+@=_-]+)*)"
+ "/(?:[A-Za-z0-9\\.,\\+=@_-]+)");
private static final Pattern CUSTOMER_MANAGED_POLICY_NAME = Pattern.compile("[\\w+=,.@-]+");
private static final Pattern CUSTOMER_MANAGED_POLICY_PATH = Pattern.compile("((/[A-Za-z0-9\\.,\\+@=_-]+)*)/");
private static final Pattern REGION_NAME = Pattern.compile("([a-z]+-){2,3}\\d");
@@ -2,7 +2,7 @@ package io.github.hectorvent.floci.services.stepfunctions;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
@@ -440,9 +440,21 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
"StateMachineDoesNotExist", "State machine does not exist", 400);
}
/**
* Key prefix matching every Step Functions ARN in {@code region}. This store is keyed by the
* full ARN, unlike the other services, which key by {@code region::name}, so the prefix has to
* carry the region's partition or a list cannot find what a create wrote.
*
* <p>Deliberately stops before the account segment: the store holds resources for more than
* one account under account isolation, so {@code RegionResolver.buildArn} is the wrong helper
* here, since it appends its own account id.
*/
private static String regionArnPrefix(String region) {
return "arn:" + AwsRegions.partitionFor(region) + ":states:" + region + ":";
}
public List<StateMachine> listStateMachines(String region) {
String prefix = "arn:aws:states:" + region + ":";
return stateMachineStore.scan(k -> k.startsWith(prefix));
return stateMachineStore.scan(k -> k.startsWith(regionArnPrefix(region)));
}
// ── State machine versions ──────────────────────────────────────────────
@@ -901,7 +913,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
}
public List<Activity> listActivities(String region) {
String prefix = "arn:aws:states:" + region + ":";
String prefix = regionArnPrefix(region);
return activityStore.scan(k -> k.startsWith(prefix) && k.contains(":activity:"));
}