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 ecd2724459..22eca5b548 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 @@ -2039,11 +2039,33 @@ public class AslExecutor { if (cause != null && JsonataEvaluator.isExpression(cause)) { cause = jsonataEvaluator.evaluateField(cause, "Cause", statesVar, variables).asText(); } + } else { + if (stateDef.has("ErrorPath")) { + error = resolveFailDynamicField(stateDef.get("ErrorPath").asText(), "ErrorPath", input, context); + } + if (stateDef.has("CausePath")) { + cause = resolveFailDynamicField(stateDef.get("CausePath").asText(), "CausePath", input, context); + } } // AWS does not prefix a Fail state's Cause. throw new FailStateException(error, cause, true); } + /** + * Resolves a Fail state's {@code ErrorPath} or {@code CausePath}: a reference path or a + * {@code States.*} intrinsic, evaluated against the state's input through the same resolver a + * {@code ".$"} payload template field uses. AWS requires the resolved value to be a string; + * an unresolvable path or a non-string result both fail the state with {@code States.Runtime}, + * since a Fail state has no {@code Catch} of its own to route around either failure. + */ + private String resolveFailDynamicField(String path, String field, JsonNode input, JsonNode context) { + JsonNode resolved = resolvePayloadTemplateReference(path, input, context, field, input); + if (!resolved.isTextual()) { + throw new FailStateException("States.Runtime", field + " must resolve to a string"); + } + return resolved.asText(); + } + private StateResult executeParallelState(String name, JsonNode stateDef, JsonNode input, HistoryChain chain, StateMachine sm, boolean jsonata, String topLevelQueryLanguage, JsonNode context, 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 c859702370..ba1690952a 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 @@ -72,7 +72,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider { // AWS-observed, it is simply the one this code commits to. private static final List JSONPATH_ONLY_FIELDS = List.of( "InputPath", "OutputPath", "ResultPath", "ResultSelector", "Parameters", "Result", "ItemsPath", - "MaxConcurrencyPath"); + "MaxConcurrencyPath", "ErrorPath", "CausePath"); // 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 @@ -1972,6 +1972,10 @@ public class StepFunctionsService implements Resettable, ResourceProvider { } } + if ("Fail".equals(stateType)) { + validateFailErrorAndCauseFields(statePath, stateDef, errors); + } + if ("Map".equals(stateType)) { validateMapConcurrency(statePath, stateDef, stateIsJsonata, errors); if (stateDef.has("ItemReader")) { @@ -2123,6 +2127,37 @@ public class StepFunctionsService implements Resettable, ResourceProvider { subWorkflowPath + "/StartAt", errors); } + /** + * A Fail state resolves its {@code Error} either from the literal {@code Error} field or + * dynamically from {@code ErrorPath}, never both; the same holds for {@code Cause} and + * {@code CausePath}. Real AWS refuses a definition that specifies both at CreateStateMachine. + */ + private static void validateFailErrorAndCauseFields(String statePath, JsonNode stateDef, List errors) { + if (stateDef.has("Error") && stateDef.has("ErrorPath")) { + errors.add("A Fail state cannot include both field 'Error' and 'ErrorPath' at " + statePath); + } + if (stateDef.has("Cause") && stateDef.has("CausePath")) { + errors.add("A Fail state cannot include both field 'Cause' and 'CausePath' at " + statePath); + } + validateFailPathFieldIsString(statePath, stateDef, "ErrorPath", errors); + validateFailPathFieldIsString(statePath, stateDef, "CausePath", errors); + } + + /** + * {@code ErrorPath}/{@code CausePath} are reference paths or {@code States.*} intrinsics, + * always given as a JSON string; a non-string value (a number, object, array, or boolean) + * is a definition error AWS rejects at {@code CreateStateMachine}, not something that should + * reach execution and fail there instead. + */ + private static void validateFailPathFieldIsString(String statePath, JsonNode stateDef, String field, + List errors) { + JsonNode value = stateDef.get(field); + if (value != null && !value.isTextual()) { + errors.add(EXPLICIT_LOCATION_MARKER + "Expected value of type [STRING]" + + MARKER_PAYLOAD_SEPARATOR + statePath + "/" + field); + } + } + private void validateMapConcurrency(String statePath, JsonNode stateDef, boolean jsonata, List errors) { if (stateDef.has("MaxConcurrency") && stateDef.has("MaxConcurrencyPath")) { diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFailStateErrorCauseTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFailStateErrorCauseTest.java new file mode 100644 index 0000000000..cc31af3efc --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFailStateErrorCauseTest.java @@ -0,0 +1,175 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +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 java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A {@code Fail} state's {@code ErrorPath} and {@code CausePath} resolve the {@code Error} and + * {@code Cause} it reports dynamically from the state's input, the same way real AWS and Step + * Functions Local do. Fixes issue #3255. + * + *

Both fields are resolved through the same reference-path resolver a {@code ".$"} payload + * template field uses, so an unresolvable path fails with {@code States.Runtime}, matching the + * precedent set for issue #2521 in {@link AslExecutorUnresolvableJsonPathTest}. + */ +@QuarkusTest +class AslExecutorFailStateErrorCauseTest { + + private static final String REGION = "us-east-2"; + private static final String ACCOUNT = "000000000000"; + + 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); + } + + /** The exact reproduction from issue #3255: both ErrorPath and CausePath resolve from input. */ + @Test + void errorPathAndCausePathResolveFromInput() { + Execution execution = run(""" + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","ErrorPath":"$.e","CausePath":"$.c"}}} + """, "{\"e\":\"StudentDeletionFailed\",\"c\":\"boom\"}"); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("StudentDeletionFailed", execution.getError()); + assertEquals("boom", execution.getCause()); + } + + /** A literal Error alongside a CausePath resolves the cause dynamically and keeps the literal error. */ + @Test + void literalErrorWithCausePathResolvesOnlyTheCause() { + Execution execution = run(""" + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","Error":"422","CausePath":"$.Cause"}}} + """, "{\"Cause\":\"Unable to create an account\"}"); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("422", execution.getError()); + assertEquals("Unable to create an account", execution.getCause()); + } + + /** ErrorPath and CausePath can also be a States.* intrinsic, per the ASL specification. */ + @Test + void errorPathAsAnIntrinsicFunctionResolves() { + Execution execution = run(""" + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","ErrorPath":"States.Format('Order{}Failed', $.orderId)"}}} + """, "{\"orderId\":42}"); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("Order42Failed", execution.getError()); + } + + /** An ErrorPath that matches nothing in the input fails with States.Runtime, not a silent miss. */ + @Test + void unresolvableErrorPathFailsWithStatesRuntime() { + Execution execution = run(""" + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","ErrorPath":"$.nope"}}} + """, "{\"other\":1}"); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("States.Runtime", execution.getError()); + assertEquals("An error occurred while executing the state 'Boom' (entered at the event id #1). " + + "The JSONPath '$.nope' specified for the field 'ErrorPath' could not be " + + "found in the input '{\"other\":1}'", execution.getCause()); + } + + /** CausePath fails the same way as ErrorPath when it cannot be resolved. */ + @Test + void unresolvableCausePathFailsWithStatesRuntime() { + Execution execution = run(""" + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","Error":"OrderFailed","CausePath":"$.nope"}}} + """, "{\"other\":1}"); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("States.Runtime", execution.getError()); + assertEquals("An error occurred while executing the state 'Boom' (entered at the event id #1). " + + "The JSONPath '$.nope' specified for the field 'CausePath' could not be " + + "found in the input '{\"other\":1}'", execution.getCause()); + } + + /** ErrorPath must select a string; any other resolved type fails with States.Runtime. */ + @Test + void errorPathResolvingToANonStringFailsWithStatesRuntime() { + Execution execution = run(""" + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","ErrorPath":"$.e"}}} + """, "{\"e\":404}"); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("States.Runtime", execution.getError()); + assertEquals("An error occurred while executing the state 'Boom' (entered at the event id #1). " + + "ErrorPath must resolve to a string", execution.getCause()); + } + + private Execution run(String definition, String input) { + StateMachine stateMachine = new StateMachine(); + stateMachine.setName("fail-error-cause-test"); + stateMachine.setStateMachineArn( + "arn:aws:states:%s:%s:stateMachine:fail-error-cause-test".formatted(REGION, ACCOUNT)); + stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT)); + stateMachine.setDefinition(definition); + + Execution execution = new Execution(); + execution.setName("fail-error-cause-test-execution"); + execution.setExecutionArn( + "arn:aws:states:%s:%s:execution:fail-error-cause-test:fail-error-cause-test-execution" + .formatted(REGION, ACCOUNT)); + execution.setStateMachineArn(stateMachine.getStateMachineArn()); + execution.setInput(input); + + List history = new ArrayList<>(); + executor.executeSync(stateMachine, execution, history, (updated, events) -> { + }); + return execution; + } + + private static T mock(Class type) { + return org.mockito.Mockito.mock(type); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsFailErrorPathValidationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsFailErrorPathValidationIntegrationTest.java new file mode 100644 index 0000000000..db714dcf3e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsFailErrorPathValidationIntegrationTest.java @@ -0,0 +1,159 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; + +/** + * A Fail state must not declare both {@code Error} and {@code ErrorPath}, nor both {@code Cause} + * and {@code CausePath}: real AWS refuses such a definition at CreateStateMachine time. Fixes + * issue #3255. + */ +@QuarkusTest +class StepFunctionsFailErrorPathValidationIntegrationTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.0"; + private static final String VALIDATE_TARGET = "AWSStepFunctions.ValidateStateMachineDefinition"; + private static final String CREATE_TARGET = "AWSStepFunctions.CreateStateMachine"; + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/service-role/sfn"; + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static Response validate(String definition) { + return given().contentType(CONTENT_TYPE).header("X-Amz-Target", VALIDATE_TARGET) + .body(OBJECT_MAPPER.createObjectNode().put("definition", definition).toString()) + .when().post("/"); + } + + private static Response create(String name, String definition) { + return given().contentType(CONTENT_TYPE).header("X-Amz-Target", CREATE_TARGET) + .body(OBJECT_MAPPER.createObjectNode() + .put("name", name) + .put("definition", definition) + .put("roleArn", ROLE_ARN).toString()) + .when().post("/"); + } + + @Test + void validateRejectsErrorAndErrorPathTogether() { + String definition = """ + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","Error":"OrderFailed","ErrorPath":"$.e"}}} + """; + + validate(definition).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( + "A Fail state cannot include both field 'Error' and 'ErrorPath'")); + } + + @Test + void validateRejectsCauseAndCausePathTogether() { + String definition = """ + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","Cause":"boom","CausePath":"$.c"}}} + """; + + validate(definition).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( + "A Fail state cannot include both field 'Cause' and 'CausePath'")); + } + + @Test + void validateAcceptsErrorPathAndCausePathAlone() { + String definition = """ + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","ErrorPath":"$.e","CausePath":"$.c"}}} + """; + + validate(definition).then().statusCode(200) + .body("result", equalTo("OK")) + .body("diagnostics", hasSize(0)); + } + + @Test + void createStateMachineRefusesErrorAndErrorPathTogether() { + String definition = """ + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","Error":"OrderFailed","ErrorPath":"$.e"}}} + """; + + create("fail-error-and-errorpath-" + System.nanoTime(), definition) + .then().statusCode(400) + .body("__type", equalTo("InvalidDefinition")); + } + + @Test + void createStateMachineRefusesCauseAndCausePathTogether() { + String definition = """ + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","Cause":"boom","CausePath":"$.c"}}} + """; + + create("fail-cause-and-causepath-" + System.nanoTime(), definition) + .then().statusCode(400) + .body("__type", equalTo("InvalidDefinition")); + } + + @Test + void validateRejectsNonStringErrorPath() { + String definition = """ + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","ErrorPath":123}}} + """; + + validate(definition).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("Expected value of type [STRING]")) + .body("diagnostics[0].location", equalTo("/States/Boom/ErrorPath")); + } + + @Test + void validateRejectsNonStringCausePath() { + String definition = """ + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","CausePath":{}}}} + """; + + validate(definition).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("Expected value of type [STRING]")) + .body("diagnostics[0].location", equalTo("/States/Boom/CausePath")); + } + + @Test + void createStateMachineRefusesNonStringErrorPath() { + String definition = """ + {"StartAt":"Boom","States":{ + "Boom":{"Type":"Fail","ErrorPath":123}}} + """; + + create("fail-non-string-errorpath-" + System.nanoTime(), definition) + .then().statusCode(400) + .body("__type", equalTo("InvalidDefinition")); + } +}