Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(stepfunctions)!: reject JSONata top-level references at definition time (#2699)

Facundo Paredes553446049294
diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md
index d69fc054a3..39aad05413 100644
--- a/docs/services/step-functions.md
+++ b/docs/services/step-functions.md
@@ -184,6 +184,33 @@ cause is the response serialized as a string, so a `Catch` can read which entry
One deviation, and it belongs to EventBridge rather than to the integration: Floci rejects an entry
addressed to an event bus that does not exist, while AWS accepts it and returns an `EventId`.
+## JSONata expressions are validated when the state machine is created
+
+A JSONata expression runs with no context item: the execution input arrives as `$states.input`
+and a variable written by `Assign` as `$name`. A path that starts from neither reads a context
+item that does not exist, and AWS refuses the whole definition:
+
+```
+An error occurred (InvalidDefinition) when calling the CreateStateMachine operation:
+Invalid State Machine Definition: 'UNSUPPORTED_JSONATA_EXPRESSION: Reference to 'phone' at the
+top level is not supported. at /States/E/Output/v'
+```
+
+Floci refuses it too, from `CreateStateMachine`, `UpdateStateMachine` and
+`ValidateStateMachineDefinition`, with that message and that location. Write
+`$states.input.phone` to read the input and `$phone` to read a variable: an earlier `Assign` of
+`phone` does not put a bare `phone` in scope on AWS either.
+
+Only the first step of a path is read against the top-level context, so a name in a later step,
+in a predicate, in a sort term or in an object grouping stays legal and
+`$states.input.items[value > 3]` is accepted. A lambda body keeps the context of the expression
+that defines it, so `$map($states.input.a, function($x){ b })` does name `b` at the top level.
+
+Two neighbouring rules stay with the execution rather than the definition. A syntax error such as
+`{% a[1,2) %}` is accepted here and fails the execution, where AWS reports
+`INVALID_JSONATA_EXPRESSION` when the state machine is created; and `$$`, which AWS refuses under
+its own message, is accepted here.
+
## Mocked service integrations
Floci supports the Step Functions Local mock configuration format
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataTopLevelReferences.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataTopLevelReferences.java
new file mode 100644
index 0000000000..4b6e87cf2b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataTopLevelReferences.java
@@ -0,0 +1,189 @@
+package io.github.hectorvent.floci.services.stepfunctions;
+
+import com.dashjoin.jsonata.Parser;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+import org.jboss.logging.Logger;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * Names every reference a Step Functions JSONata expression makes against the top-level context.
+ *
+ * <p>A Step Functions expression is evaluated with no context item: the input arrives as
+ * {@code $states.input} and workflow variables as {@code $name}. A path that starts from neither
+ * reads a context item that does not exist, and real AWS refuses the whole definition at
+ * {@code CreateStateMachine} time with
+ * {@code UNSUPPORTED_JSONATA_EXPRESSION: Reference to 'phone' at the top level is not supported.}
+ *
+ * <p>Only the first step of a path is evaluated against the top-level context. Every later step,
+ * every predicate, every sort term and every grouping expression runs against the value the step
+ * before it produced, so a name there is legal and this walk never descends into one. A lambda
+ * body, on the other hand, keeps the context of the expression that defines it, so
+ * {@code $map($states.input.a, function($x){ b })} does name {@code b} at the top level. Both
+ * halves are measured against AWS in {@code JsonataTopLevelReferencesTest}.
+ *
+ * <p>{@link Parser#parse(String)} is public and returns a public {@link Parser.Symbol}, but every
+ * field carrying the tree is package-private, and Quarkus loads application classes and dependency
+ * jars with different class loaders, so sharing the package raises {@code IllegalAccessError}
+ * instead. The fields are therefore read reflectively, and the cost is paid up front: all of them
+ * are resolved once in the static initializer, so a {@code com.dashjoin:jsonata} upgrade that
+ * renames or removes one fails loudly on the first call instead of quietly naming no reference.
+ */
+@RegisterForReflection(targets = Parser.Symbol.class, fields = true)
+final class JsonataTopLevelReferences {
+
+ private static final Logger LOG = Logger.getLogger(JsonataTopLevelReferences.class);
+
+ /** The name AWS prints for {@code $}, the context item itself. */
+ private static final String CONTEXT_ITEM = "$";
+
+ private static final Map<String, Field> TREE_FIELDS = resolveTreeFields(
+ "type", "value", "steps", "lhs", "rhs", "expression", "expressions",
+ "procedure", "arguments", "body", "condition", "then", "_else");
+
+ private JsonataTopLevelReferences() {
+ }
+
+ /**
+ * The distinct top-level references in {@code expression}, in the order they are written.
+ * An expression that does not parse names none: a syntax error is AWS's separate
+ * {@code INVALID_JSONATA_EXPRESSION} rule, and naming nothing leaves the definition accepted.
+ */
+ static List<String> in(String expression) {
+ Parser.Symbol root;
+ try {
+ root = new Parser().parse(expression);
+ } catch (Exception e) {
+ LOG.debugf(e, "JSONata expression not parsed, so no top-level reference is named: %s",
+ expression);
+ return List.of();
+ }
+ Set<String> names = new LinkedHashSet<>();
+ collect(root, names);
+ return new ArrayList<>(names);
+ }
+
+ private static void collect(Parser.Symbol node, Set<String> names) {
+ String type = node == null ? null : (String) read(node, "type");
+ if (type == null) {
+ return;
+ }
+ switch (type) {
+ case "path" -> collect(first(node, "steps"), names);
+ case "name" -> names.add(String.valueOf(read(node, "value")));
+ case "variable" -> collectContextItem(node, names);
+ case "unary" -> collectUnary(node, names);
+ case "binary", "apply" -> {
+ collect(child(node, "lhs"), names);
+ collect(child(node, "rhs"), names);
+ }
+ case "function", "partial" -> {
+ collect(child(node, "procedure"), names);
+ collectEach(children(node, "arguments"), names);
+ }
+ case "lambda" -> collect(child(node, "body"), names);
+ case "condition" -> {
+ collect(child(node, "condition"), names);
+ collect(child(node, "then"), names);
+ collect(child(node, "_else"), names);
+ }
+ case "block" -> collectEach(children(node, "expressions"), names);
+ case "bind" -> collect(child(node, "rhs"), names);
+ default -> {
+ // literal, number, string, regex, descendant, transform, sort, filter and group
+ // never read the top-level context.
+ }
+ }
+ }
+
+ /**
+ * {@code $} carries the empty name and is the context item AWS refuses. {@code $$} carries the
+ * name {@code "$"} and AWS refuses it under a different message, which is a separate rule.
+ * Every other variable is a workflow variable or a function, and AWS accepts an undefined one.
+ */
+ private static void collectContextItem(Parser.Symbol variable, Set<String> names) {
+ if ("".equals(read(variable, "value"))) {
+ names.add(CONTEXT_ITEM);
+ }
+ }
+
+ /**
+ * The array constructor carries its bracket as a {@link Character} and every other unary
+ * operator carries it as a {@link String}, so the operator is read through
+ * {@link String#valueOf(Object)} rather than compared against the field directly. The object
+ * constructor keeps its key/value pairs in the public {@code lhsObject}, and AWS reads a key
+ * at the top level too: {@code {aaa: 1}} names {@code aaa}.
+ */
+ private static void collectUnary(Parser.Symbol unary, Set<String> names) {
+ switch (String.valueOf(read(unary, "value"))) {
+ case "[" -> collectEach(children(unary, "expressions"), names);
+ case "{" -> collectEachPair(unary.lhsObject, names);
+ default -> collect(child(unary, "expression"), names);
+ }
+ }
+
+ private static void collectEach(List<Parser.Symbol> nodes, Set<String> names) {
+ if (nodes == null) {
+ return;
+ }
+ for (Parser.Symbol node : nodes) {
+ collect(node, names);
+ }
+ }
+
+ private static void collectEachPair(List<Parser.Symbol[]> pairs, Set<String> names) {
+ if (pairs == null) {
+ return;
+ }
+ for (Parser.Symbol[] pair : pairs) {
+ collect(pair[0], names);
+ collect(pair[1], names);
+ }
+ }
+
+ private static Parser.Symbol child(Parser.Symbol node, String field) {
+ return (Parser.Symbol) read(node, field);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static List<Parser.Symbol> children(Parser.Symbol node, String field) {
+ return (List<Parser.Symbol>) read(node, field);
+ }
+
+ private static Parser.Symbol first(Parser.Symbol node, String field) {
+ List<Parser.Symbol> nodes = children(node, field);
+ return nodes == null || nodes.isEmpty() ? null : nodes.get(0);
+ }
+
+ private static Object read(Parser.Symbol node, String field) {
+ try {
+ return Objects.requireNonNull(TREE_FIELDS.get(field), field).get(node);
+ } catch (IllegalAccessException e) {
+ throw new IllegalStateException(
+ "com.dashjoin:jsonata no longer allows reading Parser.Symbol." + field, e);
+ }
+ }
+
+ private static Map<String, Field> resolveTreeFields(String... names) {
+ Map<String, Field> fields = new LinkedHashMap<>();
+ for (String name : names) {
+ try {
+ Field field = Parser.Symbol.class.getDeclaredField(name);
+ field.setAccessible(true);
+ fields.put(name, field);
+ } catch (NoSuchFieldException e) {
+ throw new IllegalStateException("com.dashjoin:jsonata no longer declares "
+ + "Parser.Symbol." + name + ", so the top-level reference check has to be "
+ + "rewritten against the new parse tree", e);
+ }
+ }
+ return Map.copyOf(fields);
+ }
+}
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 a83c245553..b185dba2e8 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
@@ -57,6 +57,19 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
private static final Set<String> JSONPATH_ONLY_FIELDS = Set.of(
"InputPath", "OutputPath", "ResultPath", "ResultSelector", "Parameters", "Result", "ItemsPath",
"MaxConcurrencyPath");
+ // A {% %} string in one of these ASL fields is not an expression on AWS: Comment, Next,
+ // Default and Resource keep it as text, ErrorEquals and Retry hold error names and integers,
+ // ReaderConfig.CSVHeaders holds literal column names, and the JSONata support of
+ // Credentials.RoleArn is hidden behind an ARN check that fires first. ItemProcessor, Iterator
+ // and Branches carry nested states, walked as states of their own.
+ private static final Set<String> ASL_FIELDS_AWS_DOES_NOT_PARSE_AS_JSONATA = Set.of(
+ "Comment", "Next", "Default", "Resource", "ErrorEquals", "Retry", "Credentials",
+ "ItemProcessor", "Iterator", "Branches", "CSVHeaders");
+ // The fields whose value is a user payload rather than ASL. AWS parses every string inside
+ // one, at any depth, so a payload key that happens to be named Next or Comment is an
+ // expression there and the deny list above stops applying once the walk enters one.
+ private static final Set<String> JSONATA_PAYLOAD_FIELDS = Set.of(
+ "Output", "Assign", "Arguments", "ItemSelector", "BatchInput");
private static final Set<String> ITEM_READER_RESOURCES = Set.of(
"arn:aws:states:::s3:getObject",
"arn:aws:states:::s3:listObjectsV2");
@@ -1014,12 +1027,16 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
private static final Set<String> STATE_TYPES = Set.of(
"Pass", "Task", "Choice", "Wait", "Succeed", "Fail", "Parallel", "Map");
private static final String PARSE_ERROR_MARKER = "INVALID_JSON_DESCRIPTION:";
+ private static final String UNSUPPORTED_JSONATA_MARKER = "UNSUPPORTED_JSONATA_EXPRESSION:";
// Parse the structured location out of validator flat error strings,
// which currently encode it as "...field 'X' ... at /States/Y".
// AWS's published Diagnostic.location format is "/States/<StateName>/<FieldName>".
private static final Pattern FIELD_PATTERN = Pattern.compile("field '([^']+)'");
private static final Pattern LOCATION_SUFFIX_PATTERN = Pattern.compile(" at (/States/\\S+)$");
+ // The JSONata errors already carry the full AWS location, state names with spaces included,
+ // so their suffix is read with its own pattern rather than the whitespace-delimited one.
+ private static final Pattern JSONATA_LOCATION_SUFFIX_PATTERN = Pattern.compile(" at (/States/.+)$");
/**
* Exposes the existing ASL validator as a public, non-throwing API for
@@ -1077,28 +1094,39 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
}
private static Diagnostic toDiagnostic(String error) {
- boolean isParseError = error.startsWith(PARSE_ERROR_MARKER);
- String code = isParseError ? "INVALID_JSON_DESCRIPTION" : "SCHEMA_VALIDATION_FAILED";
- String message = isParseError
- ? error.substring(PARSE_ERROR_MARKER.length()).trim() : error;
- // null when there's no specific location to point to — handler omits the
+ // null location when there's no specific location to point to — handler omits the
// field from the response in that case, matching AWS's "optional" semantics.
+ if (error.startsWith(PARSE_ERROR_MARKER)) {
+ return new Diagnostic("ERROR", "INVALID_JSON_DESCRIPTION",
+ error.substring(PARSE_ERROR_MARKER.length()).trim(), null);
+ }
+ if (error.startsWith(UNSUPPORTED_JSONATA_MARKER)) {
+ return toJsonataDiagnostic(error.substring(UNSUPPORTED_JSONATA_MARKER.length()).trim());
+ }
+ String message = error;
String location = null;
- if (!isParseError) {
- Matcher locM = LOCATION_SUFFIX_PATTERN.matcher(message);
- Matcher fieldM = FIELD_PATTERN.matcher(message);
- if (locM.find() && fieldM.find()) {
- // Build the structured location and strip the redundant suffix
- // from the message, matching AWS's wire format.
- location = locM.group(1);
- String field = fieldM.group(1);
- if (!location.endsWith("/" + field)) {
- location = location + "/" + field;
- }
- message = message.substring(0, locM.start()).trim();
+ Matcher locM = LOCATION_SUFFIX_PATTERN.matcher(message);
+ Matcher fieldM = FIELD_PATTERN.matcher(message);
+ if (locM.find() && fieldM.find()) {
+ // Build the structured location and strip the redundant suffix
+ // from the message, matching AWS's wire format.
+ location = locM.group(1);
+ String field = fieldM.group(1);
+ if (!location.endsWith("/" + field)) {
+ location = location + "/" + field;
}
+ message = message.substring(0, locM.start()).trim();
}
- return new Diagnostic("ERROR", code, message, location);
+ return new Diagnostic("ERROR", "SCHEMA_VALIDATION_FAILED", message, location);
+ }
+
+ private static Diagnostic toJsonataDiagnostic(String message) {
+ Matcher locationMatcher = JSONATA_LOCATION_SUFFIX_PATTERN.matcher(message);
+ if (!locationMatcher.find()) {
+ return new Diagnostic("ERROR", "UNSUPPORTED_JSONATA_EXPRESSION", message, null);
+ }
+ return new Diagnostic("ERROR", "UNSUPPORTED_JSONATA_EXPRESSION",
+ message.substring(0, locationMatcher.start()).trim(), locationMatcher.group(1));
}
private static void validateStateMachineName(String name) {
@@ -1351,9 +1379,18 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
throw new AwsException("InvalidDefinition",
"Invalid State Machine Definition: '" + first.substring(PARSE_ERROR_MARKER.length()).trim() + "'", 400);
}
+ // A JSONata error already carries its own AWS code and location, so it is reported on its
+ // own rather than folded into the schema list.
+ List<String> schemaErrors = errors.stream()
+ .filter(error -> !error.startsWith(UNSUPPORTED_JSONATA_MARKER))
+ .toList();
+ if (schemaErrors.isEmpty()) {
+ throw new AwsException("InvalidDefinition",
+ "Invalid State Machine Definition: '" + first + "'", 400);
+ }
throw new AwsException("InvalidDefinition",
"Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED: "
- + String.join(", ", errors) + "'", 400);
+ + String.join(", ", schemaErrors) + "'", 400);
}
private List<String> collectValidationErrors(String definition) {
@@ -1434,6 +1471,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
+ "' is only supported for the 'JSONPath' QueryLanguage at " + statePath);
}
}
+ collectTopLevelReferences(statePath, stateDef, errors);
}
if ("Map".equals(stateType)) {
@@ -1452,12 +1490,57 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
if (branches.isArray()) {
for (int i = 0; i < branches.size(); i++) {
validateNestedStates(branches.path(i).path("States"),
- statePath + "/Branches/" + i + "/States", topLevelJsonata, errors);
+ statePath + "/Branches[" + i + "]/States", topLevelJsonata, errors);
}
}
}
}
+ /**
+ * Reports every JSONata expression in the state that reads the top-level context, which real
+ * AWS refuses at CreateStateMachine time. Only the fields AWS parses as JSONata are walked:
+ * measured against {@code validate-state-machine-definition}, a {@code {% %}} string in
+ * Comment, Next, Default, Resource, ErrorEquals, Retry, Credentials or ReaderConfig.CSVHeaders
+ * is left alone, while Output, Assign, Arguments, Items, Seconds, Condition, ItemBatcher,
+ * ItemReader, ItemSelector, ResultWriter and the rest are parsed and reported.
+ *
+ * <p>Those names are ASL fields, not payload keys. AWS parses a payload whole, so
+ * {@code Assign: {"Next": "{% phone %}"}} and {@code Arguments: {"Payload": {"Comment":
+ * "{% phone %}"}}} are both refused by name, and the deny list stops applying as soon as the
+ * walk enters one of {@link #JSONATA_PAYLOAD_FIELDS}.
+ */
+ private static void collectTopLevelReferences(String path, JsonNode node, List<String> errors) {
+ collectTopLevelReferences(path, node, false, errors);
+ }
+
+ private static void collectTopLevelReferences(String path, JsonNode node, boolean insidePayload,
+ List<String> errors) {
+ if (node.isObject()) {
+ node.fields().forEachRemaining(field -> {
+ String name = field.getKey();
+ if (insidePayload || !ASL_FIELDS_AWS_DOES_NOT_PARSE_AS_JSONATA.contains(name)) {
+ collectTopLevelReferences(path + "/" + name, field.getValue(),
+ insidePayload || JSONATA_PAYLOAD_FIELDS.contains(name), errors);
+ }
+ });
+ return;
+ }
+ if (node.isArray()) {
+ for (int index = 0; index < node.size(); index++) {
+ collectTopLevelReferences(path + "[" + index + "]", node.get(index), insidePayload,
+ errors);
+ }
+ return;
+ }
+ if (!node.isTextual() || !JsonataEvaluator.isExpression(node.asText())) {
+ return;
+ }
+ for (String reference : JsonataTopLevelReferences.in(JsonataEvaluator.unwrap(node.asText()))) {
+ errors.add(UNSUPPORTED_JSONATA_MARKER + " Reference to '" + reference
+ + "' at the top level is not supported. at " + path);
+ }
+ }
+
private void validateNestedStates(JsonNode states, String statesPath,
boolean inheritedJsonata, List<String> errors) {
if (!states.isObject()) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataTopLevelReferencesTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataTopLevelReferencesTest.java
new file mode 100644
index 0000000000..ef6ac4b784
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataTopLevelReferencesTest.java
@@ -0,0 +1,110 @@
+package io.github.hectorvent.floci.services.stepfunctions;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Every expression here was run through
+ * {@code aws stepfunctions validate-state-machine-definition --region us-east-1} as the Output of
+ * a one-state Pass machine. The names asserted are the ones AWS puts in
+ * {@code Reference to '<name>' at the top level is not supported.}, and the expressions asserted
+ * empty are the ones AWS answers {@code result: OK}.
+ */
+class JsonataTopLevelReferencesTest {
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "phone",
+ "phone[0].number",
+ "phone.number.street",
+ "-phone",
+ "phone ? 1 : 2",
+ "$states.input.a ? phone : 2",
+ "phone & 'x'",
+ "phone in $states.input.b",
+ "$sum(phone)",
+ "phone(1)",
+ "phone ~> $string()",
+ "[1..phone]",
+ "(phone)",
+ "(phone).other",
+ "[phone].other",
+ "[phone, 1]",
+ "{phone: 1}",
+ "($x := phone; $x)",
+ "$map($states.input.a, function($y){ phone })",
+ "$count(phone[inner])",
+ "phone.**.deeper"})
+ @DisplayName("AWS names the identifier read at the top level")
+ void namesTheTopLevelIdentifier(String expression) {
+ assertEquals(List.of("phone"), JsonataTopLevelReferences.in(expression));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "$states.input.phone",
+ "$states.input.a.phone",
+ "$states.input.a[0].phone",
+ "$states.input.a.phone[0]",
+ "$states.input.items[phone > 3]",
+ "$states.input.a^(phone)",
+ "$states.input.a{'k': phone}",
+ "$states.input.a.(phone)",
+ "$states.input.a.$phone",
+ "$phone",
+ "$states.input.a ~> $string()",
+ "$states.input ~> |phone|{'b': 1}|",
+ "**.phone",
+ "{'k': 1}.phone",
+ "$states.input.a[0][phone]",
+ "$states.input.a[$ > 1]",
+ "function($x){ $x.phone }",
+ "$map($states.input.a, function($x){ $x.phone })",
+ "'phone'",
+ "1 + 1",
+ "$now()"})
+ @DisplayName("AWS accepts a name that is not read from the top-level context")
+ void namesNothingWhenTheReferenceIsAnchored(String expression) {
+ assertEquals(List.of(), JsonataTopLevelReferences.in(expression));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"$", "$.phone", "$[0]", "$string($)",
+ "$map($states.input.a, function($x){ $ })"})
+ @DisplayName("the context item itself is named '$', as AWS names it")
+ void namesTheContextItem(String expression) {
+ assertEquals(List.of("$"), JsonataTopLevelReferences.in(expression));
+ }
+
+ @Test
+ @DisplayName("'$$' is AWS's separate rule and is left to it")
+ void leavesTheRootReferenceAlone() {
+ assertEquals(List.of(), JsonataTopLevelReferences.in("$$"));
+ assertEquals(List.of(), JsonataTopLevelReferences.in("$$.phone"));
+ }
+
+ @Test
+ @DisplayName("every distinct name is reported once, in writing order")
+ void reportsEveryDistinctNameOnce() {
+ assertEquals(List.of("aaa", "bbb"), JsonataTopLevelReferences.in("aaa + bbb"));
+ assertEquals(List.of("bbb", "aaa"), JsonataTopLevelReferences.in("[bbb, aaa]"));
+ assertEquals(List.of("aaa"), JsonataTopLevelReferences.in("aaa + aaa"));
+ assertEquals(List.of("aaa", "bbb"), JsonataTopLevelReferences.in("(aaa; bbb)"));
+ assertEquals(List.of("aaa", "bbb"),
+ JsonataTopLevelReferences.in("$number(aaa) + $number(bbb)"));
+ }
+
+ @Test
+ @DisplayName("a syntax error names nothing, so the definition stays accepted")
+ void namesNothingWhenTheExpressionDoesNotParse() {
+ assertEquals(List.of(), JsonataTopLevelReferences.in("phone[1,2)"));
+ assertEquals(List.of(), JsonataTopLevelReferences.in("phone %.other"));
+ assertEquals(List.of(), JsonataTopLevelReferences.in(""));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTopLevelReferenceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTopLevelReferenceIntegrationTest.java
new file mode 100644
index 0000000000..23534f302a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTopLevelReferenceIntegrationTest.java
@@ -0,0 +1,311 @@
+package io.github.hectorvent.floci.services.stepfunctions;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+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.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasSize;
+
+/**
+ * A JSONata expression that reads the top-level context is refused when the state machine is
+ * created, as real AWS refuses it. Every message and location asserted here was measured with
+ * {@code aws stepfunctions validate-state-machine-definition --region us-east-1} on the same
+ * definition, and the CreateStateMachine wire shape with
+ * {@code aws stepfunctions create-state-machine}.
+ */
+@QuarkusTest
+class StepFunctionsTopLevelReferenceIntegrationTest {
+
+ private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
+ private static final String VALIDATE_TARGET = "AWSStepFunctions.ValidateStateMachineDefinition";
+ private static final String CREATE_TARGET = "AWSStepFunctions.CreateStateMachine";
+ private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/service-role/sfn";
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ @BeforeAll
+ static void configure() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ private static Response validate(String definition) {
+ return given().contentType(CONTENT_TYPE).header("X-Amz-Target", VALIDATE_TARGET)
+ .body(OBJECT_MAPPER.createObjectNode().put("definition", definition).toString())
+ .when().post("/");
+ }
+
+ private static Response create(String name, String definition) {
+ return given().contentType(CONTENT_TYPE).header("X-Amz-Target", CREATE_TARGET)
+ .body(OBJECT_MAPPER.createObjectNode()
+ .put("name", name)
+ .put("definition", definition)
+ .put("roleArn", ROLE_ARN).toString())
+ .when().post("/");
+ }
+
+ private static void expectTopLevelReference(String definition, String reference, String location) {
+ validate(definition).then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].severity", equalTo("ERROR"))
+ .body("diagnostics[0].code", equalTo("UNSUPPORTED_JSONATA_EXPRESSION"))
+ .body("diagnostics[0].message", equalTo(
+ "Reference to '" + reference + "' at the top level is not supported."))
+ .body("diagnostics[0].location", equalTo(location));
+ }
+
+ private static void expectAccepted(String definition) {
+ validate(definition).then().statusCode(200)
+ .body("result", equalTo("OK"))
+ .body("diagnostics", hasSize(0));
+ }
+
+ private static String passWithOutput(String output) {
+ return """
+ {"QueryLanguage":"JSONata","StartAt":"E",
+ "States":{"E":{"Type":"Pass","Output":__OUTPUT__,"End":true}}}
+ """.replace("__OUTPUT__", output);
+ }
+
+ @Test
+ @DisplayName("CreateStateMachine refuses the definition with AWS's InvalidDefinition message")
+ void createStateMachineRefusesATopLevelReference() {
+ create("top-level-reference-" + System.nanoTime(),
+ passWithOutput("{\"v\":\"{% phone[0] %}\"}"))
+ .then().statusCode(400)
+ .body("__type", equalTo("InvalidDefinition"))
+ .body("message", equalTo("Invalid State Machine Definition: "
+ + "'UNSUPPORTED_JSONATA_EXPRESSION: Reference to 'phone' at the top level "
+ + "is not supported. at /States/E/Output/v'"));
+ }
+
+ @Test
+ @DisplayName("CreateStateMachine still accepts the anchored form of the same expression")
+ void createStateMachineAcceptsTheAnchoredForm() {
+ create("anchored-reference-" + System.nanoTime(),
+ passWithOutput("{\"v\":\"{% $states.input.phone[0] %}\"}"))
+ .then().statusCode(200);
+ }
+
+ @Test
+ @DisplayName("Output names the field that holds the expression")
+ void outputField() {
+ expectTopLevelReference(passWithOutput("{\"v\":\"{% phone %}\"}"),
+ "phone", "/States/E/Output/v");
+ }
+
+ @Test
+ @DisplayName("a nested Output object names the whole path down to the array element")
+ void nestedOutputField() {
+ expectTopLevelReference(passWithOutput("{\"a\":{\"b\":[\"{% phone %}\"]}}"),
+ "phone", "/States/E/Output/a/b[0]");
+ }
+
+ @Test
+ @DisplayName("Assign is parsed like Output")
+ void assignField() {
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"E",
+ "States":{"E":{"Type":"Pass","Assign":{"v":"{% phone %}"},"End":true}}}
+ """, "phone", "/States/E/Assign/v");
+ }
+
+ @Test
+ @DisplayName("a Choice condition names its rule by index")
+ void choiceCondition() {
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"C","States":{
+ "C":{"Type":"Choice","Choices":[{"Condition":"{% phone = 1 %}","Next":"E"}],
+ "Default":"E"},
+ "E":{"Type":"Pass","End":true}}}
+ """, "phone", "/States/C/Choices[0]/Condition");
+ }
+
+ @Test
+ @DisplayName("Wait Seconds is parsed")
+ void waitSeconds() {
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"E",
+ "States":{"E":{"Type":"Wait","Seconds":"{% phone %}","End":true}}}
+ """, "phone", "/States/E/Seconds");
+ }
+
+ @Test
+ @DisplayName("Fail Cause is parsed")
+ void failCause() {
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"E",
+ "States":{"E":{"Type":"Fail","Cause":"{% phone %}"}}}
+ """, "phone", "/States/E/Cause");
+ }
+
+ @Test
+ @DisplayName("Map Items is parsed and so is every state of its ItemProcessor")
+ void mapItemsAndItemProcessor() {
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"M","States":{
+ "M":{"Type":"Map","Items":"{% phone %}","ItemProcessor":{
+ "StartAt":"I","States":{"I":{"Type":"Pass","End":true}}},"End":true}}}
+ """, "phone", "/States/M/Items");
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"M","States":{
+ "M":{"Type":"Map","Items":"{% $states.input.a %}","ItemProcessor":{
+ "StartAt":"I","States":{"I":{"Type":"Pass",
+ "Output":{"v":"{% phone %}"},"End":true}}},"End":true}}}
+ """, "phone", "/States/M/ItemProcessor/States/I/Output/v");
+ }
+
+ @Test
+ @DisplayName("a Parallel branch state names its branch by index")
+ void parallelBranchState() {
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"P","States":{
+ "P":{"Type":"Parallel","Branches":[{"StartAt":"B","States":{
+ "B":{"Type":"Pass","Output":{"v":"{% phone %}"},"End":true}}}],
+ "End":true}}}
+ """, "phone", "/States/P/Branches[0]/States/B/Output/v");
+ }
+
+ @Test
+ @DisplayName("a Catch Output names its catcher by index")
+ void catchOutput() {
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"E","States":{
+ "E":{"Type":"Task","Resource":"arn:aws:states:::aws-sdk:s3:listBuckets",
+ "Arguments":{},"Catch":[{"ErrorEquals":["States.ALL"],
+ "Output":{"v":"{% phone %}"},"Next":"F"}],"End":true},
+ "F":{"Type":"Pass","End":true}}}
+ """, "phone", "/States/E/Catch[0]/Output/v");
+ }
+
+ @Test
+ @DisplayName("an earlier Assign does not make the bare name legal; only $phone is")
+ void anEarlierAssignDoesNotBindTheBareName() {
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"A","States":{
+ "A":{"Type":"Pass","Assign":{"phone":"{% 1 %}"},"Next":"E"},
+ "E":{"Type":"Pass","Output":{"v":"{% phone %}"},"End":true}}}
+ """, "phone", "/States/E/Output/v");
+ expectAccepted("""
+ {"QueryLanguage":"JSONata","StartAt":"A","States":{
+ "A":{"Type":"Pass","Assign":{"phone":"{% 1 %}"},"Next":"E"},
+ "E":{"Type":"Pass","Output":{"v":"{% $phone %}"},"End":true}}}
+ """);
+ }
+
+ @Test
+ @DisplayName("each distinct name in one field gets its own diagnostic")
+ void everyDistinctNameInOneField() {
+ validate(passWithOutput("{\"v\":\"{% aaa + bbb %}\"}"))
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(2))
+ .body("diagnostics[0].message", equalTo(
+ "Reference to 'aaa' at the top level is not supported."))
+ .body("diagnostics[1].message", equalTo(
+ "Reference to 'bbb' at the top level is not supported."))
+ .body("diagnostics[1].location", equalTo("/States/E/Output/v"));
+ }
+
+ @Test
+ @DisplayName("the context item itself is named '$'")
+ void contextItem() {
+ expectTopLevelReference(passWithOutput("{\"v\":\"{% $.phone %}\"}"),
+ "$", "/States/E/Output/v");
+ }
+
+ @Test
+ @DisplayName("a name reached through $states, a predicate or a variable is accepted")
+ void anchoredExpressionsAreAccepted() {
+ expectAccepted(passWithOutput("{\"v\":\"{% $states.input.phone %}\"}"));
+ expectAccepted(passWithOutput("{\"v\":\"{% $states.input.items[phone > 3] %}\"}"));
+ expectAccepted(passWithOutput("{\"v\":\"{% $map($states.input.a, function($x){ $x.phone }) %}\"}"));
+ expectAccepted(passWithOutput("{\"v\":\"{% $phone %}\"}"));
+ }
+
+ @Test
+ @DisplayName("a JSONPath state machine is not parsed as JSONata")
+ void jsonPathMachineIsUntouched() {
+ expectAccepted("""
+ {"StartAt":"E",
+ "States":{"E":{"Type":"Pass","Parameters":{"v":"{% phone %}"},"End":true}}}
+ """);
+ }
+
+ @Test
+ @DisplayName("Comment, Next and ErrorEquals keep a {% %} string as text, as AWS does")
+ void fieldsAwsDoesNotParse() {
+ expectAccepted("""
+ {"QueryLanguage":"JSONata","StartAt":"E",
+ "States":{"E":{"Type":"Pass","Comment":"{% phone %}","End":true}}}
+ """);
+ expectAccepted("""
+ {"QueryLanguage":"JSONata","StartAt":"E","States":{
+ "E":{"Type":"Task","Resource":"arn:aws:states:::aws-sdk:s3:listBuckets",
+ "Arguments":{},"Retry":[{"ErrorEquals":["{% phone %}"]}],"End":true}}}
+ """);
+ }
+
+ @Test
+ @DisplayName("ReaderConfig.CSVHeaders holds column names, not expressions, as AWS does")
+ void readerConfigCsvHeadersAreNotParsed() {
+ expectAccepted("""
+ {"QueryLanguage":"JSONata","StartAt":"M","States":{
+ "M":{"Type":"Map",
+ "ItemReader":{"Resource":"arn:aws:states:::s3:getObject",
+ "Arguments":{"Bucket":"b","Key":"k"},
+ "ReaderConfig":{"InputType":"CSV","CSVHeaderLocation":"GIVEN",
+ "CSVHeaders":["{% phone %}"]}},
+ "ItemProcessor":{"StartAt":"I","States":{"I":{"Type":"Pass","End":true}}},
+ "End":true}}}
+ """);
+ }
+
+ @Test
+ @DisplayName("a payload key named after an ASL field is still an expression, as AWS parses it")
+ void aPayloadKeyNamedAfterAnAslFieldIsParsed() {
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"E",
+ "States":{"E":{"Type":"Pass","Assign":{"Next":"{% phone %}"},"End":true}}}
+ """, "phone", "/States/E/Assign/Next");
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"E","States":{
+ "E":{"Type":"Task","Resource":"arn:aws:states:::lambda:invoke",
+ "Arguments":{"FunctionName":"f","Payload":{"Comment":"{% phone %}"}},
+ "End":true}}}
+ """, "phone", "/States/E/Arguments/Payload/Comment");
+ expectTopLevelReference(passWithOutput("{\"ItemProcessor\":{\"Iterator\":\"{% phone %}\"}}"),
+ "phone", "/States/E/Output/ItemProcessor/Iterator");
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"M","States":{
+ "M":{"Type":"Map","ItemSelector":{"Next":"{% phone %}"},
+ "ItemProcessor":{"StartAt":"I","States":{"I":{"Type":"Pass","End":true}}},
+ "End":true}}}
+ """, "phone", "/States/M/ItemSelector/Next");
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"M","States":{
+ "M":{"Type":"Map","ItemBatcher":{"BatchInput":{"Comment":"{% phone %}"}},
+ "ItemProcessor":{"StartAt":"I","States":{"I":{"Type":"Pass","End":true}}},
+ "End":true}}}
+ """, "phone", "/States/M/ItemBatcher/BatchInput/Comment");
+ expectTopLevelReference("""
+ {"QueryLanguage":"JSONata","StartAt":"E","States":{
+ "E":{"Type":"Task","Resource":"arn:aws:states:::lambda:invoke",
+ "Arguments":{"FunctionName":"f"},
+ "Catch":[{"ErrorEquals":["States.ALL"],"Assign":{"Retry":"{% phone %}"},
+ "Next":"D"}],"End":true},
+ "D":{"Type":"Pass","End":true}}}
+ """, "phone", "/States/E/Catch[0]/Assign/Retry");
+ }
+
+ @Test
+ @DisplayName("a syntax error is left to the execution, as it is today")
+ void syntaxErrorsAreOutOfScope() {
+ expectAccepted(passWithOutput("{\"v\":\"{% phone[1,2) %}\"}"));
+ }
+}