mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(core): read ARN resource segments by structure, not by position (#3392)
AwsArnUtils parses an ARN's five top-level fields and hands the resource back whole, because its structure is service-specific. Five services then split that resource by counting from an end, and each is wrong on input AWS accepts. SNS took the segment after the last colon as a Lambda function name, so a subscription to a qualified ARN (...:function:order-processor:PROD) invoked a function named PROD. The message was accepted, reported as published, and delivered nowhere. S3 and Step Functions already cut after ":function:"; SNS was the outlier and now matches them. Step Functions decided between a state machine ARN and a version ARN by asking whether the last segment was all digits. Digits are legal in a state machine name, so a machine named 2024 was taken apart into version 2024 of a nameless ARN, and validation then refused it: DescribeStateMachine returned InvalidArn for a state machine that exists. The rule is now the resource's segment count, stateMachine:<name> against stateMachine:<name>:<version>, and the two inline copies of the old rule route through it so all three sites agree. AppSync read the API id as the segment after the last slash, so tagging a data source looked up an API by the data source's id and answered NotFound. The model anchors AppSync's ResourceArn to apis/<26 chars> with nothing after it, so a sub-resource ARN is not taggable at all and the answer is 400. That shape is adopted verbatim except for the partition: the model spells it aws, but this emulator mints API ARNs with the region's own partition and has to accept the ARN it just returned. Two are hardening rather than live failures, and neither is reachable through the public API today, so neither carries a test: the microVM controller used a bare split where a guarded regionOf sits in the same class, and S3 Tables guarded on ":" + prefix while cutting on the prefix alone, which only diverges for a name containing the prefix that the name charset already blocks. Each behavioural fix was checked by reverting its source file and confirming the new tests fail without it.
This commit is contained in:
1 parent
862e4a1c77
commit
7c08b35f1d
8 files changed
+289
-35
No files matched your search
@@ -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;
|
||||
|
||||
@ApplicationScoped
|
||||
public 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) {
|
||||
|
||||
+1
-1
@@ -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")
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
+38
-24
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
+100
@@ -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"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user