mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(stepfunctions): refuse the definitions AWS refuses, at both validation entry points (#2786)
* fix(stepfunctions): reject definitions with no terminal state, dangling targets or unsupported fields Enforce the ASL rules AWS applies at both ValidateStateMachineDefinition and CreateStateMachine: a workflow needs a terminal state (MISSING_END_STATE, top-level only, suppressing the unreachable-state reachability check but not a dangling-target check), every reachable state and every Next/Choices[].Next/Default/Catch[].Next target must exist (MISSING_TRANSITION_TARGET), recursing into ItemProcessor and Branches with structured paths, and TimeoutSeconds/Catch/Retry are refused outside the state types that support them (SCHEMA_VALIDATION_FAILED, "Field '<name>' is not supported"). CreateStateMachine's wire message always renders " at <location>", printing the literal "null" when there is none, matching AWS exactly; ValidateStateMachineDefinition keeps omitting the location field entirely when null, which is the correct, unchanged behavior for that API. Remove the now-dead Parallel TimeoutSeconds handling in AslExecutor: no definition carrying that field can reach execution anymore. * fix(stepfunctions): reject JSONata expressions that do not parse at definition time Report INVALID_JSONATA_EXPRESSION when a JSONata expression fails to parse, using the parser's own message with its S0xxx code prefix stripped, at the field's location. Also report UNSUPPORTED_JSONATA_EXPRESSION for '$$' and for '$states.errorOutput' outside a Catch entry's own Output or Assign. Previously these were accepted at ValidateStateMachineDefinition and CreateStateMachine time and only failed later, at execution, with States.QueryEvaluationError. Every message asserted was measured against real AWS us-east-1 with `aws stepfunctions validate-state-machine-definition`, including `phone %.other` and the empty expression, which AWS also refuses. The three booleans the definition walk threaded through every recursive call (insidePayload, isCatchEntry, insideCatchOutputOrAssign) travel as a single JsonataScope value, which drops collectTopLevelReferences back under the Sonar S3776 limit. --------- Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
This commit is contained in:
1 parent
9f7b7117f1
commit
ead70eae4d
7 files changed
+1038
-89
No files matched your search
+61
-16
@@ -2,7 +2,6 @@ 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;
|
||||
@@ -14,7 +13,8 @@ import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Names every reference a Step Functions JSONata expression makes against the top-level context.
|
||||
* Parses a Step Functions JSONata expression once and reports either the message the parser refused
|
||||
* it with, or every reference it 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
|
||||
@@ -39,11 +39,20 @@ import java.util.Set;
|
||||
@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 = "$";
|
||||
|
||||
/** The pseudo-reference reported for {@code $$}, AWS's separate name rule. */
|
||||
static final String ROOT_REFERENCE = "$$";
|
||||
|
||||
/**
|
||||
* The pseudo-reference reported for a {@code $states.errorOutput} path, wherever it starts.
|
||||
* Not a top-level context read like the others: {@code $states} is always in scope, but the
|
||||
* {@code errorOutput} field only exists on it inside a {@code Catch} entry's own {@code Output}
|
||||
* and {@code Assign}, and only the caller knows whether the walk is there.
|
||||
*/
|
||||
static final String STATES_ERROR_OUTPUT = "$states.errorOutput";
|
||||
|
||||
private static final Map<String, Field> TREE_FIELDS = resolveTreeFields(
|
||||
"type", "value", "steps", "lhs", "rhs", "expression", "expressions",
|
||||
"procedure", "arguments", "body", "condition", "then", "_else");
|
||||
@@ -52,22 +61,32 @@ final class 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.
|
||||
* What parsing {@code expression} once finds: either the parser's own message, unchanged
|
||||
* (AWS's {@code INVALID_JSONATA_EXPRESSION} refuses it with the same sentence, its
|
||||
* {@code S0xxx: } code prefix stripped, and {@link com.dashjoin.jsonata.JException#getMessage()}
|
||||
* never carries that prefix), or the distinct top-level references the expression makes, in
|
||||
* the order they are written.
|
||||
*/
|
||||
static List<String> in(String expression) {
|
||||
record Analysis(List<String> topLevelReferences, String parseError) {
|
||||
static Analysis parseError(String message) {
|
||||
return new Analysis(List.of(), message);
|
||||
}
|
||||
|
||||
static Analysis references(List<String> names) {
|
||||
return new Analysis(names, null);
|
||||
}
|
||||
}
|
||||
|
||||
static Analysis analyze(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();
|
||||
return Analysis.parseError(e.getMessage());
|
||||
}
|
||||
Set<String> names = new LinkedHashSet<>();
|
||||
collect(root, names);
|
||||
return new ArrayList<>(names);
|
||||
return Analysis.references(new ArrayList<>(names));
|
||||
}
|
||||
|
||||
private static void collect(Parser.Symbol node, Set<String> names) {
|
||||
@@ -76,7 +95,12 @@ final class JsonataTopLevelReferences {
|
||||
return;
|
||||
}
|
||||
switch (type) {
|
||||
case "path" -> collect(first(node, "steps"), names);
|
||||
case "path" -> {
|
||||
collect(first(node, "steps"), names);
|
||||
if (isStatesErrorOutputPath(node)) {
|
||||
names.add(STATES_ERROR_OUTPUT);
|
||||
}
|
||||
}
|
||||
case "name" -> names.add(String.valueOf(read(node, "value")));
|
||||
case "variable" -> collectContextItem(node, names);
|
||||
case "unary" -> collectUnary(node, names);
|
||||
@@ -105,15 +129,36 @@ final class JsonataTopLevelReferences {
|
||||
|
||||
/**
|
||||
* {@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.
|
||||
* name {@code "$"} and AWS refuses it too, under a different message. 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"))) {
|
||||
String value = String.valueOf(read(variable, "value"));
|
||||
if (value.isEmpty()) {
|
||||
names.add(CONTEXT_ITEM);
|
||||
} else if (CONTEXT_ITEM.equals(value)) {
|
||||
// "$$" parses as a variable named "$": the sigil is consumed twice, once as the
|
||||
// variable marker and once as its name.
|
||||
names.add(ROOT_REFERENCE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code path}'s first step is {@code $states} and its second is {@code errorOutput}.
|
||||
* Only those two steps matter: whatever follows ({@code $states.errorOutput.Cause}) still reads
|
||||
* the same field on {@code $states} first.
|
||||
*/
|
||||
private static boolean isStatesErrorOutputPath(Parser.Symbol path) {
|
||||
List<Parser.Symbol> steps = children(path, "steps");
|
||||
if (steps == null || steps.size() < 2) {
|
||||
return false;
|
||||
}
|
||||
Parser.Symbol first = steps.get(0);
|
||||
Parser.Symbol second = steps.get(1);
|
||||
return "variable".equals(read(first, "type")) && "states".equals(read(first, "value"))
|
||||
&& "name".equals(read(second, "type")) && "errorOutput".equals(read(second, "value"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
+285
-42
@@ -83,6 +83,18 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
private static final String RESULT_WRITER_RESOURCE = "arn:aws:states:::s3:putObject";
|
||||
private static final Set<String> RESULT_WRITER_TRANSFORMATIONS = Set.of("NONE", "COMPACT", "FLATTEN");
|
||||
private static final Set<String> RESULT_WRITER_OUTPUT_TYPES = Set.of("JSON", "JSONL");
|
||||
// Measured against real AWS: TimeoutSeconds is accepted on Task only, Catch and Retry are
|
||||
// accepted on Task, Parallel and Map only. Every other state type refuses these fields with
|
||||
// "Field '<name>' is not supported". A List, not a Map.of: Map.of's iteration order is salted
|
||||
// per JVM, so a state carrying more than one disallowed field needs a fixed emission order
|
||||
// instead. TimeoutSeconds, Catch, Retry is not an AWS-observed order — field declaration order
|
||||
// is not observable in the response — it is simply the one this code commits to.
|
||||
private record FieldStateTypeRule(String field, Set<String> allowedTypes) {}
|
||||
|
||||
private static final List<FieldStateTypeRule> FIELDS_ALLOWED_STATE_TYPES = List.of(
|
||||
new FieldStateTypeRule("TimeoutSeconds", Set.of("Task")),
|
||||
new FieldStateTypeRule("Catch", Set.of("Task", "Parallel", "Map")),
|
||||
new FieldStateTypeRule("Retry", Set.of("Task", "Parallel", "Map")));
|
||||
|
||||
@Inject
|
||||
public StepFunctionsService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
@@ -1140,6 +1152,15 @@ 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:";
|
||||
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
|
||||
// (a state name, a JSONata parser message) past its flat-string marker without re-parsing free
|
||||
// text; SOH cannot appear in a state name or in JSONata parser output.
|
||||
private static final String DANGLING_TARGET_MARKER = "DANGLING_TARGET:";
|
||||
private static final char MARKER_PAYLOAD_SEPARATOR = '\u0001';
|
||||
private static final String INVALID_JSONATA_MARKER = "INVALID_JSONATA_EXPRESSION:";
|
||||
|
||||
// Parse the structured location out of validator flat error strings,
|
||||
// which currently encode it as "...field 'X' ... at /States/Y".
|
||||
@@ -1213,7 +1234,34 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
error.substring(PARSE_ERROR_MARKER.length()).trim(), null);
|
||||
}
|
||||
if (error.startsWith(UNSUPPORTED_JSONATA_MARKER)) {
|
||||
return toJsonataDiagnostic(error.substring(UNSUPPORTED_JSONATA_MARKER.length()).trim());
|
||||
return toJsonataDiagnostic("UNSUPPORTED_JSONATA_EXPRESSION",
|
||||
error.substring(UNSUPPORTED_JSONATA_MARKER.length()).trim());
|
||||
}
|
||||
if (error.startsWith(INVALID_JSONATA_MARKER)) {
|
||||
String payload = error.substring(INVALID_JSONATA_MARKER.length());
|
||||
int separator = payload.indexOf(MARKER_PAYLOAD_SEPARATOR);
|
||||
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.equals(MISSING_END_STATE_MARKER)) {
|
||||
return new Diagnostic("ERROR", "MISSING_END_STATE", "Workflow has no terminal state", null);
|
||||
}
|
||||
if (error.startsWith(UNREACHABLE_STATE_MARKER)) {
|
||||
String payload = error.substring(UNREACHABLE_STATE_MARKER.length());
|
||||
int separator = payload.indexOf(MARKER_PAYLOAD_SEPARATOR);
|
||||
return new Diagnostic("ERROR", "MISSING_TRANSITION_TARGET",
|
||||
"State \"" + payload.substring(0, separator) + "\" is not reachable.",
|
||||
payload.substring(separator + 1));
|
||||
}
|
||||
if (error.startsWith(DANGLING_TARGET_MARKER)) {
|
||||
String payload = error.substring(DANGLING_TARGET_MARKER.length());
|
||||
int separator = payload.indexOf(MARKER_PAYLOAD_SEPARATOR);
|
||||
return new Diagnostic("ERROR", "MISSING_TRANSITION_TARGET",
|
||||
"Missing 'Next' target: " + payload.substring(0, separator),
|
||||
payload.substring(separator + 1));
|
||||
}
|
||||
String message = error;
|
||||
String location = null;
|
||||
@@ -1232,15 +1280,25 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
return new Diagnostic("ERROR", "SCHEMA_VALIDATION_FAILED", message, location);
|
||||
}
|
||||
|
||||
private static Diagnostic toJsonataDiagnostic(String message) {
|
||||
private static Diagnostic toJsonataDiagnostic(String code, 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", code, message, null);
|
||||
}
|
||||
return new Diagnostic("ERROR", "UNSUPPORTED_JSONATA_EXPRESSION",
|
||||
return new Diagnostic("ERROR", code,
|
||||
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)
|
||||
@@ -1492,17 +1550,28 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
"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))
|
||||
// own rather than folded into the rest.
|
||||
List<String> nonJsonataErrors = errors.stream()
|
||||
.filter(error -> !error.startsWith(UNSUPPORTED_JSONATA_MARKER)
|
||||
&& !error.startsWith(INVALID_JSONATA_MARKER))
|
||||
.toList();
|
||||
if (schemaErrors.isEmpty()) {
|
||||
if (nonJsonataErrors.isEmpty()) {
|
||||
throw new AwsException("InvalidDefinition",
|
||||
"Invalid State Machine Definition: '" + first + "'", 400);
|
||||
"Invalid State Machine Definition: '" + flatten(toDiagnostic(first)) + "'", 400);
|
||||
}
|
||||
throw new AwsException("InvalidDefinition",
|
||||
"Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED: "
|
||||
+ String.join(", ", schemaErrors) + "'", 400);
|
||||
"Invalid State Machine Definition: '"
|
||||
+ String.join(", ", nonJsonataErrors.stream()
|
||||
.map(error -> flatten(toDiagnostic(error))).toList())
|
||||
+ "'", 400);
|
||||
}
|
||||
|
||||
// Renders one diagnostic back to a flat string for the CreateStateMachine wire message:
|
||||
// "<code>: <message> at <location>". Unlike ValidateStateMachineDefinition, which omits
|
||||
// location entirely when there is none, AWS's CreateStateMachine always renders the suffix,
|
||||
// printing the literal "null" for a diagnostic with no location — measured against real AWS.
|
||||
private static String flatten(Diagnostic diagnostic) {
|
||||
return diagnostic.code() + ": " + diagnostic.message() + " at " + diagnostic.location();
|
||||
}
|
||||
|
||||
private List<String> collectValidationErrors(String definition) {
|
||||
@@ -1533,23 +1602,135 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
errors.add("The field 'States' is required and must be a non-empty object");
|
||||
return errors;
|
||||
}
|
||||
if (startAt != null && !startAt.isBlank() && !states.has(startAt)) {
|
||||
errors.add("The value of 'StartAt' must match a state in 'States'");
|
||||
}
|
||||
|
||||
String topLevelQL = def.path("QueryLanguage").asText("JSONPath");
|
||||
boolean topLevelJsonata = "JSONata".equals(topLevelQL);
|
||||
|
||||
Set<String> topLevelStateNames = new HashSet<>();
|
||||
states.fieldNames().forEachRemaining(topLevelStateNames::add);
|
||||
|
||||
var fields = states.fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
validateState("/States/" + entry.getKey(), entry.getValue(), topLevelJsonata, errors);
|
||||
validateState("/States/" + entry.getKey(), entry.getValue(), topLevelJsonata,
|
||||
topLevelStateNames, errors);
|
||||
}
|
||||
|
||||
// MISSING_END_STATE is a top-level-only rule, and it suppresses the reachability walk at
|
||||
// that same level: a workflow with no terminal state anywhere is refused outright, with no
|
||||
// "not reachable" diagnostics piled on top of it.
|
||||
if (hasTerminalState(states)) {
|
||||
validateReachability("/States", states, startAt, "/StartAt", errors);
|
||||
} else {
|
||||
errors.add(MISSING_END_STATE_MARKER);
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
private void validateState(String statePath, JsonNode stateDef,
|
||||
boolean topLevelJsonata, List<String> errors) {
|
||||
private static boolean hasTerminalState(JsonNode states) {
|
||||
for (JsonNode state : states) {
|
||||
if (!state.isObject()) {
|
||||
continue;
|
||||
}
|
||||
String type = state.path("Type").asText(null);
|
||||
if ("Succeed".equals(type) || "Fail".equals(type) || state.path("End").asBoolean(false)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks the transition graph of one container of states (the top-level {@code States}, a
|
||||
* Map's {@code ItemProcessor}, or a Parallel branch) from its {@code StartAt}, flagging every
|
||||
* state nothing routes to. A {@code StartAt} that does not resolve to a state in the same
|
||||
* container is itself a dangling transition target, reported at {@code startAtLocation}; the
|
||||
* walk then starts from nothing, so every state in the container comes back unreachable too.
|
||||
*/
|
||||
private static void validateReachability(String containerPath, JsonNode states, String startAt,
|
||||
String startAtLocation, List<String> errors) {
|
||||
Set<String> reachable = new HashSet<>();
|
||||
if (startAt != null && !startAt.isBlank() && states.has(startAt)) {
|
||||
Deque<String> pending = new ArrayDeque<>();
|
||||
reachable.add(startAt);
|
||||
pending.add(startAt);
|
||||
while (!pending.isEmpty()) {
|
||||
for (String target : transitionTargets(states.path(pending.poll()))) {
|
||||
if (states.has(target) && reachable.add(target)) {
|
||||
pending.add(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (startAt != null && !startAt.isBlank()) {
|
||||
errors.add(DANGLING_TARGET_MARKER + startAt + MARKER_PAYLOAD_SEPARATOR + startAtLocation);
|
||||
}
|
||||
states.fieldNames().forEachRemaining(name -> {
|
||||
if (!reachable.contains(name)) {
|
||||
errors.add(UNREACHABLE_STATE_MARKER + name + MARKER_PAYLOAD_SEPARATOR + containerPath + "/" + name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static List<String> transitionTargets(JsonNode state) {
|
||||
List<String> targets = new ArrayList<>();
|
||||
addIfTextual(state, "Next", targets);
|
||||
addIfTextual(state, "Default", targets);
|
||||
for (JsonNode choice : state.path("Choices")) {
|
||||
addIfTextual(choice, "Next", targets);
|
||||
}
|
||||
for (JsonNode catcher : state.path("Catch")) {
|
||||
addIfTextual(catcher, "Next", targets);
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
private static void addIfTextual(JsonNode node, String field, List<String> targets) {
|
||||
if (node.path(field).isTextual()) {
|
||||
targets.add(node.path(field).asText());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flags every {@code Next}, {@code Default} and {@code Catch[].Next} in one state that names a
|
||||
* state absent from its own container. Independent of {@link #validateReachability}: a
|
||||
* dangling target is invalid on its own, whether or not MISSING_END_STATE suppressed the
|
||||
* unreachable-state walk for this container.
|
||||
*/
|
||||
private static void validateTransitionTargets(String statePath, JsonNode stateDef,
|
||||
Set<String> siblingStateNames, List<String> errors) {
|
||||
validateTarget(stateDef, "Next", statePath + "/Next", siblingStateNames, errors);
|
||||
validateTarget(stateDef, "Default", statePath + "/Default", siblingStateNames, errors);
|
||||
JsonNode choices = stateDef.path("Choices");
|
||||
for (int i = 0; i < choices.size(); i++) {
|
||||
validateTarget(choices.path(i), "Next", statePath + "/Choices[" + i + "]/Next",
|
||||
siblingStateNames, errors);
|
||||
}
|
||||
JsonNode catches = stateDef.path("Catch");
|
||||
for (int i = 0; i < catches.size(); i++) {
|
||||
validateTarget(catches.path(i), "Next", statePath + "/Catch[" + i + "]/Next",
|
||||
siblingStateNames, errors);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateTarget(JsonNode node, String field, String location,
|
||||
Set<String> siblingStateNames, List<String> errors) {
|
||||
JsonNode value = node.path(field);
|
||||
if (value.isTextual() && !siblingStateNames.contains(value.asText())) {
|
||||
errors.add(DANGLING_TARGET_MARKER + value.asText() + MARKER_PAYLOAD_SEPARATOR + location);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateFieldsAllowedForType(String statePath, JsonNode stateDef,
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateState(String statePath, JsonNode stateDef, boolean topLevelJsonata,
|
||||
Set<String> siblingStateNames, List<String> errors) {
|
||||
if (!stateDef.isObject()) {
|
||||
errors.add("State must be an object at " + statePath);
|
||||
return;
|
||||
@@ -1571,10 +1752,12 @@ 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;
|
||||
|
||||
validateFieldsAllowedForType(statePath, stateDef, stateType, errors);
|
||||
validateTransitionTargets(statePath, stateDef, siblingStateNames, errors);
|
||||
|
||||
// JSONPath-only fields are not allowed when the state uses JSONata
|
||||
if (stateIsJsonata) {
|
||||
for (String field : JSONPATH_ONLY_FIELDS) {
|
||||
@@ -1595,26 +1778,32 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
validateResultWriter(statePath, stateDef.get("ResultWriter"), stateIsJsonata, errors);
|
||||
}
|
||||
String processorField = stateDef.has("ItemProcessor") ? "ItemProcessor" : "Iterator";
|
||||
validateNestedStates(stateDef.path(processorField).path("States"),
|
||||
statePath + "/" + processorField + "/States", topLevelJsonata, errors);
|
||||
String processorPath = statePath + "/" + processorField;
|
||||
JsonNode processor = stateDef.path(processorField);
|
||||
validateNestedStates(processor.path("States"), processorPath + "/States", processorPath + "/StartAt",
|
||||
processor.path("StartAt").asText(null), topLevelJsonata, errors);
|
||||
} else if ("Parallel".equals(stateType)) {
|
||||
JsonNode branches = stateDef.path("Branches");
|
||||
if (branches.isArray()) {
|
||||
for (int i = 0; i < branches.size(); i++) {
|
||||
validateNestedStates(branches.path(i).path("States"),
|
||||
statePath + "/Branches[" + i + "]/States", topLevelJsonata, errors);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Reports every JSONata expression in the state that does not parse, or that reads the
|
||||
* top-level context, or that reads {@code $states.errorOutput} outside the one place it
|
||||
* exists: all three are refused by real AWS 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":
|
||||
@@ -1622,44 +1811,98 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
* walk enters one of {@link #JSONATA_PAYLOAD_FIELDS}.
|
||||
*/
|
||||
private static void collectTopLevelReferences(String path, JsonNode node, List<String> errors) {
|
||||
collectTopLevelReferences(path, node, false, errors);
|
||||
collectTopLevelReferences(path, node, JsonataScope.STATE_ROOT, errors);
|
||||
}
|
||||
|
||||
private static void collectTopLevelReferences(String path, JsonNode node, boolean insidePayload,
|
||||
private static void collectTopLevelReferences(String path, JsonNode node, JsonataScope scope,
|
||||
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);
|
||||
if (scope.parsesAsJsonata(field.getKey())) {
|
||||
collectTopLevelReferences(path + "/" + field.getKey(), field.getValue(),
|
||||
scope.enter(field.getKey()), errors);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (node.isArray()) {
|
||||
for (int index = 0; index < node.size(); index++) {
|
||||
collectTopLevelReferences(path + "[" + index + "]", node.get(index), insidePayload,
|
||||
errors);
|
||||
collectTopLevelReferences(path + "[" + index + "]", node.get(index), scope, 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);
|
||||
JsonataTopLevelReferences.Analysis analysis =
|
||||
JsonataTopLevelReferences.analyze(JsonataEvaluator.unwrap(node.asText()));
|
||||
if (analysis.parseError() != null) {
|
||||
errors.add(INVALID_JSONATA_MARKER + analysis.parseError() + MARKER_PAYLOAD_SEPARATOR + path);
|
||||
return;
|
||||
}
|
||||
for (String reference : analysis.topLevelReferences()) {
|
||||
addUnsupportedReferenceError(path, reference, scope, errors);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateNestedStates(JsonNode states, String statesPath,
|
||||
boolean inheritedJsonata, List<String> errors) {
|
||||
/**
|
||||
* The three things the walk carries down from the ASL fields it has already entered, each of
|
||||
* which changes how a {@code {% %}} string below is read: inside a payload every key is a
|
||||
* payload key, so {@link #ASL_FIELDS_AWS_DOES_NOT_PARSE_AS_JSONATA} no longer applies;
|
||||
* {@code atCatchEntry} marks a catcher object, whose own {@code Output} and {@code Assign} are
|
||||
* the one place {@code $states.errorOutput} resolves; and {@code insideCatchOutputOrAssign}
|
||||
* says the walk is in one of those two, at any depth.
|
||||
*/
|
||||
private record JsonataScope(boolean insidePayload, boolean atCatchEntry,
|
||||
boolean insideCatchOutputOrAssign) {
|
||||
|
||||
private static final JsonataScope STATE_ROOT = new JsonataScope(false, false, false);
|
||||
|
||||
private boolean parsesAsJsonata(String field) {
|
||||
return insidePayload || !ASL_FIELDS_AWS_DOES_NOT_PARSE_AS_JSONATA.contains(field);
|
||||
}
|
||||
|
||||
private JsonataScope enter(String field) {
|
||||
if (insidePayload) {
|
||||
return this;
|
||||
}
|
||||
return new JsonataScope(
|
||||
JSONATA_PAYLOAD_FIELDS.contains(field),
|
||||
"Catch".equals(field),
|
||||
insideCatchOutputOrAssign
|
||||
|| (atCatchEntry && ("Output".equals(field) || "Assign".equals(field))));
|
||||
}
|
||||
}
|
||||
|
||||
private static void addUnsupportedReferenceError(String path, String reference,
|
||||
JsonataScope scope, List<String> errors) {
|
||||
if (JsonataTopLevelReferences.STATES_ERROR_OUTPUT.equals(reference)) {
|
||||
if (!scope.insideCatchOutputOrAssign()) {
|
||||
errors.add(UNSUPPORTED_JSONATA_MARKER
|
||||
+ " Field '$states.errorOutput' does not exist. at " + path);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (JsonataTopLevelReferences.ROOT_REFERENCE.equals(reference)) {
|
||||
errors.add(UNSUPPORTED_JSONATA_MARKER + " Reference to '$$' is not supported. at " + path);
|
||||
return;
|
||||
}
|
||||
errors.add(UNSUPPORTED_JSONATA_MARKER + " Reference to '" + reference
|
||||
+ "' 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) {
|
||||
if (!states.isObject()) {
|
||||
return;
|
||||
}
|
||||
Set<String> stateNames = new HashSet<>();
|
||||
states.fieldNames().forEachRemaining(stateNames::add);
|
||||
states.fields().forEachRemaining(entry -> validateState(
|
||||
statesPath + "/" + entry.getKey(), entry.getValue(), inheritedJsonata, errors));
|
||||
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);
|
||||
}
|
||||
|
||||
private void validateMapConcurrency(String statePath, JsonNode stateDef,
|
||||
|
||||
Reference in new issue
Block a user