Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(stepfunctions): reject the QueryLanguage definitions AWS rejects (#2972)

Facundo Paredese3230a74abae
diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md
index 073b82008a..6be5dd56e2 100644
--- a/docs/services/step-functions.md
+++ b/docs/services/step-functions.md
@@ -382,6 +382,39 @@ state absent from its container or a state nothing transitions to (`MISSING_TRAN
and for a field the state type does not carry: `TimeoutSeconds` only on `Task`, and `Catch`/`Retry`
only on `Task`, `Parallel` and `Map`.
+## A state's QueryLanguage, and the fields it may carry
+
+A state's query language is JSONPath when its `QueryLanguage` field is exactly the string
+`"JSONPath"`, the state machine's when the field is absent, and JSONata for any other value: the
+wrong case, an unknown string and a non-string alike. A state inside a `Map`'s `ItemProcessor` or `Iterator`, or
+inside one of a `Parallel`'s `Branches`, falls back to the **state machine's** language and not to
+the enclosing `Map`'s or `Parallel`'s, which the Amazon States Language calls independent of it. The
+enclosing state's own fields, `Items` and `MaxConcurrency` among them, do use its own language.
+
+Three more refusals, each measured against `ValidateStateMachineDefinition` on real AWS:
+
+- A field that belongs to the other query language, at the state's path with no field suffix:
+ `The QueryLanguage is set to 'JSONPath', but field 'Output' is only supported for the 'JSONata'
+ QueryLanguage`, and the mirror of it for `InputPath`, `OutputPath`, `ResultPath`,
+ `ResultSelector`, `Parameters`, `Result`, `ItemsPath` and `MaxConcurrencyPath` on a JSONata
+ state. `Assign` belongs to neither list: AWS accepts it on both.
+- A state declaring `"QueryLanguage": "JSONPath"` under a `JSONata` state machine:
+ `'QueryLanguage' can not be 'JSONPath' if set to 'JSONata' for whole state machine`, again at the
+ state's path. A JSONata machine cannot be reverted one state at a time; the upgrade in the other
+ direction is allowed. That diagnostic is the whole answer for that state, so the fields its
+ refused language forbids are not reported on top of it, while every other check still runs.
+- `QueryLanguage` on the `ItemProcessor`, `Iterator` or branch object itself, which is not a state:
+ `Field 'QueryLanguage' is not supported` at `/States/M/ItemProcessor`.
+
+A `QueryLanguage` value outside the enum is reported at the field, `/States/X/QueryLanguage` or
+`/QueryLanguage`, with `Value should be one of the following: [JSONPath, JSONata]`, and a
+non-string value with `Expected value of type [STRING]`. That diagnostic is independent of the
+resolution above, so `"jsonpath"` is a JSONata state that also carries it, and it is not a
+downgrade: only the exact string `"JSONPath"` under a JSONata machine is.
+
+Locations follow AWS: the two messages above point at the state, `/States/X`, while every other
+schema error points at the offending field, `/States/X/MaxConcurrency`.
+
## Mocked service integrations
Floci supports the Step Functions Local mock configuration format
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 ee1703823d..ca5bd9954f 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
@@ -2027,6 +2027,9 @@ public class AslExecutor {
// Run each branch on its own worker thread under the execution's account: the request
// scope is thread-bound, so without this a branch's Task integrations would resolve to
// the default account rather than the execution's.
+ // A branch state that declares no QueryLanguage defaults to the state machine's, not to
+ // this Parallel's: the ASL specification calls the two independent, so what travels
+ // into the branch is topLevelQueryLanguage. https://states-language.net/spec.html
futures.add(executor.submit(() -> callUnderExecutionAccount(sm,
() -> executeBranch(startAt, branchStates, capturedInput, producedEventCount, sm,
topLevelQueryLanguage, branchContext, branchVariables))));
@@ -2179,6 +2182,8 @@ public class AslExecutor {
// history of its own: the item's events count against its own limit, not the parent's.
// An inline Map's iterations are part of this execution and count here.
AtomicLong childExecutionEventCount = distributed ? new AtomicLong() : producedEventCount;
+ // Same rule as the Parallel branches above: an ItemProcessor state declaring no
+ // QueryLanguage runs as the state machine's, never as this Map's.
JsonNode branchOutput = executeBranch(startAt, iteratorStates, iterInput,
childExecutionEventCount, sm, topLevelQueryLanguage, iterContext,
variables.deepCopy());
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 2e43f0dd88..1fc25d05df 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
@@ -64,9 +64,22 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
// Fields that are valid only in JSONPath mode. Validated against real AWS:
// creating a JSONata state machine with any of these fields returns SCHEMA_VALIDATION_FAILED.
- private static final Set<String> JSONPATH_ONLY_FIELDS = Set.of(
+ // A List, not a Set.of: Set.of's iteration order is salted per JVM, so a state carrying more
+ // than one of these emits its diagnostics in a different order on each run, and a caller
+ // paging with maxResults=1 receives a different one every time. The order below is not
+ // AWS-observed, it is simply the one this code commits to.
+ private static final List<String> JSONPATH_ONLY_FIELDS = List.of(
"InputPath", "OutputPath", "ResultPath", "ResultSelector", "Parameters", "Result", "ItemsPath",
"MaxConcurrencyPath");
+ // Fields that are valid only in JSONata mode. Validated against real AWS: a JSONPath state
+ // carrying any of them returns SCHEMA_VALIDATION_FAILED. Assign is deliberately absent: AWS
+ // accepts it on a JSONPath state, so it belongs to neither list. A List for the same reason as
+ // the list above, which the same expression selects between.
+ private static final List<String> JSONATA_ONLY_FIELDS = List.of("Output", "Arguments", "Items");
+ // The two spellings AWS accepts in a QueryLanguage field, exactly as written here. Any other
+ // value is reported against this enum, including one AWS still resolves to JSONata such as
+ // "jsonata" or "jsonpath".
+ private static final Set<String> QUERY_LANGUAGES = Set.of("JSONPath", "JSONata");
// 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
@@ -1229,7 +1242,11 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
"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:";
- private static final String UNSUPPORTED_FIELD_MARKER = "UNSUPPORTED_FIELD:";
+ // The diagnostics whose location AWS does not compose from the offending field name: the
+ // QueryLanguage compatibility family, which it points at the state, and the QueryLanguage enum
+ // error, which it points at the field. Every other schema error has "/<field>" appended to the
+ // state path, so these travel with their message already composed and their own location.
+ private static final String EXPLICIT_LOCATION_MARKER = "EXPLICIT_LOCATION:";
private static final String MISSING_END_STATE_MARKER = "MISSING_END_STATE:";
private static final String UNREACHABLE_STATE_MARKER = "UNREACHABLE_STATE:";
// Payload is "<value><SOH><location>", shared by every marker that must carry structured data
@@ -1320,8 +1337,11 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
return new Diagnostic("ERROR", "INVALID_JSONATA_EXPRESSION",
payload.substring(0, separator), payload.substring(separator + 1));
}
- if (error.startsWith(UNSUPPORTED_FIELD_MARKER)) {
- return toUnsupportedFieldDiagnostic(error.substring(UNSUPPORTED_FIELD_MARKER.length()));
+ if (error.startsWith(EXPLICIT_LOCATION_MARKER)) {
+ String payload = error.substring(EXPLICIT_LOCATION_MARKER.length());
+ int separator = payload.indexOf(MARKER_PAYLOAD_SEPARATOR);
+ return new Diagnostic("ERROR", "SCHEMA_VALIDATION_FAILED",
+ payload.substring(0, separator), payload.substring(separator + 1));
}
if (error.equals(MISSING_END_STATE_MARKER)) {
return new Diagnostic("ERROR", "MISSING_END_STATE", "Workflow has no terminal state", null);
@@ -1366,16 +1386,6 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
message.substring(0, locationMatcher.start()).trim(), locationMatcher.group(1));
}
- // Payload is "<field name> <location>"; unlike the generic schema-error shape, AWS points this
- // diagnostic at the state itself rather than appending the field name to the location.
- private static Diagnostic toUnsupportedFieldDiagnostic(String payload) {
- int separator = payload.indexOf(' ');
- String field = payload.substring(0, separator);
- String location = payload.substring(separator + 1);
- return new Diagnostic("ERROR", "SCHEMA_VALIDATION_FAILED",
- "Field '" + field + "' is not supported", location);
- }
-
private static void validateStateMachineName(String name) {
boolean invalidCharacter = name != null && name.codePoints().anyMatch(codePoint ->
Character.isWhitespace(codePoint)
@@ -1674,14 +1684,15 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
errors.add("The field 'StartAt' is required and must be a non-empty string");
}
+ validateQueryLanguageValue(def, "/QueryLanguage", errors);
+
JsonNode states = def.get("States");
if (states == null || !states.isObject() || states.isEmpty()) {
errors.add("The field 'States' is required and must be a non-empty object");
return errors;
}
- String topLevelQL = def.path("QueryLanguage").asText("JSONPath");
- boolean topLevelJsonata = "JSONata".equals(topLevelQL);
+ boolean topLevelJsonata = resolvesToJsonata(def, false);
Set<String> topLevelStateNames = new HashSet<>();
states.fieldNames().forEachRemaining(topLevelStateNames::add);
@@ -1801,11 +1812,75 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
String stateType, List<String> errors) {
for (FieldStateTypeRule rule : FIELDS_ALLOWED_STATE_TYPES) {
if (stateDef.has(rule.field()) && !rule.allowedTypes().contains(stateType)) {
- errors.add(UNSUPPORTED_FIELD_MARKER + rule.field() + " " + statePath);
+ errors.add(EXPLICIT_LOCATION_MARKER + "Field '" + rule.field() + "' is not supported"
+ + MARKER_PAYLOAD_SEPARATOR + statePath);
+ }
+ }
+ }
+
+ /**
+ * A field belonging to the other query language is refused on both sides. AWS reports this
+ * family at the state, never at the offending field, which is why it carries its location.
+ */
+ private static void reportFieldsOfTheOtherLanguage(String statePath, JsonNode stateDef,
+ boolean stateIsJsonata, List<String> errors) {
+ List<String> fieldsOfTheOtherLanguage =
+ stateIsJsonata ? JSONPATH_ONLY_FIELDS : JSONATA_ONLY_FIELDS;
+ String otherLanguage = stateIsJsonata ? "JSONPath" : "JSONata";
+ for (String field : fieldsOfTheOtherLanguage) {
+ if (stateDef.has(field)) {
+ errors.add(EXPLICIT_LOCATION_MARKER + "The QueryLanguage is set to '"
+ + (stateIsJsonata ? "JSONata" : "JSONPath") + "', but field '" + field
+ + "' is only supported for the '" + otherLanguage + "' QueryLanguage"
+ + MARKER_PAYLOAD_SEPARATOR + statePath);
}
}
}
+ /**
+ * The effective query language of one state, or of the state machine when {@code owner} is the
+ * definition itself. Measured against real AWS: the language is JSONPath only when the field is
+ * exactly the string {@code "JSONPath"}. Absent, it is inherited; present and anything else,
+ * the wrong case, an unknown string and a non-string alike, the owner is JSONata. The spelling
+ * is reported separately by {@link #validateQueryLanguageValue}, which runs whatever this
+ * resolves to.
+ */
+ private static boolean resolvesToJsonata(JsonNode owner, boolean inheritedJsonata) {
+ JsonNode declared = owner.path("QueryLanguage");
+ if (declared.isMissingNode()) {
+ return inheritedJsonata;
+ }
+ return !declaresJsonPath(owner);
+ }
+
+ /** The exact string that is the one way to ask for JSONPath, and the one trigger of the downgrade. */
+ private static boolean declaresJsonPath(JsonNode owner) {
+ return "JSONPath".equals(owner.path("QueryLanguage").asText(null));
+ }
+
+ /**
+ * Reports a declared {@code QueryLanguage} against AWS's enum. Measured on real AWS: this one
+ * is located at the field, {@code /States/X/QueryLanguage} or {@code /QueryLanguage}, and not at
+ * the state like the compatibility messages, and it is returned on top of whatever the resolved
+ * language produced.
+ */
+ private static void validateQueryLanguageValue(JsonNode owner, String location,
+ List<String> errors) {
+ JsonNode declared = owner.path("QueryLanguage");
+ if (declared.isMissingNode()) {
+ return;
+ }
+ if (!declared.isTextual()) {
+ errors.add(EXPLICIT_LOCATION_MARKER + "Expected value of type [STRING]"
+ + MARKER_PAYLOAD_SEPARATOR + location);
+ return;
+ }
+ if (!QUERY_LANGUAGES.contains(declared.asText())) {
+ errors.add(EXPLICIT_LOCATION_MARKER + "Value should be one of the following: "
+ + "[JSONPath, JSONata]" + MARKER_PAYLOAD_SEPARATOR + location);
+ }
+ }
+
private void validateState(String statePath, JsonNode stateDef, boolean topLevelJsonata,
Set<String> siblingStateNames, List<String> errors) {
if (!stateDef.isObject()) {
@@ -1829,20 +1904,27 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|| stateDef.path("Choices").isEmpty())) {
errors.add("Choice state must declare a non-empty field 'Choices' at " + statePath);
}
- String stateQL = stateDef.path("QueryLanguage").asText(null);
- boolean stateIsJsonata = stateQL != null ? "JSONata".equals(stateQL) : topLevelJsonata;
+ boolean stateIsJsonata = resolvesToJsonata(stateDef, topLevelJsonata);
+
+ // A JSONata state machine cannot be reverted to JSONPath one state at a time. The upgrade
+ // in the other direction is allowed, which is why this reads the machine's language.
+ boolean downgradedToJsonPath = topLevelJsonata && declaresJsonPath(stateDef);
+ if (downgradedToJsonPath) {
+ errors.add(EXPLICIT_LOCATION_MARKER + "'QueryLanguage' can not be 'JSONPath' if set to "
+ + "'JSONata' for whole state machine" + MARKER_PAYLOAD_SEPARATOR + statePath);
+ }
validateFieldsAllowedForType(statePath, stateDef, stateType, errors);
validateTransitionTargets(statePath, stateDef, siblingStateNames, errors);
- // JSONPath-only fields are not allowed when the state uses JSONata
+ // Measured on AWS: the downgrade is the whole answer for that state, and the fields its
+ // refused language forbids are not named on top of it. Only this check is skipped; every
+ // other one, the Map's MaxConcurrency range among them, still runs.
+ if (!downgradedToJsonPath) {
+ reportFieldsOfTheOtherLanguage(statePath, stateDef, stateIsJsonata, errors);
+ }
+ validateQueryLanguageValue(stateDef, statePath + "/QueryLanguage", errors);
if (stateIsJsonata) {
- for (String field : JSONPATH_ONLY_FIELDS) {
- if (stateDef.has(field)) {
- errors.add("The QueryLanguage is set to 'JSONata', but field '" + field
- + "' is only supported for the 'JSONPath' QueryLanguage at " + statePath);
- }
- }
collectTopLevelReferences(statePath, stateDef, errors);
}
@@ -1865,18 +1947,17 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
validateResultWriter(statePath, stateDef.get("ResultWriter"), stateIsJsonata, errors);
}
String processorField = stateDef.has("ItemProcessor") ? "ItemProcessor" : "Iterator";
- String processorPath = statePath + "/" + processorField;
- JsonNode processor = stateDef.path(processorField);
- validateNestedStates(processor.path("States"), processorPath + "/States", processorPath + "/StartAt",
- processor.path("StartAt").asText(null), topLevelJsonata, errors);
+ // The sub-workflow's states default to the state machine's query language, not to this
+ // Map's: the ASL specification calls the two independent.
+ validateSubWorkflow(stateDef.path(processorField), statePath + "/" + processorField,
+ topLevelJsonata, errors);
} else if ("Parallel".equals(stateType)) {
JsonNode branches = stateDef.path("Branches");
if (branches.isArray()) {
for (int i = 0; i < branches.size(); i++) {
- JsonNode branch = branches.path(i);
- String branchPath = statePath + "/Branches[" + i + "]";
- validateNestedStates(branch.path("States"), branchPath + "/States", branchPath + "/StartAt",
- branch.path("StartAt").asText(null), topLevelJsonata, errors);
+ // Same rule as ItemProcessor above: the branch inherits the machine's language.
+ validateSubWorkflow(branches.path(i), statePath + "/Branches[" + i + "]",
+ topLevelJsonata, errors);
}
}
}
@@ -1978,18 +2059,34 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
+ "' at the top level is not supported. at " + path);
}
- private void validateNestedStates(JsonNode states, String statesPath, String startAtLocation,
- String startAt, boolean inheritedJsonata, List<String> errors) {
+ /**
+ * Validates a Map's {@code ItemProcessor} or {@code Iterator}, or one of a Parallel's
+ * {@code Branches}. {@code inheritedJsonata} is the state machine's query language: a state in
+ * here that declares none defaults to the machine's and not to the enclosing Map's or
+ * Parallel's, which the ASL specification calls independent of it.
+ *
+ * @see <a href="https://states-language.net/spec.html">Amazon States Language, QueryLanguage</a>
+ */
+ private void validateSubWorkflow(JsonNode subWorkflow, String subWorkflowPath,
+ boolean inheritedJsonata, List<String> errors) {
+ // A sub-workflow is not a state and declares no query language of its own.
+ if (subWorkflow.has("QueryLanguage")) {
+ errors.add(EXPLICIT_LOCATION_MARKER + "Field 'QueryLanguage' is not supported"
+ + MARKER_PAYLOAD_SEPARATOR + subWorkflowPath);
+ }
+ JsonNode states = subWorkflow.path("States");
if (!states.isObject()) {
return;
}
+ String statesPath = subWorkflowPath + "/States";
Set<String> stateNames = new HashSet<>();
states.fieldNames().forEachRemaining(stateNames::add);
states.fields().forEachRemaining(entry -> validateState(
statesPath + "/" + entry.getKey(), entry.getValue(), inheritedJsonata, stateNames, errors));
// Unlike the top level, MISSING_END_STATE does not apply here: ItemProcessor and Branches
// are always walked for reachability regardless of whether they have a terminal state.
- validateReachability(statesPath, states, startAt, startAtLocation, errors);
+ validateReachability(statesPath, states, subWorkflow.path("StartAt").asText(null),
+ subWorkflowPath + "/StartAt", errors);
}
private void validateMapConcurrency(String statePath, JsonNode stateDef,
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedQueryLanguageTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedQueryLanguageTest.java
new file mode 100644
index 0000000000..6973bec867
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedQueryLanguageTest.java
@@ -0,0 +1,228 @@
+package io.github.hectorvent.floci.services.stepfunctions;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+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.s3.S3Service;
+import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
+import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
+import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
+import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
+import io.quarkus.test.junit.QuarkusTest;
+import io.vertx.mutiny.core.Vertx;
+import jakarta.enterprise.inject.Instance;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+
+/**
+ * Pins the query language a state inside a Map's {@code ItemProcessor} runs under.
+ *
+ * <p>The Amazon States Language specification resolves it in exactly two levels: "If a Map or
+ * Parallel State has a <code>QueryLanguage</code> field, the default query language for each state
+ * inside the Map's <code>ItemProcessor</code> or the Parallel's <code>Branches</code> fields is the
+ * state machine's query language, and is independent of the Map or Parallel State's query
+ * language." (<a href="https://states-language.net/spec.html">states-language.net/spec.html</a>)
+ *
+ * <p>Each machine below carries both halves in one execution: the Map's own {@code Items} field
+ * uses the Map's declared language, while the bare {@code Pass} inside its {@code ItemProcessor}
+ * applies JSONPath {@code .$} syntax, the state machine's. The outputs are the literals the real
+ * service returned for the same definitions.
+ */
+@QuarkusTest
+class AslExecutorNestedQueryLanguageTest {
+
+ private static final String REGION = "us-east-2";
+ private static final String ACCOUNT = "000000000000";
+ private static final String ITEMS_INPUT = "{\"items\":[{\"n\":1},{\"n\":2}]}";
+ private static final String DOUBLED_ITEMS = "[{\"doubled\":1},{\"doubled\":2}]";
+
+ private final ObjectMapper objectMapper = new ObjectMapper();
+ private AslExecutor executor;
+
+ @Inject
+ Vertx vertx;
+
+ @BeforeEach
+ 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(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),
+ objectMapper,
+ new JsonataEvaluator(objectMapper),
+ mock(Instance.class), mock(EmulatorConfig.class), vertx, null);
+ }
+
+ /**
+ * A JSONata Map over a bare ItemProcessor Pass: the Map evaluates its own {% %} expression and
+ * the Pass still resolves {@code .$}, which exists only in JSONPath, the state machine's.
+ */
+ @Test
+ @Timeout(60)
+ void jsonataMapEvaluatesItsItemsWhileItsItemProcessorPassStaysOnJsonPath() {
+ Execution execution = run("""
+ {
+ "StartAt": "ItemsMap",
+ "States": {
+ "ItemsMap": {
+ "Type": "Map",
+ "QueryLanguage": "JSONata",
+ "Items": "{% $states.input.items %}",
+ "ItemProcessor": {
+ "StartAt": "HelloWorld",
+ "States": {
+ "HelloWorld": {
+ "Type": "Pass",
+ "Parameters": {"doubled.$": "$.n"},
+ "End": true
+ }
+ }
+ },
+ "End": true
+ }
+ }
+ }
+ """);
+
+ assertEquals("SUCCEEDED", execution.getStatus());
+ assertOutputIs(DOUBLED_ITEMS, execution);
+ }
+
+ /**
+ * The same machine with the Map declaring nothing, so the Map's own field is the JSONPath
+ * ItemsPath. The inner Pass is untouched by the difference and produces the same output: the
+ * Map's declaration reaches its own fields and nothing else.
+ */
+ @Test
+ @Timeout(60)
+ void mapDeclaringNothingLeavesTheSameItemProcessorOutput() {
+ Execution execution = run("""
+ {
+ "StartAt": "ItemsMap",
+ "States": {
+ "ItemsMap": {
+ "Type": "Map",
+ "ItemsPath": "$.items",
+ "ItemProcessor": {
+ "StartAt": "HelloWorld",
+ "States": {
+ "HelloWorld": {
+ "Type": "Pass",
+ "Parameters": {"doubled.$": "$.n"},
+ "End": true
+ }
+ }
+ },
+ "End": true
+ }
+ }
+ }
+ """);
+
+ assertEquals("SUCCEEDED", execution.getStatus());
+ assertOutputIs(DOUBLED_ITEMS, execution);
+ }
+
+ /** Two JSONata Maps deep, the innermost bare Pass still applies JSONPath syntax. */
+ @Test
+ @Timeout(60)
+ void innermostPassStaysOnJsonPathUnderTwoJsonataMaps() {
+ Execution execution = run("""
+ {
+ "StartAt": "ItemsMap",
+ "States": {
+ "ItemsMap": {
+ "Type": "Map",
+ "QueryLanguage": "JSONata",
+ "Items": "{% $states.input.items %}",
+ "ItemProcessor": {
+ "StartAt": "SubItemsMap",
+ "States": {
+ "SubItemsMap": {
+ "Type": "Map",
+ "QueryLanguage": "JSONata",
+ "Items": "{% $states.input.subitems %}",
+ "ItemProcessor": {
+ "StartAt": "HelloWorld",
+ "States": {
+ "HelloWorld": {
+ "Type": "Pass",
+ "Parameters": {"doubled.$": "$.n"},
+ "End": true
+ }
+ }
+ },
+ "End": true
+ }
+ }
+ },
+ "End": true
+ }
+ }
+ }
+ """, "{\"items\":[{\"subitems\":[{\"n\":1}]},{\"subitems\":[{\"n\":2}]}]}");
+
+ assertEquals("SUCCEEDED", execution.getStatus());
+ assertOutputIs("[[{\"doubled\":1}],[{\"doubled\":2}]]", execution);
+ }
+
+ private void assertOutputIs(String expectedJson, Execution execution) {
+ try {
+ assertEquals(objectMapper.readTree(expectedJson),
+ objectMapper.readTree(execution.getOutput()),
+ "cause: " + execution.getCause());
+ } catch (JsonProcessingException e) {
+ throw new AssertionError("execution output is not JSON: " + execution.getOutput()
+ + ", cause: " + execution.getCause(), e);
+ }
+ }
+
+ private Execution run(String definition) {
+ return run(definition, ITEMS_INPUT);
+ }
+
+ private Execution run(String definition, String input) {
+ StateMachine stateMachine = new StateMachine();
+ stateMachine.setName("nested-query-language-test");
+ stateMachine.setStateMachineArn(
+ "arn:aws:states:%s:%s:stateMachine:nested-query-language-test"
+ .formatted(REGION, ACCOUNT));
+ stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT));
+ stateMachine.setDefinition(definition);
+
+ Execution execution = new Execution();
+ execution.setName("nested-query-language-execution");
+ execution.setExecutionArn(("arn:aws:states:%s:%s:execution:nested-query-language-test"
+ + ":nested-query-language-execution").formatted(REGION, ACCOUNT));
+ execution.setStateMachineArn(stateMachine.getStateMachineArn());
+ execution.setInput(input);
+ execution.setStatus("RUNNING");
+
+ List<HistoryEvent> history = new ArrayList<>();
+ executor.executeSync(stateMachine, execution, history, (updated, events) -> {
+ });
+ return execution;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsValidateStateMachineDefinitionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsValidateStateMachineDefinitionIntegrationTest.java
index 981060eae2..2b48b60f8a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsValidateStateMachineDefinitionIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsValidateStateMachineDefinitionIntegrationTest.java
@@ -12,6 +12,8 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
+import java.util.List;
+import java.util.Map;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
@@ -320,7 +322,8 @@ class StepFunctionsValidateStateMachineDefinitionIntegrationTest {
.body("diagnostics", hasSize(1))
.body("diagnostics[0].severity", equalTo("ERROR"))
.body("diagnostics[0].code", equalTo("SCHEMA_VALIDATION_FAILED"))
- .body("diagnostics[0].location", equalTo("/States/X/InputPath"));
+ // AWS locates this message family at the state, with no field suffix.
+ .body("diagnostics[0].location", equalTo("/States/X"));
}
@Test
@@ -361,7 +364,8 @@ class StepFunctionsValidateStateMachineDefinitionIntegrationTest {
.then().statusCode(200)
.body("result", equalTo("FAIL"))
.body("diagnostics", hasSize(1))
- .body("diagnostics[0].location", equalTo("/States/M/MaxConcurrencyPath"));
+ // Measured on AWS: /States/M, the state, not the field.
+ .body("diagnostics[0].location", equalTo("/States/M"));
}
@Test
@@ -1206,6 +1210,598 @@ class StepFunctionsValidateStateMachineDefinitionIntegrationTest {
+ "at /States/P'"));
}
+ // ─────────────── QueryLanguage compatibility, measured against real AWS ───────────────
+ // Output, Arguments and Items exist only in JSONata. AWS rejects each of them on a JSONPath
+ // state with "The QueryLanguage is set to 'JSONPath', but field '<f>' is only supported for
+ // the 'JSONata' QueryLanguage", located at the state and not at the field.
+
+ private static final String JSONATA_ONLY_FIELD_ON_A_JSONPATH_STATE =
+ "The QueryLanguage is set to 'JSONPath', but field '%s' is only supported "
+ + "for the 'JSONata' QueryLanguage";
+ private static final String JSONPATH_ONLY_FIELD_ON_A_JSONATA_STATE =
+ "The QueryLanguage is set to 'JSONata', but field '%s' is only supported "
+ + "for the 'JSONPath' QueryLanguage";
+
+ /**
+ * A Map's own QueryLanguage is inert for the states inside its ItemProcessor: on AWS the two
+ * definitions below fail identically, so the equality of the two diagnostic lists is the
+ * assertion. A change that propagated the Map's language into ItemProcessor would separate
+ * them.
+ */
+ @Test
+ void mapDeclaringJsonataLeavesItsItemProcessorStateOnTheMachinesJsonPath() {
+ List<Map<String, Object>> whenTheMapDeclaresJsonata =
+ diagnosticsOf(mapOverAPassCarryingOutput("\"QueryLanguage\":\"JSONata\","));
+ List<Map<String, Object>> whenTheMapDeclaresNothing =
+ diagnosticsOf(mapOverAPassCarryingOutput(""));
+
+ Assertions.assertEquals(whenTheMapDeclaresNothing, whenTheMapDeclaresJsonata,
+ "the Map's QueryLanguage must not reach the states inside its ItemProcessor");
+ assertOutputRefusedOnTheItemProcessorPass(whenTheMapDeclaresJsonata, "the Map declares JSONata");
+ assertOutputRefusedOnTheItemProcessorPass(whenTheMapDeclaresNothing, "the Map declares nothing");
+ }
+
+ /**
+ * The literal shape both sides of the pair are held to. Asserted on each list separately, so
+ * neither side is pinned only by the other: two runs agreeing on the wrong answer is what the
+ * equality above cannot see.
+ */
+ private static void assertOutputRefusedOnTheItemProcessorPass(
+ List<Map<String, Object>> diagnostics, String when) {
+ Assertions.assertEquals(1, diagnostics.size(),
+ "expected exactly one diagnostic when " + when + ", got " + diagnostics);
+ Map<String, Object> diagnostic = diagnostics.get(0);
+ Assertions.assertEquals("ERROR", diagnostic.get("severity"), when);
+ Assertions.assertEquals("SCHEMA_VALIDATION_FAILED", diagnostic.get("code"), when);
+ Assertions.assertEquals(JSONATA_ONLY_FIELD_ON_A_JSONPATH_STATE.formatted("Output"),
+ diagnostic.get("message"), when);
+ Assertions.assertEquals("/States/M/ItemProcessor/States/P", diagnostic.get("location"), when);
+ }
+
+ @Test
+ void parallelDeclaringJsonataLeavesItsBranchStateOnTheMachinesJsonPath() {
+ String def = """
+ {"QueryLanguage":"JSONPath","StartAt":"PAR","States":{
+ "PAR":{"Type":"Parallel","QueryLanguage":"JSONata",
+ "Branches":[{"StartAt":"P","States":{
+ "P":{"Type":"Pass","Output":{"doubled":"{% $states.input.n * 2 %}"},"End":true}}}],
+ "End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].code", equalTo("SCHEMA_VALIDATION_FAILED"))
+ .body("diagnostics[0].message",
+ equalTo(JSONATA_ONLY_FIELD_ON_A_JSONPATH_STATE.formatted("Output")))
+ .body("diagnostics[0].location", equalTo("/States/PAR/Branches[0]/States/P"));
+ }
+
+ @Test
+ void jsonPathStateRejectsArguments() {
+ String def = """
+ {"StartAt":"T","States":{
+ "T":{"Type":"Task","Resource":"arn:aws:states:::lambda:invoke",
+ "Arguments":{"payload":"literal"},"End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].message",
+ equalTo(JSONATA_ONLY_FIELD_ON_A_JSONPATH_STATE.formatted("Arguments")))
+ .body("diagnostics[0].location", equalTo("/States/T"));
+ }
+
+ @Test
+ void jsonPathMapRejectsItems() {
+ String def = """
+ {"StartAt":"M","States":{
+ "M":{"Type":"Map","Items":[{"n":1}],
+ "ItemProcessor":{"StartAt":"P","States":{"P":{"Type":"Pass","End":true}}},
+ "End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].message",
+ equalTo(JSONATA_ONLY_FIELD_ON_A_JSONPATH_STATE.formatted("Items")))
+ .body("diagnostics[0].location", equalTo("/States/M"));
+ }
+
+ /** AWS accepts Assign on a JSONPath state, so it is not a JSONata-only field. */
+ @Test
+ void jsonPathStateAcceptsAssign() {
+ String def = """
+ {"StartAt":"X","States":{
+ "X":{"Type":"Pass","Assign":{"counter":1},"End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("OK"))
+ .body("diagnostics", hasSize(0));
+ }
+
+ /** The Map's own fields do use the Map's own language. */
+ @Test
+ void jsonataMapAcceptsOutputOnItself() {
+ String def = """
+ {"QueryLanguage":"JSONPath","StartAt":"M","States":{
+ "M":{"Type":"Map","QueryLanguage":"JSONata","Items":"{% [1, 2] %}",
+ "Output":{"count":"{% $count($states.result) %}"},
+ "ItemProcessor":{"StartAt":"P","States":{"P":{"Type":"Pass","End":true}}},
+ "End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("OK"))
+ .body("diagnostics", hasSize(0));
+ }
+
+ /** An explicit declaration on the state itself still wins, at any depth. */
+ @Test
+ void itemProcessorStateDeclaringJsonataAcceptsOutput() {
+ String def = """
+ {"QueryLanguage":"JSONPath","StartAt":"M","States":{
+ "M":{"Type":"Map","QueryLanguage":"JSONata","Items":"{% [1, 2] %}",
+ "ItemProcessor":{"StartAt":"P","States":{
+ "P":{"Type":"Pass","QueryLanguage":"JSONata",
+ "Output":{"doubled":"{% $states.input * 2 %}"},"End":true}}},
+ "End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("OK"))
+ .body("diagnostics", hasSize(0));
+ }
+
+ // A JSONata state machine cannot be reverted to JSONPath state by state, and the ItemProcessor
+ // or branch object is not a state: it carries no QueryLanguage of its own. Both measured.
+
+ @Test
+ void stateCannotDeclareJsonPathUnderAJsonataStateMachine() {
+ String def = """
+ {"QueryLanguage":"JSONata","StartAt":"M","States":{
+ "M":{"Type":"Map","QueryLanguage":"JSONPath",
+ "ItemProcessor":{"StartAt":"P","States":{"P":{"Type":"Pass","End":true}}},
+ "End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].severity", equalTo("ERROR"))
+ .body("diagnostics[0].code", equalTo("SCHEMA_VALIDATION_FAILED"))
+ .body("diagnostics[0].message", equalTo("'QueryLanguage' can not be 'JSONPath' "
+ + "if set to 'JSONata' for whole state machine"))
+ .body("diagnostics[0].location", equalTo("/States/M"));
+ }
+
+ /** The guard reads the machine's language, not the mere presence of the field. */
+ @Test
+ void stateMayDeclareJsonPathUnderAJsonPathStateMachine() {
+ String def = """
+ {"StartAt":"X","States":{
+ "X":{"Type":"Pass","QueryLanguage":"JSONPath","InputPath":"$.a","End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("OK"))
+ .body("diagnostics", hasSize(0));
+ }
+
+ @Test
+ void stateMayDeclareJsonataUnderAJsonataStateMachine() {
+ String def = """
+ {"QueryLanguage":"JSONata","StartAt":"X","States":{
+ "X":{"Type":"Pass","QueryLanguage":"JSONata","Output":{"v":"{% 1 %}"},"End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("OK"))
+ .body("diagnostics", hasSize(0));
+ }
+
+ @Test
+ void itemProcessorCannotDeclareQueryLanguage() {
+ String def = """
+ {"StartAt":"M","States":{
+ "M":{"Type":"Map",
+ "ItemProcessor":{"QueryLanguage":"JSONata","StartAt":"P",
+ "States":{"P":{"Type":"Pass","End":true}}},
+ "End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].code", equalTo("SCHEMA_VALIDATION_FAILED"))
+ .body("diagnostics[0].message", equalTo("Field 'QueryLanguage' is not supported"))
+ .body("diagnostics[0].location", equalTo("/States/M/ItemProcessor"));
+ }
+
+ @Test
+ void parallelBranchCannotDeclareQueryLanguage() {
+ String def = """
+ {"StartAt":"PAR","States":{
+ "PAR":{"Type":"Parallel",
+ "Branches":[{"QueryLanguage":"JSONata","StartAt":"P",
+ "States":{"P":{"Type":"Pass","End":true}}}],
+ "End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].message", equalTo("Field 'QueryLanguage' is not supported"))
+ .body("diagnostics[0].location", equalTo("/States/PAR/Branches[0]"));
+ }
+
+ // ─────────── The downgrade suppresses only the field check, and only for that state ───────────
+
+ private static final String QUERY_LANGUAGE_DOWNGRADED =
+ "'QueryLanguage' can not be 'JSONPath' if set to 'JSONata' for whole state machine";
+
+ /**
+ * Measured on AWS: the downgrade is the whole answer. The {@code Output} that the state's own
+ * JSONPath forbids is not reported on top of it, so the mixing guard suppresses the
+ * other-language field check for that state.
+ */
+ @Test
+ void downgradedStateReportsTheMixingDiagnosticAndNothingAboutItsOutput() {
+ String def = """
+ {"QueryLanguage":"JSONata","StartAt":"X","States":{
+ "X":{"Type":"Pass","QueryLanguage":"JSONPath","Output":{"v":"{% 1 %}"},"End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].code", equalTo("SCHEMA_VALIDATION_FAILED"))
+ .body("diagnostics[0].message", equalTo(QUERY_LANGUAGE_DOWNGRADED))
+ .body("diagnostics[0].location", equalTo("/States/X"));
+ }
+
+ /**
+ * The suppression is scoped to the other-language field check. Measured on AWS: the same
+ * downgrade on a Map with a negative MaxConcurrency returns the mixing diagnostic and the range
+ * error together. AWS words the range error {@code Minimum value is 0}; this emulator's own
+ * wording predates this change and is not what this test is about.
+ */
+ @Test
+ void downgradedMapStillHasItsMaxConcurrencyValidated() {
+ String def = """
+ {"QueryLanguage":"JSONata","StartAt":"M","States":{
+ "M":{"Type":"Map","QueryLanguage":"JSONPath","MaxConcurrency":-1,
+ "ItemProcessor":{"StartAt":"P","States":{"P":{"Type":"Pass","End":true}}},
+ "End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(2))
+ .body("diagnostics[0].message", equalTo(QUERY_LANGUAGE_DOWNGRADED))
+ .body("diagnostics[0].location", equalTo("/States/M"))
+ .body("diagnostics[1].message",
+ equalTo("The field 'MaxConcurrency' must be a non-negative integer"))
+ .body("diagnostics[1].location", equalTo("/States/M/MaxConcurrency"));
+ }
+
+ // ─────────── A QueryLanguage outside the enum, measured against real AWS ───────────
+ // AWS does two independent things with it: it reports the value against the enum, at the field
+ // and not at the state, and it still resolves the effective language case-insensitively.
+
+ private static final String QUERY_LANGUAGE_OUTSIDE_THE_ENUM =
+ "Value should be one of the following: [JSONPath, JSONata]";
+
+ @Test
+ void lowercaseJsonataOnAStateResolvesToJsonataAndIsStillReportedAgainstTheEnum() {
+ String def = """
+ {"StartAt":"X","States":{
+ "X":{"Type":"Pass","QueryLanguage":"jsonata","Output":{"v":"{% 1 %}"},
+ "InputPath":"$.a","End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(2))
+ // The state resolved to JSONata, so InputPath is the offending field and Output is
+ // not mentioned at all.
+ .body("diagnostics[0].message", equalTo("The QueryLanguage is set to 'JSONata', "
+ + "but field 'InputPath' is only supported for the 'JSONPath' QueryLanguage"))
+ .body("diagnostics[0].location", equalTo("/States/X"))
+ .body("diagnostics[1].code", equalTo("SCHEMA_VALIDATION_FAILED"))
+ .body("diagnostics[1].message", equalTo(QUERY_LANGUAGE_OUTSIDE_THE_ENUM))
+ .body("diagnostics[1].location", equalTo("/States/X/QueryLanguage"));
+ }
+
+ @Test
+ void lowercaseJsonataUnderAJsonataMachineReportsOnlyTheEnumError() {
+ String def = """
+ {"QueryLanguage":"JSONata","StartAt":"X","States":{
+ "X":{"Type":"Pass","QueryLanguage":"jsonata","Output":{"v":"{% 1 %}"},"End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].message", equalTo(QUERY_LANGUAGE_OUTSIDE_THE_ENUM))
+ .body("diagnostics[0].location", equalTo("/States/X/QueryLanguage"));
+ }
+
+ @Test
+ void topLevelQueryLanguageOutsideTheEnumIsReportedAtItsOwnField() {
+ String def = """
+ {"QueryLanguage":"jsonata","StartAt":"X","States":{
+ "X":{"Type":"Pass","Output":{"v":"{% 1 %}"},"End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].message", equalTo(QUERY_LANGUAGE_OUTSIDE_THE_ENUM))
+ .body("diagnostics[0].location", equalTo("/QueryLanguage"));
+ }
+
+ @Test
+ void nonStringTopLevelQueryLanguageIsReportedAsATypeError() {
+ String def = """
+ {"QueryLanguage":5,"StartAt":"X","States":{"X":{"Type":"Pass","End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].message", equalTo("Expected value of type [STRING]"))
+ .body("diagnostics[0].location", equalTo("/QueryLanguage"));
+ }
+
+ // ─────────── What a value outside the enum resolves to, measured against real AWS ───────────
+ // The effective language is JSONPath only when the field is exactly "JSONPath". Absent, it is
+ // inherited; present and anything else, wrong case, unknown string and non-string alike, the
+ // state is JSONata. The enum and type diagnostics are independent of that resolution.
+
+ @Test
+ void unrecognisedQueryLanguageOnAStateResolvesToJsonataAndRejectsInputPath() {
+ String def = """
+ {"StartAt":"X","States":{
+ "X":{"Type":"Pass","QueryLanguage":"foo","InputPath":"$.a","End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(2))
+ .body("diagnostics[0].message",
+ equalTo(JSONPATH_ONLY_FIELD_ON_A_JSONATA_STATE.formatted("InputPath")))
+ .body("diagnostics[0].location", equalTo("/States/X"))
+ .body("diagnostics[1].message", equalTo(QUERY_LANGUAGE_OUTSIDE_THE_ENUM))
+ .body("diagnostics[1].location", equalTo("/States/X/QueryLanguage"));
+ }
+
+ @Test
+ void unrecognisedQueryLanguageOnAStateAcceptsOutput() {
+ String def = """
+ {"StartAt":"X","States":{
+ "X":{"Type":"Pass","QueryLanguage":"foo","Output":{"v":"{% 1 %}"},"End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].message", equalTo(QUERY_LANGUAGE_OUTSIDE_THE_ENUM))
+ .body("diagnostics[0].location", equalTo("/States/X/QueryLanguage"));
+ }
+
+ /**
+ * Only the exact string is a downgrade. {@code "jsonpath"} resolves to JSONata, so there is
+ * nothing to report but the spelling, and the mixing diagnostic must not appear.
+ */
+ @Test
+ void lowercaseJsonPathUnderAJsonataMachineIsNotADowngrade() {
+ String def = """
+ {"QueryLanguage":"JSONata","StartAt":"X","States":{
+ "X":{"Type":"Pass","QueryLanguage":"jsonpath","End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].message", equalTo(QUERY_LANGUAGE_OUTSIDE_THE_ENUM))
+ .body("diagnostics[0].location", equalTo("/States/X/QueryLanguage"));
+ }
+
+ @Test
+ void lowercaseTopLevelQueryLanguageResolvesToJsonataAndAcceptsOutput() {
+ String def = """
+ {"QueryLanguage":"jsonpath","StartAt":"X","States":{
+ "X":{"Type":"Pass","Output":{"v":"{% 1 %}"},"End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].message", equalTo(QUERY_LANGUAGE_OUTSIDE_THE_ENUM))
+ .body("diagnostics[0].location", equalTo("/QueryLanguage"));
+ }
+
+ @Test
+ void lowercaseTopLevelQueryLanguageResolvesToJsonataAndRejectsInputPath() {
+ String def = """
+ {"QueryLanguage":"jsonpath","StartAt":"X","States":{
+ "X":{"Type":"Pass","InputPath":"$.a","End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(2))
+ .body("diagnostics[0].message", equalTo(QUERY_LANGUAGE_OUTSIDE_THE_ENUM))
+ .body("diagnostics[0].location", equalTo("/QueryLanguage"))
+ .body("diagnostics[1].message",
+ equalTo(JSONPATH_ONLY_FIELD_ON_A_JSONATA_STATE.formatted("InputPath")))
+ .body("diagnostics[1].location", equalTo("/States/X"));
+ }
+
+ @Test
+ void nonStringQueryLanguageOnAStateResolvesToJsonataAndRejectsInputPath() {
+ String def = """
+ {"StartAt":"X","States":{
+ "X":{"Type":"Pass","QueryLanguage":5,"InputPath":"$.a","End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(2))
+ .body("diagnostics[0].message",
+ equalTo(JSONPATH_ONLY_FIELD_ON_A_JSONATA_STATE.formatted("InputPath")))
+ .body("diagnostics[0].location", equalTo("/States/X"))
+ .body("diagnostics[1].message", equalTo("Expected value of type [STRING]"))
+ .body("diagnostics[1].location", equalTo("/States/X/QueryLanguage"));
+ }
+
+ // ─────────── One state, two disallowed fields: the emission order is fixed ───────────
+ // The order below is not AWS-observable, it is the one this validator commits to. What matters
+ // is that it is the same on every JVM: a salted iteration order makes a maxResults=1 caller
+ // receive a different diagnostic on each run.
+
+ @Test
+ void twoJsonataOnlyFieldsOnAJsonPathStateEmitInTheOrderTheListDeclares() {
+ String def = """
+ {"StartAt":"T","States":{
+ "T":{"Type":"Task","Resource":"arn:aws:states:::lambda:invoke",
+ "Output":{"v":1},"Arguments":{"payload":"literal"},"End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(2))
+ .body("diagnostics[0].message",
+ equalTo(JSONATA_ONLY_FIELD_ON_A_JSONPATH_STATE.formatted("Output")))
+ .body("diagnostics[0].location", equalTo("/States/T"))
+ .body("diagnostics[1].message",
+ equalTo(JSONATA_ONLY_FIELD_ON_A_JSONPATH_STATE.formatted("Arguments")))
+ .body("diagnostics[1].location", equalTo("/States/T"));
+ }
+
+ @Test
+ void threeJsonPathOnlyFieldsOnAJsonataStateEmitInTheOrderTheListDeclares() {
+ String def = """
+ {"QueryLanguage":"JSONata","StartAt":"X","States":{
+ "X":{"Type":"Pass","InputPath":"$.a","OutputPath":"$.b","ResultPath":"$.c",
+ "End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(3))
+ .body("diagnostics[0].message",
+ equalTo(JSONPATH_ONLY_FIELD_ON_A_JSONATA_STATE.formatted("InputPath")))
+ .body("diagnostics[1].message",
+ equalTo(JSONPATH_ONLY_FIELD_ON_A_JSONATA_STATE.formatted("OutputPath")))
+ .body("diagnostics[2].message",
+ equalTo(JSONPATH_ONLY_FIELD_ON_A_JSONATA_STATE.formatted("ResultPath")));
+ }
+
+ // ─────────── The legacy Iterator spelling, and a bare ItemProcessor Pass ───────────
+
+ /** Measured on AWS: Iterator carries no QueryLanguage either, and the location names Iterator. */
+ @Test
+ void legacyIteratorCannotDeclareQueryLanguage() {
+ String def = """
+ {"StartAt":"M","States":{
+ "M":{"Type":"Map",
+ "Iterator":{"QueryLanguage":"JSONata","StartAt":"P",
+ "States":{"P":{"Type":"Pass","End":true}}},
+ "End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("FAIL"))
+ .body("diagnostics", hasSize(1))
+ .body("diagnostics[0].code", equalTo("SCHEMA_VALIDATION_FAILED"))
+ .body("diagnostics[0].message", equalTo("Field 'QueryLanguage' is not supported"))
+ .body("diagnostics[0].location", equalTo("/States/M/Iterator"));
+ }
+
+ /** The control: the same Iterator without the field is accepted, as AWS accepts it. */
+ @Test
+ void legacyIteratorWithoutQueryLanguageIsAccepted() {
+ String def = """
+ {"StartAt":"M","States":{
+ "M":{"Type":"Map",
+ "Iterator":{"StartAt":"P","States":{"P":{"Type":"Pass","End":true}}},
+ "End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("OK"))
+ .body("diagnostics", hasSize(0));
+ }
+
+ /**
+ * A JSONata machine, a Map declaring nothing, an ItemProcessor Pass declaring nothing and
+ * carrying Output: the inner state inherits the machine's JSONata, so AWS accepts it. The
+ * mirror of {@link #mapDeclaringJsonataLeavesItsItemProcessorStateOnTheMachinesJsonPath} from
+ * the other side of the two-level rule.
+ */
+ @Test
+ void jsonataMachineAcceptsOutputOnABareItemProcessorPass() {
+ String def = """
+ {"QueryLanguage":"JSONata","StartAt":"M","States":{
+ "M":{"Type":"Map",
+ "ItemProcessor":{"StartAt":"P","States":{
+ "P":{"Type":"Pass","Output":{"doubled":"{% $states.input.n * 2 %}"},
+ "End":true}}},
+ "End":true}}}
+ """;
+
+ validateDefinition(def)
+ .then().statusCode(200)
+ .body("result", equalTo("OK"))
+ .body("diagnostics", hasSize(0));
+ }
+
+ private static String mapOverAPassCarryingOutput(String mapQueryLanguage) {
+ return """
+ {"QueryLanguage":"JSONPath","StartAt":"M","States":{
+ "M":{"Type":"Map",__MAP_QUERY_LANGUAGE__
+ "ItemProcessor":{"StartAt":"P","States":{
+ "P":{"Type":"Pass","Output":{"doubled":"{% $states.input.n * 2 %}"},"End":true}}},
+ "End":true}}}
+ """.replace("__MAP_QUERY_LANGUAGE__", mapQueryLanguage);
+ }
+
+ private static List<Map<String, Object>> diagnosticsOf(String definition) {
+ return validateDefinition(definition).jsonPath().getList("diagnostics");
+ }
+
private static String mapDefinition(String topLevelFields, String concurrencyFields) {
return "{" + topLevelFields
+ "\"StartAt\":\"M\",\"States\":{\"M\":{\"Type\":\"Map\","