diff --git a/docs/services/codepipeline.md b/docs/services/codepipeline.md index 5e6c10177e..bc19c773c6 100644 --- a/docs/services/codepipeline.md +++ b/docs/services/codepipeline.md @@ -39,6 +39,14 @@ The following providers execute against local Floci services: AWS-managed providers without a corresponding Floci execution adapter fail the action with an AWS-shaped action error. Floci does not call real AWS accounts or third-party SaaS providers. +## Approvals + +`PutApprovalResult` completes waiting Manual approval actions with AWS-shaped validation +and error responses. Floci validates the stage and action names, enforces `result.status` +as `Approved` or `Rejected`, limits `result.summary` to 512 characters, returns +`InvalidApprovalTokenException` for unknown tokens, and returns +`ApprovalAlreadyCompletedException` if the same approval token is reused after completion. + ## Configuration | Variable | Default | Description | diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index e51c9486cb..0c0faa5739 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -71,6 +71,25 @@ uniformly between zero and the computed delay, as on AWS. One deviation. The del between attempts is capped at 30 seconds, the same cap Floci applies to `Wait` states, so emulated runs stay fast. +## JSONata nulls + +An expression that evaluates to JSON `null` produces a value, not a missing one. It keeps its key +in `Output`, in `Assign` and in a Task's `Arguments`, at any nesting depth, and it stays in place as +an array element: + +``` +"Output": {"v": "{% $states.input.bar %}"} on input {"bar": null} -> {"v": null} +``` + +The same `null` is a value inside the expression too: `$exists()` on it is true and `$type()` on it +is `"null"`. Only an expression that returns nothing loses its key, which is what +`$states.input.absent` and the functions listed below that evaluate to undefined do. + +Two deviations. `$count()` on a JSON null answers `0`; AWS answers `1`. And dropping the key of an +expression that returned nothing is Floci's own behaviour: AWS fails the state instead, with +`States.QueryEvaluationError` and `The JSONata expression '$states.input.absent' specified for the +field 'Output/v' returned nothing (undefined).` + ## JSONata functions State machines with `"QueryLanguage": "JSONata"` reach the six functions Step Functions adds on @@ -99,9 +118,103 @@ JSONata's own `$string` follows AWS's number notation: a whole number is written `1e21` and in exponent notation from there, on both signs, so `$string(1e20)` is `100000000000000000000` and `$string(1e21)` is `1e+21`. -One deviation. AWS bounds the memory an expression may use and fails a `$range` of roughly half a -million elements with `Expression evaluation memory limit exceeded`; Floci has no such bound and -builds the array. +Evaluation is bounded, as it is on AWS: one expression may run for five seconds and nest 500 +levels deep, and past either the state fails with `States.QueryEvaluationError`. Both bounds sit +well above what AWS itself accepts, so an expression that evaluates there evaluates here. AWS +refuses a non-tail-recursive function past a nesting depth near 100, and the largest sequence it +accepts evaluates here in about a tenth of a second. + +One deviation. AWS also bounds the *memory* an expression may use, refusing +`[1..900000] ~> $count()` with `Expression evaluation memory limit exceeded` while accepting the +same expression at 800,000 elements. Floci bounds time and depth but not memory, and its ranges +are lazy, so that expression answers immediately at any size. + +## Nested workflows + +A parent workflow calls a child workflow through one of several integrations, and they differ in +more than syntax: + +| Resource | Child type | A child that fails | Result | +| --- | --- | --- | --- | +| `arn:aws:states:::states:startExecution` | Standard | not awaited | `{executionArn, startDate}` | +| `arn:aws:states:::states:startExecution.sync` | Standard | fails the calling task | execution envelope, `output` as a JSON string | +| `arn:aws:states:::states:startExecution.sync:2` | Standard | fails the calling task | the child output, parsed | +| `arn:aws:states:::aws-sdk:sfn:startExecution` | Standard | not awaited | `{ExecutionArn, StartDate}` | +| `arn:aws:states:::aws-sdk:sfn:startSyncExecution` | Express | reported through `Status` | PascalCase envelope, `Output` as a JSON string | + +`states:startExecution` and `aws-sdk:sfn:startExecution` are the same API through two different +integrations, and only the casing of the result tells them apart. + +`startSyncExecution` is the only one that does not fail the calling task when the child fails: the +SDK call itself succeeded, so the task result carries `Status`, `Error` and `Cause` and the parent +decides what to do next. + +## AWS SDK task integrations + +A resource of the form `arn:aws:states:::aws-sdk::` calls the service's API and +returns its response. Two conventions separate that result from the same API's wire response, and +both are AWS's: + +- **Field names are the SDK's**, so a `startDate` on the wire is a `StartDate` in the task result. +- **A timestamp is an ISO-8601 string** such as `2026-08-28T20:34:59.712Z`, where the wire response + carries epoch seconds. + +A failure names the SDK exception class, which always ends in `Exception`: +`StartExecution` answers a missing state machine with the error code `StateMachineDoesNotExist` on +the wire and the task fails with `Sfn.StateMachineDoesNotExistException`. + +| Resource | Result | Notable failure | +| --- | --- | --- | +| `arn:aws:states:::aws-sdk:sfn:startExecution` | `{ExecutionArn, StartDate}` | `Sfn.ExecutionAlreadyExistsException` when `Name` is reused | +| `arn:aws:states:::aws-sdk:sfn:startSyncExecution` | execution envelope | `Sfn.StateMachineTypeNotSupportedException` for a Standard child | +| `arn:aws:states:::aws-sdk:sfn:sendTaskSuccess` | `{}` | `Sfn.InvalidTokenException` when no task is waiting on the token | +| `arn:aws:states:::aws-sdk:sfn:sendTaskFailure` | `{}` | `Sfn.InvalidTokenException` | +| `arn:aws:states:::aws-sdk:scheduler:createSchedule` | `{ScheduleArn}` | `Scheduler.ConflictException` when the name is taken | +| `arn:aws:states:::aws-sdk:scheduler:updateSchedule` | `{ScheduleArn}` | `Scheduler.ResourceNotFoundException` | + +`sendTaskSuccess` and `sendTaskFailure` resolve a token a `.waitForTaskToken` task is parked on. A +token nobody is waiting for fails the calling task rather than reporting a delivery that never +happened. + +## Publishing events + +`arn:aws:states:::events:putEvents` returns the PutEvents response itself, `Entries` and +`FailedEntryCount`, and one rejected entry fails the whole task with `EventBridge.FailedEntry`. The +cause is the response serialized as a string, so a `Catch` can read which entry was rejected: + +```json +{"FailedEntryCount":1,"Entries":[{"EventId":"08cbdc46-…"},{"ErrorCode":"InvalidArgument","ErrorMessage":"EventBus not found: no-such-bus"}]} +``` + +One deviation, and it belongs to EventBridge rather than to the integration: Floci rejects an entry +addressed to an event bus that does not exist, while AWS accepts it and returns an `EventId`. + +## JSONata expressions are validated when the state machine is created + +A JSONata expression runs with no context item: the execution input arrives as `$states.input` +and a variable written by `Assign` as `$name`. A path that starts from neither reads a context +item that does not exist, and AWS refuses the whole definition: + +``` +An error occurred (InvalidDefinition) when calling the CreateStateMachine operation: +Invalid State Machine Definition: 'UNSUPPORTED_JSONATA_EXPRESSION: Reference to 'phone' at the +top level is not supported. at /States/E/Output/v' +``` + +Floci refuses it too, from `CreateStateMachine`, `UpdateStateMachine` and +`ValidateStateMachineDefinition`, with that message and that location. Write +`$states.input.phone` to read the input and `$phone` to read a variable: an earlier `Assign` of +`phone` does not put a bare `phone` in scope on AWS either. + +Only the first step of a path is read against the top-level context, so a name in a later step, +in a predicate, in a sort term or in an object grouping stays legal and +`$states.input.items[value > 3]` is accepted. A lambda body keeps the context of the expression +that defines it, so `$map($states.input.a, function($x){ b })` does name `b` at the top level. + +Two neighbouring rules stay with the execution rather than the definition. A syntax error such as +`{% a[1,2) %}` is accepted here and fails the execution, where AWS reports +`INVALID_JSONATA_EXPRESSION` when the state machine is created; and `$$`, which AWS refuses under +its own message, is accepted here. ## Mocked service integrations diff --git a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java index bce62efef2..19b1467e16 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java +++ b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java @@ -39,6 +39,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; @@ -322,12 +323,40 @@ public class CodePipelineService { String pipelineName = text(request, "pipelineName"); requirePipeline(account, region, pipelineName); List executions = executions(account, region, pipelineName); - JsonNode filter = request.path("filter"); - if (filter.hasNonNull("succeededInStage")) { - String stage = filter.path("succeededInStage").asText(); + JsonNode filter = request.get("filter"); + if (filter != null && !filter.isNull() && !filter.isObject()) { + throw new AwsException("ValidationException", "filter must be an object", 400); + } + if (filter != null && filter.isObject()) { + requireOnlyMembers(filter, "filter", Set.of("succeededInStage")); + } + JsonNode succeededInStage = filter == null ? null : filter.get("succeededInStage"); + if (succeededInStage != null && !succeededInStage.isNull()) { + if (!succeededInStage.isObject()) { + throw new AwsException("ValidationException", + "succeededInStage requires stageName", 400); + } + requireOnlyMembers(succeededInStage, "succeededInStage", Set.of("stageName")); + JsonNode stageNameNode = succeededInStage.get("stageName"); + if (stageNameNode == null || stageNameNode.isNull() || !stageNameNode.isTextual() + || stageNameNode.asText().isBlank()) { + throw new AwsException("ValidationException", + "succeededInStage requires stageName", 400); + } + String stage = stageNameNode.asText(); executions = executions.stream().filter(e -> actionExecutionsForStage(e, stage).stream() .allMatch(a -> "Succeeded".equals(a.getStatus()))).toList(); } + if (request.hasNonNull("maxResults")) { + JsonNode maxResultsNode = request.get("maxResults"); + if (!maxResultsNode.isIntegralNumber()) { + throw new AwsException("ValidationException", "maxResults must be an integer", 400); + } + int maxResults = maxResultsNode.asInt(); + if (maxResults < 1 || maxResults > 100) { + throw new AwsException("ValidationException", "maxResults must be between 1 and 100", 400); + } + } Page page = page(request, executions.size(), 100); ObjectNode response = mapper.createObjectNode(); ArrayNode summaries = response.putArray("pipelineExecutionSummaries"); @@ -414,23 +443,60 @@ public class CodePipelineService { String stageName = text(request, "stageName"); String actionName = text(request, "actionName"); String token = text(request, "token"); - String status = request.path("result").path("status").asText(); + JsonNode resultNode = request.get("result"); + if (resultNode == null || resultNode.isNull()) { + throw new AwsException("ValidationException", "result is required", 400); + } + if (!resultNode.isObject()) { + throw new AwsException("ValidationException", "result must be an object", 400); + } + String status = text(resultNode, "status"); + if (!List.of("Approved", "Rejected").contains(status)) { + throw new AwsException("ValidationException", + "result.status must be one of [Approved, Rejected]", 400); + } + JsonNode summaryNode = resultNode.get("summary"); + String summary = ""; + if (summaryNode != null && !summaryNode.isNull()) { + if (!summaryNode.isTextual()) { + throw new AwsException("ValidationException", "result.summary must be a string", 400); + } + summary = summaryNode.asText(); + } + if (summary.length() > 512) { + throw new AwsException("ValidationException", + "result.summary must not exceed 512 characters", 400); + } + + CodePipelinePipeline pipeline = requirePipeline(account, region, pipelineName); + CodePipelineExecution execution = executions(account, region, pipelineName).stream() .filter(e -> e.getActionExecutions().stream() .anyMatch(a -> stageName.equals(a.getStageName()) && actionName.equals(a.getActionName()) - && token.equals(a.getToken()) - && "InProgress".equals(a.getStatus()))) + && token.equals(a.getToken()))) .findFirst() - .orElseThrow(() -> new AwsException( - "InvalidApprovalTokenException", "Approval token is invalid", 400)); - ActionExecution approval = execution.getActionExecutions().stream() + .orElse(null); + + ActionExecution approval = execution == null ? null : execution.getActionExecutions().stream() .filter(a -> stageName.equals(a.getStageName()) && actionName.equals(a.getActionName())) - .filter(a -> token.equals(a.getToken()) && "InProgress".equals(a.getStatus())) + .filter(a -> token.equals(a.getToken())) .findFirst() - .orElseThrow(); + .orElse(null); + + if (approval == null) { + requireStage(pipeline, stageName); + requireAction(pipeline, stageName, actionName); + throw new AwsException("InvalidApprovalTokenException", "Approval token is invalid", 400); + } + + if (!"InProgress".equals(approval.getStatus())) { + throw new AwsException("ApprovalAlreadyCompletedException", + "The approval action has already been approved or rejected.", 400); + } + approval.setStatus("Approved".equals(status) ? "Succeeded" : "Failed"); - approval.setSummary(request.path("result").path("summary").asText(status)); + approval.setSummary(summary); approval.setLastUpdateTime(now()); putExecution(execution); return mapper.createObjectNode().put("approvedAt", now()); @@ -1127,6 +1193,14 @@ public class CodePipelineService { } } + private static void requireOnlyMembers(JsonNode node, String label, Set allowed) { + node.fieldNames().forEachRemaining(field -> { + if (!allowed.contains(field)) { + throw new AwsException("ValidationException", "Unknown " + label + " member: " + field, 400); + } + }); + } + private void requireStage(CodePipelinePipeline pipeline, String stageName) { for (JsonNode stage : pipeline.getDeclaration().path("stages")) { if (stageName.equals(stage.path("name").asText())) { @@ -1136,6 +1210,20 @@ public class CodePipelineService { throw new AwsException("StageNotFoundException", "Stage not found: " + stageName, 400); } + private void requireAction(CodePipelinePipeline pipeline, String stageName, String actionName) { + for (JsonNode stage : pipeline.getDeclaration().path("stages")) { + if (stageName.equals(stage.path("name").asText())) { + for (JsonNode action : stage.path("actions")) { + if (actionName.equals(action.path("name").asText())) { + return; + } + } + throw new AwsException("ActionNotFoundException", "Action not found: " + actionName, 400); + } + } + throw new AwsException("StageNotFoundException", "Stage not found: " + stageName, 400); + } + private ObjectNode executionNode(CodePipelineExecution execution) { ObjectNode node = mapper.valueToTree(execution); node.remove(List.of("accountId", "region", "startTime", "lastUpdateTime", diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandler.java index 1f44fc182e..a92b907e4a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandler.java @@ -125,6 +125,12 @@ public class MySqlProtocolHandler { // permanently one behind the client's for the rest of the connection phase. sequenceOffset = 1; clientResponseRaw[3] = (byte) (clientResponseRaw[3] - sequenceOffset); + // Real clients keep CLIENT_SSL set in the HandshakeResponse they send over the + // now-encrypted stream. The backend connection stays plaintext, and a MySQL server + // treats any first packet with CLIENT_SSL as an SSLRequest — it would sit waiting for + // a TLS ClientHello that never comes while the proxy waits for its auth verdict, + // deadlocking the connection. Clear the bit (the mirror of forceClientSslCapability). + clearClientSslCapability(clientResponseRaw); } else { clientResponseRaw = clientFirstRaw; if (clientResponseRaw.length < 40) { @@ -259,6 +265,15 @@ public class MySqlProtocolHandler { } } + /** + * Clears the {@code CLIENT_SSL} bit in a raw HandshakeResponse41 packet's capability flags. + * The client capabilities are the first 4 payload bytes, little-endian; {@code CLIENT_SSL} + * (0x0800) lives in the second byte. + */ + private static void clearClientSslCapability(byte[] raw) { + raw[5] &= (byte) ~(CLIENT_SSL >> 8); + } + /** * Sets the {@code CLIENT_SSL} bit in a raw Handshake V10 packet's capability flags, so the * client is offered TLS even when the (plaintext) backend didn't advertise it. Walks the same diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerController.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerController.java index 3febecc115..d3624d0dac 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerController.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerController.java @@ -354,7 +354,12 @@ public class SchedulerController { return null; } - private ScheduleRequest parseScheduleRequest(JsonNode node) { + /** + * Reads the PascalCase CreateSchedule / UpdateSchedule body. The Step Functions + * {@code aws-sdk:scheduler:*} Task integrations pass the same shape as {@code Arguments}, + * so they parse it here instead of restating the mapping. + */ + public ScheduleRequest parseScheduleRequest(JsonNode node) { ScheduleRequest req = new ScheduleRequest(); req.setGroupName(textField(node, "GroupName")); req.setScheduleExpression(textField(node, "ScheduleExpression")); @@ -471,8 +476,8 @@ public class SchedulerController { private EcsParameters parseEcsParameters(JsonNode node) { EcsParameters ecs = new EcsParameters(); - if (node.has("CapacityProviderStrategy") && node.get("CapacityProviderStrategy").isArray()) { - ecs.setCapacityProviderStrategy(mapList(node.get("CapacityProviderStrategy"))); + if (node.has("CapacityProviderStrategy") && !node.get("CapacityProviderStrategy").isNull()) { + ecs.setCapacityProviderStrategy(mapList("CapacityProviderStrategy", node.get("CapacityProviderStrategy"))); } if (node.has("EnableECSManagedTags") && !node.get("EnableECSManagedTags").isNull()) { ecs.setEnableECSManagedTags(node.get("EnableECSManagedTags").asBoolean()); @@ -489,11 +494,11 @@ public class SchedulerController { if (node.has("LaunchType") && !node.get("LaunchType").isNull()) { ecs.setLaunchType(node.get("LaunchType").asText()); } - if (node.has("PlacementConstraints") && node.get("PlacementConstraints").isArray()) { - ecs.setPlacementConstraints(mapList(node.get("PlacementConstraints"))); + if (node.has("PlacementConstraints") && !node.get("PlacementConstraints").isNull()) { + ecs.setPlacementConstraints(mapList("PlacementConstraints", node.get("PlacementConstraints"))); } - if (node.has("PlacementStrategy") && node.get("PlacementStrategy").isArray()) { - ecs.setPlacementStrategy(mapList(node.get("PlacementStrategy"))); + if (node.has("PlacementStrategy") && !node.get("PlacementStrategy").isNull()) { + ecs.setPlacementStrategy(mapList("PlacementStrategy", node.get("PlacementStrategy"))); } if (node.has("TaskCount") && !node.get("TaskCount").isNull()) { ecs.setTaskCount(node.get("TaskCount").asInt()); @@ -507,8 +512,8 @@ public class SchedulerController { if (node.has("ReferenceId") && !node.get("ReferenceId").isNull()) { ecs.setReferenceId(node.get("ReferenceId").asText()); } - if (node.has("Tags") && node.get("Tags").isArray()) { - ecs.setTags(mapList(node.get("Tags"))); + if (node.has("Tags") && !node.get("Tags").isNull()) { + ecs.setTags(mapList("Tags", node.get("Tags"))); } if (node.has("NetworkConfiguration") && !node.get("NetworkConfiguration").isNull()) { ecs.setNetworkConfiguration(parseNetworkConfiguration(node.get("NetworkConfiguration"))); @@ -516,10 +521,49 @@ public class SchedulerController { return ecs; } - private List> mapList(JsonNode node) { - return objectMapper.convertValue(node, - objectMapper.getTypeFactory().constructCollectionType(List.class, - objectMapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class))); + /** + * Reads one of the {@code EcsParameters} lists of objects. An element that is not an object is a + * malformed body, which AWS answers with 400 {@code SerializationException}, so the conversion + * failure is named here instead of escaping as a server error. + */ + private List> mapList(String field, JsonNode node) { + if (!node.isArray()) { + throw malformedList(field, "objects"); + } + try { + return objectMapper.convertValue(node, + objectMapper.getTypeFactory().constructCollectionType(List.class, + objectMapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class))); + } catch (IllegalArgumentException e) { + throw malformedList(field, "objects"); + } + } + + /** + * {@link #mapList(String, JsonNode)} for the {@code awsvpcConfiguration} lists of strings. + * A number or a boolean is checked before the conversion because Jackson writes it out as a + * string rather than refusing it, which would store a value AWS never accepts. + */ + private List stringList(String field, JsonNode node) { + if (!node.isArray()) { + throw malformedList(field, "strings"); + } + for (JsonNode element : node) { + if (!element.isTextual()) { + throw malformedList(field, "strings"); + } + } + try { + return objectMapper.convertValue(node, + objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)); + } catch (IllegalArgumentException e) { + throw malformedList(field, "strings"); + } + } + + private AwsException malformedList(String field, String elementType) { + return new AwsException("SerializationException", + "EcsParameters " + field + " must be a list of " + elementType + ".", 400); } private NetworkConfiguration parseNetworkConfiguration(JsonNode node) { @@ -532,11 +576,11 @@ public class SchedulerController { private AwsVpcConfiguration parseAwsVpcConfiguration(JsonNode node) { AwsVpcConfiguration vpc = new AwsVpcConfiguration(); - if (node.has("Subnets") && node.get("Subnets").isArray()) { - vpc.setSubnets(objectMapper.convertValue(node.get("Subnets"), objectMapper.getTypeFactory().constructCollectionType(List.class, String.class))); + if (node.has("Subnets") && !node.get("Subnets").isNull()) { + vpc.setSubnets(stringList("Subnets", node.get("Subnets"))); } - if (node.has("SecurityGroups") && node.get("SecurityGroups").isArray()) { - vpc.setSecurityGroups(objectMapper.convertValue(node.get("SecurityGroups"), objectMapper.getTypeFactory().constructCollectionType(List.class, String.class))); + if (node.has("SecurityGroups") && !node.get("SecurityGroups").isNull()) { + vpc.setSecurityGroups(stringList("SecurityGroups", node.get("SecurityGroups"))); } if (node.has("AssignPublicIp") && !node.get("AssignPublicIp").isNull()) { vpc.setAssignPublicIp(node.get("AssignPublicIp").asText()); 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 4851f68368..f4264bb300 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 @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHan import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.ecs.EcsService; import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition; @@ -20,6 +21,10 @@ import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; import io.github.hectorvent.floci.services.ecs.model.LaunchType; import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.scheduler.SchedulerController; +import io.github.hectorvent.floci.services.scheduler.SchedulerService; +import io.github.hectorvent.floci.services.scheduler.model.Schedule; +import io.github.hectorvent.floci.services.scheduler.model.ScheduleRequest; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.lambda.model.InvocationType; @@ -61,6 +66,9 @@ import org.jboss.logging.Logger; import java.net.URI; import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -107,6 +115,17 @@ public class AslExecutor { private static final long ECS_SYNC_POLL_INTERVAL_MS = 100; private static final String QUERY_LANGUAGE_JSONATA = "JSONata"; + private static final String AWS_SDK_SFN_PREFIX = "arn:aws:states:::aws-sdk:sfn:"; + private static final String AWS_SDK_SCHEDULER_PREFIX = "arn:aws:states:::aws-sdk:scheduler:"; + + /** + * A timestamp inside an {@code aws-sdk:} Task result is the SDK's ISO-8601 rendering of an + * {@code Instant} — {@code 2026-08-28T20:34:59.712Z} — where the same field on the wire + * response of the underlying API carries epoch seconds. + */ + private static final DateTimeFormatter SDK_TIMESTAMP = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC); + private static final Set HTTP_ALLOWED_METHODS = Set.of( "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"); private static final Set HTTP_FORBIDDEN_HEADERS = Set.of( @@ -153,6 +172,9 @@ public class AslExecutor { private final S3Service s3Service; private final EcsService ecsService; private final EcsJsonHandler ecsJsonHandler; + private final EventBridgeHandler eventBridgeHandler; + private final SchedulerService schedulerService; + private final SchedulerController schedulerController; private final ObjectMapper objectMapper; private final JsonataEvaluator jsonataEvaluator; private final Instance sfnService; @@ -172,6 +194,8 @@ public class AslExecutor { SqsJsonHandler sqsJsonHandler, CloudFormationQueryHandler cloudFormationHandler, Ec2Service ec2Service, S3Service s3Service, EcsService ecsService, EcsJsonHandler ecsJsonHandler, + EventBridgeHandler eventBridgeHandler, SchedulerService schedulerService, + SchedulerController schedulerController, ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator, Instance sfnService, EmulatorConfig config, Vertx vertx, CustomResourceLiveness customResourceLiveness) { @@ -186,6 +210,9 @@ public class AslExecutor { this.s3Service = s3Service; this.ecsService = ecsService; this.ecsJsonHandler = ecsJsonHandler; + this.eventBridgeHandler = eventBridgeHandler; + this.schedulerService = schedulerService; + this.schedulerController = schedulerController; this.objectMapper = objectMapper; this.jsonataEvaluator = jsonataEvaluator; this.sfnService = sfnService; @@ -818,6 +845,26 @@ public class AslExecutor { return invokeEcsRunTask(mode, input, region); } + // AWS SDK service integrations: Step Functions + if (resource.startsWith(AWS_SDK_SFN_PREFIX)) { + String action = resource.substring(AWS_SDK_SFN_PREFIX.length()); + String region = extractRegionFromArn(sm.getStateMachineArn()); + return invokeAwsSdkSfn(action, input, region); + } + + // AWS SDK service integrations: EventBridge Scheduler + if (resource.startsWith(AWS_SDK_SCHEDULER_PREFIX)) { + String action = resource.substring(AWS_SDK_SCHEDULER_PREFIX.length()); + String region = extractRegionFromArn(sm.getStateMachineArn()); + return invokeAwsSdkScheduler(action, input, region); + } + + // EventBridge optimized integration + if (resource.equals("arn:aws:states:::events:putEvents")) { + String region = extractRegionFromArn(sm.getStateMachineArn()); + return invokeOptimizedPutEvents(input, region); + } + // Nested state machine integration if (resource.startsWith("arn:aws:states:::states:startExecution")) { String mode = resource.substring("arn:aws:states:::states:startExecution".length()); @@ -942,6 +989,194 @@ public class AslExecutor { return s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1); } + /** + * The {@code arn:aws:states:::aws-sdk:sfn:*} family. Every one of these calls Step Functions' + * own API and returns its raw response, which is what separates + * {@code aws-sdk:sfn:startExecution} from the optimized {@code states:startExecution} + * handled by {@link #invokeNestedStateMachine}. + */ + private JsonNode invokeAwsSdkSfn(String action, JsonNode input, String region) throws Exception { + return switch (action) { + case "startExecution" -> invokeAwsSdkSfnStartExecution(input, region); + case "startSyncExecution" -> invokeAwsSdkSfnStartSyncExecution(input, region); + case "sendTaskSuccess" -> invokeAwsSdkSfnSendTaskSuccess(input); + case "sendTaskFailure" -> invokeAwsSdkSfnSendTaskFailure(input); + default -> throw new FailStateException("States.TaskFailed", + "Unsupported resource: " + AWS_SDK_SFN_PREFIX + action); + }; + } + + /** + * An {@code aws-sdk:} Task failure carries the name of the SDK exception class, which always + * ends in {@code Exception}. AWS answers a missing state machine with + * {@code Sfn.StateMachineDoesNotExistException}, while the StartExecution wire response names + * that same error {@code StateMachineDoesNotExist}. + */ + private static String sdkExceptionName(String service, String errorCode) { + return errorCode.endsWith("Exception") + ? service + "." + errorCode + : service + "." + errorCode + "Exception"; + } + + private static String sdkTimestamp(double epochSeconds) { + return SDK_TIMESTAMP.format(Instant.ofEpochMilli(Math.round(epochSeconds * 1000))); + } + + /** + * Reads an SDK payload argument such as {@code Input} or {@code Output}. Its AWS type is a JSON + * string; AWS also accepts the object form and serializes it, and an absent one is an empty + * object. + */ + private String sdkPayload(JsonNode node) throws Exception { + if (node.isMissingNode() || node.isNull()) { + return "{}"; + } + return node.isTextual() ? node.asText() : objectMapper.writeValueAsString(node); + } + + /** + * AWS SDK integration for {@code sfn:startExecution}. Unlike the optimized + * {@code states:startExecution}, which returns {@code executionArn} and {@code startDate} in + * the casing of the wire response, this one returns the SDK's own {@code ExecutionArn} and an + * ISO-8601 {@code StartDate}. Neither waits for the child. + */ + private JsonNode invokeAwsSdkSfnStartExecution(JsonNode input, String region) throws Exception { + String smArn = input.path("StateMachineArn").asText(null); + if (smArn == null || smArn.isBlank()) { + throw new FailStateException("Sfn.InvalidArnException", + "StateMachineArn is required for StartExecution"); + } + io.github.hectorvent.floci.services.stepfunctions.model.Execution exec; + try { + exec = sfnService.get().startExecution(smArn, input.path("Name").asText(null), + sdkPayload(input.path("Input")), region); + } catch (AwsException e) { + throw new FailStateException(sdkExceptionName("Sfn", e.getErrorCode()), e.getMessage()); + } + ObjectNode response = objectMapper.createObjectNode(); + response.put("ExecutionArn", exec.getExecutionArn()); + response.put("StartDate", sdkTimestamp(exec.getStartDate())); + return response; + } + + /** + * AWS SDK integration for {@code sfn:sendTaskSuccess}. AWS fails the calling task with + * {@code Sfn.InvalidTokenException} when the token names no waiting task, so a token that + * resolved nothing is never reported as a delivered result. + */ + private JsonNode invokeAwsSdkSfnSendTaskSuccess(JsonNode input) throws Exception { + String taskToken = input.path("TaskToken").asText(null); + if (!sfnService.get().sendTaskSuccess(taskToken, sdkPayload(input.path("Output")))) { + throw new FailStateException("Sfn.InvalidTokenException", "Invalid Token: 'Invalid token'"); + } + return objectMapper.createObjectNode(); + } + + /** AWS SDK integration for {@code sfn:sendTaskFailure}, token semantics as in SendTaskSuccess. */ + private JsonNode invokeAwsSdkSfnSendTaskFailure(JsonNode input) { + String taskToken = input.path("TaskToken").asText(null); + if (!sfnService.get().sendTaskFailure(taskToken, input.path("Cause").asText(null), + input.path("Error").asText(null))) { + throw new FailStateException("Sfn.InvalidTokenException", "Invalid Token: 'Invalid token'"); + } + return objectMapper.createObjectNode(); + } + + /** + * AWS SDK integrations for {@code scheduler:createSchedule} and {@code scheduler:updateSchedule}. + * The Task {@code Arguments} are the CreateSchedule body with {@code Name} folded in, so they go + * through the controller's parse, and both actions answer with the schedule ARN alone. The parse + * rejects a malformed {@code Target} with the same {@code AwsException} the service raises, so it + * belongs inside the translation that makes those failures reachable for {@code Retry} and + * {@code Catch}. + */ + private JsonNode invokeAwsSdkScheduler(String action, JsonNode input, String region) { + boolean creating = "createSchedule".equals(action); + if (!creating && !"updateSchedule".equals(action)) { + throw new FailStateException("States.TaskFailed", + "Unsupported resource: " + AWS_SDK_SCHEDULER_PREFIX + action); + } + try { + ScheduleRequest request = schedulerController.parseScheduleRequest(input); + request.setName(input.path("Name").asText(null)); + Schedule schedule = creating + ? schedulerService.createSchedule(request, region) + : schedulerService.updateSchedule(request, region); + ObjectNode response = objectMapper.createObjectNode(); + response.put("ScheduleArn", schedule.getArn()); + return response; + } catch (AwsException e) { + throw new FailStateException(sdkExceptionName("Scheduler", e.getErrorCode()), e.getMessage()); + } + } + + /** + * Optimized EventBridge integration for {@code events:putEvents}. The task result is the + * PutEvents response itself, and one failed entry fails the whole task with + * {@code EventBridge.FailedEntry}, carrying the response as the cause so the caller can see + * which entry it was. + */ + private JsonNode invokeOptimizedPutEvents(JsonNode input, String region) throws Exception { + jakarta.ws.rs.core.Response response; + try { + response = eventBridgeHandler.handle("PutEvents", input, region); + } catch (AwsException e) { + throw new FailStateException(sdkExceptionName("EventBridge", e.getErrorCode()), e.getMessage()); + } + if (!(response.getEntity() instanceof JsonNode result)) { + throw new FailStateException("EventBridge.SdkClientException", "PutEvents returned no response body"); + } + if (result.path("FailedEntryCount").asInt() > 0) { + throw new FailStateException("EventBridge.FailedEntry", objectMapper.writeValueAsString(result)); + } + return result; + } + + /** + * AWS SDK integration for {@code sfn:startSyncExecution}, the way an EXPRESS child workflow is + * called. It differs from the optimized {@code states:startExecution.sync} integration in three + * ways: the child must be EXPRESS, the response envelope uses PascalCase field names with + * {@code Output} as a JSON string, and a child execution that fails is reported through + * {@code Status} rather than failing the calling task. + */ + private JsonNode invokeAwsSdkSfnStartSyncExecution(JsonNode input, String region) throws Exception { + String smArn = input.path("StateMachineArn").asText(null); + if (smArn == null || smArn.isBlank()) { + throw new FailStateException("Sfn.InvalidArnException", + "StateMachineArn is required for StartSyncExecution"); + } + io.github.hectorvent.floci.services.stepfunctions.model.Execution exec; + try { + exec = sfnService.get().startSyncExecution(smArn, input.path("Name").asText(null), + sdkPayload(input.path("Input")), region); + } catch (AwsException e) { + throw new FailStateException(sdkExceptionName("Sfn", e.getErrorCode()), e.getMessage()); + } + + ObjectNode envelope = objectMapper.createObjectNode(); + envelope.put("ExecutionArn", exec.getExecutionArn()); + envelope.put("StateMachineArn", exec.getStateMachineArn()); + envelope.put("Name", exec.getName()); + envelope.put("Status", exec.getStatus()); + envelope.put("StartDate", sdkTimestamp(exec.getStartDate())); + if (exec.getStopDate() != null) { + envelope.put("StopDate", sdkTimestamp(exec.getStopDate())); + } + if (exec.getInput() != null) { + envelope.put("Input", exec.getInput()); + } + if (exec.getOutput() != null) { + envelope.put("Output", exec.getOutput()); + } + if (exec.getError() != null) { + envelope.put("Error", exec.getError()); + } + if (exec.getCause() != null) { + envelope.put("Cause", exec.getCause()); + } + return envelope; + } + private JsonNode invokeNestedStateMachine(String mode, JsonNode input, String region) throws Exception { String smArn = input.path("StateMachineArn").asText(null); if (smArn == null || smArn.isBlank()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEvaluator.java index a908639b5a..bfa2f02e72 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEvaluator.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEvaluator.java @@ -10,6 +10,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.MissingNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.enterprise.context.ApplicationScoped; @@ -74,12 +75,49 @@ public class JsonataEvaluator { "a", "arrays", "b", "booleans", "f", "functions", "n", "numbers", "o", "objects", "s", "strings"); + /** + * How long one expression may evaluate before the state fails with + * {@code States.QueryEvaluationError}. AWS bounds evaluation and Floci did not, so an + * expression with no base case pinned a core and left the execution {@code RUNNING} for ever. + * JSONata optimises the tail call, so such an expression loops instead of overflowing the + * stack: no {@code Error} is thrown and only a clock can end it. + * + *

Five seconds is the dashjoin library's own default and roughly fifty times the slowest + * evaluation of a payload AWS itself accepts: AWS refuses a sequence of 900,000 elements on + * its memory limit, and summing one that size here takes about 100 ms. Deliberately generous, + * because a bound that fails a working state machine costs more than one that lets a runaway + * expression burn a core for five seconds. + */ + static final long EVALUATION_TIMEOUT_MILLIS = 5_000; + + /** + * How deep evaluation may nest before the state fails. A non-tail-recursive function nests at + * roughly {@code 3n+5} for {@code $f(n)}; measured against AWS with {@code test-state}, AWS + * accepts {@code n=30} (depth 95) and refuses {@code n=40} (depth 125), so its own ceiling + * sits near 100. Five times that leaves no expression AWS accepts able to reach this bound, + * and it still trips before the JVM stack does: on a 1 MB thread stack the bound raises a + * JSONata error while 1000 or more overflows the stack instead. + */ + static final int MAX_EVALUATION_DEPTH = 500; + private final ObjectMapper objectMapper; private final ObjectReader strictJsonReader; private final Map stepFunctionsExtensions; + private final long evaluationTimeoutMillis; + private final int maxEvaluationDepth; @Inject public JsonataEvaluator(ObjectMapper objectMapper) { + this(objectMapper, EVALUATION_TIMEOUT_MILLIS, MAX_EVALUATION_DEPTH); + } + + /** + * Bounds evaluation at values other than the shipped ones, so a test can trip the time bound + * without waiting {@link #EVALUATION_TIMEOUT_MILLIS} for it. + */ + JsonataEvaluator(ObjectMapper objectMapper, long evaluationTimeoutMillis, int maxEvaluationDepth) { + this.evaluationTimeoutMillis = evaluationTimeoutMillis; + this.maxEvaluationDepth = maxEvaluationDepth; this.objectMapper = objectMapper; // AWS rejects what a lenient parser accepts: a second document after the first, a repeated // key, an empty string. All three come back as D3137 there, so $parse reads through this @@ -125,7 +163,16 @@ public class JsonataEvaluator { String expr = isExpression(expression) ? unwrap(expression) : expression; try { Jsonata jsonataExpr = jsonata(expr); + // Off, the library keeps JSONata's null marker in the result instead of flattening it + // into a Java null. On, an expression that evaluated to JSON null and one that returned + // nothing both arrive here as a Java null, and AWS keeps the first while dropping the + // second. + jsonataExpr.setOutputConvertNulls(false); Jsonata.Frame frame = jsonataExpr.createFrame(); + // Without this the library evaluates unbounded: a recursive expression with no base + // case loops for ever and the execution never leaves RUNNING. The bounds raise a + // JSONata error, which the catch below turns into States.QueryEvaluationError. + frame.setRuntimeBounds(evaluationTimeoutMillis, maxEvaluationDepth); stepFunctionsExtensions.forEach(frame::bind); // Workflow variables (the Assign field) are referenced as top-level $name in AWS's // JSONata dialect, e.g. $CheckpointCount. They are bound alongside $states, never @@ -220,9 +267,18 @@ public class JsonataEvaluator { } JsonNode resolveTemplate(JsonNode template, JsonNode statesVar, JsonNode variables) { - if (template == null || template.isNull() || template.isMissingNode()) { + if (template == null || template.isMissingNode()) { return template; } + JsonNode resolved = resolveTemplateNode(template, statesVar, variables); + // A resolved Output or Arguments is serialized as it stands, and a missing node writes + // itself as the empty string, which no client can parse. "Returned nothing" is a value only + // in the positions resolveTemplateNode reads it in: an object field it drops, an array + // element it fails the state on. As the whole field there is nothing to drop it from. + return resolved.isMissingNode() ? NullNode.getInstance() : resolved; + } + + private JsonNode resolveTemplateNode(JsonNode template, JsonNode statesVar, JsonNode variables) { if (template.isTextual()) { String text = template.asText(); if (isExpression(text)) { @@ -235,10 +291,11 @@ public class JsonataEvaluator { Iterator> fields = template.fields(); while (fields.hasNext()) { Map.Entry entry = fields.next(); - JsonNode value = resolveTemplate(entry.getValue(), statesVar, variables); - // Per JSONata spec: undefined (null) values are omitted from object output, - // matching real AWS Step Functions behavior. - if (value != null && !value.isNull() && !value.isMissingNode()) { + JsonNode value = resolveTemplateNode(entry.getValue(), statesVar, variables); + // Per JSONata spec: an expression that returned nothing is omitted from object + // output, matching real AWS Step Functions behavior. A JSON null is a value and + // keeps its key: AWS answers {"v":null} to Output {"v":"{% null %}"}. + if (!value.isMissingNode()) { resolved.set(entry.getKey(), value); } } @@ -248,10 +305,11 @@ public class JsonataEvaluator { ArrayNode resolved = objectMapper.createArrayNode(); for (int i = 0; i < template.size(); i++) { JsonNode element = template.get(i); - JsonNode value = resolveTemplate(element, statesVar, variables); - // Per real AWS behavior: undefined array elements fail the execution. + JsonNode value = resolveTemplateNode(element, statesVar, variables); + // Per real AWS behavior: an array element that returned nothing fails the execution. // Unlike object fields (which are omitted), undefined in an array is a runtime error. - if (value == null || value.isNull() || value.isMissingNode()) { + // A JSON null is a value and stays: AWS answers [null,1] to ["{% null %}",1]. + if (value.isMissingNode()) { String expr = element.isTextual() ? element.asText() : element.toString(); throw new FailStateException("States.Runtime", "The JSONata expression '" + expr + "' at array index " + i + " returned nothing (undefined)."); @@ -260,21 +318,46 @@ public class JsonataEvaluator { } return resolved; } - // Primitives (number, boolean) pass through + // Primitives (number, boolean, null) pass through return template; } - private Object toObject(JsonNode node) { - if (node == null || node.isNull() || node.isMissingNode()) { + /** + * Binds $states and the workflow variables as JSONata values, so a JSON null inside them stays + * a null the expression can see: $exists() on it is true and $type() on it is "null", as on + * AWS. Only an absent node is undefined. + */ + private static Object toObject(JsonNode node) { + if (node == null || node.isMissingNode()) { return null; } - return objectMapper.convertValue(node, Object.class); + return toJsonataValue(node); } + /** + * The evaluation result. A Java null is the expression returning nothing, which + * {@link #resolveTemplateNode} drops from an object; the JSONata null marker is a JSON null, + * which it keeps. Nested inside an object or an array there is no undefined, so every null + * there is a JSON null. + */ private JsonNode toJsonNode(Object value) { - if (value == null) { + return value == null ? MissingNode.getInstance() : fromJsonataValue(value); + } + + private JsonNode fromJsonataValue(Object value) { + if (value == null || value == Jsonata.NULL_VALUE) { return NullNode.getInstance(); } + if (value instanceof Map map) { + ObjectNode object = objectMapper.createObjectNode(); + map.forEach((key, element) -> object.set(String.valueOf(key), fromJsonataValue(element))); + return object; + } + if (value instanceof List list) { + ArrayNode array = objectMapper.createArrayNode(); + list.forEach(element -> array.add(fromJsonataValue(element))); + return array; + } return objectMapper.valueToTree(value); } diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataTopLevelReferences.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataTopLevelReferences.java new file mode 100644 index 0000000000..4b6e87cf2b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataTopLevelReferences.java @@ -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. + * + *

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.} + * + *

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}. + * + *

{@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 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 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 names = new LinkedHashSet<>(); + collect(root, names); + return new ArrayList<>(names); + } + + private static void collect(Parser.Symbol node, Set 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 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 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 nodes, Set names) { + if (nodes == null) { + return; + } + for (Parser.Symbol node : nodes) { + collect(node, names); + } + } + + private static void collectEachPair(List pairs, Set 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 children(Parser.Symbol node, String field) { + return (List) read(node, field); + } + + private static Parser.Symbol first(Parser.Symbol node, String field) { + List 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 resolveTreeFields(String... names) { + Map 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); + } +} 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 9ad33b7bd7..b185dba2e8 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 @@ -57,6 +57,19 @@ public class StepFunctionsService implements Resettable, ResourceProvider { private static final Set 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 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 JSONATA_PAYLOAD_FIELDS = Set.of( + "Output", "Assign", "Arguments", "ItemSelector", "BatchInput"); private static final Set ITEM_READER_RESOURCES = Set.of( "arn:aws:states:::s3:getObject", "arn:aws:states:::s3:listObjectsV2"); @@ -727,26 +740,37 @@ public class StepFunctionsService implements Resettable, ResourceProvider { // ──────────────────────────── Tasks ──────────────────────────── - public void sendTaskSuccess(String taskToken, String output) { - CompletableFuture future = pendingTaskTokens.remove(taskToken); - if (future != null) { - try { - future.complete(objectMapper.readTree(output)); - } catch (Exception e) { - future.completeExceptionally(new RuntimeException("Invalid JSON output: " + e.getMessage())); - } - } else { + /** + * @return whether the token named a task that was waiting for it. The + * {@code aws-sdk:sfn:sendTaskSuccess} Task integration fails the calling state when it + * did not, the way AWS answers an unknown token with {@code InvalidToken}. + */ + public boolean sendTaskSuccess(String taskToken, String output) { + CompletableFuture future = taskToken != null ? pendingTaskTokens.remove(taskToken) : null; + if (future == null) { LOG.warnv("SendTaskSuccess: no pending task for token {0}", taskToken); + return false; } + try { + future.complete(objectMapper.readTree(output)); + } catch (Exception e) { + future.completeExceptionally(new RuntimeException("Invalid JSON output: " + e.getMessage())); + } + return true; } - public void sendTaskFailure(String taskToken, String cause, String error) { - CompletableFuture future = pendingTaskTokens.remove(taskToken); - if (future != null) { - future.completeExceptionally(new AslExecutor.FailStateException(error, cause)); - } else { + /** + * @return whether the token named a task that was waiting for it, as in + * {@link #sendTaskSuccess(String, String)}. + */ + public boolean sendTaskFailure(String taskToken, String cause, String error) { + CompletableFuture future = taskToken != null ? pendingTaskTokens.remove(taskToken) : null; + if (future == null) { LOG.warnv("SendTaskFailure: no pending task for token {0}", taskToken); + return false; } + future.completeExceptionally(new AslExecutor.FailStateException(error, cause)); + return true; } public void sendTaskHeartbeat(String taskToken) { @@ -1003,12 +1027,16 @@ public class StepFunctionsService implements Resettable, ResourceProvider { private static final Set 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//". 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 @@ -1066,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) { @@ -1340,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 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 collectValidationErrors(String definition) { @@ -1423,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)) { @@ -1441,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. + * + *

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 errors) { + collectTopLevelReferences(path, node, false, errors); + } + + private static void collectTopLevelReferences(String path, JsonNode node, boolean insidePayload, + List 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 errors) { if (!states.isObject()) { diff --git a/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineIntegrationTest.java index a92b60565f..2e2e12cd7f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineIntegrationTest.java @@ -27,6 +27,139 @@ class CodePipelineIntegrationTest { RestAssuredJsonUtils.configureAwsContentTypes(); } + @Test + void getPipelineReturnsCurrentStructureAndMetadata() { + String pipelineName = "get-pipeline-it"; + post("CreatePipeline", pipeline(pipelineName, """ + { + "name": "Source", + "actions": [{ + "name": "SourceAction", + "actionTypeId": { + "category": "Source", + "owner": "AWS", + "provider": "S3", + "version": "1" + }, + "runOrder": 1 + }] + }, + { + "name": "Build", + "actions": [{ + "name": "BuildAction", + "actionTypeId": { + "category": "Build", + "owner": "AWS", + "provider": "CodeBuild", + "version": "1" + }, + "runOrder": 1 + }] + } + """)).then().statusCode(200); + + post("GetPipeline", """ + {"name": "%s"} + """.formatted(pipelineName)) + .then() + .statusCode(200) + .body("pipeline.name", equalTo(pipelineName)) + .body("pipeline.version", equalTo(1)) + .body("pipeline.pipelineType", equalTo("V1")) + .body("pipeline.executionMode", equalTo("SUPERSEDED")) + .body("metadata.pipelineArn", equalTo("arn:aws:codepipeline:us-east-1:000000000000:" + pipelineName)) + .body("metadata.created", notNullValue()) + .body("metadata.updated", notNullValue()); + + post("GetPipeline", """ + {"name": "%s", "version": 2} + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("PipelineVersionNotFoundException")); + + post("DeletePipeline", """ + {"name": "%s"} + """.formatted(pipelineName)).then().statusCode(200); + } + + @Test + void updatePipelineReplacesStructureAndIncrementsVersion() { + String pipelineName = "update-pipeline-it"; + post("CreatePipeline", pipeline(pipelineName, """ + { + "name": "Source", + "actions": [{ + "name": "SourceAction", + "actionTypeId": { + "category": "Source", + "owner": "AWS", + "provider": "S3", + "version": "1" + } + }] + }, + { + "name": "Build", + "actions": [{ + "name": "BuildAction", + "actionTypeId": { + "category": "Build", + "owner": "AWS", + "provider": "CodeBuild", + "version": "1" + } + }] + } + """)).then().statusCode(200); + + post("UpdatePipeline", pipeline(pipelineName, """ + { + "name": "Source", + "actions": [{ + "name": "SourceActionV2", + "actionTypeId": { + "category": "Source", + "owner": "AWS", + "provider": "S3", + "version": "1" + } + }] + }, + { + "name": "Deploy", + "actions": [{ + "name": "DeployAction", + "actionTypeId": { + "category": "Deploy", + "owner": "AWS", + "provider": "CodeDeploy", + "version": "1" + } + }] + } + """)) + .then() + .statusCode(200) + .body("pipeline.name", equalTo(pipelineName)) + .body("pipeline.version", equalTo(2)) + .body("pipeline.stages[1].name", equalTo("Deploy")); + + post("GetPipeline", """ + {"name": "%s"} + """.formatted(pipelineName)) + .then() + .statusCode(200) + .body("pipeline.version", equalTo(2)) + .body("pipeline.stages[0].actions[0].name", equalTo("SourceActionV2")) + .body("pipeline.stages[1].name", equalTo("Deploy")); + + post("DeletePipeline", """ + {"name": "%s"} + """.formatted(pipelineName)).then().statusCode(200); + } + @Test void pipelineLifecycleExecutesS3SourceAndDeployActions() throws Exception { createBucket("codepipeline-source"); @@ -104,6 +237,25 @@ class CodePipelineIntegrationTest { .body("pipelineExecution.artifactRevisions", hasSize(1)) .body("pipelineExecution.artifactRevisions[0].name", equalTo("SourceObject")); + post("ListPipelineExecutions", """ + {"pipelineName": "%s"} + """.formatted(pipelineName)) + .then() + .statusCode(200) + .body("pipelineExecutionSummaries", hasSize(1)) + .body("pipelineExecutionSummaries[0].pipelineExecutionId", equalTo(executionId)) + .body("pipelineExecutionSummaries[0].status", equalTo("Succeeded")); + + post("ListPipelineExecutions", """ + { + "pipelineName": "%s", + "filter": {"succeededInStage": {"stageName": "Deploy"}} + } + """.formatted(pipelineName)) + .then() + .statusCode(200) + .body("pipelineExecutionSummaries", hasSize(1)); + post("GetPipelineState", """ {"name": "%s"} """.formatted(pipelineName)) @@ -169,6 +321,227 @@ class CodePipelineIntegrationTest { """.formatted(pipelineName)).then().statusCode(200); } + @Test + void listPipelineExecutionsValidatesFilterAndMaxResults() { + String pipelineName = "list-executions-validation-pipeline"; + post("CreatePipeline", pipeline(pipelineName, """ + { + "name": "Source", + "actions": [{ + "name": "SourceAction", + "actionTypeId": { + "category": "Source", + "owner": "AWS", + "provider": "S3", + "version": "1" + }, + "runOrder": 1 + }] + }, + { + "name": "Build", + "actions": [{ + "name": "BuildAction", + "actionTypeId": { + "category": "Build", + "owner": "AWS", + "provider": "CodeBuild", + "version": "1" + }, + "runOrder": 1 + }] + } + """)) + .then() + .statusCode(200); + + post("ListPipelineExecutions", """ + { + "pipelineName": "%s", + "filter": {"succeededInStage": {"stageName": 42}} + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("succeededInStage requires stageName")); + + post("ListPipelineExecutions", """ + { + "pipelineName": "%s", + "filter": {"succeededInStage": {"stageName": "Source", "extra": 1}} + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("Unknown")); + + post("ListPipelineExecutions", """ + { + "pipelineName": "%s", + "filter": {"succeededInStage": {"stageName": "Source"}, "extra": 1} + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("Unknown")); + + post("ListPipelineExecutions", """ + { + "pipelineName": "%s", + "filter": {"succeededInStage": null} + } + """.formatted(pipelineName)) + .then() + .statusCode(200); + + post("ListPipelineExecutions", """ + { + "pipelineName": "%s", + "maxResults": "5" + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("maxResults must be")); + + post("ListPipelineExecutions", """ + { + "pipelineName": "%s", + "maxResults": 5.5 + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("maxResults must be")); + + post("ListPipelineExecutions", """ + { + "pipelineName": "%s", + "maxResults": 0 + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("between 1 and 100")); + + post("ListPipelineExecutions", """ + { + "pipelineName": "%s", + "maxResults": 101 + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("between 1 and 100")); + } + + @Test + void putApprovalResultSurvivesStageRenameForInFlightApproval() throws Exception { + String pipelineName = "approval-rename-pipeline"; + post("CreatePipeline", pipeline(pipelineName, """ + { + "name": "Approve", + "actions": [{ + "name": "ManualApproval", + "actionTypeId": { + "category": "Approval", + "owner": "AWS", + "provider": "Manual", + "version": "1" + }, + "configuration": {}, + "runOrder": 1 + }] + }, + { + "name": "Deploy", + "actions": [{ + "name": "PlaceholderAction", + "actionTypeId": { + "category": "Deploy", + "owner": "AWS", + "provider": "S3", + "version": "1" + }, + "configuration": { + "BucketName": "codepipeline-artifacts", + "ObjectKey": "placeholder" + }, + "runOrder": 1 + }] + } + """)) + .then() + .statusCode(200); + + post("StartPipelineExecution", """ + {"name": "%s"} + """.formatted(pipelineName)) + .then() + .statusCode(200); + + String approvalToken = waitForApprovalToken(pipelineName); + + post("UpdatePipeline", pipeline(pipelineName, """ + { + "name": "ApproveRenamed", + "actions": [{ + "name": "ManualApprovalRenamed", + "actionTypeId": { + "category": "Approval", + "owner": "AWS", + "provider": "Manual", + "version": "1" + }, + "configuration": {}, + "runOrder": 1 + }] + }, + { + "name": "Deploy", + "actions": [{ + "name": "PlaceholderAction", + "actionTypeId": { + "category": "Deploy", + "owner": "AWS", + "provider": "S3", + "version": "1" + }, + "configuration": { + "BucketName": "codepipeline-artifacts", + "ObjectKey": "placeholder" + }, + "runOrder": 1 + }] + } + """)) + .then() + .statusCode(200); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "Approve", + "actionName": "ManualApproval", + "token": "%s", + "result": { + "status": "Approved", + "summary": "Approved despite rename" + } + } + """.formatted(pipelineName, approvalToken)) + .then() + .statusCode(200) + .body("approvedAt", notNullValue()); + } + @Test void customActionUsesAwsWorkerJobProtocol() throws Exception { createBucket("codepipeline-custom-source"); @@ -255,6 +628,367 @@ class CodePipelineIntegrationTest { """).then().statusCode(200); } + @Test + void putApprovalResultApprovesAndRejectsManualApprovalActions() throws Exception { + String pipelineName = "approval-test-pipeline"; + post("CreatePipeline", pipeline(pipelineName, """ + { + "name": "Approve", + "actions": [{ + "name": "ManualApproval", + "actionTypeId": { + "category": "Approval", + "owner": "AWS", + "provider": "Manual", + "version": "1" + }, + "configuration": {}, + "runOrder": 1 + }] + }, + { + "name": "Deploy", + "actions": [{ + "name": "PlaceholderAction", + "actionTypeId": { + "category": "Deploy", + "owner": "AWS", + "provider": "S3", + "version": "1" + }, + "configuration": { + "BucketName": "codepipeline-artifacts", + "ObjectKey": "placeholder" + }, + "runOrder": 1 + }] + } + """)) + .then() + .statusCode(200); + + String executionId = post("StartPipelineExecution", """ + {"name": "%s"} + """.formatted(pipelineName)) + .then() + .statusCode(200) + .extract().path("pipelineExecutionId"); + + String approvalToken = waitForApprovalToken(pipelineName); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "Approve", + "actionName": "ManualApproval", + "token": "%s", + "result": { + "status": "Approved", + "summary": "Approved by test" + } + } + """.formatted(pipelineName, approvalToken)) + .then() + .statusCode(200) + .body("approvedAt", notNullValue()); + + waitForApprovalStatus(pipelineName, "Succeeded") + .then() + .statusCode(200) + .body("stageStates[0].actionStates[0].latestExecution.status", equalTo("Succeeded")) + .body("stageStates[0].actionStates[0].latestExecution.summary", equalTo("Approved by test")); + + String pipelineName2 = "rejection-test-pipeline"; + post("CreatePipeline", pipeline(pipelineName2, """ + { + "name": "Approve", + "actions": [{ + "name": "ManualApproval", + "actionTypeId": { + "category": "Approval", + "owner": "AWS", + "provider": "Manual", + "version": "1" + }, + "configuration": {}, + "runOrder": 1 + }] + }, + { + "name": "Deploy", + "actions": [{ + "name": "PlaceholderAction", + "actionTypeId": { + "category": "Deploy", + "owner": "AWS", + "provider": "S3", + "version": "1" + }, + "configuration": { + "BucketName": "codepipeline-artifacts", + "ObjectKey": "placeholder" + }, + "runOrder": 1 + }] + } + """)) + .then() + .statusCode(200); + + String executionId2 = post("StartPipelineExecution", """ + {"name": "%s"} + """.formatted(pipelineName2)) + .then() + .statusCode(200) + .extract().path("pipelineExecutionId"); + + String approvalToken2 = waitForApprovalToken(pipelineName2); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "Approve", + "actionName": "ManualApproval", + "token": "%s", + "result": { + "status": "Rejected", + "summary": "Rejected by test" + } + } + """.formatted(pipelineName2, approvalToken2)) + .then() + .statusCode(200) + .body("approvedAt", notNullValue()); + + waitForApprovalStatus(pipelineName2, "Failed") + .then() + .statusCode(200) + .body("stageStates[0].actionStates[0].latestExecution.status", equalTo("Failed")) + .body("stageStates[0].actionStates[0].latestExecution.summary", equalTo("Rejected by test")); + } + + @Test + void putApprovalResultValidatesErrors() throws Exception { + String pipelineName = "error-test-pipeline"; + post("CreatePipeline", pipeline(pipelineName, """ + { + "name": "Approve", + "actions": [{ + "name": "ManualApproval", + "actionTypeId": { + "category": "Approval", + "owner": "AWS", + "provider": "Manual", + "version": "1" + }, + "configuration": {}, + "runOrder": 1 + }] + }, + { + "name": "Deploy", + "actions": [{ + "name": "PlaceholderAction", + "actionTypeId": { + "category": "Deploy", + "owner": "AWS", + "provider": "S3", + "version": "1" + }, + "configuration": { + "BucketName": "codepipeline-artifacts", + "ObjectKey": "placeholder" + }, + "runOrder": 1 + }] + } + """)) + .then() + .statusCode(200); + + post("PutApprovalResult", """ + { + "pipelineName": "nonexistent", + "stageName": "Approve", + "actionName": "ManualApproval", + "token": "00000000-0000-0000-0000-000000000000", + "result": { + "status": "Approved", + "summary": "" + } + } + """) + .then() + .statusCode(400) + .body("__type", containsString("PipelineNotFoundException")); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "NonexistentStage", + "actionName": "ManualApproval", + "token": "00000000-0000-0000-0000-000000000000", + "result": { + "status": "Approved", + "summary": "" + } + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("StageNotFoundException")); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "Approve", + "actionName": "NonexistentAction", + "token": "00000000-0000-0000-0000-000000000000", + "result": { + "status": "Approved", + "summary": "" + } + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("ActionNotFoundException")); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "Approve", + "actionName": "ManualApproval", + "token": "00000000-0000-0000-0000-000000000000" + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("result is required")); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "Approve", + "actionName": "ManualApproval", + "token": "00000000-0000-0000-0000-000000000000", + "result": "Approved" + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("result must be an object")); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "Approve", + "actionName": "ManualApproval", + "token": "00000000-0000-0000-0000-000000000000", + "result": { + "status": "Approved", + "summary": 12345 + } + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("result.summary must be a string")); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "Approve", + "actionName": "ManualApproval", + "token": "00000000-0000-0000-0000-000000000000", + "result": { + "status": "Invalid", + "summary": "" + } + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("result.status must be one of")); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "Approve", + "actionName": "ManualApproval", + "token": "00000000-0000-0000-0000-000000000000", + "result": { + "status": "Approved", + "summary": "%s" + } + } + """.formatted(pipelineName, "a".repeat(513))) + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("must not exceed 512 characters")); + + String executionId = post("StartPipelineExecution", """ + {"name": "%s"} + """.formatted(pipelineName)) + .then() + .statusCode(200) + .extract().path("pipelineExecutionId"); + + String approvalToken = waitForApprovalToken(pipelineName); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "Approve", + "actionName": "ManualApproval", + "token": "00000000-0000-0000-0000-000000000000", + "result": { + "status": "Approved", + "summary": "" + } + } + """.formatted(pipelineName)) + .then() + .statusCode(400) + .body("__type", containsString("InvalidApprovalTokenException")); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "Approve", + "actionName": "ManualApproval", + "token": "%s", + "result": { + "status": "Approved", + "summary": "First approval" + } + } + """.formatted(pipelineName, approvalToken)) + .then() + .statusCode(200); + + post("PutApprovalResult", """ + { + "pipelineName": "%s", + "stageName": "Approve", + "actionName": "ManualApproval", + "token": "%s", + "result": { + "status": "Approved", + "summary": "Second approval attempt" + } + } + """.formatted(pipelineName, approvalToken)) + .then() + .statusCode(400) + .body("__type", containsString("ApprovalAlreadyCompletedException")); + } + @Test void webhookStageTransitionAndValidationErrorsUseAwsShapes() { post("PutWebhook", """ @@ -342,6 +1076,39 @@ class CodePipelineIntegrationTest { throw new AssertionError("Pipeline did not reach " + expected + ", last status: " + status); } + private Response waitForApprovalStatus(String pipelineName, String expectedStatus) throws Exception { + Instant deadline = Instant.now().plus(Duration.ofSeconds(5)); + Response response; + String status; + do { + response = post("GetPipelineState", """ + {"name": "%s"} + """.formatted(pipelineName)); + status = response.jsonPath().getString("stageStates[0].actionStates[0].latestExecution.status"); + if (expectedStatus.equals(status)) { + return response; + } + Thread.sleep(50); + } while (Instant.now().isBefore(deadline)); + throw new AssertionError("Approval action did not reach " + expectedStatus + ", last status: " + status); + } + + private String waitForApprovalToken(String pipelineName) throws Exception { + Instant deadline = Instant.now().plus(Duration.ofSeconds(5)); + String token; + do { + token = post("GetPipelineState", """ + {"name": "%s"} + """.formatted(pipelineName)) + .jsonPath().getString("stageStates[0].actionStates[0].latestExecution.token"); + if (token != null) { + return token; + } + Thread.sleep(50); + } while (Instant.now().isBefore(deadline)); + throw new AssertionError("Approval token was not issued for pipeline " + pipelineName); + } + private static Response post(String action, String body) { return given() .header("X-Amz-Target", TARGET + action) diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java index 141f4ed131..a17cd7629d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java @@ -153,8 +153,11 @@ class MySqlProtocolHandlerTest { byte[] scramble = scrambleNativePassword("secret", nonce); // Real clients send this at sequence 2 after the TLS upgrade — the proxy must - // rewrite it to 1 before forwarding to the (plaintext-only) backend. - byte[] response = buildHandshakeResponse41("admin", scramble, (byte) 2); + // rewrite it to 1 before forwarding to the (plaintext-only) backend. They also + // keep CLIENT_SSL set in it; a real backend would treat a first packet carrying + // that bit as an SSLRequest and hang waiting for a TLS handshake. + byte[] response = buildHandshakeResponse41("admin", scramble, (byte) 2, + CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION | CLIENT_SSL); tlsOut.write(response); tlsOut.flush(); @@ -178,6 +181,11 @@ class MySqlProtocolHandlerTest { assertEquals((byte) 1, backendResponseSeq.get(), "backend never saw the SSLRequest, so it must receive the real response at sequence 1"); assertEquals("admin", extractUsername(backendResponsePayload.get())); + int backendCaps = (backendResponsePayload.get()[0] & 0xFF) + | ((backendResponsePayload.get()[1] & 0xFF) << 8); + assertEquals(0, backendCaps & CLIENT_SSL, + "the plaintext backend must not see CLIENT_SSL, or it treats the response as an " + + "SSLRequest and waits forever for a TLS handshake"); } @Test @@ -238,7 +246,8 @@ class MySqlProtocolHandlerTest { OutputStream tlsOut = sslClient.getOutputStream(); byte[] scramble = scrambleNativePassword("secret", nonce); - byte[] response = buildHandshakeResponse41("admin", scramble, (byte) 2); + byte[] response = buildHandshakeResponse41("admin", scramble, (byte) 2, + CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION | CLIENT_SSL); tlsOut.write(response); tlsOut.flush(); @@ -352,8 +361,14 @@ class MySqlProtocolHandlerTest { private static byte[] buildHandshakeResponse41(String username, byte[] scramble, byte sequence) throws IOException { + return buildHandshakeResponse41(username, scramble, sequence, + CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION); + } + + private static byte[] buildHandshakeResponse41(String username, byte[] scramble, byte sequence, + int capabilities) throws IOException { ByteArrayOutputStream payload = new ByteArrayOutputStream(); - writeInt32LE(payload, CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION); + writeInt32LE(payload, capabilities); writeInt32LE(payload, 0); // max packet size payload.write(0x21); // charset payload.write(new byte[23]); // reserved diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerIntegrationTest.java index 6ba184449a..5017452659 100644 --- a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerIntegrationTest.java @@ -9,6 +9,8 @@ import org.junit.jupiter.api.TestMethodOrder; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.List; + import static io.restassured.RestAssured.given; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @@ -1005,4 +1007,129 @@ class SchedulerIntegrationTest { .then() .statusCode(405); } + + @Test + @Order(39) + void createScheduleWithMalformedEcsParameterListsReturns400() { + // CapacityProviderStrategy is a list of objects and Subnets a list of strings. An element of + // the wrong shape is a malformed body, which AWS answers with 400 SerializationException + // rather than with a server error. + given() + .contentType("application/json") + .body(""" + { + "ScheduleExpression": "rate(1 hour)", + "FlexibleTimeWindow": {"Mode": "OFF"}, + "Target": { + "Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/batch", + "RoleArn": "arn:aws:iam::000000000000:role/scheduler-role", + "EcsParameters": { + "TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/proof:1", + "CapacityProviderStrategy": ["FARGATE"] + } + } + } + """) + .when() + .post("/schedules/ecs-scalar-capacity-provider") + .then() + .statusCode(400); + + given() + .contentType("application/json") + .body(""" + { + "ScheduleExpression": "rate(1 hour)", + "FlexibleTimeWindow": {"Mode": "OFF"}, + "Target": { + "Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/batch", + "RoleArn": "arn:aws:iam::000000000000:role/scheduler-role", + "EcsParameters": { + "TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/proof:1", + "NetworkConfiguration": { + "awsvpcConfiguration": {"Subnets": [{"Id": "subnet-a"}]} + } + } + } + } + """) + .when() + .post("/schedules/ecs-object-subnet") + .then() + .statusCode(400); + } + + @Test + @Order(40) + void createScheduleWithAScalarSubnetReturnsSerializationException() { + // Jackson converts a number or a boolean to a String rather than refusing it, so a + // scalar element reaches the store unless the conversion is checked before it runs. + // AWS answers 400 SerializationException, measured through the Scheduler API. + for (String element : new String[]{"123", "true"}) { + given() + .contentType("application/json") + .body(""" + { + "ScheduleExpression": "rate(1 hour)", + "FlexibleTimeWindow": {"Mode": "OFF"}, + "Target": { + "Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/batch", + "RoleArn": "arn:aws:iam::000000000000:role/scheduler-role", + "EcsParameters": { + "TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/proof:1", + "NetworkConfiguration": { + "awsvpcConfiguration": {"Subnets": [%s]} + } + } + } + } + """.formatted(element)) + .when() + .post("/schedules/ecs-scalar-subnet-" + element) + .then() + .statusCode(400) + .body("__type", containsString("SerializationException")); + } + } + + @Test + @Order(41) + void createScheduleWithANonListEcsParameterReturnsSerializationException() { + // Every EcsParameters list field answers 400 SerializationException "Expected list or null" + // on AWS when it holds a scalar, measured through the Scheduler API for all six. + record ListField(String path, String body) { } + var fields = List.of( + new ListField("CapacityProviderStrategy", "\"CapacityProviderStrategy\": \"FARGATE\""), + new ListField("PlacementConstraints", "\"PlacementConstraints\": \"distinctInstance\""), + new ListField("PlacementStrategy", "\"PlacementStrategy\": \"spread\""), + new ListField("Tags", "\"Tags\": \"owner\""), + new ListField("Subnets", + "\"NetworkConfiguration\": {\"awsvpcConfiguration\": {\"Subnets\": \"subnet-a\"}}"), + new ListField("SecurityGroups", + "\"NetworkConfiguration\": {\"awsvpcConfiguration\": {\"SecurityGroups\": \"sg-a\"}}")); + + for (ListField field : fields) { + given() + .contentType("application/json") + .body(""" + { + "ScheduleExpression": "rate(1 hour)", + "FlexibleTimeWindow": {"Mode": "OFF"}, + "Target": { + "Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/batch", + "RoleArn": "arn:aws:iam::000000000000:role/scheduler-role", + "EcsParameters": { + "TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/proof:1", + %s + } + } + } + """.formatted(field.body())) + .when() + .post("/schedules/ecs-non-list-" + field.path()) + .then() + .statusCode(400) + .body("__type", containsString("SerializationException")); + } + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorArrayParamsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorArrayParamsTest.java index 6b6568bf1d..070038e6b2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorArrayParamsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorArrayParamsTest.java @@ -19,7 +19,7 @@ class AslExecutorArrayParamsTest { private AslExecutor newExecutor() { return new AslExecutor(null, null, null, null, null, null, null, null, - null, null, mapper, null, null, null, null, null); + null, null, null, null, null, mapper, null, null, null, null, null); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java index b4a5048784..03fe2aea8a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java @@ -88,6 +88,9 @@ class AslExecutorCatchTest { 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java index 6d68ab9cb0..f603f272ec 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java @@ -69,6 +69,9 @@ class AslExecutorEcsRunTaskModeTest { mock(io.github.hectorvent.floci.services.s3.S3Service.class), ecsService, ecsJsonHandler, + 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), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorErrorTerminationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorErrorTerminationTest.java index 63473d5220..8b9b5728f8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorErrorTerminationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorErrorTerminationTest.java @@ -82,6 +82,9 @@ class AslExecutorErrorTerminationTest { 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 CrashingJsonataEvaluator(objectMapper), mock(Instance.class), mock(EmulatorConfig.class), vertx, diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHttpInvokeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHttpInvokeTest.java index 9579bc8f51..ebf6bcf37a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHttpInvokeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHttpInvokeTest.java @@ -169,6 +169,9 @@ class AslExecutorHttpInvokeTest { mock(io.github.hectorvent.floci.services.s3.S3Service.class), mock(EcsService.class), mock(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), @@ -285,6 +288,47 @@ class AslExecutorHttpInvokeTest { assertTrue(body.path("active").asBoolean()); } + @Test + void jsonataArgumentsSendAnExplicitNullAndOmitOnlyWhatReturnedNothing() throws Exception { + // AWS keeps the null in the arguments a Task is invoked with: TestState TRACE reports + // afterArguments {"FunctionName":"nope","Payload":{"v":null}} for Payload {"v":"{% null %}"}. + Execution execution = run(""" + { + "QueryLanguage": "JSONata", + "StartAt": "CallHttp", + "States": { + "CallHttp": { + "Type": "Task", + "Resource": "arn:aws:states:::http:invoke", + "Arguments": { + "ApiEndpoint": "%s/text", + "Method": "POST", + "Authentication": { + "ConnectionArn": "%s" + }, + "RequestBody": { + "fromInput": "{%% $lookup($states.input, 'customerId') %%}", + "returnedNothing": "{%% $states.input.absent %%}", + "active": true + } + }, + "End": true + } + } + } + """.formatted(baseUrl, CONNECTION_ARN), """ + { + "customerId": null + } + """); + + assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); + JsonNode body = objectMapper.readTree(onlyRequest().body()); + assertTrue(body.path("fromInput").isNull(), body.toString()); + assertTrue(body.path("returnedNothing").isMissingNode(), body.toString()); + assertTrue(body.path("active").asBoolean()); + } + @Test void nonSuccessStatusFailsWithStatesHttpStatusCodeError() throws Exception { Execution execution = run(""" diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicContextTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicContextTest.java index 85d3db7c7f..824faaed90 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicContextTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicContextTest.java @@ -23,7 +23,7 @@ class AslExecutorIntrinsicContextTest { /** Only ObjectMapper is exercised by the path/intrinsic resolution methods under test. */ private AslExecutor newExecutor() { return new AslExecutor(null, null, null, null, null, null, null, null, - null, null, mapper, null, null, null, null, null); + null, null, null, null, null, mapper, null, null, null, null, null); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorJsonMergeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorJsonMergeTest.java index 5a0fcaa0ee..32bf400c18 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorJsonMergeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorJsonMergeTest.java @@ -48,6 +48,9 @@ class AslExecutorJsonMergeTest { mock(S3Service.class), mock(EcsService.class), mock(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), mapper, new JsonataEvaluator(mapper), mock(Instance.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorLambdaInvokeResultTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorLambdaInvokeResultTest.java index 35202a9bec..2aa8306934 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorLambdaInvokeResultTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorLambdaInvokeResultTest.java @@ -86,6 +86,9 @@ class AslExecutorLambdaInvokeResultTest { 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java index a0fa83d306..63793084b9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java @@ -59,6 +59,9 @@ class AslExecutorMockedResponsesTest { 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorPathIntrinsicsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorPathIntrinsicsTest.java index f95b30ad10..aab9644436 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorPathIntrinsicsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorPathIntrinsicsTest.java @@ -42,6 +42,9 @@ class AslExecutorPathIntrinsicsTest { mock(io.github.hectorvent.floci.services.s3.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), mapper, new JsonataEvaluator(mapper), mock(Instance.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultWriterTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultWriterTest.java index 8810095034..0ae7d9be20 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultWriterTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultWriterTest.java @@ -65,6 +65,9 @@ class AslExecutorResultWriterTest { s3Service, 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), mapper, new JsonataEvaluator(mapper), mock(Instance.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorRetryTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorRetryTest.java index ffc2b84bbc..9b6f7c1e50 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorRetryTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorRetryTest.java @@ -76,6 +76,9 @@ class AslExecutorRetryTest { 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTerminalStateTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTerminalStateTest.java index 983d672a78..77485f8235 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTerminalStateTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTerminalStateTest.java @@ -60,6 +60,9 @@ class AslExecutorTerminalStateTest { 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEvaluatorTest.java index f37573b381..a953eaa0cf 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEvaluatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEvaluatorTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import static org.junit.jupiter.api.Assertions.*; @@ -84,12 +85,12 @@ class JsonataEvaluatorTest { } @Test - void evaluate_returnsNullForMissingField() throws Exception { + void evaluate_returnsNothingForMissingField() throws Exception { JsonNode statesVar = objectMapper.readTree(""" {"input": {"name": "Alice"}} """); JsonNode result = evaluator.evaluate("{% $states.input.missing %}", statesVar); - assertTrue(result.isNull()); + assertTrue(result.isMissingNode()); } @Test @@ -215,7 +216,7 @@ class JsonataEvaluatorTest { void parse_noArgumentReturnsUndefined() { JsonNode statesVar = objectMapper.createObjectNode(); JsonNode result = evaluator.evaluate("{% $parse() %}", statesVar); - assertTrue(result.isNull()); + assertTrue(result.isMissingNode()); } @Test @@ -259,14 +260,14 @@ class JsonataEvaluatorTest { void partition_emptyArrayReturnsUndefined() { JsonNode statesVar = objectMapper.createObjectNode(); JsonNode result = evaluator.evaluate("{% $partition([], 2) %}", statesVar); - assertTrue(result.isNull()); + assertTrue(result.isMissingNode()); } @Test void partition_chunkSizeZeroReturnsUndefined() { JsonNode statesVar = objectMapper.createObjectNode(); JsonNode result = evaluator.evaluate("{% $partition([1,2,3], 0) %}", statesVar); - assertTrue(result.isNull()); + assertTrue(result.isMissingNode()); } @Test @@ -318,21 +319,21 @@ class JsonataEvaluatorTest { void range_wrongSignStepReturnsUndefined() { JsonNode statesVar = objectMapper.createObjectNode(); JsonNode result = evaluator.evaluate("{% $range(5, 1, 1) %}", statesVar); - assertTrue(result.isNull()); + assertTrue(result.isMissingNode()); } @Test void range_stepZeroReturnsUndefined() { JsonNode statesVar = objectMapper.createObjectNode(); JsonNode result = evaluator.evaluate("{% $range(1, 5, 0) %}", statesVar); - assertTrue(result.isNull()); + assertTrue(result.isMissingNode()); } @Test void range_missingStepReturnsUndefined() { JsonNode statesVar = objectMapper.createObjectNode(); JsonNode result = evaluator.evaluate("{% $range(1, 5) %}", statesVar); - assertTrue(result.isNull()); + assertTrue(result.isMissingNode()); } @Test @@ -374,7 +375,7 @@ class JsonataEvaluatorTest { void hash_missingAlgorithmReturnsUndefined() { JsonNode statesVar = objectMapper.createObjectNode(); JsonNode result = evaluator.evaluate("{% $hash('Hello') %}", statesVar); - assertTrue(result.isNull()); + assertTrue(result.isMissingNode()); } @Test @@ -449,7 +450,7 @@ class JsonataEvaluatorTest { assertEquals("[-2,-1,0]", evaluator.evaluate("{% $range(-2.9, 0, 1) %}", statesVar).toString()); assertEquals("[5,4,3,2,1]", evaluator.evaluate("{% $range(5, 1, -1.5) %}", statesVar).toString()); // -0.5 rounds to 0, which is undefined, while -2 stays negative and is an error. - assertTrue(evaluator.evaluate("{% $partition([1,2,3,4], -0.5) %}", statesVar).isNull()); + assertTrue(evaluator.evaluate("{% $partition([1,2,3,4], -0.5) %}", statesVar).isMissingNode()); } @Test @@ -479,7 +480,7 @@ class JsonataEvaluatorTest { @Test void hash_missingAlgorithmIsUndefinedButNonStringOneIsASignatureError() { JsonNode statesVar = objectMapper.createObjectNode(); - assertTrue(evaluator.evaluate("{% $hash('a') %}", statesVar).isNull()); + assertTrue(evaluator.evaluate("{% $hash('a') %}", statesVar).isMissingNode()); AslExecutor.FailStateException ex = assertThrows(AslExecutor.FailStateException.class, () -> evaluator.evaluate("{% $hash('a', 5) %}", statesVar)); assertTrue(ex.cause.contains("T0410")); @@ -550,6 +551,74 @@ class JsonataEvaluatorTest { assertEquals("[1,2]", result.toString()); } + /** + * The expression from issue #2667. JSONata optimises the tail call, so it loops instead of + * overflowing the stack: nothing is thrown, and before the time bound the execution stayed + * RUNNING for ever with a core pinned. The evaluator is built with a 250 ms bound rather than + * the shipped {@link JsonataEvaluator#EVALUATION_TIMEOUT_MILLIS} so the suite stays fast, and + * the method timeout makes an unbounded evaluation fail the test instead of blocking the run. + */ + @Test + @Timeout(30) + void recursionWithNoBaseCaseFailsOnTheTimeBound() { + JsonataEvaluator shortlyBounded = + new JsonataEvaluator(objectMapper, 250, JsonataEvaluator.MAX_EVALUATION_DEPTH); + JsonNode statesVar = objectMapper.createObjectNode(); + + AslExecutor.FailStateException ex = assertThrows(AslExecutor.FailStateException.class, + () -> shortlyBounded.evaluate("{% ($f := function($x){ $f($x+1) }; $f(1)) %}", statesVar)); + + assertEquals("States.QueryEvaluationError", ex.error); + assertEquals("Expression evaluation timeout: Check for infinite loop", ex.cause); + } + + /** + * Recursion the library cannot optimise grows the evaluation nesting instead of looping, and + * without a depth bound it ends in a StackOverflowError, which is an Error and so escapes the + * evaluator's catch. The shipped bound is what turns it into a state failure. + * + *

The cause is AWS's own string for this failure, followed by the {@code Depth=N max=M} + * suffix that names the bound that was hit. AWS writes one space after the full stop where + * the library writes two. + */ + @Test + @Timeout(30) + void nonTailRecursionFailsOnTheDepthBound() { + JsonNode statesVar = objectMapper.createObjectNode(); + + AslExecutor.FailStateException ex = assertThrows(AslExecutor.FailStateException.class, + () -> evaluator.evaluate( + "{% ($f := function($x){ $x <= 0 ? 0 : 1 + $f($x-1) }; $f(1000000)) %}", statesVar)); + + assertEquals("States.QueryEvaluationError", ex.error); + assertEquals("Stack overflow error: Check for non-terminating recursive" + + " function. Consider rewriting as tail-recursive. Depth=501 max=500", ex.cause); + } + + /** + * The boundary from below: the risk of a bound is that it fails a working state machine, so + * these must all still evaluate. Measured with {@code aws stepfunctions test-state}, AWS + * returns 30 for the first and 800000 for the second, which makes them the ceiling of what + * AWS itself accepts on each axis: it refuses the recursion at n=40 (nesting depth 125) and + * the sequence at 900,000 elements. + * + *

The last two AWS refuses on its memory limit and Floci evaluates, which is where the + * bounds are deliberately looser than AWS rather than tighter. + */ + @Test + @Timeout(60) + void expensiveButLegitimateExpressionsStayWithinTheShippedBounds() { + JsonNode statesVar = objectMapper.createObjectNode(); + String recursionHead = "{% ($f := function($x){ $x <= 0 ? 0 : 1 + $f($x-1) }; $f("; + + assertEquals(30, evaluator.evaluate(recursionHead + "30)) %}", statesVar).asInt()); + assertEquals(800000, evaluator.evaluate("{% [1..800000] ~> $count() %}", statesVar).asInt()); + + assertEquals(160, evaluator.evaluate(recursionHead + "160)) %}", statesVar).asInt()); + assertEquals(40000200000L, + evaluator.evaluate("{% $sum($map([1..200000], function($v){$v * 2})) %}", statesVar).asLong()); + } + @Test void string_writesAWholeNumberInFullBelowTheExponentBoundary() { // dashjoin stops writing digits at Long.MAX_VALUE, 9.223372036854776E18, and prints @@ -614,7 +683,9 @@ class JsonataEvaluatorTest { assertEquals("abc", evaluator.evaluate("{% $string('abc') %}", statesVar).asText()); assertEquals("null", evaluator.evaluate("{% $string(null) %}", statesVar).asText()); assertEquals("{\n \"a\": 1\n}", evaluator.evaluate("{% $string({'a': 1}, true) %}", statesVar).asText()); - assertTrue(evaluator.evaluate("{% $string() %}", statesVar).isNull()); + // $string() with no argument returns nothing, which this change stops reporting as an + // explicit null. AWS fails the state on it, which is #2665's subject and not this one's. + assertTrue(evaluator.evaluate("{% $string() %}", statesVar).isMissingNode()); assertEquals("[\"100000000000000000000\",\"1e+21\"]", evaluator.evaluate("{% $map([1e20, 1e21], $string) %}", statesVar).toString()); } @@ -731,4 +802,87 @@ class JsonataEvaluatorTest { assertEquals("States.QueryEvaluationError", ex.error); assertTrue(ex.cause.contains("nope"), ex.cause); } + + @Test + void anExplicitNullKeepsItsKeyAndOnlyWhatReturnedNothingIsDropped() throws Exception { + JsonNode statesVar = objectMapper.readTree(""" + {"input": {"bar": null}} + """); + JsonNode template = objectMapper.readTree(""" + {"fromInput": "{% $lookup($states.input, 'bar') %}", + "returnedNothing": "{% $states.input.absent %}", + "kept": 1} + """); + + assertEquals("{\"fromInput\":null,\"kept\":1}", + evaluator.resolveTemplate(template, statesVar).toString()); + } + + @Test + void anExplicitNullSurvivesInsideANestedObject() throws Exception { + JsonNode statesVar = objectMapper.createObjectNode(); + JsonNode template = objectMapper.readTree(""" + {"outer": {"fromExpression": "{% null %}", "kept": 1}} + """); + + assertEquals("{\"outer\":{\"fromExpression\":null,\"kept\":1}}", + evaluator.resolveTemplate(template, statesVar).toString()); + } + + @Test + void aWholeTemplateIsANullWhetherItEvaluatedToNullOrReturnedNothing() throws Exception { + JsonNode statesVar = objectMapper.createObjectNode(); + + assertTrue(evaluator.resolveTemplate(objectMapper.readTree("\"{% null %}\""), statesVar).isNull()); + // AWS fails the second one with States.QueryEvaluationError, which #2665 covers. Until then + // it is a null and not a missing node: an Output or Arguments is serialized as it stands, + // and a missing node writes itself as the empty string rather than as JSON. + assertTrue(evaluator.resolveTemplate(objectMapper.readTree("\"{% $states.input.absent %}\""), statesVar) + .isNull()); + } + + @Test + void anExplicitNullIsAnArrayElementWhileNothingStillFailsTheState() throws Exception { + JsonNode statesVar = objectMapper.createObjectNode(); + + assertEquals("{\"values\":[null,1]}", evaluator.resolveTemplate(objectMapper.readTree(""" + {"values": ["{% null %}", 1]} + """), statesVar).toString()); + + AslExecutor.FailStateException failure = assertThrows(AslExecutor.FailStateException.class, + () -> evaluator.resolveTemplate(objectMapper.readTree(""" + {"values": ["{% $states.input.absent %}"]} + """), statesVar)); + assertTrue(failure.cause.contains("returned nothing (undefined)"), failure.cause); + } + + @Test + void aLiteralNullInTheTemplateKeepsItsKey() throws Exception { + JsonNode statesVar = objectMapper.createObjectNode(); + + assertEquals("{\"literal\":null,\"kept\":1}", evaluator.resolveTemplate(objectMapper.readTree(""" + {"literal": null, "kept": 1} + """), statesVar).toString()); + } + + @Test + void anInputNullIsAValueForExistsAndType() throws Exception { + JsonNode statesVar = objectMapper.readTree(""" + {"input": {"bar": null}} + """); + + assertTrue(evaluator.evaluate("{% $exists($states.input.bar) %}", statesVar).asBoolean()); + assertEquals("null", evaluator.evaluate("{% $type($states.input.bar) %}", statesVar).asText()); + } + + @Test + void anAssignedNullReadsBackAsANull() throws Exception { + JsonNode statesVar = objectMapper.createObjectNode(); + JsonNode variables = objectMapper.readTree(""" + {"nullVariable": null} + """); + + assertTrue(evaluator.evaluate("{% $nullVariable %}", statesVar, variables).isNull()); + assertTrue(evaluator.evaluate("{% $exists($nullVariable) %}", statesVar, variables).asBoolean()); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataTopLevelReferencesTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataTopLevelReferencesTest.java new file mode 100644 index 0000000000..ef6ac4b784 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataTopLevelReferencesTest.java @@ -0,0 +1,110 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Every expression here was run through + * {@code aws stepfunctions validate-state-machine-definition --region us-east-1} as the Output of + * a one-state Pass machine. The names asserted are the ones AWS puts in + * {@code Reference to '' at the top level is not supported.}, and the expressions asserted + * empty are the ones AWS answers {@code result: OK}. + */ +class JsonataTopLevelReferencesTest { + + @ParameterizedTest + @ValueSource(strings = { + "phone", + "phone[0].number", + "phone.number.street", + "-phone", + "phone ? 1 : 2", + "$states.input.a ? phone : 2", + "phone & 'x'", + "phone in $states.input.b", + "$sum(phone)", + "phone(1)", + "phone ~> $string()", + "[1..phone]", + "(phone)", + "(phone).other", + "[phone].other", + "[phone, 1]", + "{phone: 1}", + "($x := phone; $x)", + "$map($states.input.a, function($y){ phone })", + "$count(phone[inner])", + "phone.**.deeper"}) + @DisplayName("AWS names the identifier read at the top level") + void namesTheTopLevelIdentifier(String expression) { + assertEquals(List.of("phone"), JsonataTopLevelReferences.in(expression)); + } + + @ParameterizedTest + @ValueSource(strings = { + "$states.input.phone", + "$states.input.a.phone", + "$states.input.a[0].phone", + "$states.input.a.phone[0]", + "$states.input.items[phone > 3]", + "$states.input.a^(phone)", + "$states.input.a{'k': phone}", + "$states.input.a.(phone)", + "$states.input.a.$phone", + "$phone", + "$states.input.a ~> $string()", + "$states.input ~> |phone|{'b': 1}|", + "**.phone", + "{'k': 1}.phone", + "$states.input.a[0][phone]", + "$states.input.a[$ > 1]", + "function($x){ $x.phone }", + "$map($states.input.a, function($x){ $x.phone })", + "'phone'", + "1 + 1", + "$now()"}) + @DisplayName("AWS accepts a name that is not read from the top-level context") + void namesNothingWhenTheReferenceIsAnchored(String expression) { + assertEquals(List.of(), JsonataTopLevelReferences.in(expression)); + } + + @ParameterizedTest + @ValueSource(strings = {"$", "$.phone", "$[0]", "$string($)", + "$map($states.input.a, function($x){ $ })"}) + @DisplayName("the context item itself is named '$', as AWS names it") + void namesTheContextItem(String expression) { + assertEquals(List.of("$"), JsonataTopLevelReferences.in(expression)); + } + + @Test + @DisplayName("'$$' is AWS's separate rule and is left to it") + void leavesTheRootReferenceAlone() { + assertEquals(List.of(), JsonataTopLevelReferences.in("$$")); + assertEquals(List.of(), JsonataTopLevelReferences.in("$$.phone")); + } + + @Test + @DisplayName("every distinct name is reported once, in writing order") + void reportsEveryDistinctNameOnce() { + assertEquals(List.of("aaa", "bbb"), JsonataTopLevelReferences.in("aaa + bbb")); + assertEquals(List.of("bbb", "aaa"), JsonataTopLevelReferences.in("[bbb, aaa]")); + assertEquals(List.of("aaa"), JsonataTopLevelReferences.in("aaa + aaa")); + assertEquals(List.of("aaa", "bbb"), JsonataTopLevelReferences.in("(aaa; bbb)")); + assertEquals(List.of("aaa", "bbb"), + JsonataTopLevelReferences.in("$number(aaa) + $number(bbb)")); + } + + @Test + @DisplayName("a syntax error names nothing, so the definition stays accepted") + void namesNothingWhenTheExpressionDoesNotParse() { + assertEquals(List.of(), JsonataTopLevelReferences.in("phone[1,2)")); + assertEquals(List.of(), JsonataTopLevelReferences.in("phone %.other")); + assertEquals(List.of(), JsonataTopLevelReferences.in("")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java new file mode 100644 index 0000000000..3baf95ae21 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java @@ -0,0 +1,598 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +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.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Integration tests for the {@code arn:aws:states:::aws-sdk:} task integrations of Step Functions + * itself and of EventBridge Scheduler: {@code sfn:startExecution}, {@code sfn:sendTaskSuccess}, + * {@code sfn:sendTaskFailure}, {@code scheduler:createSchedule} and {@code scheduler:updateSchedule}. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class StepFunctionsAwsSdkTaskIntegrationTest { + + private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0"; + private static final String SQS_CONTENT_TYPE = "application/x-amz-json-1.0"; + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role"; + private static final String ISO_INSTANT = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"; + private static final ObjectMapper mapper = new ObjectMapper(); + + private static String quickChildArn; + private static String slowChildArn; + private static String callbackQueueUrl; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(0) + void setup_createChildrenAndCallbackQueue() { + quickChildArn = createStateMachine("aws-sdk-task-child-quick", """ + { + "StartAt": "Done", + "States": {"Done": {"Type": "Pass", "End": true}} + } + """); + slowChildArn = createStateMachine("aws-sdk-task-child-slow", """ + { + "StartAt": "Linger", + "States": { + "Linger": {"Type": "Wait", "Seconds": 5, "Next": "Done"}, + "Done": {"Type": "Pass", "End": true} + } + } + """); + callbackQueueUrl = createQueue("aws-sdk-task-callback"); + } + + // ──────────────────────────── sfn:startExecution ──────────────────────────── + + @Test + @Order(1) + void startExecutionReturnsThePascalCaseArnAndAnIsoStartDate() throws Exception { + var smArn = createStateMachine("aws-sdk-start-execution", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Start", + "States": { + "Start": { + "Type": "Task", + "Resource": "arn:aws:states:::aws-sdk:sfn:startExecution", + "Arguments": {"StateMachineArn": "CHILD_ARN", "Input": {"amount": 1200}}, + "End": true + } + } + } + """.replace("CHILD_ARN", quickChildArn)); + + var result = mapper.readTree(succeedingOutputOf(smArn, "{}")); + assertTrue(result.path("ExecutionArn").asText() + .contains(":execution:aws-sdk-task-child-quick:"), + "unexpected ExecutionArn: " + result.path("ExecutionArn").asText()); + assertTrue(result.path("StartDate").asText().matches(ISO_INSTANT), + "StartDate is not the SDK's ISO-8601 rendering: " + result.path("StartDate")); + assertEquals(2, result.size(), "StartExecution returns ExecutionArn and StartDate only"); + + // The child really ran, with the Input the task passed it. + var child = describeExecution(result.path("ExecutionArn").asText()); + assertEquals("{\"amount\":1200}", child.jsonPath().getString("input")); + } + + @Test + @Order(2) + void startExecutionDoesNotWaitForTheChild() throws Exception { + var smArn = createStateMachine("aws-sdk-start-execution-no-wait", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Start", + "States": { + "Start": { + "Type": "Task", + "Resource": "arn:aws:states:::aws-sdk:sfn:startExecution", + "Arguments": {"StateMachineArn": "CHILD_ARN"}, + "End": true + } + } + } + """.replace("CHILD_ARN", slowChildArn)); + + var result = mapper.readTree(succeedingOutputOf(smArn, "{}")); + var child = describeExecution(result.path("ExecutionArn").asText()); + assertEquals("RUNNING", child.jsonPath().getString("status"), + "the parent finished before the 5s child, so the child is still running"); + } + + @Test + @Order(3) + void startExecutionOnAMissingStateMachineFailsWithTheSdkExceptionName() { + var smArn = createStateMachine("aws-sdk-start-execution-missing", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Start", + "States": { + "Start": { + "Type": "Task", + "Resource": "arn:aws:states:::aws-sdk:sfn:startExecution", + "Arguments": { + "StateMachineArn": "arn:aws:states:us-east-1:000000000000:stateMachine:nope" + }, + "End": true + } + } + } + """); + + var describe = waitForTerminalState(startExecution(smArn, "{}")); + assertEquals("FAILED", describe.jsonPath().getString("status")); + assertEquals("Sfn.StateMachineDoesNotExistException", describe.jsonPath().getString("error")); + } + + @Test + @Order(4) + void startExecutionReusingAnExecutionNameFailsWithTheSdkExceptionName() { + var smArn = createStateMachine("aws-sdk-start-execution-named", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Start", + "States": { + "Start": { + "Type": "Task", + "Resource": "arn:aws:states:::aws-sdk:sfn:startExecution", + "Arguments": {"StateMachineArn": "CHILD_ARN", "Name": "taken-once"}, + "End": true + } + } + } + """.replace("CHILD_ARN", quickChildArn)); + + assertEquals("SUCCEEDED", waitForTerminalState(startExecution(smArn, "{}")) + .jsonPath().getString("status")); + + var describe = waitForTerminalState(startExecution(smArn, "{}")); + assertEquals("FAILED", describe.jsonPath().getString("status")); + assertEquals("Sfn.ExecutionAlreadyExistsException", describe.jsonPath().getString("error")); + } + + // ──────────────────────────── sfn:sendTaskSuccess / sendTaskFailure ──────────────────────────── + + @Test + @Order(5) + void sendTaskSuccessResolvesTheWaitingExecutionWithItsOutput() throws Exception { + var waitingExecArn = startExecution(createWaiterStateMachine("aws-sdk-send-success-waiter"), "{}"); + var taskToken = receiveTaskToken(); + + var senderArn = createStateMachine("aws-sdk-send-success", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Resume", + "States": { + "Resume": { + "Type": "Task", + "Resource": "arn:aws:states:::aws-sdk:sfn:sendTaskSuccess", + "Arguments": { + "TaskToken": "{% $states.input.token %}", + "Output": {"approved": true} + }, + "End": true + } + } + } + """); + + assertEquals("{}", succeedingOutputOf(senderArn, tokenInput(taskToken)), + "SendTaskSuccess answers with an empty response"); + + var waiter = waitForTerminalState(waitingExecArn); + assertEquals("SUCCEEDED", waiter.jsonPath().getString("status")); + assertTrue(mapper.readTree(waiter.jsonPath().getString("output")).path("approved").asBoolean()); + } + + @Test + @Order(6) + void sendTaskFailureFailsTheWaitingExecutionWithItsErrorAndCause() throws Exception { + var waitingExecArn = startExecution(createWaiterStateMachine("aws-sdk-send-failure-waiter"), "{}"); + var taskToken = receiveTaskToken(); + + var senderArn = createStateMachine("aws-sdk-send-failure", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Reject", + "States": { + "Reject": { + "Type": "Task", + "Resource": "arn:aws:states:::aws-sdk:sfn:sendTaskFailure", + "Arguments": { + "TaskToken": "{% $states.input.token %}", + "Error": "PoolClosed", + "Cause": "the pool is already closed" + }, + "End": true + } + } + } + """); + + assertEquals("{}", succeedingOutputOf(senderArn, tokenInput(taskToken))); + + var waiter = waitForTerminalState(waitingExecArn); + assertEquals("FAILED", waiter.jsonPath().getString("status")); + assertEquals("PoolClosed", waiter.jsonPath().getString("error")); + assertEquals("the pool is already closed", waiter.jsonPath().getString("cause")); + } + + @Test + @Order(7) + void sendTaskSuccessOnATokenNobodyIsWaitingForFailsTheTask() { + var smArn = createStateMachine("aws-sdk-send-success-bad-token", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Resume", + "States": { + "Resume": { + "Type": "Task", + "Resource": "arn:aws:states:::aws-sdk:sfn:sendTaskSuccess", + "Arguments": {"TaskToken": "not-a-real-token", "Output": {}}, + "End": true + } + } + } + """); + + var describe = waitForTerminalState(startExecution(smArn, "{}")); + assertEquals("FAILED", describe.jsonPath().getString("status")); + assertEquals("Sfn.InvalidTokenException", describe.jsonPath().getString("error")); + assertEquals("Invalid Token: 'Invalid token'", describe.jsonPath().getString("cause")); + } + + @Test + @Order(8) + void sendTaskFailureOnATokenNobodyIsWaitingForFailsTheTask() { + var smArn = createStateMachine("aws-sdk-send-failure-bad-token", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Reject", + "States": { + "Reject": { + "Type": "Task", + "Resource": "arn:aws:states:::aws-sdk:sfn:sendTaskFailure", + "Arguments": {"TaskToken": "not-a-real-token", "Error": "E", "Cause": "c"}, + "End": true + } + } + } + """); + + var describe = waitForTerminalState(startExecution(smArn, "{}")); + assertEquals("FAILED", describe.jsonPath().getString("status")); + assertEquals("Sfn.InvalidTokenException", describe.jsonPath().getString("error")); + } + + // ──────────────────────────── scheduler:createSchedule / updateSchedule ──────────────────────────── + + @Test + @Order(9) + void createScheduleReturnsTheScheduleArnAndTheScheduleIsReadable() throws Exception { + var result = mapper.readTree(succeedingOutputOf( + createStateMachine("aws-sdk-create-schedule", scheduleTask("createSchedule", + "payout-nightly", "rate(1 day)")), "{}")); + + assertTrue(result.path("ScheduleArn").asText().endsWith(":schedule/default/payout-nightly"), + "unexpected ScheduleArn: " + result.path("ScheduleArn").asText()); + assertEquals(1, result.size(), "CreateSchedule returns ScheduleArn only"); + + given().when().get("/schedules/payout-nightly") + .then().statusCode(200) + .body("ScheduleExpression", org.hamcrest.Matchers.equalTo("rate(1 day)")); + } + + @Test + @Order(10) + void updateScheduleKeepsTheArnAndChangesTheExpression() throws Exception { + var result = mapper.readTree(succeedingOutputOf( + createStateMachine("aws-sdk-update-schedule", scheduleTask("updateSchedule", + "payout-nightly", "rate(2 days)")), "{}")); + + assertTrue(result.path("ScheduleArn").asText().endsWith(":schedule/default/payout-nightly")); + + given().when().get("/schedules/payout-nightly") + .then().statusCode(200) + .body("ScheduleExpression", org.hamcrest.Matchers.equalTo("rate(2 days)")); + } + + @Test + @Order(11) + void createScheduleOnANameAlreadyTakenFailsWithConflict() { + var describe = waitForTerminalState(startExecution( + createStateMachine("aws-sdk-create-schedule-twice", scheduleTask("createSchedule", + "payout-nightly", "rate(1 day)")), "{}")); + + assertEquals("FAILED", describe.jsonPath().getString("status")); + assertEquals("Scheduler.ConflictException", describe.jsonPath().getString("error")); + } + + @Test + @Order(12) + void updateScheduleOnAScheduleThatDoesNotExistFailsWithResourceNotFound() { + var describe = waitForTerminalState(startExecution( + createStateMachine("aws-sdk-update-missing-schedule", scheduleTask("updateSchedule", + "no-such-schedule", "rate(1 day)")), "{}")); + + assertEquals("FAILED", describe.jsonPath().getString("status")); + assertEquals("Scheduler.ResourceNotFoundException", describe.jsonPath().getString("error")); + } + + @Test + @Order(13) + void createScheduleWithIncompleteEventBridgeParametersIsCatchableAsAValidationException() throws Exception { + var smArn = createStateMachine("aws-sdk-create-schedule-invalid-target", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Schedule", + "States": { + "Schedule": { + "Type": "Task", + "Resource": "arn:aws:states:::aws-sdk:scheduler:createSchedule", + "Arguments": { + "Name": "payout-invalid-target", + "ScheduleExpression": "rate(1 day)", + "FlexibleTimeWindow": {"Mode": "OFF"}, + "Target": { + "Arn": "TARGET_ARN", + "RoleArn": "ROLE", + "EventBridgeParameters": {"DetailType": "payout.requested"} + } + }, + "Catch": [{ + "ErrorEquals": ["Scheduler.ValidationException"], + "Next": "Recovered", + "Output": {"caughtError": "{% $states.errorOutput.Error %}"} + }], + "End": true + }, + "Recovered": {"Type": "Pass", "End": true} + } + } + """ + .replace("TARGET_ARN", quickChildArn) + .replace("ROLE", ROLE_ARN)); + + var result = mapper.readTree(succeedingOutputOf(smArn, "{}")); + assertEquals("Scheduler.ValidationException", result.path("caughtError").asText(), + "a target the parser rejects must reach Catch as an SDK exception, not States.Runtime"); + } + + @Test + @Order(14) + void createScheduleWithAMalformedListIsCatchableAsASerializationException() throws Exception { + // A malformed EcsParameters list is refused before the conversion runs, so it reaches Catch + // as the SDK exception AWS sends rather than as States.Runtime. + for (String[] shape : new String[][]{ + {"scalar-strategy", "\"CapacityProviderStrategy\": [\"FARGATE\"]"}, + {"non-list-strategy", "\"CapacityProviderStrategy\": \"FARGATE\""}, + {"scalar-subnet", + "\"NetworkConfiguration\": {\"awsvpcConfiguration\": {\"Subnets\": [123]}}"}, + {"non-list-subnet", + "\"NetworkConfiguration\": {\"awsvpcConfiguration\": {\"Subnets\": \"subnet-a\"}}"}}) { + var smArn = createStateMachine("aws-sdk-create-schedule-" + shape[0], """ + { + "QueryLanguage": "JSONata", + "StartAt": "Schedule", + "States": { + "Schedule": { + "Type": "Task", + "Resource": "arn:aws:states:::aws-sdk:scheduler:createSchedule", + "Arguments": { + "Name": "payout-SHAPE", + "ScheduleExpression": "rate(1 day)", + "FlexibleTimeWindow": {"Mode": "OFF"}, + "Target": { + "Arn": "TARGET_ARN", + "RoleArn": "ROLE", + "EcsParameters": { + "TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/p:1", + MALFORMED_FIELD + } + } + }, + "Catch": [{ + "ErrorEquals": ["Scheduler.SerializationException"], + "Next": "Recovered", + "Output": {"caughtError": "{% $states.errorOutput.Error %}"} + }], + "End": true + }, + "Recovered": {"Type": "Pass", "End": true} + } + } + """ + .replace("MALFORMED_FIELD", shape[1]) + .replace("SHAPE", shape[0]) + .replace("TARGET_ARN", quickChildArn) + .replace("ROLE", ROLE_ARN)); + + var result = mapper.readTree(succeedingOutputOf(smArn, "{}")); + assertEquals("Scheduler.SerializationException", result.path("caughtError").asText(), + shape[0] + " must reach Catch as an SDK exception, not States.Runtime"); + } + } + + private static String scheduleTask(String action, String scheduleName, String expression) { + return """ + { + "QueryLanguage": "JSONata", + "StartAt": "Schedule", + "States": { + "Schedule": { + "Type": "Task", + "Resource": "arn:aws:states:::aws-sdk:scheduler:ACTION", + "Arguments": { + "Name": "SCHEDULE_NAME", + "ScheduleExpression": "EXPRESSION", + "FlexibleTimeWindow": {"Mode": "OFF"}, + "Target": {"Arn": "TARGET_ARN", "RoleArn": "ROLE"} + }, + "End": true + } + } + } + """ + .replace("ACTION", action) + .replace("SCHEDULE_NAME", scheduleName) + .replace("EXPRESSION", expression) + .replace("TARGET_ARN", quickChildArn) + .replace("ROLE", ROLE_ARN); + } + + /** A state machine that parks on a task token and posts it to the callback queue. */ + private static String createWaiterStateMachine(String name) { + return createStateMachine(name, """ + { + "QueryLanguage": "JSONata", + "StartAt": "Wait", + "States": { + "Wait": { + "Type": "Task", + "Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken", + "Arguments": { + "QueueUrl": "QUEUE_URL", + "MessageBody": {"token": "{% $states.context.Task.Token %}"} + }, + "End": true + } + } + } + """.replace("QUEUE_URL", callbackQueueUrl)); + } + + private String receiveTaskToken() throws Exception { + for (var i = 0; i < 50; i++) { + var resp = given() + .header("X-Amz-Target", "AmazonSQS.ReceiveMessage") + .contentType(SQS_CONTENT_TYPE) + .body("{\"QueueUrl\":\"%s\",\"MaxNumberOfMessages\":1,\"WaitTimeSeconds\":1}" + .formatted(callbackQueueUrl)) + .when().post("/"); + resp.then().statusCode(200); + var messages = mapper.readTree(resp.body().asString()).path("Messages"); + if (messages.size() == 1) { + var message = messages.get(0); + deleteMessage(message.path("ReceiptHandle").asText()); + var token = mapper.readTree(message.path("Body").asText()).path("token").asText(); + assertFalse(token.isBlank(), "the waiting task published a blank token"); + return token; + } + Thread.sleep(100); + } + fail("The waiting execution never published its task token"); + return null; + } + + private static void deleteMessage(String receiptHandle) { + given() + .header("X-Amz-Target", "AmazonSQS.DeleteMessage") + .contentType(SQS_CONTENT_TYPE) + .body("{\"QueueUrl\":\"%s\",\"ReceiptHandle\":\"%s\"}" + .formatted(callbackQueueUrl, receiptHandle)) + .when().post("/") + .then().statusCode(200); + } + + private static String tokenInput(String taskToken) throws Exception { + return mapper.createObjectNode().put("token", taskToken).toString(); + } + + private String succeedingOutputOf(String smArn, String input) { + var describe = waitForTerminalState(startExecution(smArn, input)); + assertEquals("SUCCEEDED", describe.jsonPath().getString("status"), + "cause: " + describe.jsonPath().getString("cause")); + return describe.jsonPath().getString("output"); + } + + private static String createQueue(String name) { + var resp = given() + .header("X-Amz-Target", "AmazonSQS.CreateQueue") + .contentType(SQS_CONTENT_TYPE) + .body("{\"QueueName\":\"%s\"}".formatted(name)) + .when().post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("QueueUrl"); + } + + private static String createStateMachine(String name, String definition) { + var resp = given() + .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"name": "%s", "roleArn": "%s", "definition": %s} + """.formatted(name, ROLE_ARN, quote(definition))) + .when().post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("stateMachineArn"); + } + + private static String startExecution(String smArn, String input) { + var resp = given() + .header("X-Amz-Target", "AWSStepFunctions.StartExecution") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"stateMachineArn": "%s", "input": %s} + """.formatted(smArn, quote(input))) + .when().post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("executionArn"); + } + + private static Response describeExecution(String execArn) { + return given() + .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"executionArn": "%s"} + """.formatted(execArn)) + .when().post("/"); + } + + private static Response waitForTerminalState(String execArn) { + for (var i = 0; i < 150; i++) { + var resp = describeExecution(execArn); + if (!"RUNNING".equals(resp.jsonPath().getString("status"))) { + return resp; + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + fail("Interrupted while waiting for execution " + execArn); + } + } + fail("Execution did not complete within timeout: " + execArn); + return null; + } + + private static String quote(String raw) { + return "\"" + raw + .replace("\\", "\\\\") + .replace("\"", "\\\"") + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t") + + "\""; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonataIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonataIntegrationTest.java index 949fc2b1b4..9587bd2a59 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonataIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonataIntegrationTest.java @@ -1225,6 +1225,104 @@ class StepFunctionsJsonataIntegrationTest { assertTrue(output.contains("Jane Doe")); } + @Test + void outputKeepsAnExplicitNullInEveryPositionAndDropsOnlyWhatReturnedNothing() throws Exception { + // AWS returns {"v":null} for an expression that evaluates to JSON null, in an object field, + // nested, as an array element and as a literal. Only an expression that returned nothing + // loses its key. + String definition = """ + { + "QueryLanguage": "JSONata", + "StartAt": "Transform", + "States": { + "Transform": { + "Type": "Pass", + "Output": { + "fromInput": "{% $lookup($states.input, 'bar') %}", + "fromLiteralExpression": "{% null %}", + "literal": null, + "nested": {"inner": "{% null %}", "kept": 1}, + "values": ["{% null %}", 1], + "returnedNothing": "{% $states.input.absent %}" + }, + "End": true + } + } + } + """; + + String smArn = createStateMachine("jsonata-explicit-null-test", definition); + String execArn = startExecution(smArn, "{\"bar\": null}"); + JsonNode output = objectMapper.readTree(waitForExecution(execArn)); + + assertTrue(output.path("fromInput").isNull(), output.toString()); + assertTrue(output.path("fromLiteralExpression").isNull(), output.toString()); + assertTrue(output.path("literal").isNull(), output.toString()); + assertTrue(output.path("nested").path("inner").isNull(), output.toString()); + assertEquals("[null,1]", output.path("values").toString()); + assertTrue(output.path("returnedNothing").isMissingNode(), output.toString()); + } + + @Test + void anAssignedNullReadsBackAsANullInTheNextState() throws Exception { + // AWS keeps the null in the variables map: TestState TRACE reports {"x":null} for + // Assign {"x": "{% null %}"}. A state never sees its own Assign, so the read is one state on. + String definition = """ + { + "QueryLanguage": "JSONata", + "StartAt": "AssignNull", + "States": { + "AssignNull": { + "Type": "Pass", + "Assign": {"nullVariable": "{% $states.input.bar %}"}, + "Next": "ReadItBack" + }, + "ReadItBack": { + "Type": "Pass", + "Output": { + "fromVariable": "{% $nullVariable %}", + "exists": "{% $exists($nullVariable) %}" + }, + "End": true + } + } + } + """; + + String smArn = createStateMachine("jsonata-assign-null-test", definition); + String execArn = startExecution(smArn, "{\"bar\": null}"); + JsonNode output = objectMapper.readTree(waitForExecution(execArn)); + + assertTrue(output.path("fromVariable").isNull(), output.toString()); + assertTrue(output.path("exists").asBoolean(), output.toString()); + } + + @Test + void aWholeOutputThatReturnedNothingStaysReadableJson() throws Exception { + // AWS fails this state with States.QueryEvaluationError, which #2665 covers. Until then the + // execution succeeds, and what DescribeExecution hands back has to parse: an output field + // holding the empty string is not JSON any client can read. + String definition = """ + { + "QueryLanguage": "JSONata", + "StartAt": "Transform", + "States": { + "Transform": { + "Type": "Pass", + "Output": "{% $states.input.absent %}", + "End": true + } + } + } + """; + + String smArn = createStateMachine("jsonata-whole-output-nothing-test", definition); + String execArn = startExecution(smArn, "{}"); + String output = waitForExecution(execArn); + + assertTrue(objectMapper.readTree(output).isNull(), output); + } + @Test void assignedVariablesSurviveBeyondNextStateOutput() throws Exception { // Variables set via Assign persist across states even after a later state replaces the output. diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPutEventsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPutEventsIntegrationTest.java new file mode 100644 index 0000000000..603b790670 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPutEventsIntegrationTest.java @@ -0,0 +1,320 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +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.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.util.ArrayList; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Integration tests for the optimized {@code arn:aws:states:::events:putEvents} task integration. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class StepFunctionsPutEventsIntegrationTest { + + private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0"; + private static final String SQS_CONTENT_TYPE = "application/x-amz-json-1.0"; + private static final String EVENTS_CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role"; + private static final String RESOURCE = "arn:aws:states:::events:putEvents"; + private static final String SOURCE = "floci.putevents.task"; + private static final ObjectMapper mapper = new ObjectMapper(); + + private static String sinkQueueUrl; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(0) + void setup_routeTheSourceToASqsQueue() { + sinkQueueUrl = createQueue("put-events-task-sink"); + putRule("put-events-task-rule", "{\\\"source\\\":[\\\"" + SOURCE + "\\\"]}"); + putTarget("put-events-task-rule", queueArn(sinkQueueUrl)); + } + + @Test + @Order(1) + void publishedEventReachesTheRuleTargetAndTheResultCarriesItsEventId() throws Exception { + var smArn = createStateMachine("put-events-delivers", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Publish", + "States": { + "Publish": { + "Type": "Task", + "Resource": "RESOURCE_ARN", + "Arguments": { + "Entries": [{ + "Source": "SOURCE_NAME", + "DetailType": "payout requested", + "Detail": "{\\"amount\\": 1200}" + }] + }, + "End": true + } + } + } + """.replace("RESOURCE_ARN", RESOURCE).replace("SOURCE_NAME", SOURCE)); + + var result = mapper.readTree(succeedingOutputOf(smArn)); + assertEquals(0, result.path("FailedEntryCount").asInt()); + var eventId = result.path("Entries").get(0).path("EventId").asText(); + assertFalse(eventId.isBlank()); + + var delivered = mapper.readTree(receiveSingleMessage(sinkQueueUrl).path("Body").asText()); + assertEquals(eventId, delivered.path("id").asText()); + assertEquals("payout requested", delivered.path("detail-type").asText()); + assertEquals(1200, delivered.path("detail").path("amount").asInt()); + } + + @Test + @Order(2) + void taskResultCarriesTheSameFieldsThePutEventsApiReturns() throws Exception { + var smArn = createStateMachine("put-events-same-envelope", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Publish", + "States": { + "Publish": { + "Type": "Task", + "Resource": "RESOURCE_ARN", + "Arguments": { + "Entries": [{"Source": "floci.unrouted", "DetailType": "t", "Detail": "{}"}] + }, + "End": true + } + } + } + """.replace("RESOURCE_ARN", RESOURCE)); + + var taskResult = mapper.readTree(succeedingOutputOf(smArn)); + var apiResult = mapper.readTree(given() + .header("X-Amz-Target", "AWSEvents.PutEvents") + .contentType(EVENTS_CONTENT_TYPE) + .body(""" + {"Entries":[{"Source":"floci.unrouted","DetailType":"t","Detail":"{}"}]} + """) + .when().post("/") + .then().statusCode(200) + .extract().body().asString()); + + assertEquals(fieldNames(apiResult), fieldNames(taskResult)); + assertEquals(fieldNames(apiResult.path("Entries").get(0)), + fieldNames(taskResult.path("Entries").get(0))); + assertEquals(apiResult.path("FailedEntryCount").asInt(), taskResult.path("FailedEntryCount").asInt()); + } + + @Test + @Order(3) + void oneRejectedEntryFailsTheTaskWithFailedEntryAndTheWholeResponseAsCause() throws Exception { + var smArn = createStateMachine("put-events-failed-entry", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Publish", + "States": { + "Publish": { + "Type": "Task", + "Resource": "RESOURCE_ARN", + "Arguments": { + "Entries": [ + {"Source": "floci.unrouted", "DetailType": "t", "Detail": "{}"}, + {"EventBusName": "no-such-bus", "Source": "floci.unrouted", + "DetailType": "t", "Detail": "{}"} + ] + }, + "End": true + } + } + } + """.replace("RESOURCE_ARN", RESOURCE)); + + var describe = waitForTerminalState(startExecution(smArn)); + assertEquals("FAILED", describe.jsonPath().getString("status")); + assertEquals("EventBridge.FailedEntry", describe.jsonPath().getString("error")); + + // The cause is the PutEvents response itself, so the caller can tell which entry failed. + var cause = mapper.readTree(describe.jsonPath().getString("cause")); + assertEquals(1, cause.path("FailedEntryCount").asInt()); + assertFalse(cause.path("Entries").get(0).path("EventId").asText().isBlank()); + assertEquals("InvalidArgument", cause.path("Entries").get(1).path("ErrorCode").asText()); + } + + @Test + @Order(4) + void aFailedEntryIsCatchableByItsErrorName() throws Exception { + var smArn = createStateMachine("put-events-catch", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Publish", + "States": { + "Publish": { + "Type": "Task", + "Resource": "RESOURCE_ARN", + "Arguments": { + "Entries": [{"EventBusName": "no-such-bus", "Source": "floci.unrouted", + "DetailType": "t", "Detail": "{}"}] + }, + "Catch": [{"ErrorEquals": ["EventBridge.FailedEntry"], "Next": "Recovered"}], + "End": true + }, + "Recovered": { + "Type": "Pass", + "Output": {"recovered": true}, + "End": true + } + } + } + """.replace("RESOURCE_ARN", RESOURCE)); + + assertTrue(mapper.readTree(succeedingOutputOf(smArn)).path("recovered").asBoolean()); + } + + private static List fieldNames(JsonNode node) { + var names = new ArrayList(); + node.fieldNames().forEachRemaining(names::add); + return names; + } + + private String succeedingOutputOf(String smArn) { + var describe = waitForTerminalState(startExecution(smArn)); + assertEquals("SUCCEEDED", describe.jsonPath().getString("status"), + "cause: " + describe.jsonPath().getString("cause")); + return describe.jsonPath().getString("output"); + } + + private static String createQueue(String name) { + var resp = given() + .header("X-Amz-Target", "AmazonSQS.CreateQueue") + .contentType(SQS_CONTENT_TYPE) + .body("{\"QueueName\":\"%s\"}".formatted(name)) + .when().post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("QueueUrl"); + } + + private static String queueArn(String queueUrl) { + var resp = given() + .header("X-Amz-Target", "AmazonSQS.GetQueueAttributes") + .contentType(SQS_CONTENT_TYPE) + .body("{\"QueueUrl\":\"%s\",\"AttributeNames\":[\"QueueArn\"]}".formatted(queueUrl)) + .when().post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("Attributes.QueueArn"); + } + + private static void putRule(String name, String eventPattern) { + given() + .header("X-Amz-Target", "AWSEvents.PutRule") + .contentType(EVENTS_CONTENT_TYPE) + .body(""" + {"Name":"%s","EventPattern":"%s","State":"ENABLED"} + """.formatted(name, eventPattern)) + .when().post("/") + .then().statusCode(200); + } + + private static void putTarget(String rule, String targetArn) { + given() + .header("X-Amz-Target", "AWSEvents.PutTargets") + .contentType(EVENTS_CONTENT_TYPE) + .body(""" + {"Rule":"%s","Targets":[{"Id":"1","Arn":"%s"}]} + """.formatted(rule, targetArn)) + .when().post("/") + .then().statusCode(200); + } + + private JsonNode receiveSingleMessage(String queueUrl) throws Exception { + for (var i = 0; i < 20; i++) { + var resp = given() + .header("X-Amz-Target", "AmazonSQS.ReceiveMessage") + .contentType(SQS_CONTENT_TYPE) + .body("{\"QueueUrl\":\"%s\",\"MaxNumberOfMessages\":1,\"WaitTimeSeconds\":1}" + .formatted(queueUrl)) + .when().post("/"); + resp.then().statusCode(200); + var messages = mapper.readTree(resp.body().asString()).path("Messages"); + if (messages.size() == 1) { + return messages.get(0); + } + Thread.sleep(100); + } + fail("No event was delivered to " + queueUrl); + return null; + } + + private static String createStateMachine(String name, String definition) { + var resp = given() + .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"name": "%s", "roleArn": "%s", "definition": %s} + """.formatted(name, ROLE_ARN, quote(definition))) + .when().post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("stateMachineArn"); + } + + private static String startExecution(String smArn) { + var resp = given() + .header("X-Amz-Target", "AWSStepFunctions.StartExecution") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"stateMachineArn": "%s", "input": "{}"} + """.formatted(smArn)) + .when().post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("executionArn"); + } + + private static Response waitForTerminalState(String execArn) { + for (var i = 0; i < 100; i++) { + var resp = given() + .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"executionArn": "%s"} + """.formatted(execArn)) + .when().post("/"); + if (!"RUNNING".equals(resp.jsonPath().getString("status"))) { + return resp; + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + fail("Interrupted while waiting for execution " + execArn); + } + } + fail("Execution did not complete within timeout: " + execArn); + return null; + } + + private static String quote(String raw) { + return "\"" + raw + .replace("\\", "\\\\") + .replace("\"", "\\\"") + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t") + + "\""; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsStartSyncExecutionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsStartSyncExecutionIntegrationTest.java new file mode 100644 index 0000000000..7ec5e16cfc --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsStartSyncExecutionIntegrationTest.java @@ -0,0 +1,283 @@ +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.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Integration tests for the {@code arn:aws:states:::aws-sdk:sfn:startSyncExecution} task + * integration, the way a Standard workflow calls an EXPRESS child workflow. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class StepFunctionsStartSyncExecutionIntegrationTest { + + private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0"; + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role"; + private static final String RESOURCE = "arn:aws:states:::aws-sdk:sfn:startSyncExecution"; + private static final ObjectMapper mapper = new ObjectMapper(); + + private static String succeedingChildArn; + private static String failingChildArn; + private static String standardChildArn; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(0) + void setup_createChildStateMachines() { + succeedingChildArn = createStateMachine("sync-exec-child-ok", "EXPRESS", """ + { + "QueryLanguage": "JSONata", + "StartAt": "Approve", + "States": { + "Approve": { + "Type": "Pass", + "Output": {"approved": true, "echoedAmount": "{% $states.input.amount %}"}, + "End": true + } + } + } + """); + + failingChildArn = createStateMachine("sync-exec-child-fail", "EXPRESS", """ + { + "StartAt": "Reject", + "States": { + "Reject": { + "Type": "Fail", + "Error": "PoolClosed", + "Cause": "the pool is already closed" + } + } + } + """); + + standardChildArn = createStateMachine("sync-exec-child-standard", null, """ + { + "StartAt": "Approve", + "States": { + "Approve": {"Type": "Pass", "End": true} + } + } + """); + } + + @Test + @Order(1) + void succeedingChildReturnsPascalCaseEnvelopeWithOutputAsJsonString() throws Exception { + var parentArn = createStateMachine("sync-exec-parent-ok", null, callChild(""" + { + "QueryLanguage": "JSONata", + "StartAt": "CallChild", + "States": { + "CallChild": { + "Type": "Task", + "Resource": "RESOURCE_ARN", + "Arguments": { + "StateMachineArn": "CHILD_ARN", + "Input": {"amount": 1200} + }, + "Output": { + "status": "{% $states.result.Status %}", + "childOutput": "{% $states.result.Output %}", + "childArn": "{% $states.result.StateMachineArn %}", + "startDate": "{% $states.result.StartDate %}" + }, + "End": true + } + } + } + """, succeedingChildArn)); + + var describe = waitForTerminalState(startExecution(parentArn, "{}")); + assertEquals("SUCCEEDED", describe.jsonPath().getString("status")); + + var output = mapper.readTree(describe.jsonPath().getString("output")); + assertEquals("SUCCEEDED", output.path("status").asText()); + assertEquals(succeedingChildArn, output.path("childArn").asText()); + + // The SDK renders a timestamp as ISO-8601, where the wire response carries epoch seconds. + assertTrue(output.path("startDate").asText() + .matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"), + "StartDate is not the SDK's ISO-8601 rendering: " + output.path("startDate")); + + // Output arrives as a JSON string, the way the AWS SDK integration returns it. + var childOutput = mapper.readTree(output.path("childOutput").asText()); + assertTrue(childOutput.path("approved").asBoolean()); + assertEquals(1200, childOutput.path("echoedAmount").asInt()); + } + + @Test + @Order(2) + void failingChildIsReportedThroughStatusWithoutFailingTheTask() throws Exception { + var parentArn = createStateMachine("sync-exec-parent-fail", null, callChild(""" + { + "QueryLanguage": "JSONata", + "StartAt": "CallChild", + "States": { + "CallChild": { + "Type": "Task", + "Resource": "RESOURCE_ARN", + "Arguments": { + "StateMachineArn": "CHILD_ARN", + "Input": {} + }, + "Output": { + "status": "{% $states.result.Status %}", + "error": "{% $states.result.Error %}", + "cause": "{% $states.result.Cause %}" + }, + "End": true + } + } + } + """, failingChildArn)); + + var describe = waitForTerminalState(startExecution(parentArn, "{}")); + assertEquals("SUCCEEDED", describe.jsonPath().getString("status")); + + var output = mapper.readTree(describe.jsonPath().getString("output")); + assertEquals("FAILED", output.path("status").asText()); + assertEquals("PoolClosed", output.path("error").asText()); + assertEquals("the pool is already closed", output.path("cause").asText()); + } + + @Test + @Order(3) + void standardChildFailsTheTaskWithTheServicePrefixedError() { + var parentArn = createStateMachine("sync-exec-parent-standard-child", null, """ + { + "QueryLanguage": "JSONata", + "StartAt": "CallChild", + "States": { + "CallChild": { + "Type": "Task", + "Resource": "%s", + "Arguments": { + "StateMachineArn": "%s", + "Input": {} + }, + "End": true + } + } + } + """.formatted(RESOURCE, standardChildArn)); + + var describe = waitForTerminalState(startExecution(parentArn, "{}")); + assertEquals("FAILED", describe.jsonPath().getString("status")); + assertEquals("Sfn.StateMachineTypeNotSupportedException", describe.jsonPath().getString("error")); + assertTrue(describe.jsonPath().getString("cause").contains("only supported for EXPRESS")); + } + + @Test + @Order(4) + void missingStateMachineArnFailsTheTask() { + var parentArn = createStateMachine("sync-exec-parent-no-arn", null, """ + { + "QueryLanguage": "JSONata", + "StartAt": "CallChild", + "States": { + "CallChild": { + "Type": "Task", + "Resource": "%s", + "Arguments": {"Input": {}}, + "End": true + } + } + } + """.formatted(RESOURCE)); + + var describe = waitForTerminalState(startExecution(parentArn, "{}")); + assertEquals("FAILED", describe.jsonPath().getString("status")); + assertEquals("Sfn.InvalidArnException", describe.jsonPath().getString("error")); + } + + /** + * Substitutes the two ARNs by token instead of {@code String.formatted}, because a JSONata + * definition contains {@code {% ... %}} delimiters that a format string reads as conversions. + */ + private static String callChild(String definition, String childArn) { + return definition + .replace("RESOURCE_ARN", RESOURCE) + .replace("CHILD_ARN", childArn); + } + + private static String createStateMachine(String name, String type, String definition) { + var typeField = type != null ? "\"type\": \"%s\",".formatted(type) : ""; + var resp = given() + .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine") + .contentType(SFN_CONTENT_TYPE) + .body(""" + { + "name": "%s", + %s + "roleArn": "%s", + "definition": %s + } + """.formatted(name, typeField, ROLE_ARN, quote(definition))) + .when().post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("stateMachineArn"); + } + + private static String startExecution(String smArn, String input) { + var resp = given() + .header("X-Amz-Target", "AWSStepFunctions.StartExecution") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"stateMachineArn": "%s", "input": %s} + """.formatted(smArn, quote(input))) + .when().post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("executionArn"); + } + + private static Response waitForTerminalState(String execArn) { + for (var i = 0; i < 100; i++) { + var resp = given() + .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"executionArn": "%s"} + """.formatted(execArn)) + .when().post("/"); + var status = resp.jsonPath().getString("status"); + if (!"RUNNING".equals(status)) { + return resp; + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + fail("Interrupted while waiting for execution " + execArn); + } + } + fail("Execution did not complete within timeout: " + execArn); + return null; + } + + private static String quote(String raw) { + return "\"" + raw + .replace("\\", "\\\\") + .replace("\"", "\\\"") + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t") + + "\""; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTopLevelReferenceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTopLevelReferenceIntegrationTest.java new file mode 100644 index 0000000000..23534f302a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTopLevelReferenceIntegrationTest.java @@ -0,0 +1,311 @@ +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.DisplayName; +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 JSONata expression that reads the top-level context is refused when the state machine is + * created, as real AWS refuses it. Every message and location asserted here was measured with + * {@code aws stepfunctions validate-state-machine-definition --region us-east-1} on the same + * definition, and the CreateStateMachine wire shape with + * {@code aws stepfunctions create-state-machine}. + */ +@QuarkusTest +class StepFunctionsTopLevelReferenceIntegrationTest { + + 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("/"); + } + + private static void expectTopLevelReference(String definition, String reference, String location) { + validate(definition).then().statusCode(200) + .body("result", equalTo("FAIL")) + .body("diagnostics", hasSize(1)) + .body("diagnostics[0].severity", equalTo("ERROR")) + .body("diagnostics[0].code", equalTo("UNSUPPORTED_JSONATA_EXPRESSION")) + .body("diagnostics[0].message", equalTo( + "Reference to '" + reference + "' at the top level is not supported.")) + .body("diagnostics[0].location", equalTo(location)); + } + + private static void expectAccepted(String definition) { + validate(definition).then().statusCode(200) + .body("result", equalTo("OK")) + .body("diagnostics", hasSize(0)); + } + + private static String passWithOutput(String output) { + return """ + {"QueryLanguage":"JSONata","StartAt":"E", + "States":{"E":{"Type":"Pass","Output":__OUTPUT__,"End":true}}} + """.replace("__OUTPUT__", output); + } + + @Test + @DisplayName("CreateStateMachine refuses the definition with AWS's InvalidDefinition message") + void createStateMachineRefusesATopLevelReference() { + create("top-level-reference-" + System.nanoTime(), + passWithOutput("{\"v\":\"{% phone[0] %}\"}")) + .then().statusCode(400) + .body("__type", equalTo("InvalidDefinition")) + .body("message", equalTo("Invalid State Machine Definition: " + + "'UNSUPPORTED_JSONATA_EXPRESSION: Reference to 'phone' at the top level " + + "is not supported. at /States/E/Output/v'")); + } + + @Test + @DisplayName("CreateStateMachine still accepts the anchored form of the same expression") + void createStateMachineAcceptsTheAnchoredForm() { + create("anchored-reference-" + System.nanoTime(), + passWithOutput("{\"v\":\"{% $states.input.phone[0] %}\"}")) + .then().statusCode(200); + } + + @Test + @DisplayName("Output names the field that holds the expression") + void outputField() { + expectTopLevelReference(passWithOutput("{\"v\":\"{% phone %}\"}"), + "phone", "/States/E/Output/v"); + } + + @Test + @DisplayName("a nested Output object names the whole path down to the array element") + void nestedOutputField() { + expectTopLevelReference(passWithOutput("{\"a\":{\"b\":[\"{% phone %}\"]}}"), + "phone", "/States/E/Output/a/b[0]"); + } + + @Test + @DisplayName("Assign is parsed like Output") + void assignField() { + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"E", + "States":{"E":{"Type":"Pass","Assign":{"v":"{% phone %}"},"End":true}}} + """, "phone", "/States/E/Assign/v"); + } + + @Test + @DisplayName("a Choice condition names its rule by index") + void choiceCondition() { + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"C","States":{ + "C":{"Type":"Choice","Choices":[{"Condition":"{% phone = 1 %}","Next":"E"}], + "Default":"E"}, + "E":{"Type":"Pass","End":true}}} + """, "phone", "/States/C/Choices[0]/Condition"); + } + + @Test + @DisplayName("Wait Seconds is parsed") + void waitSeconds() { + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"E", + "States":{"E":{"Type":"Wait","Seconds":"{% phone %}","End":true}}} + """, "phone", "/States/E/Seconds"); + } + + @Test + @DisplayName("Fail Cause is parsed") + void failCause() { + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"E", + "States":{"E":{"Type":"Fail","Cause":"{% phone %}"}}} + """, "phone", "/States/E/Cause"); + } + + @Test + @DisplayName("Map Items is parsed and so is every state of its ItemProcessor") + void mapItemsAndItemProcessor() { + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"M","States":{ + "M":{"Type":"Map","Items":"{% phone %}","ItemProcessor":{ + "StartAt":"I","States":{"I":{"Type":"Pass","End":true}}},"End":true}}} + """, "phone", "/States/M/Items"); + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"M","States":{ + "M":{"Type":"Map","Items":"{% $states.input.a %}","ItemProcessor":{ + "StartAt":"I","States":{"I":{"Type":"Pass", + "Output":{"v":"{% phone %}"},"End":true}}},"End":true}}} + """, "phone", "/States/M/ItemProcessor/States/I/Output/v"); + } + + @Test + @DisplayName("a Parallel branch state names its branch by index") + void parallelBranchState() { + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"P","States":{ + "P":{"Type":"Parallel","Branches":[{"StartAt":"B","States":{ + "B":{"Type":"Pass","Output":{"v":"{% phone %}"},"End":true}}}], + "End":true}}} + """, "phone", "/States/P/Branches[0]/States/B/Output/v"); + } + + @Test + @DisplayName("a Catch Output names its catcher by index") + void catchOutput() { + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"E","States":{ + "E":{"Type":"Task","Resource":"arn:aws:states:::aws-sdk:s3:listBuckets", + "Arguments":{},"Catch":[{"ErrorEquals":["States.ALL"], + "Output":{"v":"{% phone %}"},"Next":"F"}],"End":true}, + "F":{"Type":"Pass","End":true}}} + """, "phone", "/States/E/Catch[0]/Output/v"); + } + + @Test + @DisplayName("an earlier Assign does not make the bare name legal; only $phone is") + void anEarlierAssignDoesNotBindTheBareName() { + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"A","States":{ + "A":{"Type":"Pass","Assign":{"phone":"{% 1 %}"},"Next":"E"}, + "E":{"Type":"Pass","Output":{"v":"{% phone %}"},"End":true}}} + """, "phone", "/States/E/Output/v"); + expectAccepted(""" + {"QueryLanguage":"JSONata","StartAt":"A","States":{ + "A":{"Type":"Pass","Assign":{"phone":"{% 1 %}"},"Next":"E"}, + "E":{"Type":"Pass","Output":{"v":"{% $phone %}"},"End":true}}} + """); + } + + @Test + @DisplayName("each distinct name in one field gets its own diagnostic") + void everyDistinctNameInOneField() { + validate(passWithOutput("{\"v\":\"{% aaa + bbb %}\"}")) + .then().statusCode(200) + .body("result", equalTo("FAIL")) + .body("diagnostics", hasSize(2)) + .body("diagnostics[0].message", equalTo( + "Reference to 'aaa' at the top level is not supported.")) + .body("diagnostics[1].message", equalTo( + "Reference to 'bbb' at the top level is not supported.")) + .body("diagnostics[1].location", equalTo("/States/E/Output/v")); + } + + @Test + @DisplayName("the context item itself is named '$'") + void contextItem() { + expectTopLevelReference(passWithOutput("{\"v\":\"{% $.phone %}\"}"), + "$", "/States/E/Output/v"); + } + + @Test + @DisplayName("a name reached through $states, a predicate or a variable is accepted") + void anchoredExpressionsAreAccepted() { + expectAccepted(passWithOutput("{\"v\":\"{% $states.input.phone %}\"}")); + expectAccepted(passWithOutput("{\"v\":\"{% $states.input.items[phone > 3] %}\"}")); + expectAccepted(passWithOutput("{\"v\":\"{% $map($states.input.a, function($x){ $x.phone }) %}\"}")); + expectAccepted(passWithOutput("{\"v\":\"{% $phone %}\"}")); + } + + @Test + @DisplayName("a JSONPath state machine is not parsed as JSONata") + void jsonPathMachineIsUntouched() { + expectAccepted(""" + {"StartAt":"E", + "States":{"E":{"Type":"Pass","Parameters":{"v":"{% phone %}"},"End":true}}} + """); + } + + @Test + @DisplayName("Comment, Next and ErrorEquals keep a {% %} string as text, as AWS does") + void fieldsAwsDoesNotParse() { + expectAccepted(""" + {"QueryLanguage":"JSONata","StartAt":"E", + "States":{"E":{"Type":"Pass","Comment":"{% phone %}","End":true}}} + """); + expectAccepted(""" + {"QueryLanguage":"JSONata","StartAt":"E","States":{ + "E":{"Type":"Task","Resource":"arn:aws:states:::aws-sdk:s3:listBuckets", + "Arguments":{},"Retry":[{"ErrorEquals":["{% phone %}"]}],"End":true}}} + """); + } + + @Test + @DisplayName("ReaderConfig.CSVHeaders holds column names, not expressions, as AWS does") + void readerConfigCsvHeadersAreNotParsed() { + expectAccepted(""" + {"QueryLanguage":"JSONata","StartAt":"M","States":{ + "M":{"Type":"Map", + "ItemReader":{"Resource":"arn:aws:states:::s3:getObject", + "Arguments":{"Bucket":"b","Key":"k"}, + "ReaderConfig":{"InputType":"CSV","CSVHeaderLocation":"GIVEN", + "CSVHeaders":["{% phone %}"]}}, + "ItemProcessor":{"StartAt":"I","States":{"I":{"Type":"Pass","End":true}}}, + "End":true}}} + """); + } + + @Test + @DisplayName("a payload key named after an ASL field is still an expression, as AWS parses it") + void aPayloadKeyNamedAfterAnAslFieldIsParsed() { + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"E", + "States":{"E":{"Type":"Pass","Assign":{"Next":"{% phone %}"},"End":true}}} + """, "phone", "/States/E/Assign/Next"); + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"E","States":{ + "E":{"Type":"Task","Resource":"arn:aws:states:::lambda:invoke", + "Arguments":{"FunctionName":"f","Payload":{"Comment":"{% phone %}"}}, + "End":true}}} + """, "phone", "/States/E/Arguments/Payload/Comment"); + expectTopLevelReference(passWithOutput("{\"ItemProcessor\":{\"Iterator\":\"{% phone %}\"}}"), + "phone", "/States/E/Output/ItemProcessor/Iterator"); + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"M","States":{ + "M":{"Type":"Map","ItemSelector":{"Next":"{% phone %}"}, + "ItemProcessor":{"StartAt":"I","States":{"I":{"Type":"Pass","End":true}}}, + "End":true}}} + """, "phone", "/States/M/ItemSelector/Next"); + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"M","States":{ + "M":{"Type":"Map","ItemBatcher":{"BatchInput":{"Comment":"{% phone %}"}}, + "ItemProcessor":{"StartAt":"I","States":{"I":{"Type":"Pass","End":true}}}, + "End":true}}} + """, "phone", "/States/M/ItemBatcher/BatchInput/Comment"); + expectTopLevelReference(""" + {"QueryLanguage":"JSONata","StartAt":"E","States":{ + "E":{"Type":"Task","Resource":"arn:aws:states:::lambda:invoke", + "Arguments":{"FunctionName":"f"}, + "Catch":[{"ErrorEquals":["States.ALL"],"Assign":{"Retry":"{% phone %}"}, + "Next":"D"}],"End":true}, + "D":{"Type":"Pass","End":true}}} + """, "phone", "/States/E/Catch[0]/Assign/Retry"); + } + + @Test + @DisplayName("a syntax error is left to the execution, as it is today") + void syntaxErrorsAreOutOfScope() { + expectAccepted(passWithOutput("{\"v\":\"{% phone[1,2) %}\"}")); + } +}