mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(stepfunctions)!: reject JSONata top-level references at definition time (#2699)
* fix(stepfunctions)!: reject JSONata top-level references at definition time
A Step Functions JSONata expression is evaluated with no context item: the
execution input arrives as $states.input and an Assign variable as $name. A
path whose first step is a bare name reads a context item that does not exist,
and real AWS refuses the definition from CreateStateMachine,
UpdateStateMachine and ValidateStateMachineDefinition with
UNSUPPORTED_JSONATA_EXPRESSION: Reference to '<name>' at the top level is not
supported. Floci accepted those definitions and failed the execution instead.
Every JSONata string in a JSONata state is now walked before the state machine
is stored, and each distinct top-level name is reported with the message and
the /States/... location AWS prints. Only the first step of a path is read
against the top-level context, so later steps, predicates, sort terms and
group expressions stay legal; a lambda body keeps the defining context and is
walked. Syntax errors and $$ keep their current behaviour.
The parse tree of com.dashjoin:jsonata is package-private and Quarkus loads
application classes and dependency jars under different class loaders, so the
tree fields are read reflectively, resolved once at class initialization and
registered for native image.
BREAKING CHANGE: state machines whose JSONata expressions reference a bare
top-level name are now rejected at creation, as on AWS. Anchor the reference
with $states.input.<name> for input or $<name> for an Assign variable.
* fix(stepfunctions): parse a JSONata payload key named after an ASL field
The deny list of fields AWS does not parse as JSONata was applied to every
key at every depth, so a payload key named Next, Comment, Resource, Retry,
Default, ErrorEquals, Credentials, Branches, ItemProcessor or Iterator hid
its expression. AWS parses a payload whole: `Assign: {"Next": "{% phone %}"}`
and `Arguments: {"Payload": {"Comment": "{% phone %}"}}` are both refused
with `Reference to 'phone' at the top level is not supported.` The deny list
now stops applying once the walk enters Output, Assign, Arguments,
ItemSelector or BatchInput.
The same walk refused `ItemReader.ReaderConfig.CSVHeaders`, which holds
literal column names: `validate-state-machine-definition` returns OK for it
and `create-state-machine` stores the machine, so CSVHeaders joins the list.
---------
Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
This commit is contained in:
1 parent
0090739617
commit
5534460492
5 files changed
+742
-22
No files matched your search
+189
@@ -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);
|
||||
}
|
||||
}
|
||||
+105
-22
@@ -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.
|
||||
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();
|
||||
}
|
||||
if (error.startsWith(PARSE_ERROR_MARKER)) {
|
||||
return new Diagnostic("ERROR", "INVALID_JSON_DESCRIPTION",
|
||||
error.substring(PARSE_ERROR_MARKER.length()).trim(), null);
|
||||
}
|
||||
return new Diagnostic("ERROR", code, message, location);
|
||||
if (error.startsWith(UNSUPPORTED_JSONATA_MARKER)) {
|
||||
return toJsonataDiagnostic(error.substring(UNSUPPORTED_JSONATA_MARKER.length()).trim());
|
||||
}
|
||||
String message = error;
|
||||
String location = null;
|
||||
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", "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()) {
|
||||
|
||||
Reference in new issue
Block a user