fix(stepfunctions): refuse a payload-template field that is neither a JSONPath nor one intrinsic call (#9374)

This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-11-26 18:33:05 -04:00
1 parent 52fb3589fc
commit 3990b9a731
3 files changed
+406

No files matched your search

@@ -146,6 +146,14 @@ public class StepFunctionsService implements Resettable, ResourceProvider, Store
// 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");
// The payload templates AslExecutor.resolveParameters evaluates on a JSONPath state. Every
// field of one whose name ends with '.$' must begin with '$' or be a single Intrinsic Function
// call, so the validator walks each of these from the state, nested objects and arrays included.
// The Assign of every Catch and Choices entry is resolved through applyJsonPathAssign too and
// is walked by validatePayloadTemplateFields on top of the state-level Assign listed here.
private static final List<String> JSONPATH_PAYLOAD_TEMPLATES = List.of(
"Parameters", "ResultSelector", "ItemSelector", "Assign", "Credentials",
"ItemBatcher/BatchInput", "ItemReader/Parameters", "ResultWriter/Parameters");
private static final Set<String> ITEM_READER_INPUT_TYPES = Set.of(
"MANIFEST", "JSON", "CSV", "JSONL", "PARQUET");
private static final Set<String> RESULT_WRITER_TRANSFORMATIONS = Set.of("NONE", "COMPACT", "FLATTEN");
@@ -2681,6 +2689,8 @@ public class StepFunctionsService implements Resettable, ResourceProvider, Store
validateQueryLanguageValue(stateDef, statePath + "/QueryLanguage", errors);
if (stateIsJsonata) {
collectTopLevelReferences(statePath, stateDef, errors);
} else {
validatePayloadTemplateFields(statePath, stateDef, errors);
}
// Structurally validate JSONPath Choice rules (comparator allowlist, exactly-one operator,
@@ -2842,6 +2852,106 @@ public class StepFunctionsService implements Resettable, ResourceProvider, Store
+ "' at the top level is not supported. at " + path);
}
/**
* Flags every {@code .$} field of the JSONPath payload templates
* {@link AslExecutor#resolveParameters} evaluates whose value is neither a JSONPath (it does
* not begin with {@code $}) nor a single Intrinsic Function call: a name, its argument list in
* parentheses, and nothing but whitespace after the {@code )} that closes that list. AWS
* reports such a value as a definition error, while the executor drops what follows and
* succeeds. Reported at the template carrying the field, the state path plus the template
* field path, nested objects and arrays included, matching the depth the executor resolves
* them at. {@code Assign} is additionally carried by every entry of a Catch and a Choices
* list, which the executor resolves through {@link AslExecutor#applyJsonPathAssign} when the
* state fails or a rule matches; a state-level {@code Assign} is the Default path's and is
* covered by the plain field above.
*/
private static void validatePayloadTemplateFields(String statePath, JsonNode stateDef,
List<String> errors) {
for (String templatePath : JSONPATH_PAYLOAD_TEMPLATES) {
JsonNode template = stateDef;
for (String segment : templatePath.split("/")) {
template = template.path(segment);
}
validatePayloadTemplate(statePath, templatePath, template, errors);
}
for (String listField : List.of("Catch", "Choices")) {
JsonNode entries = stateDef.path(listField);
if (!entries.isArray()) {
continue;
}
for (int i = 0; i < entries.size(); i++) {
validatePayloadTemplate(statePath, listField + "[" + i + "]/Assign",
entries.get(i).path("Assign"), errors);
}
}
}
private static void validatePayloadTemplate(String statePath, String templatePath, JsonNode template,
List<String> errors) {
if (template.isObject()) {
Iterator<Map.Entry<String, JsonNode>> fields = template.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
String key = entry.getKey();
JsonNode value = entry.getValue();
if (key.endsWith(".$") && value.isTextual()
&& !isValidPayloadTemplateValue(value.asText())) {
errors.add(EXPLICIT_LOCATION_MARKER + "The value for the field '" + key
+ "' must be a valid JSONPath or a valid intrinsic function call"
+ MARKER_PAYLOAD_SEPARATOR + statePath + "/" + templatePath);
} else if (value.isObject() || value.isArray()) {
validatePayloadTemplate(statePath, templatePath + "/" + key, value, errors);
}
}
return;
}
for (int index = 0; index < template.size(); index++) {
validatePayloadTemplate(statePath, templatePath + "[" + index + "]",
template.get(index), errors);
}
}
/**
* Whether one {@code .$} field value is a JSONPath reference ({@code $} or {@code $$} first)
* or a single Intrinsic Function call: a name, at least one non-whitespace character of it
* before the {@code (} that opens the argument list, and nothing but whitespace after the
* {@code )} that closes it. The {@code )} closing the argument list is found with
* string literals skipped, a literal running from one {@code '} to its matching {@code '} with
* a backslash escaping the next character, so a quoted {@code \'} does not end it; anything
* after that {@code )}, including an index suffix, is not part of a call.
*/
private static boolean isValidPayloadTemplateValue(String value) {
if (value.startsWith("$")) {
return true;
}
int open = value.indexOf('(');
if (open < 0 || value.substring(0, open).isBlank()) {
return false;
}
int depth = 0;
boolean inLiteral = false;
for (int i = open; i < value.length(); i++) {
char c = value.charAt(i);
if (inLiteral) {
if (c == '\\') {
i++;
} else if (c == '\'') {
inLiteral = false;
}
} else if (c == '\'') {
inLiteral = true;
} else if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
if (depth == 0) {
return value.substring(i + 1).isBlank();
}
}
}
return false;
}
/**
* 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
@@ -0,0 +1,248 @@
package io.floci.aws.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.stepfunctions.model.Activity;
import io.floci.aws.services.stepfunctions.model.Execution;
import io.floci.aws.services.stepfunctions.model.StateMachine;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Which values a {@code .$} field of a JSONPath payload template accepts: a JSONPath reference or
* one Intrinsic Function call, a name followed by its argument list in parentheses, with nothing
* but whitespace after the {@code )} that closes it. A string literal is skipped when that
* {@code )} is found, with a backslash escaping the next character, so a quoted {@code \'} does
* not end it. A refused value is reported at the template carrying the field, not at the field,
* and the walk also covers the {@code Assign} of every Catch and Choices entry, which the
* executor resolves too. Over a real service with
* in-memory stores, a mocked {@link AslExecutor} and a mocked publisher, through
* {@link StepFunctionsService#validateStateMachineDefinition}, which serves create, update and
* validate alike.
*/
class StepFunctionsIntrinsicFieldValidationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
static Stream<String> acceptedValues() {
return Stream.of("$.a", "$$", "States.Format('it''s {}', $.a)", "States.Array($.a)",
"States.Array()", "States.Array($.a) ");
}
@ParameterizedTest
@MethodSource("acceptedValues")
void parameterValueThatIsAPathOrOneIntrinsicCallIsAccepted(String value) {
StepFunctionsService.ValidationResult result = validate(definitionWithParameter(value));
assertTrue(result.valid(), "expected OK for " + value + ", got " + result.diagnostics());
assertEquals(List.of(), result.diagnostics());
}
static Stream<String> refusedValues() {
return Stream.of("foo", "()", " (foo)", "States.StringToJson($.payload).status",
"States.Array($.a, $.b)[0]", "States.Format('don\\'t', $.a) extra", "",
"States.Array('literal').x");
}
@ParameterizedTest
@MethodSource("refusedValues")
void parameterValueThatIsNeitherAPathNorOneIntrinsicCallIsRefused(String value) {
StepFunctionsService.ValidationResult result = validate(definitionWithParameter(value));
assertEquals(false, result.valid(), "expected FAIL for " + value);
assertEquals(1, result.diagnostics().size());
StepFunctionsService.Diagnostic diagnostic = result.diagnostics().get(0);
assertEquals("ERROR", diagnostic.severity());
assertEquals("SCHEMA_VALIDATION_FAILED", diagnostic.code());
assertEquals("The value for the field 'x.$' must be a valid JSONPath"
+ " or a valid intrinsic function call", diagnostic.message());
assertEquals("/States/S/Parameters", diagnostic.location());
}
@Test
void nestedTemplateWithMixedValidValuesIsAccepted() {
ObjectNode parameters = MAPPER.createObjectNode();
parameters.put("a.$", "$.x");
parameters.put("b.$", "$$");
parameters.put("c.$", "States.Array($.a)");
parameters.put("d.$", "States.Format('it''s {}', $.a)");
parameters.putObject("nested").put("e.$", "$.y");
parameters.putArray("list").addObject()
.put("f.$", "$.z")
.put("g.$", "States.Array($.a)");
StepFunctionsService.ValidationResult result = validate(definitionWith("Parameters", parameters));
assertTrue(result.valid(), "expected OK, got " + result.diagnostics());
assertEquals(List.of(), result.diagnostics());
}
@Test
void nestedRefusedValueIsReportedAtItsContainingTemplate() {
ObjectNode parameters = MAPPER.createObjectNode();
parameters.putArray("ContainerOverrides").addObject()
.putArray("Environment").addObject()
.put("Value.$", "foo");
StepFunctionsService.Diagnostic diagnostic = onlyDiagnostic(definitionWith("Parameters", parameters));
assertEquals("The value for the field 'Value.$' must be a valid JSONPath"
+ " or a valid intrinsic function call", diagnostic.message());
assertEquals("/States/S/Parameters/ContainerOverrides[0]/Environment[0]",
diagnostic.location());
}
@Test
void refusedResultSelectorValueIsReportedAtItsTemplate() {
ObjectNode selector = MAPPER.createObjectNode();
selector.put("r.$", "States.StringToJson($.payload).status");
StepFunctionsService.Diagnostic diagnostic = onlyDiagnostic(definitionWith("ResultSelector", selector));
assertEquals("/States/T/ResultSelector", diagnostic.location());
}
@Test
void refusedBatchInputValueIsReportedAtItsTemplate() {
ObjectNode root = MAPPER.createObjectNode();
root.put("StartAt", "M");
ObjectNode map = root.putObject("States").putObject("M");
map.put("Type", "Map").put("End", true);
map.putObject("ItemBatcher").putObject("BatchInput").put("b.$", "foo");
map.putObject("ItemProcessor").put("StartAt", "P");
map.putObject("States").putObject("P").put("Type", "Pass").put("End", true);
StepFunctionsService.Diagnostic diagnostic = onlyDiagnostic(root.toString());
assertEquals("The value for the field 'b.$' must be a valid JSONPath"
+ " or a valid intrinsic function call", diagnostic.message());
assertEquals("/States/M/ItemBatcher/BatchInput", diagnostic.location());
}
@Test
void refusedCatchAssignValueIsReportedAtItsTemplate() {
ObjectNode catcher = MAPPER.createObjectNode();
catcher.putArray("ErrorEquals").add("States.ALL");
catcher.put("Next", "T");
catcher.putObject("Assign").put("v.$", "States.Array('literal').x");
StepFunctionsService.Diagnostic diagnostic = onlyDiagnostic(definitionWith("Catch", arrayWith(catcher)));
assertEquals("The value for the field 'v.$' must be a valid JSONPath"
+ " or a valid intrinsic function call", diagnostic.message());
assertEquals("/States/T/Catch[0]/Assign", diagnostic.location());
}
@Test
void catchAssignValueThatIsAPathIsAccepted() {
ObjectNode catcher = MAPPER.createObjectNode();
catcher.putArray("ErrorEquals").add("States.ALL");
catcher.put("Next", "T");
catcher.putObject("Assign").put("v.$", "$.x");
StepFunctionsService.ValidationResult result = validate(definitionWith("Catch", arrayWith(catcher)));
assertTrue(result.valid(), "expected OK, got " + result.diagnostics());
assertEquals(List.of(), result.diagnostics());
}
@Test
void refusedChoiceAssignValueIsReportedAtItsTemplate() {
ObjectNode rule = MAPPER.createObjectNode();
rule.put("Variable", "$.a");
rule.put("StringEquals", "x");
rule.put("Next", "C");
rule.putObject("Assign").put("v.$", "States.Array('literal').x");
StepFunctionsService.Diagnostic diagnostic = onlyDiagnostic(choiceDefinitionWith(arrayWith(rule)));
assertEquals("The value for the field 'v.$' must be a valid JSONPath"
+ " or a valid intrinsic function call", diagnostic.message());
assertEquals("/States/C/Choices[0]/Assign", diagnostic.location());
}
@Test
void choiceAssignValueThatIsAPathIsAccepted() {
ObjectNode rule = MAPPER.createObjectNode();
rule.put("Variable", "$.a");
rule.put("StringEquals", "x");
rule.put("Next", "C");
rule.putObject("Assign").put("v.$", "$.x");
StepFunctionsService.ValidationResult result = validate(choiceDefinitionWith(arrayWith(rule)));
assertTrue(result.valid(), "expected OK, got " + result.diagnostics());
assertEquals(List.of(), result.diagnostics());
}
private static ArrayNode arrayWith(JsonNode entry) {
return MAPPER.createArrayNode().add(entry);
}
private static String choiceDefinitionWith(ArrayNode choices) {
ObjectNode root = MAPPER.createObjectNode();
root.put("StartAt", "C");
ObjectNode states = root.putObject("States");
states.putObject("C")
.put("Type", "Choice")
.put("Default", "D")
.set("Choices", choices);
states.putObject("D").put("Type", "Pass").put("End", true);
return root.toString();
}
private static StepFunctionsService.Diagnostic onlyDiagnostic(String definition) {
StepFunctionsService.ValidationResult result = validate(definition);
assertEquals(1, result.diagnostics().size(), result.diagnostics().toString());
return result.diagnostics().get(0);
}
private static StepFunctionsService.ValidationResult validate(String definition) {
return buildService().validateStateMachineDefinition(definition, null, null, null);
}
private static String definitionWithParameter(String value) {
ObjectNode parameters = MAPPER.createObjectNode();
parameters.put("x.$", value);
return definitionWith("Parameters", parameters);
}
private static String definitionWith(String templateField, JsonNode template) {
boolean passState = "Parameters".equals(templateField);
ObjectNode root = MAPPER.createObjectNode();
root.put("StartAt", passState ? "S" : "T");
ObjectNode state = root.putObject("States").putObject(passState ? "S" : "T");
if (passState) {
state.put("Type", "Pass").put("End", true);
} else {
state.put("Type", "Task").put("Resource", "arn:aws:states:::lambda:invoke").put("End", true);
}
state.set(templateField, template);
return root.toString();
}
private static StepFunctionsService buildService() {
AccountAwareStorageBackend<StateMachine> smStore = AccountAwareStorageBackend.inMemory("000000000000");
AccountAwareStorageBackend<Execution> execStore = AccountAwareStorageBackend.inMemory("000000000000");
AccountAwareStorageBackend<Activity> actStore = AccountAwareStorageBackend.inMemory("000000000000");
StorageFactory factory = mock(StorageFactory.class);
doReturn(smStore).doReturn(execStore).doReturn(actStore)
.when(factory).create(anyString(), anyString(), any());
RegionResolver region = mock(RegionResolver.class);
when(region.buildArn(eq("states"), any(), anyString()))
.thenAnswer(i -> "arn:aws:states:us-east-1:000000000000:" + i.getArgument(2));
return new StepFunctionsService(factory, region, mock(AslExecutor.class), new ObjectMapper(),
mock(SfnMockLoader.class), mock(StepFunctionsEventPublisher.class));
}
}
@@ -1983,6 +1983,54 @@ class StepFunctionsValidateStateMachineDefinitionIntegrationTest {
""".replace("__MAP_QUERY_LANGUAGE__", mapQueryLanguage);
}
// The three values the issue reports as wrongly accepted: a bare name, a call with a suffix
// after its argument list, and a call with an index after it. All three must be FAIL.
private static Stream<String> valuesNeitherJsonPathNorIntrinsicCall() {
return Stream.of("foo", "States.StringToJson($.payload).status", "States.Array($.a, $.b)[0]");
}
@ParameterizedTest
@MethodSource("valuesNeitherJsonPathNorIntrinsicCall")
void payloadTemplateValueNeitherJsonPathNorIntrinsicCall_returnsFailWithSchemaError(String value) {
validateDefinition(passWithParameter(value))
.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(
"The value for the field 'x.$' must be a valid JSONPath"
+ " or a valid intrinsic function call"))
.body("diagnostics[0].location", equalTo("/States/S/Parameters"));
}
@Test
void payloadTemplateValueNeitherJsonPathNorIntrinsicCall_rejectedAtCreateStateMachine() {
createStateMachine("intrinsic-field-" + System.nanoTime(), passWithParameter("foo"))
.then().statusCode(400)
.body("__type", equalTo("InvalidDefinition"))
.body("message", containsString(
"The value for the field 'x.$' must be a valid JSONPath"
+ " or a valid intrinsic function call"));
}
@Test
void payloadTemplateValueThatIsOneIntrinsicCall_returnsOK() {
validateDefinition(passWithParameter("States.Array($.a)"))
.then().statusCode(200)
.body("result", equalTo("OK"))
.body("diagnostics", hasSize(0));
}
private static String passWithParameter(String value) {
ObjectNode root = OBJECT_MAPPER.createObjectNode();
root.put("StartAt", "S");
root.putObject("States").putObject("S")
.put("Type", "Pass").put("End", true)
.putObject("Parameters").put("x.$", value);
return root.toString();
}
private static List<Map<String, Object>> diagnosticsOf(String definition) {
return validateDefinition(definition).jsonPath().getList("diagnostics");
}