diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index 295801d5a6..8000f3eb78 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -142,6 +142,15 @@ One deviation. AWS starts the `TimeoutSeconds` clock when a worker picks the tas it emits `ActivityStarted`. Floci emits `ActivityStarted` at schedule time, so both clocks start when the task is scheduled. +## Intrinsic arguments + +A `$.` reference passed to a `States.*` intrinsic must find something. An argument that matches +nothing fails the execution with `States.Runtime`, as on AWS. + +One deviation. Indexing something that is not an array makes AWS leak its JSONPath library and +write `Filter: [0] can only be applied to arrays. Current context is: 1`. Floci writes its own +`The JsonPath argument for the field '$.other[0]' could not be found in the input ...` there. + ## JSONata nulls An expression that evaluates to JSON `null` produces a value, not a missing one. It keeps its key diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java index 997bb5e5a1..38e6a447a0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java @@ -3381,8 +3381,23 @@ public class AslExecutor { * Supports: States.StringToJson, States.JsonToString, States.Format, * States.Array, States.ArrayLength, States.ArrayContains, States.MathAdd, States.UUID. * Throws FailStateException("States.Runtime") for unrecognized functions. + * + *
An argument that matches nothing fails the execution, and the cause names the whole + * expression. Only this outermost call knows it, so a nested intrinsic evaluated as an + * argument runs through {@link #applyIntrinsic} and lets the miss travel up to here. */ private JsonNode evaluateIntrinsic(String expr, JsonNode root, JsonNode context) { + try { + return applyIntrinsic(expr, root, context); + } catch (MissingIntrinsicArgumentException e) { + throw new FailStateException("States.Runtime", + "The function '" + expr + "' had the following error: The JsonPath argument " + + "for the field '" + e.path + "' could not be found in the input '" + + e.input + "'"); + } + } + + private JsonNode applyIntrinsic(String expr, JsonNode root, JsonNode context) { int parenOpen = expr.indexOf('('); int parenClose = expr.lastIndexOf(')'); if (parenOpen < 0 || parenClose < 0) { @@ -3519,8 +3534,8 @@ public class AslExecutor { } /** - * Resolve a single intrinsic argument: either a $.path reference, a quoted string literal, - * or a numeric literal. + * Resolve a single intrinsic argument: a $.path reference, a nested {@code States.*} call, a + * quoted string literal, or a numeric literal. */ private JsonNode resolveIntrinsicArg(String arg, JsonNode root, JsonNode context) { arg = arg.trim(); @@ -3532,13 +3547,16 @@ public class AslExecutor { // site already threads context; this fallback (and the noContext_* test pinning it) only // exists until context is also threaded into the remaining resolvePath callers. if (context != null && arg.startsWith("$$.")) { - return resolvePath("$." + arg.substring(3), context); + return resolveIntrinsicReference("$." + arg.substring(3), context, null, root); } if (context != null && "$$".equals(arg)) { return context; } - if (arg.startsWith("$.") || "$".equals(arg)) { - return resolvePath(arg, root, context); + if (arg.startsWith("$.") || arg.startsWith("$[") || "$".equals(arg)) { + return resolveIntrinsicReference(arg, root, context, root); + } + if (arg.startsWith("States.")) { + return applyIntrinsic(arg, root, context); } if (arg.startsWith("'") && arg.endsWith("'")) { return objectMapper.getNodeFactory().textNode(arg.substring(1, arg.length() - 1)); @@ -3558,12 +3576,46 @@ public class AslExecutor { try { return objectMapper.getNodeFactory().numberNode(Double.parseDouble(arg)); } catch (NumberFormatException e2) { - // fall through: treat as bare path (may itself be a nested States.* intrinsic) + // fall through: treat as a bare path return resolvePath(arg, root, context); } } } + /** + * Resolves a {@code $.} or {@code $$.} reference used as an intrinsic argument. A reference + * that matches nothing fails the execution, as on real AWS, instead of formatting as null. + * {@code searchRoot} is what the path is resolved against and {@code input} is what the cause + * names, which for a {@code $$.} argument is still the state input rather than the Context + * Object it searched. + * + *
An index past the end of an array is a miss here, unlike a plain {@code "field.$"}
+ * reference, which AWS resolves to null. The two forms really do differ.
+ */
+ private JsonNode resolveIntrinsicReference(String path, JsonNode searchRoot, JsonNode context,
+ JsonNode input) {
+ var value = resolvePathNode(path, searchRoot, context);
+ if (value.isMissingNode()) {
+ throw new MissingIntrinsicArgumentException(path, input);
+ }
+ return value;
+ }
+
+ /**
+ * An intrinsic argument that matched nothing. It carries the miss out to the outermost
+ * {@link #evaluateIntrinsic} call, the only one that knows the expression the cause names.
+ */
+ private static class MissingIntrinsicArgumentException extends RuntimeException {
+ final String path;
+ final JsonNode input;
+
+ MissingIntrinsicArgumentException(String path, JsonNode input) {
+ super(path);
+ this.path = path;
+ this.input = input;
+ }
+ }
+
/**
* Split a comma-separated intrinsic args string, respecting nested parentheses and quoted strings.
*/
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicMissingArgumentTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicMissingArgumentTest.java
new file mode 100644
index 0000000000..37f5f49f3e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicMissingArgumentTest.java
@@ -0,0 +1,236 @@
+package io.github.hectorvent.floci.services.stepfunctions;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
+import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
+import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;
+import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;
+import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
+import jakarta.enterprise.inject.Instance;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+
+/**
+ * A {@code $.} argument of a {@code States.*} intrinsic that matches nothing fails with
+ * {@code States.Runtime}. Every cause here was captured from real AWS (us-east-1), and Step
+ * Functions Local 2.0.0 writes the same text. The cause names the whole expression, and an
+ * out-of-range array index that a plain {@code "field.$"} reference resolves to null is a miss
+ * here.
+ */
+class AslExecutorIntrinsicMissingArgumentTest {
+
+ private final ObjectMapper mapper = new ObjectMapper();
+ private AslExecutor executor;
+
+ @BeforeEach
+ @SuppressWarnings("unchecked")
+ void setUp() {
+ executor = new AslExecutor(
+ mock(LambdaExecutorService.class),
+ mock(LambdaFunctionStore.class),
+ mock(DynamoDbService.class),
+ mock(DynamoDbJsonHandler.class),
+ mock(SqsJsonHandler.class),
+ mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class),
+ mock(io.github.hectorvent.floci.services.ec2.Ec2Service.class),
+ mock(io.github.hectorvent.floci.services.s3.S3Service.class),
+ mock(io.github.hectorvent.floci.services.ecs.EcsService.class),
+ mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),
+ mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
+ mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
+ mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
+ mapper,
+ new JsonataEvaluator(mapper),
+ mock(Instance.class),
+ mock(EmulatorConfig.class),
+ null,
+ null);
+ }
+
+ @Test
+ void unresolvableArgumentFailsWithTheCauseAwsWrites() throws Exception {
+ var failure = assertThrows(AslExecutor.FailStateException.class,
+ () -> resolve("{\"v.$\":\"States.Format('{}', $.nope)\"}", "{\"other\":1}"));
+
+ assertEquals("States.Runtime", failure.error);
+ assertEquals("The function 'States.Format('{}', $.nope)' had the following error: "
+ + "The JsonPath argument for the field '$.nope' could not be found in the input "
+ + "'{\"other\":1}'", failure.cause);
+ }
+
+ /** The expression is echoed as written, spacing included. */
+ @Test
+ void theCauseEchoesTheExpressionVerbatim() throws Exception {
+ var failure = assertThrows(AslExecutor.FailStateException.class,
+ () -> resolve("{\"v.$\":\"States.Format('{}',$.nope)\"}", "{\"other\":1}"));
+
+ assertEquals("The function 'States.Format('{}',$.nope)' had the following error: "
+ + "The JsonPath argument for the field '$.nope' could not be found in the input "
+ + "'{\"other\":1}'", failure.cause);
+ }
+
+ /** A later argument fails alike, and the cause names that argument rather than the first. */
+ @Test
+ void aLaterArgumentNamesItself() throws Exception {
+ var failure = assertThrows(AslExecutor.FailStateException.class,
+ () -> resolve("{\"v.$\":\"States.Format('{} {}', $.other, $.a.b)\"}", "{\"other\":1}"));
+
+ assertEquals("The function 'States.Format('{} {}', $.other, $.a.b)' had the following "
+ + "error: The JsonPath argument for the field '$.a.b' could not be found in the "
+ + "input '{\"other\":1}'", failure.cause);
+ }
+
+ /**
+ * A reference path in the format template position is left as written rather than resolved, so
+ * it never reaches the argument check. Real AWS and Step Functions Local resolve it and fail
+ * here. That is a separate gap from issue #2870 and is tracked by issue #2927.
+ */
+ @Test
+ void aReferencePathAsTheFormatTemplateIsStillTakenLiterally() throws Exception {
+ var resolved = resolve("{\"v.$\":\"States.Format($.nope, 1)\"}", "{\"other\":1}");
+
+ assertEquals("\"$.nope\"", resolved.path("v").toString());
+ }
+
+ /** The whole expression is named, not the inner function that took the failing argument. */
+ @Test
+ void nestedIntrinsicNamesTheWholeExpression() throws Exception {
+ var failure = assertThrows(AslExecutor.FailStateException.class,
+ () -> resolve("{\"v.$\":\"States.Format('{}', States.Format('{}', $.nope))\"}",
+ "{\"other\":1}"));
+
+ assertEquals("The function 'States.Format('{}', States.Format('{}', $.nope))' had the "
+ + "following error: The JsonPath argument for the field '$.nope' could not be "
+ + "found in the input '{\"other\":1}'", failure.cause);
+ }
+
+ /** Every intrinsic resolves its arguments through the same path, so every one of them fails. */
+ @Test
+ void otherIntrinsicsFailOnAnUnresolvableArgument() {
+ assertIntrinsicFails("States.ArrayLength($.nope)", "$.nope");
+ assertIntrinsicFails("States.Array(1, $.nope)", "$.nope");
+ assertIntrinsicFails("States.JsonToString($.nope)", "$.nope");
+ assertIntrinsicFails("States.StringToJson($.nope)", "$.nope");
+ assertIntrinsicFails("States.MathAdd($.nope, 1)", "$.nope");
+ assertIntrinsicFails("States.ArrayContains($.nope, 1)", "$.nope");
+ assertIntrinsicFails("States.JsonMerge($.nope, $.other, false)", "$.nope");
+ }
+
+ /** Only absence fails. A present but explicitly null argument still formats as null. */
+ @Test
+ void explicitNullArgumentStillFormats() throws Exception {
+ var resolved = resolve("{\"v.$\":\"States.Format('{}', $.nul)\"}", "{\"nul\":null}");
+
+ assertEquals("\"null\"", resolved.path("v").toString());
+ }
+
+ /** A wildcard projection that matches nothing is an empty array, not an absent argument. */
+ @Test
+ void wildcardMatchingNothingIsAnEmptyArray() throws Exception {
+ var resolved = resolve("{\"v.$\":\"States.ArrayLength($.items[*].nope)\"}", "{\"items\":[1,2]}");
+
+ assertEquals(0, resolved.path("v").asInt());
+ }
+
+ /**
+ * The two payload template forms really do differ here. A plain {@code "idx.$": "$.items[5]"}
+ * resolves to null on AWS and the execution succeeds, while the same path as an intrinsic
+ * argument is a miss. Both were run against real AWS in us-east-1.
+ */
+ @Test
+ void indexPastTheEndOfAnArrayFails() throws Exception {
+ var failure = assertThrows(AslExecutor.FailStateException.class,
+ () -> resolve("{\"v.$\":\"States.Format('{}', $.items[5])\"}", "{\"items\":[1,2]}"));
+
+ assertEquals("The function 'States.Format('{}', $.items[5])' had the following error: "
+ + "The JsonPath argument for the field '$.items[5]' could not be found in the "
+ + "input '{\"items\":[1,2]}'", failure.cause);
+ }
+
+ /** Reading a field off the absent element fails alike. */
+ @Test
+ void navigatingPastAnOutOfRangeIndexFails() throws Exception {
+ var failure = assertThrows(AslExecutor.FailStateException.class,
+ () -> resolve("{\"v.$\":\"States.Format('{}', $.items[5].x)\"}", "{\"items\":[1]}"));
+
+ assertEquals("The function 'States.Format('{}', $.items[5].x)' had the following error: "
+ + "The JsonPath argument for the field '$.items[5].x' could not be found in the "
+ + "input '{\"items\":[1]}'", failure.cause);
+ }
+
+ /**
+ * Indexing something that is not an array fails too. AWS leaks its JSONPath library here and
+ * writes {@code Filter: [0] can only be applied to arrays. Current context is: 1} in place of
+ * the sentence below. Floci keeps its own wording, so only the failure itself matches.
+ */
+ @Test
+ void indexingANonArrayFails() throws Exception {
+ var failure = assertThrows(AslExecutor.FailStateException.class,
+ () -> resolve("{\"v.$\":\"States.Format('{}', $.other[0])\"}", "{\"other\":1}"));
+
+ assertEquals("States.Runtime", failure.error);
+ assertEquals("The function 'States.Format('{}', $.other[0])' had the following error: "
+ + "The JsonPath argument for the field '$.other[0]' could not be found in the "
+ + "input '{\"other\":1}'", failure.cause);
+ }
+
+ /**
+ * A {@code $$.} argument reports the path rewritten against the Context Object and names the
+ * state input, not the Context Object it searched. Step Functions Local words it this way, and
+ * it is the one place the two payload template forms differ: a plain {@code "ctx.$"} reference
+ * reports the Context Object.
+ */
+ @Test
+ void unresolvableContextArgumentNamesTheRewrittenPathAndTheStateInput() throws Exception {
+ var context = mapper.readTree("{\"State\":{\"Name\":\"P\"}}");
+ var template = mapper.readTree("{\"v.$\":\"States.Format('{}', $$.Nope.Deep)\"}");
+
+ var failure = assertThrows(AslExecutor.FailStateException.class,
+ () -> executor.resolveParameters(template, mapper.readTree("{\"other\":1}"), context));
+
+ assertEquals("The function 'States.Format('{}', $$.Nope.Deep)' had the following error: "
+ + "The JsonPath argument for the field '$.Nope.Deep' could not be found in the "
+ + "input '{\"other\":1}'", failure.cause);
+ }
+
+ /** A bare $ argument is the whole input, so it never misses. */
+ @Test
+ void wholeInputArgumentResolves() throws Exception {
+ var resolved = resolve("{\"v.$\":\"States.JsonToString($)\"}", "{\"other\":1}");
+
+ assertEquals("{\"other\":1}", resolved.path("v").asText());
+ }
+
+ /** ResultSelector and ItemSelector run through the same resolver, so they fail the same way. */
+ @Test
+ void resultSelectorFailsOnAnUnresolvableArgument() throws Exception {
+ var failure = assertThrows(AslExecutor.FailStateException.class,
+ () -> resolve("{\"v.$\":\"States.Format('{}', $[0].nope)\"}", "[{\"other\":1}]"));
+
+ assertEquals("The function 'States.Format('{}', $[0].nope)' had the following error: "
+ + "The JsonPath argument for the field '$[0].nope' could not be found in the "
+ + "input '[{\"other\":1}]'", failure.cause);
+ }
+
+ private void assertIntrinsicFails(String expression, String argument) {
+ var failure = assertThrows(AslExecutor.FailStateException.class,
+ () -> resolve("{\"v.$\":\"" + expression + "\"}", "{\"other\":1}"),
+ expression);
+
+ assertEquals("States.Runtime", failure.error);
+ assertEquals("The function '" + expression + "' had the following error: The JsonPath "
+ + "argument for the field '" + argument + "' could not be found in the input "
+ + "'{\"other\":1}'", failure.cause);
+ }
+
+ private JsonNode resolve(String template, String input) throws Exception {
+ return executor.resolveParameters(
+ mapper.readTree(template), mapper.readTree(input), mapper.createObjectNode());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsIntrinsicMissingArgumentIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsIntrinsicMissingArgumentIntegrationTest.java
new file mode 100644
index 0000000000..bc292afca1
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsIntrinsicMissingArgumentIntegrationTest.java
@@ -0,0 +1,172 @@
+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.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * End to end coverage for issue #2870. A {@code $.} argument of a {@code States.*} intrinsic that
+ * matches nothing used to resolve to null and the execution succeeded. The causes asserted here
+ * come from real AWS in us-east-1, minus the
+ * {@code An error occurred while executing the state '