feat(stepfunctions): dispatch ECS Lambda mapping and secret SDK tasks (#7004)

* feat(stepfunctions): dispatch ECS Lambda mapping and secret SDK tasks

* fix(stepfunctions): render ECS task-set StabilityStatusAt as ISO-8601

* refactor(stepfunctions): share recase and timestamp helpers with SDK management invoker

Reuse AslExecutor.recaseKeys (with a verbatim-key set), capitalizeFirst and a
single renderSdkTimestamps walker instead of copies in SdkManagementTaskInvoker,
and inject the invoker through the AslExecutor constructor.
This commit is contained in:
jwoa95 authored and GitHub committed 2026-10-31 22:00:04 -04:00
1 parent d4f87659a7
commit 812ab3becf
7 files changed
+506 -18

No files matched your search

+38
View File
@@ -563,6 +563,12 @@ the wire and the task fails with `Sfn.StateMachineDoesNotExistException`.
| Resource | Result | Notable failure |
| --- | --- | --- |
| `arn:aws:states:::aws-sdk:ecs:updateService` | `{Service}` | `Ecs.ServiceNotFoundException` |
| `arn:aws:states:::aws-sdk:ecs:listServices` | `{ServiceArns, NextToken?}` | `Ecs.ClusterNotFoundException` |
| `arn:aws:states:::aws-sdk:ecs:describeServices` | `{Services, Failures}` | Missing services appear in `Failures` |
| `arn:aws:states:::aws-sdk:lambda:listEventSourceMappings` | `{EventSourceMappings}` | `Lambda.InvalidParameterValueException` |
| `arn:aws:states:::aws-sdk:lambda:updateEventSourceMapping` | mapping metadata, including `UUID` | `Lambda.ResourceNotFoundException` |
| `arn:aws:states:::aws-sdk:secretsmanager:describeSecret` | secret metadata, including `VersionIdsToStages` | `SecretsManager.ResourceNotFoundException` |
| `arn:aws:states:::aws-sdk:sfn:startExecution` | `{ExecutionArn, StartDate}` | `Sfn.ExecutionAlreadyExistsException` when `Name` is reused on a Standard child |
| `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 |
@@ -581,6 +587,38 @@ Callback tokens are owned by the execution account. Foreign callbacks return
or evicted tokens return `InvalidToken`. Invalid JSON output leaves a pending token available
for a corrected callback. Token state remains in memory.
The six ECS, Lambda mapping, and Secrets Manager management tasks above delegate
to the existing local service handlers in the execution account and state-machine
region. They use PascalCase request/response members and ISO-8601 response
timestamps. Opaque dictionary keys, including secret version IDs and ECS log
options, retain their original spelling. `describeSecret` returns metadata without
the secret value. Disabled services fail with a catchable service exception.
ECS `listServices` supports the same `MaxResults` and opaque `NextToken` as the
direct ECS API. Lambda mapping tasks currently return an unpaginated list;
`Marker` and `MaxItems` are rejected with `Lambda.InvalidParameterValueException`
instead of being silently ignored. These six integrations do not evaluate the
state-machine execution role's per-action IAM policies. Name-based lookups use the
execution scope; explicit ARNs retain the underlying service's cross-account lookup
behavior. The underlying services' validation still applies. They implement
request-response calls, without job-completion polling.
For example, force a deployment of an existing disposable service:
```json
{
"StartAt": "Restart",
"States": {
"Restart": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:ecs:updateService",
"Parameters": {"Cluster": "example", "Service": "example", "ForceNewDeployment": true},
"End": true
}
}
}
```
Redshift Data API execution returns a statement `Id` before SQL completes. Follow the
`executeStatement` task with `describeStatement`, a Choice on `Status`, and a Wait state
before polling again. Read results only after `FINISHED`; route `FAILED` and `ABORTED`
+6
View File
@@ -528,6 +528,12 @@
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sfn</artifactId>
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>ecs</artifactId>
@@ -214,6 +214,7 @@ public class AslExecutor {
*/
private static final DateTimeFormatter SDK_TIMESTAMP =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
private static final Set<String> REDSHIFT_DATA_TIMESTAMPS = Set.of("CreatedAt", "UpdatedAt", "SessionTtl");
private static final Set<String> HTTP_ALLOWED_METHODS = Set.of(
"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD");
@@ -277,6 +278,7 @@ public class AslExecutor {
private final ApiGatewayTaskInvoker apiGatewayTaskInvoker;
private final EmrTaskInvoker emrTaskInvoker;
private final EmrServerlessTaskInvoker emrServerlessTaskInvoker;
private final SdkManagementTaskInvoker sdkManagementTaskInvoker;
private final EmulatorConfig config;
private final NestedTaskCredentials nestedTaskCredentials;
private final CustomResourceLiveness customResourceLiveness;
@@ -311,7 +313,8 @@ public class AslExecutor {
CustomResourceLiveness customResourceLiveness, RedshiftDataJsonHandler redshiftDataHandler,
ServiceRegistry serviceRegistry, NestedTaskCredentials nestedTaskCredentials,
LambdaTaskAuthorizer lambdaTaskAuthorizer, ApiGatewayTaskInvoker apiGatewayTaskInvoker,
EmrTaskInvoker emrTaskInvoker, EmrServerlessTaskInvoker emrServerlessTaskInvoker) {
EmrTaskInvoker emrTaskInvoker, EmrServerlessTaskInvoker emrServerlessTaskInvoker,
SdkManagementTaskInvoker sdkManagementTaskInvoker) {
this(lambdaExecutor, targetResolver, dynamoDb, dynamoDbJsonHandler,
sqsJsonHandler, snsJsonHandler, cloudFormationHandler,
ec2Service, s3Service, ecsService, ecsJsonHandler,
@@ -319,7 +322,7 @@ public class AslExecutor {
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, redshiftDataHandler, serviceRegistry,
nestedTaskCredentials, lambdaTaskAuthorizer, null, null, apiGatewayTaskInvoker, emrTaskInvoker,
emrServerlessTaskInvoker, null);
emrServerlessTaskInvoker, sdkManagementTaskInvoker, null);
}
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver,
@@ -338,10 +341,12 @@ public class AslExecutor {
NestedTaskCredentials nestedTaskCredentials, LambdaTaskAuthorizer lambdaTaskAuthorizer,
Duration expressMaxExecutionTimeOverride, LongSupplier nanoTimeOverride,
ApiGatewayTaskInvoker apiGatewayTaskInvoker, EmrTaskInvoker emrTaskInvoker,
EmrServerlessTaskInvoker emrServerlessTaskInvoker, NestedWaiter nestedWaiter) {
EmrServerlessTaskInvoker emrServerlessTaskInvoker, SdkManagementTaskInvoker sdkManagementTaskInvoker,
NestedWaiter nestedWaiter) {
this.apiGatewayTaskInvoker = apiGatewayTaskInvoker;
this.emrTaskInvoker = emrTaskInvoker;
this.emrServerlessTaskInvoker = emrServerlessTaskInvoker;
this.sdkManagementTaskInvoker = sdkManagementTaskInvoker;
this.nestedTaskCredentials = nestedTaskCredentials;
this.serviceRegistry = serviceRegistry;
this.lambdaTaskAuthorizer = lambdaTaskAuthorizer;
@@ -406,7 +411,7 @@ public class AslExecutor {
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null, null, null, null, null, null, null,
null, null);
null, null, null);
}
// Kept for tests that do not exercise the Redshift Data API integration.
@@ -427,7 +432,8 @@ public class AslExecutor {
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
clock, sleeper, maxWaitSecondsOverride, null, null, null, null, null, null, null, null, null, null);
clock, sleeper, maxWaitSecondsOverride, null, null, null, null, null, null, null, null, null, null,
null);
}
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore,
@@ -1460,6 +1466,10 @@ public class AslExecutor {
return invokeS3PutObject(input);
}
if (SdkManagementTaskInvoker.supports(integration)) {
return sdkManagementTaskInvoker.invoke(integration, input, extractRegionFromArn(sm.getStateMachineArn()));
}
// ECS optimized integration: arn:<partition>:states:::ecs:runTask (request-response, .sync, .waitForTaskToken).
// The .waitForTaskToken suffix is already stripped by executeTaskState, so a waitForTaskToken
// variant arrives here as the bare runTask resource and simply launches the task while the token
@@ -1647,7 +1657,7 @@ public class AslExecutor {
}
}
private static String capitalizeFirst(String s) {
static String capitalizeFirst(String s) {
return s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
@@ -1675,7 +1685,7 @@ public class AslExecutor {
* {@code Sfn.StateMachineDoesNotExistException}, while the StartExecution wire response names
* that same error {@code StateMachineDoesNotExist}.
*/
private static String sdkExceptionName(String service, String errorCode) {
static String sdkExceptionName(String service, String errorCode) {
return errorCode.endsWith("Exception")
? service + "." + errorCode
: service + "." + errorCode + "Exception";
@@ -2465,6 +2475,16 @@ public class AslExecutor {
* handed to the ECS handlers).
*/
static JsonNode recaseKeys(ObjectMapper mapper, JsonNode node, boolean upperFirst) {
return recaseKeys(mapper, node, upperFirst, Set.of());
}
/**
* {@link #recaseKeys(ObjectMapper, JsonNode, boolean)} that copies the value of each member named in
* {@code verbatim} unchanged, for maps whose keys are user data rather than model members. The
* member's own key is still recased and is matched as it arrives, so list it in each casing it can
* arrive in.
*/
static JsonNode recaseKeys(ObjectMapper mapper, JsonNode node, boolean upperFirst, Set<String> verbatim) {
if (node == null) {
return null;
}
@@ -2473,14 +2493,15 @@ public class AslExecutor {
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> e = fields.next();
out.set(recaseKey(e.getKey(), upperFirst), recaseKeys(mapper, e.getValue(), upperFirst));
out.set(recaseKey(e.getKey(), upperFirst), verbatim.contains(e.getKey())
? e.getValue().deepCopy() : recaseKeys(mapper, e.getValue(), upperFirst, verbatim));
}
return out;
}
if (node.isArray()) {
ArrayNode out = mapper.createArrayNode();
for (JsonNode item : node) {
out.add(recaseKeys(mapper, item, upperFirst));
out.add(recaseKeys(mapper, item, upperFirst, verbatim));
}
return out;
}
@@ -2649,21 +2670,28 @@ public class AslExecutor {
return objectMapper.createObjectNode();
}
JsonNode rendered = body.deepCopy();
renderRedshiftDataTimestamps(rendered);
renderSdkTimestamps(rendered, REDSHIFT_DATA_TIMESTAMPS, Set.of());
return rendered;
}
private static void renderRedshiftDataTimestamps(JsonNode node) {
/**
* Rewrites in place every numeric member named in {@code timestamps}, at any depth, as the SDK's
* ISO-8601 rendering. The walk does not descend into members named in {@code verbatim}, maps
* whose keys are user data rather than model members.
*/
static void renderSdkTimestamps(JsonNode node, Set<String> timestamps, Set<String> verbatim) {
if (node instanceof ObjectNode object) {
for (String field : List.of("CreatedAt", "UpdatedAt", "SessionTtl")) {
JsonNode value = object.get(field);
if (value != null && value.isNumber()) {
object.put(field, sdkTimestamp(value.asDouble()));
Iterator<Map.Entry<String, JsonNode>> fields = object.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
if (timestamps.contains(field.getKey()) && field.getValue().isNumber()) {
object.put(field.getKey(), sdkTimestamp(field.getValue().asDouble()));
} else if (!verbatim.contains(field.getKey())) {
renderSdkTimestamps(field.getValue(), timestamps, verbatim);
}
}
object.elements().forEachRemaining(AslExecutor::renderRedshiftDataTimestamps);
} else if (node instanceof ArrayNode array) {
array.elements().forEachRemaining(AslExecutor::renderRedshiftDataTimestamps);
array.forEach(item -> renderSdkTimestamps(item, timestamps, verbatim));
}
}
@@ -0,0 +1,120 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
import io.github.hectorvent.floci.services.lambda.LambdaController;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.util.Set;
import static io.github.hectorvent.floci.services.stepfunctions.AslExecutor.FailStateException;
/** AWS SDK management tasks delegated to the same handlers as the public APIs. */
@ApplicationScoped
public class SdkManagementTaskInvoker {
private static final Set<String> ECS_ACTIONS = Set.of("updateService", "listServices", "describeServices");
private static final Set<String> LAMBDA_ACTIONS = Set.of("listEventSourceMappings", "updateEventSourceMapping");
private static final Set<String> DICTIONARIES = Set.of("options", "Options", "dockerLabels", "DockerLabels",
"VersionIdsToStages", "Endpoints");
private static final Set<String> TIMESTAMPS = Set.of("CreatedAt", "UpdatedAt", "StartedAt", "FinishedAt",
"CreatedDate", "LastChangedDate", "LastAccessedDate", "LastRotatedDate", "NextRotationDate", "DeletedDate",
"LastModified", "StartingPositionTimestamp", "StabilityStatusAt");
private final EcsJsonHandler ecs;
private final LambdaController lambda;
private final SecretsManagerJsonHandler secrets;
private final ServiceRegistry registry;
private final ObjectMapper mapper;
@Inject
public SdkManagementTaskInvoker(EcsJsonHandler ecs, LambdaController lambda, SecretsManagerJsonHandler secrets,
ServiceRegistry registry, ObjectMapper mapper) {
this.ecs = ecs;
this.lambda = lambda;
this.secrets = secrets;
this.registry = registry;
this.mapper = mapper;
}
static boolean supports(StatesIntegration integration) {
return integration.sdk() && integration.suffix().isEmpty() && switch (integration.service()) {
case "ecs" -> ECS_ACTIONS.contains(integration.api());
case "lambda" -> LAMBDA_ACTIONS.contains(integration.api());
case "secretsmanager" -> "describeSecret".equals(integration.api());
default -> false;
};
}
JsonNode invoke(StatesIntegration integration, JsonNode input, String region) throws Exception {
String prefix = switch (integration.service()) {
case "ecs" -> "Ecs";
case "lambda" -> "Lambda";
default -> "SecretsManager";
};
try {
if (!registry.isServiceEnabled(integration.service())) {
throw new AwsException("ServiceNotAvailableException", "Service is disabled: " + integration.service(), 400);
}
if (input == null || !input.isObject()) {
throw new AwsException("InvalidParameterValueException", "The task input must be a JSON object.", 400);
}
return RequestScopes.callAsChecked(null, region, () -> {
try (Response response = dispatch(integration, input, region)) {
JsonNode body = response.getEntity() instanceof JsonNode json ? json.deepCopy()
: response.getEntity() instanceof String json ? mapper.readTree(json)
: mapper.valueToTree(response.getEntity());
if (response.getStatus() >= 400) {
String code = body.path("__type").asText("ServiceException");
code = code.substring(code.lastIndexOf('#') + 1);
throw new AwsException(code, body.path("message").asText(
body.path("Message").asText("Service request failed")), response.getStatus());
}
JsonNode result = "ecs".equals(integration.service())
? AslExecutor.recaseKeys(mapper, body, true, DICTIONARIES) : body;
AslExecutor.renderSdkTimestamps(result, TIMESTAMPS, DICTIONARIES);
return result;
}
});
} catch (AwsException error) {
throw new FailStateException(AslExecutor.sdkExceptionName(prefix, error.getErrorCode()), error.getMessage());
}
}
private Response dispatch(StatesIntegration integration, JsonNode input, String region) {
return switch (integration.service()) {
case "ecs" -> ecs.handle(AslExecutor.capitalizeFirst(integration.api()),
AslExecutor.recaseKeys(mapper, input, false, DICTIONARIES), region);
case "secretsmanager" -> secrets.handle("DescribeSecret", input, region);
case "lambda" -> switch (integration.api()) {
case "listEventSourceMappings" -> {
if (input.has("Marker") || input.has("MaxItems")) {
throw new AwsException("InvalidParameterValueException",
"Pagination for Lambda mapping SDK tasks is not supported by Floci.", 400);
}
yield lambda.listEventSourceMappings(input.path("FunctionName").asText(null),
input.path("EventSourceArn").asText(null));
}
case "updateEventSourceMapping" -> {
String uuid = input.path("UUID").asText(null);
if (uuid == null || uuid.isBlank()) {
throw new AwsException("InvalidParameterValueException", "UUID is required.", 400);
}
ObjectNode request = input.deepCopy();
request.remove("UUID");
yield lambda.updateEventSourceMapping(uuid, request.toString());
}
default -> throw new IllegalStateException("Unsupported Lambda management action");
};
default -> throw new IllegalStateException("Unsupported SDK management service");
};
}
}
@@ -300,7 +300,7 @@ final class AslExecutorFixture {
jsonataEvaluator != null ? jsonataEvaluator : new JsonataEvaluator(objectMapper),
sfnService, config, vertx, customResourceLiveness, clock, sleeper, maxWaitSeconds,
redshiftDataHandler, serviceRegistry, null, lambdaTaskAuthorizer, expressMaxExecutionTime,
nanoTime, null, emrTaskInvoker, emrServerlessTaskInvoker, nestedWaiter);
nanoTime, null, emrTaskInvoker, emrServerlessTaskInvoker, null, nestedWaiter);
}
}
}
@@ -0,0 +1,91 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
import io.github.hectorvent.floci.services.lambda.LambdaController;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class SdkManagementTaskInvokerTest {
private final ObjectMapper mapper = new ObjectMapper();
private final EcsJsonHandler ecs = mock(EcsJsonHandler.class);
private final ServiceRegistry registry = mock(ServiceRegistry.class);
private final SdkManagementTaskInvoker invoker = new SdkManagementTaskInvoker(ecs,
mock(LambdaController.class), mock(SecretsManagerJsonHandler.class), registry, mapper);
@Test
void recasesModeledEcsMembersWithoutChangingLogOptionKeysOrValues() throws Exception {
when(registry.isServiceEnabled("ecs")).thenReturn(true);
JsonNode response = mapper.readTree("""
{"service":{"createdAt":1.5,"serviceConnectConfiguration":{
"logConfiguration":{"options":{"CreatedAt":42,"lowercase-key":"value"}}}}}
""");
when(ecs.handle(eq("UpdateService"), any(), eq("eu-west-2")))
.thenReturn(Response.ok(response).build());
JsonNode request = mapper.readTree("""
{"Cluster":"example","Service":"example","ServiceConnectConfiguration":{
"LogConfiguration":{"Options":{"CreatedAt":42,"lowercase-key":"value"}}}}
""");
JsonNode result = invoker.invoke(integration(), request, "eu-west-2");
ArgumentCaptor<JsonNode> input = ArgumentCaptor.forClass(JsonNode.class);
verify(ecs).handle(eq("UpdateService"), input.capture(), eq("eu-west-2"));
assertEquals(request.path("ServiceConnectConfiguration").path("LogConfiguration").path("Options"),
input.getValue().path("serviceConnectConfiguration").path("logConfiguration").path("options"));
assertEquals("1970-01-01T00:00:01.500Z", result.path("Service").path("CreatedAt").asText());
assertEquals(response.path("service").path("serviceConnectConfiguration").path("logConfiguration").path("options"),
result.path("Service").path("ServiceConnectConfiguration").path("LogConfiguration").path("Options"));
}
@Test
void rendersTaskSetTimestampsAsIsoStrings() throws Exception {
when(registry.isServiceEnabled("ecs")).thenReturn(true);
JsonNode response = mapper.readTree("""
{"services":[{"serviceName":"example","taskSets":[{"id":"ecs-svc/1",
"createdAt":1.5,"updatedAt":2,"stabilityStatusAt":3.25}]}]}
""");
when(ecs.handle(eq("DescribeServices"), any(), eq("us-east-1")))
.thenReturn(Response.ok(response).build());
JsonNode result = invoker.invoke(
StatesIntegration.parse("arn:aws:states:::aws-sdk:ecs:describeServices").orElseThrow(),
mapper.readTree("{\"Cluster\":\"example\",\"Services\":[\"example\"]}"), "us-east-1");
JsonNode taskSet = result.path("Services").path(0).path("TaskSets").path(0);
assertEquals("1970-01-01T00:00:01.500Z", taskSet.path("CreatedAt").asText());
assertEquals("1970-01-01T00:00:02.000Z", taskSet.path("UpdatedAt").asText());
assertEquals("1970-01-01T00:00:03.250Z", taskSet.path("StabilityStatusAt").asText());
}
@Test
void aDisabledServiceFailsBeforeCallingItsHandler() {
AslExecutor.FailStateException error = assertThrows(AslExecutor.FailStateException.class,
() -> invoker.invoke(integration(), mapper.createObjectNode(), "us-east-1"));
assertEquals("Ecs.ServiceNotAvailableException", error.error);
verifyNoInteractions(ecs);
}
@Test
void handlerErrorResponsesBecomeCatchableSdkExceptions() {
when(registry.isServiceEnabled("ecs")).thenReturn(true);
when(ecs.handle(anyString(), any(), anyString())).thenReturn(Response.status(400)
.entity(new AwsErrorResponse("ClientException", "synthetic failure")).build());
AslExecutor.FailStateException error = assertThrows(AslExecutor.FailStateException.class,
() -> invoker.invoke(integration(), mapper.createObjectNode(), "us-east-1"));
assertEquals("Ecs.ClientException", error.error);
assertEquals("synthetic failure", error.cause);
}
private static StatesIntegration integration() {
return StatesIntegration.parse("arn:aws:states:::aws-sdk:ecs:updateService").orElseThrow();
}
}
@@ -0,0 +1,205 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sfn.SfnClient;
import software.amazon.awssdk.services.sfn.model.DescribeExecutionResponse;
import java.net.URI;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
class StepFunctionsSdkManagementIntegrationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String ACCOUNT = "771661200001";
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@CsvSource({"us-east-1,aws", "eu-west-2,aws", "cn-north-1,aws-cn"})
void ecsManagementTasksUseExistingServicesAndSdkResponseCasing(String region, String partition) throws Exception {
String cluster = "sdk-management-" + UUID.randomUUID();
String family = cluster + "-task";
String target = "AmazonEC2ContainerServiceV20141113.";
call("ecs", target + "CreateCluster", Map.of("clusterName", cluster), region, ACCOUNT);
String definition = call("ecs", target + "RegisterTaskDefinition", Map.of("family", family,
"containerDefinitions", List.of(Map.of("name", "app", "image", "example:test", "memory", 128))),
region, ACCOUNT).path("taskDefinition.taskDefinitionArn");
try {
for (String name : List.of("first", "second")) {
call("ecs", target + "CreateService", Map.of("cluster", cluster, "serviceName", name,
"taskDefinition", definition, "desiredCount", 0), region, ACCOUNT);
}
JsonNode page = task("ecs", "listServices", Map.of("Cluster", cluster, "MaxResults", 1), region, partition);
assertEquals(1, page.path("ServiceArns").size());
assertTrue(page.path("NextToken").isTextual());
JsonNode next = task("ecs", "listServices", Map.of("Cluster", cluster, "MaxResults", 1,
"NextToken", page.path("NextToken").asText()), region, partition);
assertEquals(1, next.path("ServiceArns").size());
assertNotEquals(page.path("ServiceArns"), next.path("ServiceArns"));
JsonNode updated = task("ecs", "updateService", Map.of("Cluster", cluster, "Service", "first",
"ForceNewDeployment", true, "DeploymentConfiguration",
Map.of("MinimumHealthyPercent", 0, "MaximumPercent", 100)), region, partition);
assertEquals("first", updated.path("Service").path("ServiceName").asText());
assertEquals(0, updated.path("Service").path("DeploymentConfiguration").path("MinimumHealthyPercent").asInt(-1));
assertTrue(updated.path("Service").path("CreatedAt").isTextual());
JsonNode described = task("ecs", "describeServices", Map.of("Cluster", cluster,
"Services", List.of("first", "missing")), region, partition);
assertEquals("first", described.path("Services").get(0).path("ServiceName").asText());
assertEquals("MISSING", described.path("Failures").get(0).path("Reason").asText());
JsonNode otherAccount = runTask("ecs", "listServices", Map.of("Cluster", cluster), region, partition,
"771661200002", true);
assertTrue(otherAccount.path("Error").asText().startsWith("Ecs."));
} finally {
for (String name : List.of("first", "second")) {
call("ecs", target + "DeleteService", Map.of("cluster", cluster, "service", name, "force", true), region, ACCOUNT);
}
call("ecs", target + "DeregisterTaskDefinition", Map.of("taskDefinition", definition), region, ACCOUNT);
call("ecs", target + "DeleteTaskDefinitions", Map.of("taskDefinitions", List.of(definition)), region, ACCOUNT);
call("ecs", target + "DeleteCluster", Map.of("cluster", cluster), region, ACCOUNT);
}
}
@Test
void describeSecretPreservesOpaqueVersionIdsAndReturnsCatchableErrors() throws Exception {
String region = "eu-west-2";
String name = "sdk-secret-" + UUID.randomUUID();
String version = "lowercase-" + UUID.randomUUID();
String arn = call("secretsmanager", "secretsmanager.CreateSecret", Map.of("Name", name,
"SecretString", "synthetic", "ClientRequestToken", version), region, ACCOUNT).path("ARN");
try {
JsonNode described = task("secretsmanager", "describeSecret", Map.of("SecretId", arn), region, "aws");
assertEquals(arn, described.path("ARN").asText());
assertEquals("AWSCURRENT", described.path("VersionIdsToStages").path(version).get(0).asText());
assertTrue(described.path("CreatedDate").isTextual());
assertFalse(described.has("SecretString"));
JsonNode error = runTask("secretsmanager", "describeSecret", Map.of("SecretId", name), region, "aws",
"771661200002", true);
assertEquals("SecretsManager.ResourceNotFoundException", error.path("Error").asText());
} finally {
call("secretsmanager", "secretsmanager.DeleteSecret", Map.of("SecretId", arn,
"ForceDeleteWithoutRecovery", true), region, ACCOUNT);
}
}
@Test
void lambdaMappingTasksUpdateAnActualMappingAndPreserveItsUuid() throws Exception {
String region = "eu-west-2";
String name = "sdk-mapping-" + UUID.randomUUID();
// An empty ZIP is a valid deployment archive; no invocation is needed for this management fixture.
Response created = lambda("post", "/2015-03-31/functions", Map.of("FunctionName", name,
"Runtime", "python3.12", "Role", "arn:aws:iam::" + ACCOUNT + ":role/test-role",
"Handler", "index.handler", "Code", Map.of("ZipFile", "UEsFBgAAAAAAAAAAAAAAAAAAAAAAAA==")), region);
String function = created.path("FunctionArn");
String source = "arn:aws:sqs:" + region + ":" + ACCOUNT + ":" + name;
String uuid = lambda("post", "/2015-03-31/event-source-mappings", Map.of("FunctionName", function,
"EventSourceArn", source, "Enabled", false), region).path("UUID");
try {
JsonNode listed = task("lambda", "listEventSourceMappings", Map.of("FunctionName", function), region, "aws");
assertEquals(uuid, listed.path("EventSourceMappings").get(0).path("UUID").asText());
JsonNode updated = task("lambda", "updateEventSourceMapping", Map.of("UUID", uuid,
"Enabled", false, "BatchSize", 3), region, "aws");
assertEquals(uuid, updated.path("UUID").asText());
assertEquals(3, updated.path("BatchSize").asInt());
assertEquals("Disabled", updated.path("State").asText());
assertTrue(updated.path("LastModified").isTextual());
assertEquals(3, lambda("get", "/2015-03-31/event-source-mappings/" + uuid, Map.of(), region)
.<Integer>path("BatchSize"));
JsonNode pagination = runTask("lambda", "listEventSourceMappings", Map.of("FunctionName", function,
"MaxItems", 1), region, "aws", ACCOUNT, true);
assertEquals("Lambda.InvalidParameterValueException", pagination.path("Error").asText());
JsonNode error = runTask("lambda", "updateEventSourceMapping", Map.of("UUID", uuid,
"Enabled", true), region, "aws", "771661200002", true);
assertEquals("Lambda.ResourceNotFoundException", error.path("Error").asText());
} finally {
lambda("delete", "/2015-03-31/event-source-mappings/" + uuid, Map.of(), region);
lambda("delete", "/2015-03-31/functions/" + name, Map.of(), region);
}
}
private static JsonNode task(String service, String action, Map<String, Object> parameters,
String region, String partition) throws Exception {
return runTask(service, action, parameters, region, partition, ACCOUNT, false);
}
private static JsonNode runTask(String service, String action, Map<String, Object> parameters,
String region, String partition, String account, boolean catchError) throws Exception {
ObjectNode task = MAPPER.createObjectNode().put("Type", "Task").put("End", true)
.put("Resource", "arn:" + partition + ":states:::aws-sdk:" + service + ":" + action);
task.set("Parameters", MAPPER.valueToTree(parameters));
ObjectNode states = MAPPER.createObjectNode();
states.set("Call", task);
if (catchError) {
task.remove("End");
task.set("Catch", MAPPER.valueToTree(List.of(Map.of("ErrorEquals", List.of("States.ALL"), "Next", "Caught"))));
task.put("Next", "Caught");
states.set("Caught", MAPPER.valueToTree(Map.of("Type", "Pass", "End", true)));
}
ObjectNode definition = MAPPER.createObjectNode().put("StartAt", "Call");
definition.set("States", states);
try (SfnClient client = SfnClient.builder()
.endpointOverride(URI.create("http://localhost:" + RestAssured.port))
.httpClientBuilder(UrlConnectionHttpClient.builder()).region(Region.of(region))
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test"))).build()) {
String arn = client.createStateMachine(request -> request.name("sdk-" + UUID.randomUUID())
.roleArn("arn:" + partition + ":iam::" + account + ":role/test-role")
.definition(definition.toString())).stateMachineArn();
try {
String execution = client.startExecution(request -> request.stateMachineArn(arn).input("{}"))
.executionArn();
await().atMost(Duration.ofSeconds(10)).until(() -> !"RUNNING".equals(client.describeExecution(
request -> request.executionArn(execution)).statusAsString()));
DescribeExecutionResponse result = client.describeExecution(request -> request.executionArn(execution));
assertEquals("SUCCEEDED", result.statusAsString(), result.toString());
return MAPPER.readTree(result.output());
} finally {
client.deleteStateMachine(request -> request.stateMachineArn(arn));
}
}
}
private static Response call(String service, String target, Map<String, ?> request, String region, String account) {
return given().contentType("states".equals(service) ? "application/x-amz-json-1.0" : "application/x-amz-json-1.1")
.header("X-Amz-Target", target)
.header("Authorization", authorization(service, region, account)).body(request)
.post("/").then().statusCode(200).extract().response();
}
private static Response lambda(String method, String path, Map<String, ?> request, String region) {
return given().contentType("application/json").header("Authorization", authorization("lambda", region, ACCOUNT))
.body(request).request(method, path).then().statusCode(lessThan(300))
.extract().response();
}
private static String authorization(String service, String region, String account) {
return "AWS4-HMAC-SHA256 Credential=" + account + "/20261030/" + region + "/" + service
+ "/aws4_request, SignedHeaders=host, Signature=synthetic";
}
}