Light, fluffy, and always free - The AWS Local Emulator alternative
fix(core): read ARN resource segments by structure, not by position (#3392)
Hector Ventura7c08b35f1d47
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.javaindex c946acfa1b..8a25e43d11 100644--- a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.appsync;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.config.EmulatorConfig;@@ -22,6 +23,8 @@ import java.time.Clock;import java.time.Duration;import java.util.*;import java.util.Base64;+import java.util.regex.Matcher;+import java.util.regex.Pattern;@ApplicationScopedpublic class AppSyncService {@@ -1128,11 +1131,36 @@ public class AppSyncService {return regionResolver.buildArn("appsync", region, "apis/" + apiId + "/functions/" + functionId);}+ /**+ * The model's own {@code ResourceArn} shape for AppSync tagging. Only an API-level ARN is+ * taggable: the pattern is anchored to {@code apis/<26 chars>} with nothing after it, so a+ * data source or function ARN is not a valid ResourceArn at all.+ *+ * <p>The partition is the one place this departs from the model, which spells it {@code aws}.+ * This emulator mints its API ARNs with the region's own partition, so keeping the literal+ * would mean refusing to tag an API using the exact ARN it had just returned.+ */+ private static final Pattern RESOURCE_ARN = Pattern.compile(+ "^arn:" + AwsArnUtils.PARTITION_REGEX+ + ":appsync:[A-Za-z0-9_/.-]{0,63}:\\d{12}:apis/([0-9A-Za-z_-]{26})$");++ /**+ * API id out of a tagging ResourceArn.+ *+ * <p>Splitting on {@code /} and taking the last segment read the sub-resource id as the API+ * id, so tagging {@code .../apis/<api>/datasources/<ds>} looked up an API called+ * {@code <ds>} and answered NotFound. AWS rejects that ARN outright, so the shape is+ * validated instead.+ */private String extractApiIdFromArn(String arn) {- if (arn == null) throw new AwsException("BadRequestException", "Invalid ARN", 400);- String[] parts = arn.split("/");- if (parts.length < 2) throw new AwsException("BadRequestException", "Invalid ARN format", 400);- return parts[parts.length - 1];+ if (arn == null) {+ throw new AwsException("BadRequestException", "Invalid ARN", 400);+ }+ Matcher matcher = RESOURCE_ARN.matcher(arn);+ if (!matcher.matches()) {+ throw new AwsException("BadRequestException", "Invalid ARN format", 400);+ }+ return matcher.group(1);}private String coerceString(Object value) {diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.java b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.javaindex 1f3326cf2d..d44ba5a184 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.java@@ -489,7 +489,7 @@ public class LambdaMicrovmsController {node.put("imageVersion", vm.imageVersion);node.put("endpoint", vm.endpoint);node.put("maximumDurationInSeconds", 28800);- String region = vm.imageArn.split(":")[3];+ String region = regionOf(vm.imageArn);node.putArray("egressNetworkConnectors").add("arn:aws:lambda:" + region + ":aws:network-connector:aws-network-connector:INTERNET_EGRESS");node.putArray("ingressNetworkConnectors")diff --git a/src/main/java/io/github/hectorvent/floci/services/s3tables/S3TablesService.java b/src/main/java/io/github/hectorvent/floci/services/s3tables/S3TablesService.javaindex 307b1c73f4..ff7cd26274 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3tables/S3TablesService.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3tables/S3TablesService.java@@ -309,10 +309,13 @@ public class S3TablesService {}private String resourceName(String arn, String prefix) {- if (arn == null || !arn.startsWith("arn:") || !arn.contains(":" + prefix)) {+ // Guard and cut must use the same needle. Checking for ":" + prefix but cutting on prefix+ // alone means a name that itself contains the prefix is cut at the wrong place.+ String needle = ":" + prefix;+ if (arn == null || !arn.startsWith("arn:") || !arn.contains(needle)) {throw notFound("The table bucket does not exist.");}- return arn.substring(arn.lastIndexOf(prefix) + prefix.length());+ return arn.substring(arn.indexOf(needle) + needle.length());}private void persist(TableBucket bucket, String region) {diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.javaindex cefa3f87f4..dd419d2d79 100644--- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java@@ -1486,13 +1486,31 @@ public class SnsService implements Resettable, ResourceProvider {}}- private static String extractFunctionName(String functionArn) {- int idx = functionArn.lastIndexOf(':');- return idx >= 0 ? functionArn.substring(idx + 1) : functionArn;+ private static final String FUNCTION_MARKER = ":function:";++ /**+ * Function name out of a Lambda ARN, which may carry a qualifier:+ * {@code arn:aws:lambda:<region>:<account>:function:<name>[:<alias-or-version>]}.+ *+ * <p>Taking the segment after the last colon reads the qualifier as the function name, so a+ * subscription to {@code ...:function:order-processor:PROD} invoked a function called+ * {@code PROD} and the message went nowhere. Cut after {@code :function:} instead, matching+ * what S3 and Step Functions already do for the same ARN.+ */+ static String extractFunctionName(String functionArn) {+ if (functionArn == null) {+ return null;+ }+ int functionMarker = functionArn.indexOf(FUNCTION_MARKER);+ if (functionMarker < 0) {+ return functionArn;+ }+ String suffix = functionArn.substring(functionMarker + FUNCTION_MARKER.length());+ int qualifierSeparator = suffix.indexOf(':');+ return qualifierSeparator >= 0 ? suffix.substring(0, qualifierSeparator) : suffix;}private static String extractRegionFromArn(String arn) {- if (arn == null || !arn.startsWith("arn:aws:")) return null;return AwsArnUtils.regionOrDefault(arn, null);}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.javaindex 062705a808..4c4b2aa803 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@@ -419,21 +419,17 @@ public class StepFunctionsService implements Resettable, ResourceProvider {return copyStateMachine(stateMachine.get());}- int versionSeparator = arn != null ? arn.lastIndexOf(':') : -1;- if (versionSeparator > 0 && versionSeparator < arn.length() - 1) {- String versionText = arn.substring(versionSeparator + 1);- if (versionText.chars().allMatch(Character::isDigit)) {- String baseArn = arn.substring(0, versionSeparator);- Optional<StateMachine> baseStateMachine = stateMachineStore.get(baseArn);- if (baseStateMachine.isPresent()) {- return baseStateMachine.get().getVersions().stream()- .filter(version -> arn.equals(version.getStateMachineVersionArn()))- .findFirst()- .map(version -> stateMachineFromVersion(baseStateMachine.get(), version))- .orElseThrow(() -> new AwsException(- "StateMachineDoesNotExist",- "State machine does not exist", 400));- }+ VersionArn parsedVersion = parseVersionArn(arn);+ if (parsedVersion != null) {+ Optional<StateMachine> baseStateMachine = stateMachineStore.get(parsedVersion.baseArn());+ if (baseStateMachine.isPresent()) {+ return baseStateMachine.get().getVersions().stream()+ .filter(version -> arn.equals(version.getStateMachineVersionArn()))+ .findFirst()+ .map(version -> stateMachineFromVersion(baseStateMachine.get(), version))+ .orElseThrow(() -> new AwsException(+ "StateMachineDoesNotExist",+ "State machine does not exist", 400));}}throw new AwsException(@@ -518,11 +514,11 @@ public class StepFunctionsService implements Resettable, ResourceProvider {}public synchronized void deleteStateMachineVersion(String stateMachineVersionArn) {- int lastColon = stateMachineVersionArn.lastIndexOf(':');- if (lastColon < 0) {+ VersionArn parsed = parseVersionArn(stateMachineVersionArn);+ if (parsed == null) {return;}- String baseArn = stateMachineVersionArn.substring(0, lastColon);+ String baseArn = parsed.baseArn();stateMachineStore.get(baseArn).ifPresent(current -> {StateMachine updated = copyStateMachine(current);updated.getVersions().removeIf(@@ -1230,25 +1226,43 @@ public class StepFunctionsService implements Resettable, ResourceProvider {return copy;}+ private static final String STATE_MACHINE_RESOURCE = "stateMachine";+private record VersionArn(String baseArn, int version) {}+ /**+ * Splits a state machine <em>version</em> ARN into its base ARN and version number, or returns+ * {@code null} when {@code arn} is not one.+ *+ * <p>Decided by the shape of the resource, not by whether the tail happens to be digits. A+ * state machine ARN is {@code stateMachine:<name>} and a version ARN is+ * {@code stateMachine:<name>:<version>}, so the segment count settles it. Digits are legal in+ * a state machine name, and reading the tail alone meant a machine named {@code 2024} was+ * taken apart into version 2024 of a nameless ARN, which the caller then rejected as+ * InvalidArn: an existing state machine that could not be described.+ */private static VersionArn parseVersionArn(String arn) {if (arn == null) {return null;}- int separator = arn.lastIndexOf(':');- if (separator < 0 || separator == arn.length() - 1) {+ AwsArnUtils.Arn parsed;+ try {+ parsed = AwsArnUtils.parse(arn);+ } catch (IllegalArgumentException e) {return null;}- String suffix = arn.substring(separator + 1);- if (!suffix.chars().allMatch(Character::isDigit)) {+ String[] segments = parsed.resource().split(":", -1);+ if (segments.length != 3+ || !STATE_MACHINE_RESOURCE.equals(segments[0])+ || segments[2].isEmpty()+ || !segments[2].chars().allMatch(Character::isDigit)) {return null;}try {return new VersionArn(- arn.substring(0, separator),- Integer.parseInt(suffix));+ arn.substring(0, arn.length() - segments[2].length() - 1),+ Integer.parseInt(segments[2]));} catch (NumberFormatException ignored) {return null;}diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceTest.javaindex 1ddfc69965..a1b3da8cbb 100644--- a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceTest.java@@ -386,4 +386,65 @@ class AppSyncServiceTest {return instant;}}++ /**+ * Tagging takes an API-level ARN. Reading the API id as "the segment after the last slash"+ * took the sub-resource id instead, so tagging a data source looked up an API by the data+ * source's id and answered NotFound. Botocore anchors AppSync's ResourceArn to+ * {@code apis/<26 chars>} with nothing after it, so a sub-resource ARN is not taggable at all+ * and the answer is a 400, not a 404.+ */+ @Test+ void tagResourceAcceptsAnApiArnAndTagsThatApi() {+ GraphqlApi api = service.createGraphqlApi(+ Map.of("name", "taggable", "authenticationType", "API_KEY"), "us-east-1");+ String apiArn = "arn:aws:appsync:us-east-1:000000000000:apis/" + api.getApiId();++ service.tagResource(apiArn, Map.of("env", "test"));++ assertEquals("test", service.getTags(apiArn).get("env"));+ }++ /**+ * The ARN AppSync hands back carries the region's partition, so pinning the tagging pattern to+ * {@code arn:aws:appsync:} meant refusing to tag an API using the exact ARN just returned.+ * Botocore spells the literal, but this emulator has to accept its own output.+ */+ @org.junit.jupiter.params.ParameterizedTest+ @org.junit.jupiter.params.provider.CsvSource({+ "us-east-1, aws",+ "us-gov-west-1, aws-us-gov",+ "cn-north-1, aws-cn",+ "us-isob-east-1, aws-iso-b"})+ void tagResourceAcceptsAnApiArnFromAnyPartition(String region, String partition) {+ GraphqlApi api = service.createGraphqlApi(+ Map.of("name", "p-" + region, "authenticationType", "API_KEY"), region);+ String apiArn = "arn:" + partition + ":appsync:" + region + ":000000000000:apis/" + api.getApiId();++ service.tagResource(apiArn, Map.of("env", "test"));++ assertEquals("test", service.getTags(apiArn).get("env"));+ }++ @Test+ void tagResourceRejectsASubResourceArn() {+ GraphqlApi api = service.createGraphqlApi(+ Map.of("name", "subresource", "authenticationType", "API_KEY"), "us-east-1");+ String dataSourceArn = "arn:aws:appsync:us-east-1:000000000000:apis/"+ + api.getApiId() + "/datasources/myDS";++ AwsException thrown = assertThrows(AwsException.class,+ () -> service.tagResource(dataSourceArn, Map.of("env", "test")));++ assertEquals(400, thrown.getHttpStatus());+ assertEquals("BadRequestException", thrown.getErrorCode());+ }++ @Test+ void tagResourceRejectsAnArnThatIsNotAppSync() {+ assertThrows(AwsException.class, () -> service.tagResource(+ "arn:aws:sqs:us-east-1:000000000000:apis/abcdefghijklmnopqrstuvwxyz", Map.of()));+ assertThrows(AwsException.class, () -> service.tagResource("apis/abc", Map.of()));+ assertThrows(AwsException.class, () -> service.tagResource(null, Map.of()));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.javaindex 6ee77dc46e..2969c3bb6b 100644--- a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java@@ -491,4 +491,34 @@ class SnsServiceTest {"arn:aws:sns:us-east-1:000000000000:ghost-topic", REGION));}++ /**+ * A Lambda subscription endpoint may be a qualified ARN. Taking the segment after the last+ * colon read the alias as the function name, so a subscription to+ * {@code ...:function:order-processor:PROD} invoked a function called {@code PROD}: the+ * message was accepted, reported as published, and delivered nowhere.+ */+ @Test+ void extractFunctionNameIgnoresTheQualifier() {+ String base = "arn:aws:lambda:us-east-1:000000000000:function:order-processor";++ assertEquals("order-processor", SnsService.extractFunctionName(base));+ assertEquals("order-processor", SnsService.extractFunctionName(base + ":PROD"));+ assertEquals("order-processor", SnsService.extractFunctionName(base + ":42"));+ assertEquals("order-processor", SnsService.extractFunctionName(base + ":$LATEST"));+ }++ /** Other partitions carry the same resource grammar. */+ @Test+ void extractFunctionNameWorksInAnyPartition() {+ assertEquals("order-processor", SnsService.extractFunctionName(+ "arn:aws-us-gov:lambda:us-gov-west-1:000000000000:function:order-processor:PROD"));+ }++ /** A bare function name is a legal endpoint too and passes through unchanged. */+ @Test+ void extractFunctionNameLeavesABareNameAlone() {+ assertEquals("order-processor", SnsService.extractFunctionName("order-processor"));+ assertNull(SnsService.extractFunctionName(null));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNumericNameIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNumericNameIntegrationTest.javanew file mode 100644index 0000000000..eaf763d2bd--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNumericNameIntegrationTest.java@@ -0,0 +1,100 @@+package io.github.hectorvent.floci.services.stepfunctions;++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.ValueSource;++import java.util.ArrayList;+import java.util.List;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;++/**+ * A state machine ARN and a state machine <em>version</em> ARN differ by one trailing segment:+ * {@code stateMachine:<name>} against {@code stateMachine:<name>:<version>}. Deciding between them+ * by asking whether the last segment is all digits misreads a numeric name, and digits are legal+ * in a state machine name. Describing a machine called {@code 2024} used to answer InvalidArn,+ * because the numeric tail was stripped as a version and the nameless remainder failed validation.+ */+@QuarkusTest+class StepFunctionsNumericNameIntegrationTest {++ private static final String CT = "application/x-amz-json-1.0";+ private static final String DEF =+ "{\\\"StartAt\\\":\\\"D\\\",\\\"States\\\":{\\\"D\\\":{\\\"Type\\\":\\\"Pass\\\",\\\"End\\\":true}}}";++ /** @QuarkusTest classes share one emulator, so anything created here is removed again. */+ private final List<String> created = new ArrayList<>();++ @BeforeAll+ static void setup() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @AfterEach+ void deleteCreated() {+ for (String arn : created) {+ call("DeleteStateMachine", "{\"stateMachineArn\":\"" + arn + "\"}");+ }+ created.clear();+ }++ private static Response call(String target, String body) {+ return given().header("X-Amz-Target", "AWSStepFunctions." + target)+ .contentType(CT).body(body).when().post("/");+ }++ private String create(String name) {+ String arn = call("CreateStateMachine",+ "{\"name\":\"" + name + "\",\"definition\":\"" + DEF+ + "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r\"}")+ .then().statusCode(200).extract().jsonPath().getString("stateMachineArn");+ created.add(arn);+ return arn;+ }++ @ParameterizedTest+ @ValueSource(strings = {"2024", "1", "00", "42"})+ void describesAStateMachineWhoseNameIsAllDigits(String name) {+ String arn = create(name);++ call("DescribeStateMachine", "{\"stateMachineArn\":\"" + arn + "\"}")+ .then()+ .statusCode(200)+ .body("name", equalTo(name));+ }++ /** The version ARN it was being confused with must still resolve as a version. */+ @Test+ void stillResolvesARealVersionArn() {+ String name = "numeric-versioned-" + System.nanoTime();+ String arn = create(name);++ String versionArn = call("PublishStateMachineVersion",+ "{\"stateMachineArn\":\"" + arn + "\"}")+ .then().statusCode(200).extract().jsonPath().getString("stateMachineVersionArn");++ call("DescribeStateMachine", "{\"stateMachineArn\":\"" + versionArn + "\"}")+ .then()+ .statusCode(200)+ .body("name", equalTo(name));+ }++ /** A version suffix on a machine that does not exist is still not found, not InvalidArn. */+ @Test+ void reportsAMissingVersionAsNotFound() {+ String arn = "arn:aws:states:us-east-1:000000000000:stateMachine:no-such-machine:3";++ call("DescribeStateMachine", "{\"stateMachineArn\":\"" + arn + "\"}")+ .then()+ .statusCode(400)+ .body(containsString("StateMachineDoesNotExist"));+ }+}