From cf0db6edc95518aa756e0937bd4df824cbafcebb Mon Sep 17 00:00:00 2001 From: Marvelous Ikponmwosa <46595957+marvikomo@users.noreply.github.com> Date: Fri, 15 May 2026 05:36:37 +0100 Subject: [PATCH] add ValidateStateMachineDefinition action (#845) * add ValidateStateMachineDefinition action * populate diagnostic.location with /States// * addressed review --- docs/services/index.md | 2 +- docs/services/step-functions.md | 1 + .../StepFunctionsJsonHandler.java | 48 ++++ .../stepfunctions/StepFunctionsService.java | 118 ++++++++- ...StateMachineDefinitionIntegrationTest.java | 223 ++++++++++++++++++ 5 files changed, 383 insertions(+), 9 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsValidateStateMachineDefinitionIntegrationTest.java diff --git a/docs/services/index.md b/docs/services/index.md index 3ea1360e8a..6861740508 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -25,7 +25,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [KMS](kms.md) | `POST /` + `X-Amz-Target: TrentService.*` | JSON 1.1 | 23 | | [Kinesis](kinesis.md) | `POST /` + `X-Amz-Target: Kinesis_20131202.*` | JSON 1.1 | 24 | | [Secrets Manager](secrets-manager.md) | `POST /` + `X-Amz-Target: secretsmanager.*` | JSON 1.1 | 16 | -| [Step Functions](step-functions.md) | `POST /` + `X-Amz-Target: AmazonStatesService.*` | JSON 1.1 | 18 | +| [Step Functions](step-functions.md) | `POST /` + `X-Amz-Target: AmazonStatesService.*` | JSON 1.1 | 19 | | [CloudFormation](cloudformation.md) | `POST /` with `Action=` param | Query | 19 | | [EventBridge](eventbridge.md) | `POST /` + `X-Amz-Target: AmazonEventBridge.*` | JSON 1.1 | 16 | | [EventBridge Scheduler](scheduler.md) | `/schedules/*`, `/schedule-groups/*`, `/tags/*` | REST JSON | 12 | diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index 6e8fddf8c7..fdb8ab74f3 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -11,6 +11,7 @@ | `DescribeStateMachine` | Get state machine definition and metadata | | `ListStateMachines` | List all state machines | | `DeleteStateMachine` | Delete a state machine | +| `ValidateStateMachineDefinition` | Validate an ASL definition without creating a state machine | | `StartExecution` | Start a new execution | | `DescribeExecution` | Get execution status and output | | `ListExecutions` | List executions for a state machine | diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java index 74b213e74a..db5a51bacd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.stepfunctions; import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import io.github.hectorvent.floci.core.common.AwsException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; @@ -36,6 +37,7 @@ public class StepFunctionsJsonHandler { case "DescribeStateMachine" -> handleDescribeStateMachine(request); case "ListStateMachines" -> handleListStateMachines(request, region); case "DeleteStateMachine" -> handleDeleteStateMachine(request); + case "ValidateStateMachineDefinition" -> handleValidateStateMachineDefinition(request); case "StartExecution" -> handleStartExecution(request, region); case "StartSyncExecution" -> handleStartSyncExecution(request, region); case "DescribeExecution" -> handleDescribeExecution(request); @@ -106,6 +108,32 @@ public class StepFunctionsJsonHandler { return Response.ok(objectMapper.createObjectNode()).build(); } + private Response handleValidateStateMachineDefinition(JsonNode request) { + String definition = request.path("definition").asText(null); + String type = request.path("type").asText(null); + String severity = request.path("severity").asText(null); + Integer maxResults = parseOptionalInt(request, "maxResults"); + + StepFunctionsService.ValidationResult result = + service.validateStateMachineDefinition(definition, type, severity, maxResults); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("result", result.valid() ? "OK" : "FAIL"); + ArrayNode diags = response.putArray("diagnostics"); + for (StepFunctionsService.Diagnostic d : result.diagnostics()) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("severity", d.severity()); + node.put("code", d.code()); + node.put("message", d.message()); + if (d.location() != null) { + node.put("location", d.location()); + } + diags.add(node); + } + response.put("truncated", result.truncated()); + return Response.ok(response).build(); + } + private Response handleStartExecution(JsonNode request, String region) { Execution exec = service.startExecution( request.path("stateMachineArn").asText(), @@ -316,4 +344,24 @@ public class StepFunctionsJsonHandler { return tags; } + /** + * Reads an optional integer field from the JSON request, rejecting wrong types + * with a typed ValidationException. JsonNode.asInt() silently coerces strings, + * fractional numbers, and explicit nulls to 0, which would let invalid payloads + * slip through as 0 (and thus be treated as "use default" by the service). + * Returns null when the field is absent or explicitly null in the JSON. + */ + private static Integer parseOptionalInt(JsonNode request, String fieldName) { + JsonNode node = request.get(fieldName); + if (node == null || node.isNull()) { + return null; + } + if (!node.isIntegralNumber()) { + throw new AwsException("ValidationException", + "Value '" + node + "' at '" + fieldName + + "' failed to satisfy constraint: Member must be an integer.", 400); + } + return node.intValue(); + } + } 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 73b01a1044..d3034a3008 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 @@ -25,6 +25,8 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; @ApplicationScoped public class StepFunctionsService { @@ -355,13 +357,118 @@ public class StepFunctionsService { // ──────────────────────────── Validation ──────────────────────────── + public record Diagnostic(String severity, String code, String message, String location) {} + public record ValidationResult(boolean valid, List diagnostics, boolean truncated) {} + + private static final int MAX_DEFINITION_LENGTH = 1_048_576; + private static final String PARSE_ERROR_MARKER = "INVALID_JSON_DESCRIPTION:"; + + // Parse the structured location out of the validator's flat error strings, + // which currently encode it as "...field 'X' is only supported... at /States/Y". + // AWS's published Diagnostic.location format is "/States//". + private static final Pattern FIELD_PATTERN = Pattern.compile("field '([^']+)' is only supported"); + private static final Pattern LOCATION_SUFFIX_PATTERN = Pattern.compile(" at (/States/\\S+)$"); + + /** + * Exposes the existing ASL validator as a public, non-throwing API for + * AWS {@code ValidateStateMachineDefinition}. Errors are returned as + * diagnostics rather than thrown; no state machine is created. Mirrors + * the wire shape of the AWS API. + */ + public ValidationResult validateStateMachineDefinition(String definition, String type, + String severity, Integer maxResults) { + if (definition == null || definition.isBlank()) { + throw new AwsException("ValidationException", "definition is required.", 400); + } + if (definition.length() > MAX_DEFINITION_LENGTH) { + throw new AwsException("ValidationException", + "definition exceeds maximum length of " + MAX_DEFINITION_LENGTH + " characters.", 400); + } + if (maxResults != null && (maxResults < 0 || maxResults > 100)) { + throw new AwsException("ValidationException", + "maxResults must be between 0 and 100.", 400); + } + if (severity != null && !severity.isBlank() + && !"ERROR".equals(severity) && !"WARNING".equals(severity)) { + throw new AwsException("ValidationException", + "severity must be ERROR or WARNING.", 400); + } + if (type != null && !type.isBlank() + && !"STANDARD".equals(type) && !"EXPRESS".equals(type)) { + throw new AwsException("ValidationException", + "type must be STANDARD or EXPRESS.", 400); + } + // Per AWS spec: maxResults=0 (or absent/null) → use default of 100. + // Out-of-range values are rejected above; no clamping needed here. + int cap = (maxResults == null || maxResults == 0) ? 100 : maxResults; + List errors = collectValidationErrors(definition); + List all = errors.stream() + .map(StepFunctionsService::toDiagnostic) + .toList(); + + // Apply the severity filter per spec: ERROR (the default) returns only + // error diagnostics; WARNING returns both warnings and errors. Floci's + // validator only emits ERROR today so the filter is currently a no-op, + // but it's wired now so adding warning-level checks later doesn't break + // the contract for callers who passed severity=ERROR. + String effectiveSeverity = severity == null || severity.isBlank() ? "ERROR" : severity; + List filtered = "WARNING".equals(effectiveSeverity) + ? all + : all.stream().filter(d -> "ERROR".equals(d.severity())).toList(); + + boolean truncated = filtered.size() > cap; + List page = truncated ? filtered.subList(0, cap) : filtered; + // valid == "no ERROR-level diagnostics". Floci only produces ERRORs today; + // explicit check future-proofs us when warnings are added. + boolean valid = page.stream().noneMatch(d -> "ERROR".equals(d.severity())); + return new ValidationResult(valid, page, truncated); + } + + 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 + // 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) + "/" + fieldM.group(1); + message = message.substring(0, locM.start()).trim(); + } + } + return new Diagnostic("ERROR", code, message, location); + } + private void validateDefinition(String definition) { + List errors = collectValidationErrors(definition); + if (errors.isEmpty()) { + return; + } + String first = errors.get(0); + if (first.startsWith(PARSE_ERROR_MARKER)) { + // Preserve historical wire shape for parse errors triggered via CreateStateMachine. + throw new AwsException("InvalidDefinition", + "Invalid State Machine Definition: '" + first.substring(PARSE_ERROR_MARKER.length()).trim() + "'", 400); + } + throw new AwsException("InvalidDefinition", + "Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED: " + + String.join(", ", errors) + "'", 400); + } + + private List collectValidationErrors(String definition) { + List errors = new ArrayList<>(); JsonNode def; try { def = objectMapper.readTree(definition); } catch (Exception e) { - throw new AwsException("InvalidDefinition", - "Invalid State Machine Definition: '" + e.getMessage() + "'", 400); + errors.add(PARSE_ERROR_MARKER + e.getMessage()); + return errors; } String topLevelQL = def.path("QueryLanguage").asText("JSONPath"); @@ -370,17 +477,12 @@ public class StepFunctionsService { if (states.isObject()) { var fields = states.fields(); - List errors = new ArrayList<>(); while (fields.hasNext()) { var entry = fields.next(); validateState(entry.getKey(), entry.getValue(), topLevelJsonata, errors); } - if (!errors.isEmpty()) { - throw new AwsException("InvalidDefinition", - "Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED: " - + String.join(", ", errors) + "'", 400); - } } + return errors; } private void validateState(String stateName, JsonNode stateDef, boolean topLevelJsonata, List errors) { 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 new file mode 100644 index 0000000000..33f1c1ba3d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsValidateStateMachineDefinitionIntegrationTest.java @@ -0,0 +1,223 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; + +/** + * Integration tests for SFN ValidateStateMachineDefinition via the JSON 1.0 wire path. + * All wire fields are lowercase per the official AWS spec. + */ +@QuarkusTest +class StepFunctionsValidateStateMachineDefinitionIntegrationTest { + + private static final String CT = "application/x-amz-json-1.0"; + private static final String TARGET = "AWSStepFunctions.ValidateStateMachineDefinition"; + private static final String LIST_TARGET = "AWSStepFunctions.ListStateMachines"; + + // ASL with the inner double-quotes already JSON-escaped, so it embeds cleanly + // inside the outer JSON request body as the value of "definition". + private static final String VALID_ASL = + "{\\\"StartAt\\\":\\\"Done\\\",\\\"States\\\":{\\\"Done\\\":{\\\"Type\\\":\\\"Pass\\\",\\\"End\\\":true}}}"; + + // JSONata state declaring three JSONPath-only fields → 3 distinct errors. + private static final String JSONATA_WITH_3_JSONPATH_FIELDS = + "{\\\"QueryLanguage\\\":\\\"JSONata\\\",\\\"StartAt\\\":\\\"X\\\"," + + "\\\"States\\\":{\\\"X\\\":{\\\"Type\\\":\\\"Pass\\\",\\\"End\\\":true," + + "\\\"InputPath\\\":\\\"$.a\\\"," + + "\\\"OutputPath\\\":\\\"$.b\\\"," + + "\\\"ResultPath\\\":\\\"$.c\\\"}}}"; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void validDefinition_returnsOK() { + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"" + VALID_ASL + "\"}") + .when().post("/") + .then().statusCode(200) + .body("result", equalTo("OK")) + .body("diagnostics", hasSize(0)) + .body("truncated", is(false)); + } + + @Test + void malformedJson_returnsFailWithInvalidJson() { + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"{not json\"}") + .when().post("/") + .then().statusCode(200) + .body("result", equalTo("FAIL")) + .body("diagnostics", hasSize(1)) + .body("diagnostics[0].severity", equalTo("ERROR")) + .body("diagnostics[0].code", equalTo("INVALID_JSON_DESCRIPTION")) + // No location for JSON parse errors — there's no state path to point to yet. + .body("diagnostics[0].location", nullValue()); + } + + @Test + void jsonataStateWithJsonpathField_returnsFailWithSchemaError() { + // A single JSONata state declaring InputPath → exactly 1 error. + String def = "{\\\"QueryLanguage\\\":\\\"JSONata\\\",\\\"StartAt\\\":\\\"X\\\"," + + "\\\"States\\\":{\\\"X\\\":{\\\"Type\\\":\\\"Pass\\\",\\\"End\\\":true," + + "\\\"InputPath\\\":\\\"$.a\\\"}}}"; + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"" + def + "\"}") + .when().post("/") + .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].location", equalTo("/States/X/InputPath")); + } + + @Test + void emptyDefinition_returns400() { + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"\"}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + } + + @Test + void missingDefinition_returns400() { + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + } + + @Test + void maxResultsTruncates() { + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"" + JSONATA_WITH_3_JSONPATH_FIELDS + "\",\"maxResults\":1}") + .when().post("/") + .then().statusCode(200) + .body("result", equalTo("FAIL")) + .body("diagnostics", hasSize(1)) + .body("truncated", is(true)); + } + + @Test + void maxResultsZeroUsesDefault() { + // Per AWS spec: maxResults=0 means "use default of 100", not "return zero". + // The 3 errors from JSONATA_WITH_3_JSONPATH_FIELDS all fit under 100 → no truncation. + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"" + JSONATA_WITH_3_JSONPATH_FIELDS + "\",\"maxResults\":0}") + .when().post("/") + .then().statusCode(200) + .body("result", equalTo("FAIL")) + .body("diagnostics", hasSize(3)) + .body("truncated", is(false)); + } + + @Test + void validDefinition_doesNotTouchStorage() { + // Snapshot the state-machine list, validate a definition, snapshot again — must match. + int before = given().contentType(CT).header("X-Amz-Target", LIST_TARGET) + .body("{}") + .when().post("/") + .then().statusCode(200) + .extract().jsonPath().getList("stateMachines").size(); + + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"" + VALID_ASL + "\"}") + .when().post("/") + .then().statusCode(200); + + int after = given().contentType(CT).header("X-Amz-Target", LIST_TARGET) + .body("{}") + .when().post("/") + .then().statusCode(200) + .extract().jsonPath().getList("stateMachines").size(); + + // Same count proves validate didn't create a state machine. + Assertions.assertEquals(before, after, + "validate must not touch storage (before=" + before + " after=" + after + ")"); + } + + @Test + void typeParameterAccepted() { + // Floci's validator is type-agnostic; the param round-trips without changing behavior. + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"" + VALID_ASL + "\",\"type\":\"EXPRESS\"}") + .when().post("/") + .then().statusCode(200) + .body("result", equalTo("OK")); + } + + @Test + void maxResultsAbove100Rejected() { + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"" + VALID_ASL + "\",\"maxResults\":101}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + } + + @Test + void maxResultsBelowZeroRejected() { + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"" + VALID_ASL + "\",\"maxResults\":-1}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + } + + @Test + void severityInvalidEnumRejected() { + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"" + VALID_ASL + "\",\"severity\":\"GARBAGE\"}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + } + + @Test + void typeInvalidEnumRejected() { + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"" + VALID_ASL + "\",\"type\":\"BOGUS\"}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + } + + @Test + void maxResultsNonIntegerRejected() { + // JsonNode.asInt() would silently coerce "abc" to 0, which the service then + // treats as "use default". Reject at the handler boundary instead. + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"" + VALID_ASL + "\",\"maxResults\":\"abc\"}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + } + + @Test + void maxResultsFractionalRejected() { + given().contentType(CT).header("X-Amz-Target", TARGET) + .body("{\"definition\":\"" + VALID_ASL + "\",\"maxResults\":1.7}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + } +}