From 1726c6a8a336440398d6388ece92c2c04004560d Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Thu, 10 Sep 2026 22:10:55 -0500 Subject: [PATCH] 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. --- .../floci/core/common/AwsArnUtils.java | 38 +++++ .../services/apigateway/AwsServiceRouter.java | 11 +- .../graphql/auth/IamAuthValidator.java | 14 +- .../dynamodb/DynamoDbJsonHandler.java | 9 +- .../ecs/container/EcsContainerManager.java | 5 +- .../eventbridge/EventBridgeService.java | 12 +- .../iam/AssumeRolePolicyEvaluator.java | 17 +- .../services/iam/ResourceArnBuilder.java | 8 +- .../floci/services/kms/KmsService.java | 2 +- .../secretsmanager/SecretsManagerService.java | 35 +++-- .../floci/services/sqs/SqsService.java | 2 +- .../services/ssoadmin/SsoAdminService.java | 9 +- .../stepfunctions/StepFunctionsService.java | 20 ++- .../floci/core/common/AwsArnUtilsTest.java | 39 +++++ .../AwsServiceRouterIntegrationUriTest.java | 83 ++++++++++ .../graphql/auth/IamAuthValidatorTest.java | 27 ++++ ...DbTagResourcePartitionIntegrationTest.java | 147 ++++++++++++++++++ .../EcsContainerManagerSecretsTest.java | 34 ++++ .../EventBridgeArnIntegrationTest.java | 71 +++++++++ .../iam/AssumeRolePolicyEvaluatorTest.java | 39 +++++ .../services/iam/ResourceArnBuilderTest.java | 23 +++ .../floci/services/kms/KmsServiceTest.java | 16 ++ .../SecretsManagerServiceTest.java | 33 ++++ .../floci/services/sqs/SqsServiceTest.java | 67 ++++++++ .../ssoadmin/SsoAdminServiceTest.java | 51 ++++++ .../StepFunctionsListPartitionTest.java | 107 +++++++++++++ 26 files changed, 876 insertions(+), 43 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouterIntegrationUriTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTagResourcePartitionIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsListPartitionTest.java diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.java index fb9ca15f16..3757554572 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.java @@ -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. + * + *

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. + * + *

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. + * + *

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 diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java index 0352056ea1..a70da7f159 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java @@ -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}} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java index cf1a6ee226..00026a00cf 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java @@ -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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java index 3d744a80a9..c47bb60510 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java @@ -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(); diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java index ab2fa072a3..4ea6f41d87 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java @@ -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()); diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java index 5499b4384e..3cc3ad5cc6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java @@ -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::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; diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java index 5c3a842331..6ee57597ef 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java @@ -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. + * + *

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(); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index 1a3976ea28..6961f3f55b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -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; diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java index 1eeed08165..1c06517645 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java @@ -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/")) { diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java index b2fe2666f3..ec4a7eae4d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java @@ -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:::secret: - 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::secretsmanager:::secret: + // 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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java index a2846696e9..caf1c14cf5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java @@ -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 { diff --git a/src/main/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminService.java b/src/main/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminService.java index fb42f61438..3c1cc9c408 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminService.java @@ -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"); diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java index ba1690952a..062705a808 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java @@ -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. + * + *

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 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 listActivities(String region) { - String prefix = "arn:aws:states:" + region + ":"; + String prefix = regionArnPrefix(region); return activityStore.scan(k -> k.startsWith(prefix) && k.contains(":activity:")); } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AwsArnUtilsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AwsArnUtilsTest.java index 149a9ae494..80ddb4f34e 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/AwsArnUtilsTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/AwsArnUtilsTest.java @@ -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", diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouterIntegrationUriTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouterIntegrationUriTest.java new file mode 100644 index 0000000000..9264e5d1f4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouterIntegrationUriTest.java @@ -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::apigateway:::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)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidatorTest.java index 82b1aaa9b8..7221d32906 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidatorTest.java @@ -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))); diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTagResourcePartitionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTagResourcePartitionIntegrationTest.java new file mode 100644 index 0000000000..8179c1e7dd --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTagResourcePartitionIntegrationTest.java @@ -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. + * + *

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> createdTables = new ArrayList<>(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @AfterEach + void deleteCreatedTables() { + for (Map.Entry 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")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecretsTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecretsTest.java index 881fa83b5b..84ce2f7d66 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecretsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecretsTest.java @@ -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> envCaptor = ArgumentCaptor.forClass(List.class); + verify(builder).withEnv(envCaptor.capture()); + + List 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"; diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeArnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeArnIntegrationTest.java index d43f37aff6..e3285c9dc9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeArnIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeArnIntegrationTest.java @@ -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. + * + *

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 prefix 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() { diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java index 6797faf19c..766e6644a7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java @@ -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( diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java index 4e319f33ca..d39c9e0cfd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java @@ -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"; diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java index 6639c08832..ffe8137544 100644 --- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java index 77d65a3ef8..a8df6fa728 100644 --- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java index 95a1cdbae1..1e880fb452 100644 --- a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java @@ -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. + * + *

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"); diff --git a/src/test/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminServiceTest.java index c7e0565015..1671fd3037 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminServiceTest.java @@ -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"); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsListPartitionTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsListPartitionTest.java new file mode 100644 index 0000000000..9e6bd12330 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsListPartitionTest.java @@ -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. + * + *

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.inMemory(ACCOUNT)) + .doReturn(AccountAwareStorageBackend.inMemory(ACCOUNT)) + .doReturn(AccountAwareStorageBackend.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 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 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()); + } +}