feat(stepfunctions): add UpdateStateMachine and update in place on stack updates (#1867)

* feat(stepfunctions): add UpdateStateMachine and update in place on stack updates

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* fix(cloudformation): preserve log group on failed rename

* fix(cloudformation): scope update rollback to attempted resources

* fix(cloudformation): delete resources after stack updates

* test(cloudformation): wire cloudfront fixture dependency

* fix: include Step Functions update date in describe response

* fix: preserve Step Functions describe response shape

* fix: preserve generated Step Functions names
This commit is contained in:
Alex Banna authored and GitHub committed 2026-08-13 22:36:15 -04:00
1 parent da5ff910b4
commit 97ac3cabb5
15 files changed
+4569 -119

No files matched your search

@@ -0,0 +1,162 @@
package com.floci.test;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudformation.model.DescribeStackResourcesRequest;
import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest;
import software.amazon.awssdk.services.cloudformation.model.Stack;
import software.amazon.awssdk.services.cloudformation.model.StackResource;
import software.amazon.awssdk.services.sfn.SfnClient;
import software.amazon.awssdk.services.sfn.model.DescribeStateMachineResponse;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("CloudFormation Step Functions update")
class CloudFormationStepFunctionsUpdateTest {
private static final Logger LOGGER =
Logger.getLogger(CloudFormationStepFunctionsUpdateTest.class.getName());
private static final String ROLE_ARN =
"arn:aws:iam::000000000000:role/cfn-step-functions-update-role";
private static CloudFormationClient cloudFormation;
private static SfnClient stepFunctions;
private static String stackName;
@BeforeAll
static void setup() {
cloudFormation = TestFixtures.cloudFormationClient();
stepFunctions = TestFixtures.sfnClient();
stackName = TestFixtures.uniqueName("cfn-sfn-update");
}
@AfterAll
static void cleanup() {
if (cloudFormation != null) {
if (stackName != null) {
try {
cloudFormation.deleteStack(request -> request.stackName(stackName));
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to clean up CloudFormation update test", e);
}
}
cloudFormation.close();
}
if (stepFunctions != null) {
stepFunctions.close();
}
}
@Test
void sdkUpdatesStateMachineInPlace() throws InterruptedException {
String stateMachineName = TestFixtures.uniqueName("cfn-managed-sfn");
String initialDefinition =
"{\"StartAt\":\"Initial\",\"States\":{\"Initial\":"
+ "{\"Type\":\"Pass\",\"End\":true}}}";
String updatedDefinition =
"{\"StartAt\":\"Updated\",\"States\":{\"Updated\":"
+ "{\"Type\":\"Pass\",\"End\":true}}}";
cloudFormation.createStack(request -> request
.stackName(stackName)
.templateBody(template(
stateMachineName, initialDefinition, "initial")));
assertThat(waitForTerminalStatus(stackName, 30))
.isEqualTo("CREATE_COMPLETE");
StackResource initialResource = stateMachineResource(stackName);
String stateMachineArn = initialResource.physicalResourceId();
DescribeStateMachineResponse initial =
stepFunctions.describeStateMachine(
request -> request.stateMachineArn(stateMachineArn));
cloudFormation.updateStack(request -> request
.stackName(stackName)
.templateBody(template(
stateMachineName, updatedDefinition, "updated")));
assertThat(waitForTerminalStatus(stackName, 30))
.isEqualTo("UPDATE_COMPLETE");
StackResource updatedResource = stateMachineResource(stackName);
assertThat(updatedResource.physicalResourceId())
.isEqualTo(stateMachineArn);
assertThat(updatedResource.resourceStatusAsString())
.isEqualTo("UPDATE_COMPLETE");
DescribeStateMachineResponse updated =
stepFunctions.describeStateMachine(
request -> request.stateMachineArn(stateMachineArn));
assertThat(updated.definition()).isEqualTo(updatedDefinition);
assertThat(updated.revisionId()).isNotEqualTo(initial.revisionId());
}
private static StackResource stateMachineResource(String name) {
List<StackResource> resources = cloudFormation.describeStackResources(
DescribeStackResourcesRequest.builder()
.stackName(name)
.build()).stackResources();
return resources.stream()
.filter(resource -> "AWS::StepFunctions::StateMachine"
.equals(resource.resourceType()))
.findFirst()
.orElseThrow();
}
private static String waitForTerminalStatus(
String name, int maxSeconds) throws InterruptedException {
long deadline = System.currentTimeMillis() + maxSeconds * 1000L;
while (System.currentTimeMillis() < deadline) {
List<Stack> stacks = cloudFormation.describeStacks(
DescribeStacksRequest.builder()
.stackName(name)
.build()).stacks();
if (!stacks.isEmpty()) {
String status = stacks.get(0).stackStatusAsString();
if (!status.endsWith("_IN_PROGRESS")) {
return status;
}
}
Thread.sleep(250);
}
throw new AssertionError(
"Stack " + name
+ " did not reach a terminal state within "
+ maxSeconds + " seconds");
}
private static String template(
String stateMachineName,
String definition,
String marker) {
String escapedDefinition = definition.replace("\\", "\\\\")
.replace("\"", "\\\"");
return """
{
"Resources": {
"StateMachine": {
"Type": "AWS::StepFunctions::StateMachine",
"Properties": {
"StateMachineName": "%s",
"RoleArn": "%s",
"DefinitionString": "%s"
}
}
},
"Outputs": {
"Marker": {"Value": "%s"}
}
}
""".formatted(
stateMachineName,
ROLE_ARN,
escapedDefinition,
marker);
}
}
@@ -0,0 +1,92 @@
package com.floci.test;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.sfn.SfnClient;
import software.amazon.awssdk.services.sfn.model.DescribeStateMachineResponse;
import software.amazon.awssdk.services.sfn.model.IncludedData;
import software.amazon.awssdk.services.sfn.model.LogLevel;
import software.amazon.awssdk.services.sfn.model.UpdateStateMachineResponse;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("SFN UpdateStateMachine")
class StepFunctionsUpdateStateMachineTest {
private static final Logger LOGGER = Logger.getLogger(StepFunctionsUpdateStateMachineTest.class.getName());
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/service-role/test-role";
private static final String INITIAL_DEFINITION = """
{"StartAt":"Initial","States":{"Initial":{"Type":"Pass","End":true}}}
""".strip();
private static final String UPDATED_DEFINITION = """
{"StartAt":"Updated","States":{"Updated":{"Type":"Pass","End":true}}}
""".strip();
private static SfnClient sfn;
private static String stateMachineArn;
@BeforeAll
static void setup() {
sfn = TestFixtures.sfnClient();
stateMachineArn = sfn.createStateMachine(b -> b
.name(TestFixtures.uniqueName("update-sm"))
.definition(INITIAL_DEFINITION)
.roleArn(ROLE_ARN))
.stateMachineArn();
}
@AfterAll
static void cleanup() {
if (sfn != null) {
if (stateMachineArn != null) {
try {
sfn.deleteStateMachine(b -> b.stateMachineArn(stateMachineArn));
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to clean up Step Functions update compatibility test", e);
}
}
sfn.close();
}
}
@Test
void sdkUpdatesAndDescribesStateMachine() {
UpdateStateMachineResponse update = sfn.updateStateMachine(b -> b
.stateMachineArn(stateMachineArn)
.definition(UPDATED_DEFINITION)
.roleArn(ROLE_ARN)
.loggingConfiguration(logging -> logging
.level(LogLevel.OFF)
.includeExecutionData(false))
.tracingConfiguration(tracing -> tracing.enabled(true))
.publish(true)
.versionDescription("compatibility snapshot"));
assertThat(update.updateDate()).isNotNull();
assertThat(update.revisionId()).isNotBlank();
DescribeStateMachineResponse describe = sfn.describeStateMachine(b -> b
.stateMachineArn(stateMachineArn));
assertThat(describe.definition()).isEqualTo(UPDATED_DEFINITION);
assertThat(describe.roleArn()).isEqualTo(ROLE_ARN);
assertThat(describe.revisionId()).isEqualTo(update.revisionId());
assertThat(describe.loggingConfiguration().level()).isEqualTo(LogLevel.OFF);
assertThat(describe.tracingConfiguration().enabled()).isTrue();
DescribeStateMachineResponse version = sfn.describeStateMachine(b -> b
.stateMachineArn(update.stateMachineVersionArn()));
assertThat(version.stateMachineArn()).isEqualTo(update.stateMachineVersionArn());
assertThat(version.definition()).isEqualTo(UPDATED_DEFINITION);
assertThat(version.description()).isEqualTo("compatibility snapshot");
DescribeStateMachineResponse metadata = sfn.describeStateMachine(b -> b
.stateMachineArn(update.stateMachineVersionArn())
.includedData(IncludedData.METADATA_ONLY));
assertThat(metadata.definition()).isEqualTo("{}");
}
}
+6 -1
View File
@@ -1,6 +1,6 @@
# Step Functions
**Protocol:** JSON 1.1 (`X-Amz-Target: AmazonStatesService.*`)
**Protocol:** AWS JSON 1.0 (`X-Amz-Target: AWSStepFunctions.*`)
**Endpoint:** `POST http://localhost:4566/`
## Supported Actions
@@ -9,6 +9,7 @@
| Action | Description |
| --- | --- |
| `CreateStateMachine` | Create a state machine (Standard or Express) |
| `UpdateStateMachine` | Update definition, role, logging, tracing, or encryption settings and optionally publish a version |
| `DescribeStateMachine` | Get state machine definition and metadata |
| `ListStateMachines` | List all state machines |
| `DeleteStateMachine` | Delete a state machine |
@@ -35,6 +36,10 @@
| `UntagResource` | - |
<!-- floci:actions:end -->
`UpdateStateMachine` returns the new revision ID and update timestamp. CloudFormation updates
definition, role, logging, tracing, encryption, and tags without replacing the state machine;
changes to `StateMachineName` or `StateMachineType` use replacement semantics.
## Map concurrency
Map states honor `MaxConcurrency` and, for JSONPath state machines, `MaxConcurrencyPath`.
@@ -130,6 +130,8 @@ public class CloudFormationResourceProvisioner {
private static final String INLINE_CLEANUP_ROLE_TARGETS_ATTR = "__FlociInlineCleanupRoleTargets";
private static final String INLINE_CLEANUP_USER_TARGETS_ATTR = "__FlociInlineCleanupUserTargets";
private static final String INLINE_CLEANUP_GROUP_TARGETS_ATTR = "__FlociInlineCleanupGroupTargets";
private static final String SFN_NAME_MODE_ATTR = "FlociStepFunctionsNameMode";
static final String SFN_UPDATE_SNAPSHOT_ATTR = "__FlociStepFunctionsUpdateSnapshot";
private static final String EVENT_BUS_CREATED_TIME_ATTR = "FlociEventBusCreatedTime";
private static final String EVENT_BUS_MANAGED_TAG_KEYS_ATTR = "FlociEventBusManagedTagKeys";
private static final String EVENT_BUS_MANAGED_POLICY_ATTR = "FlociEventBusManagedPolicy";
@@ -139,6 +141,8 @@ public class CloudFormationResourceProvisioner {
Pattern.compile("[\\p{L}\\p{N}\\p{Z}_.:/=+\\-@]*");
private static final String NAME_MODE_EXPLICIT = "explicit";
private static final String NAME_MODE_GENERATED = "generated";
private static final int GENERATED_NAME_SUFFIX_LENGTH = 12;
private static final int STEP_FUNCTIONS_NAME_MAX_LENGTH = 80;
private static final String LOG_GROUP_NAME_MODE_ATTR = "FlociLogGroupNameMode";
private static final String SECRET_TARGET_MANAGED_KEYS_ATTR = "__FlociSecretTargetManagedKeys";
private static final String SECRET_TARGET_OWNER_ATTR = "__FlociSecretTargetOwner";
@@ -345,7 +349,13 @@ public class CloudFormationResourceProvisioner {
case "AWS::ApiGatewayV2::Deployment" -> provisionApiGatewayV2Deployment(resource, properties, engine, region);
case "AWS::Pipes::Pipe" -> provisionPipe(resource, properties, engine, region, stackName);
case "AWS::StepFunctions::StateMachine" ->
provisionStepFunctionsStateMachine(resource, properties, engine, region, stackName);
provisionStepFunctionsStateMachine(
resource,
properties,
engine,
region,
accountId,
stackName);
case "AWS::Lambda::EventSourceMapping" ->
provisionLambdaEventSourceMapping(resource, properties, engine, region);
case "AWS::Cognito::UserPool" ->
@@ -842,9 +852,18 @@ public class CloudFormationResourceProvisioner {
if (priorPhysicalId != null && priorPhysicalId.equals(name) && logsService.logGroupExists(name, region)) {
reconcileLogGroup(name, retentionInDays, tags, region);
} else {
logsService.createLogGroup(name, retentionInDays, tags, region);
if (priorPhysicalId != null && !priorPhysicalId.equals(name)
&& logsService.logGroupExists(priorPhysicalId, region)) {
boolean preservedPriorGroup = priorPhysicalId != null
&& !priorPhysicalId.equals(name)
&& logsService.logGroupExists(priorPhysicalId, region);
try {
logsService.createLogGroup(name, retentionInDays, tags, region);
} catch (RuntimeException failure) {
if (preservedPriorGroup) {
r.getAttributes().put(UPDATE_ROLLBACK_RESTORED_ATTR, "true");
}
throw failure;
}
if (preservedPriorGroup) {
logsService.deleteLogGroup(priorPhysicalId, region);
}
}
@@ -3606,51 +3625,603 @@ public class CloudFormationResourceProvisioner {
private void provisionStepFunctionsStateMachine(StackResource r, JsonNode props,
CloudFormationTemplateEngine engine,
String region, String stackName) {
String name = resolveOptional(props, "StateMachineName", engine);
if (name == null || name.isBlank()) {
name = generatePhysicalName(stackName, r.getLogicalId(), 80, false);
String region, String accountId,
String stackName) {
String explicitName = resolveOptional(props, "StateMachineName", engine);
boolean hasExplicitName = explicitName != null && !explicitName.isBlank();
String roleArn = resolveOptional(props, "RoleArn", engine);
if (roleArn == null || roleArn.isBlank()) {
throw new AwsException("ValidationError", "RoleArn is required for a state machine", 400);
}
String type = resolveOrDefault(props, "StateMachineType", engine, "STANDARD");
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
String definition = resolveStateMachineDefinition(props, engine);
JsonNode loggingConfiguration = resolveStateMachineLoggingConfiguration(props, engine);
JsonNode tracingConfiguration = resolveStateMachineTracingConfiguration(props, engine);
JsonNode encryptionConfiguration = resolveStateMachineEncryptionConfiguration(props, engine);
StateMachine existing = findStateMachine(r.getPhysicalId());
String desiredNameMode = hasExplicitName ? NAME_MODE_EXPLICIT : NAME_MODE_GENERATED;
String previousNameMode = r.getAttributes().get(SFN_NAME_MODE_ATTR);
if (existing != null && previousNameMode == null) {
previousNameMode = inferStepFunctionsNameMode(existing, stackName, r.getLogicalId());
}
boolean nameModeReplacement = existing != null
&& !Objects.equals(previousNameMode, desiredNameMode);
boolean typeReplacement = existing != null && !Objects.equals(existing.getType(), type);
String name;
if (hasExplicitName) {
name = explicitName;
} else if (existing != null && !nameModeReplacement && !typeReplacement) {
name = existing.getName();
} else {
name = generatePhysicalName(
stackName, r.getLogicalId(), STEP_FUNCTIONS_NAME_MAX_LENGTH, false);
}
String desiredArn = AwsArnUtils.Arn.of(
"states", region, accountId, "stateMachine:" + name).toString();
boolean nameReplacement = existing != null && !Objects.equals(existing.getName(), name);
boolean replacement = nameReplacement || nameModeReplacement || typeReplacement;
if (replacement && Objects.equals(existing.getName(), name)) {
throw new AwsException("ValidationError",
"Cannot replace state machine " + existing.getName()
+ " without a new StateMachineName", 400);
}
String roleArn = resolveOptional(props, "RoleArn", engine);
String type = resolveOptional(props, "StateMachineType", engine);
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
boolean configurationChanged = existing != null
&& !stateMachineConfigurationMatches(
existing,
definition,
roleArn,
loggingConfiguration,
tracingConfiguration,
encryptionConfiguration);
boolean tagsChanged = existing != null && !Objects.equals(existing.getTags(), tags);
String definition = resolveStateMachineDefinition(props, engine);
StateMachine sm = stepFunctionsService.createStateMachine(name, definition, roleArn, type, region, tags);
StateMachine sm;
if (existing == null) {
sm = stepFunctionsService.createStateMachine(
name, definition, roleArn, type, region, tags,
loggingConfiguration, tracingConfiguration, encryptionConfiguration);
} else if (!replacement && !configurationChanged && !tagsChanged) {
sm = existing;
} else {
String replacementRevisionId = replacement
? UUID.randomUUID().toString()
: null;
beginStepFunctionsUpdate(
r,
existing,
replacement,
replacement ? desiredArn : null,
replacementRevisionId);
if (replacement) {
sm = stepFunctionsService.createStateMachineWithRevisionId(
name, definition, roleArn, type, region, tags,
loggingConfiguration,
tracingConfiguration,
encryptionConfiguration,
replacementRevisionId);
markStepFunctionsReplacementCreated(r, sm);
} else {
sm = existing;
if (configurationChanged) {
sm = stepFunctionsService.updateStateMachine(
existing.getStateMachineArn(),
new StepFunctionsService.UpdateStateMachineRequest(
definition,
roleArn,
loggingConfiguration, true,
tracingConfiguration, true,
encryptionConfiguration, true,
false,
null)).stateMachine();
}
if (tagsChanged) {
stepFunctionsService.replaceStateMachineTags(sm.getStateMachineArn(), tags);
sm = stepFunctionsService.describeStateMachine(sm.getStateMachineArn());
}
}
}
r.setPhysicalId(sm.getStateMachineArn());
r.getAttributes().put("Arn", sm.getStateMachineArn());
r.getAttributes().put("Name", sm.getName());
r.getAttributes().put("StateMachineRevisionId", sm.getRevisionId());
r.getAttributes().put(SFN_NAME_MODE_ATTR, desiredNameMode);
}
private StateMachine findStateMachine(String stateMachineArn) {
if (stateMachineArn == null || stateMachineArn.isBlank()) {
return null;
}
try {
return stepFunctionsService.describeStateMachine(stateMachineArn);
} catch (AwsException e) {
if ("StateMachineDoesNotExist".equals(e.getErrorCode())) {
return null;
}
throw e;
}
}
private String inferStepFunctionsNameMode(
StateMachine existing, String stackName, String logicalId) {
String base = stackName + "-" + logicalId;
int keep = STEP_FUNCTIONS_NAME_MAX_LENGTH - GENERATED_NAME_SUFFIX_LENGTH - 1;
String prefix = base.substring(0, Math.min(base.length(), keep));
while (prefix.endsWith("-")) {
prefix = prefix.substring(0, prefix.length() - 1);
}
String generatedPrefix = prefix.isEmpty() ? "" : prefix + "-";
String name = existing.getName();
if (name == null || !name.startsWith(generatedPrefix)) {
return NAME_MODE_EXPLICIT;
}
String suffix = name.substring(generatedPrefix.length());
boolean generatedSuffix = suffix.length() == GENERATED_NAME_SUFFIX_LENGTH
&& suffix.chars().allMatch(c -> c >= '0' && c <= '9' || c >= 'a' && c <= 'f');
return generatedSuffix
? NAME_MODE_GENERATED
: NAME_MODE_EXPLICIT;
}
private boolean stateMachineConfigurationMatches(
StateMachine existing,
String definition,
String roleArn,
JsonNode loggingConfiguration,
JsonNode tracingConfiguration,
JsonNode encryptionConfiguration) {
return Objects.equals(existing.getDefinition(), definition)
&& Objects.equals(existing.getRoleArn(), roleArn)
&& Objects.equals(
effectiveLoggingConfiguration(existing.getLoggingConfiguration()),
loggingConfiguration)
&& Objects.equals(
effectiveTracingConfiguration(existing.getTracingConfiguration()),
tracingConfiguration)
&& Objects.equals(
effectiveEncryptionConfiguration(existing.getEncryptionConfiguration()),
encryptionConfiguration);
}
private JsonNode effectiveLoggingConfiguration(JsonNode configuration) {
return configuration != null ? configuration : defaultStateMachineLoggingConfiguration();
}
private JsonNode effectiveTracingConfiguration(JsonNode configuration) {
return configuration != null ? configuration : defaultStateMachineTracingConfiguration();
}
private JsonNode effectiveEncryptionConfiguration(JsonNode configuration) {
return configuration != null ? configuration : defaultStateMachineEncryptionConfiguration();
}
private JsonNode resolveStateMachineLoggingConfiguration(
JsonNode props, CloudFormationTemplateEngine engine) {
if (props == null || !props.has("LoggingConfiguration")
|| props.get("LoggingConfiguration").isNull()) {
return defaultStateMachineLoggingConfiguration();
}
JsonNode source = engine.resolveNode(props.get("LoggingConfiguration"));
if (!source.isObject()) {
throw new AwsException("ValidationError",
"LoggingConfiguration must be an object", 400);
}
ObjectNode result = objectMapper.createObjectNode();
JsonNode level = source.get("Level");
if (level != null && !level.isTextual()) {
throw new AwsException("ValidationError",
"LoggingConfiguration.Level must be a string", 400);
}
result.put("level", level != null ? level.asText() : "OFF");
JsonNode includeExecutionData = source.get("IncludeExecutionData");
if (includeExecutionData != null && !includeExecutionData.isBoolean()) {
throw new AwsException("ValidationError",
"LoggingConfiguration.IncludeExecutionData must be a boolean", 400);
}
result.put("includeExecutionData",
includeExecutionData != null && includeExecutionData.asBoolean());
ArrayNode destinations = result.putArray("destinations");
JsonNode sourceDestinations = source.get("Destinations");
if (sourceDestinations != null) {
if (!sourceDestinations.isArray()) {
throw new AwsException("ValidationError",
"LoggingConfiguration.Destinations must be an array", 400);
}
for (JsonNode destination : sourceDestinations) {
JsonNode logGroupArn = destination.path("CloudWatchLogsLogGroup").get("LogGroupArn");
if (logGroupArn == null || !logGroupArn.isTextual()) {
throw new AwsException("ValidationError",
"LoggingConfiguration destination LogGroupArn must be a string", 400);
}
destinations.addObject()
.putObject("cloudWatchLogsLogGroup")
.put("logGroupArn", logGroupArn.asText());
}
}
return result;
}
private ObjectNode defaultStateMachineLoggingConfiguration() {
ObjectNode result = objectMapper.createObjectNode();
result.put("level", "OFF");
result.put("includeExecutionData", false);
result.putArray("destinations");
return result;
}
private JsonNode resolveStateMachineTracingConfiguration(
JsonNode props, CloudFormationTemplateEngine engine) {
if (props == null || !props.has("TracingConfiguration")
|| props.get("TracingConfiguration").isNull()) {
return defaultStateMachineTracingConfiguration();
}
JsonNode source = engine.resolveNode(props.get("TracingConfiguration"));
if (!source.isObject()) {
throw new AwsException("ValidationError",
"TracingConfiguration must be an object", 400);
}
JsonNode enabled = source.get("Enabled");
if (enabled != null && !enabled.isBoolean()) {
throw new AwsException("ValidationError",
"TracingConfiguration.Enabled must be a boolean", 400);
}
return objectMapper.createObjectNode()
.put("enabled", enabled != null && enabled.asBoolean());
}
private ObjectNode defaultStateMachineTracingConfiguration() {
return objectMapper.createObjectNode().put("enabled", false);
}
private JsonNode resolveStateMachineEncryptionConfiguration(
JsonNode props, CloudFormationTemplateEngine engine) {
if (props == null || !props.has("EncryptionConfiguration")
|| props.get("EncryptionConfiguration").isNull()) {
return defaultStateMachineEncryptionConfiguration();
}
JsonNode source = engine.resolveNode(props.get("EncryptionConfiguration"));
if (!source.isObject()) {
throw new AwsException("ValidationError",
"EncryptionConfiguration must be an object", 400);
}
JsonNode type = source.get("Type");
if (type == null || !type.isTextual() || type.asText().isBlank()) {
throw new AwsException("ValidationError",
"EncryptionConfiguration.Type is required and must be a string", 400);
}
ObjectNode result = objectMapper.createObjectNode().put("type", type.asText());
JsonNode keyId = source.get("KmsKeyId");
if (keyId != null) {
if (!keyId.isTextual()) {
throw new AwsException("ValidationError",
"EncryptionConfiguration.KmsKeyId must be a string", 400);
}
result.put("kmsKeyId", keyId.asText());
}
JsonNode reusePeriod = source.get("KmsDataKeyReusePeriodSeconds");
if (reusePeriod != null) {
if (!reusePeriod.isIntegralNumber()) {
throw new AwsException("ValidationError",
"EncryptionConfiguration.KmsDataKeyReusePeriodSeconds must be an integer", 400);
}
result.put("kmsDataKeyReusePeriodSeconds", reusePeriod.intValue());
}
return result;
}
private ObjectNode defaultStateMachineEncryptionConfiguration() {
return objectMapper.createObjectNode().put("type", "AWS_OWNED_KEY");
}
private void beginStepFunctionsUpdate(
StackResource resource,
StateMachine existing,
boolean replacement,
String replacementArn,
String replacementRevisionId) {
if (resource.getAttributes().containsKey(SFN_UPDATE_SNAPSHOT_ATTR)) {
return;
}
ObjectNode snapshot = objectMapper.createObjectNode();
snapshot.put("physicalId", resource.getPhysicalId());
snapshot.put("replacement", replacement);
if (replacementArn != null) {
snapshot.put("replacementArn", replacementArn);
}
if (replacementRevisionId != null) {
snapshot.put("replacementRevisionId", replacementRevisionId);
}
snapshot.put("replacementCreated", false);
snapshot.put("cleanupAttempts", 0);
snapshot.set("stateMachine", objectMapper.valueToTree(existing));
ObjectNode attributes = snapshot.putObject("attributes");
resource.getAttributes().forEach(attributes::put);
resource.getAttributes().put(SFN_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
}
private void markStepFunctionsReplacementCreated(
StackResource resource, StateMachine replacement) {
String rawSnapshot = resource.getAttributes().get(SFN_UPDATE_SNAPSHOT_ATTR);
if (rawSnapshot == null) {
throw new IllegalStateException(
"Step Functions replacement metadata is missing for "
+ resource.getLogicalId());
}
try {
ObjectNode snapshot = (ObjectNode) objectMapper.readTree(rawSnapshot);
snapshot.put("replacementCreated", true);
snapshot.put("replacementArn", replacement.getStateMachineArn());
snapshot.put("replacementRevisionId", replacement.getRevisionId());
resource.getAttributes().put(
SFN_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
} catch (Exception e) {
throw new IllegalStateException(
"Could not record Step Functions replacement ownership for "
+ resource.getLogicalId(), e);
}
}
UpdateCleanupResult completeUpdate(StackResource resource) {
String rawSnapshot = resource.getAttributes().get(SFN_UPDATE_SNAPSHOT_ATTR);
if (rawSnapshot == null) {
return new UpdateCleanupResult(false, true, null, 0, null);
}
try {
JsonNode snapshot = objectMapper.readTree(rawSnapshot);
String previousArn = snapshot.path("physicalId").asText(null);
if (!snapshot.path("replacement").asBoolean(false)
|| previousArn == null
|| Objects.equals(previousArn, resource.getPhysicalId())) {
return new UpdateCleanupResult(true, true, previousArn, 0, null);
}
if ("Retain".equals(resource.getUpdateReplacePolicy())) {
return new UpdateCleanupResult(true, true, previousArn, 0, null);
}
int attempts = snapshot.path("cleanupAttempts").asInt(0);
String failureReason = snapshot.path("cleanupFailureReason").asText(null);
if (attempts >= 3) {
return new UpdateCleanupResult(
true, false, previousArn, attempts, failureReason);
}
try {
String previousRevisionId = snapshot.path("stateMachine")
.path("revisionId")
.asText(null);
StateMachine cleanupTarget = findStateMachine(previousArn);
if (cleanupTarget != null
&& !stepFunctionsService.deleteStateMachineIfRevisionMatches(
previousArn, previousRevisionId)) {
throw new IllegalStateException(
"The old state machine no longer matches the replacement snapshot");
}
return new UpdateCleanupResult(
true, true, previousArn, attempts, null);
} catch (Exception e) {
attempts++;
((ObjectNode) snapshot).put("cleanupAttempts", attempts);
((ObjectNode) snapshot).put("cleanupFailureReason", e.getMessage());
resource.getAttributes().put(
SFN_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
return new UpdateCleanupResult(
true, false, previousArn, attempts, e.getMessage());
}
} catch (Exception e) {
throw new IllegalStateException(
"Could not finalize Step Functions state machine "
+ resource.getLogicalId(), e);
}
}
String updateCleanupPhysicalId(StackResource resource) {
if ("Retain".equals(resource.getUpdateReplacePolicy())) {
return null;
}
String rawSnapshot = resource.getAttributes().get(SFN_UPDATE_SNAPSHOT_ATTR);
if (rawSnapshot == null) {
return null;
}
try {
JsonNode snapshot = objectMapper.readTree(rawSnapshot);
if (!snapshot.path("replacement").asBoolean(false)) {
return null;
}
return snapshot.path("physicalId").asText(null);
} catch (Exception e) {
throw new IllegalStateException(
"Could not read Step Functions cleanup metadata for "
+ resource.getLogicalId(), e);
}
}
boolean hasReplacementUpdate(StackResource resource) {
String rawSnapshot = resource.getAttributes().get(SFN_UPDATE_SNAPSHOT_ATTR);
if (rawSnapshot == null) {
return false;
}
try {
return objectMapper.readTree(rawSnapshot).path("replacement").asBoolean(false);
} catch (Exception e) {
throw new IllegalStateException(
"Could not read Step Functions update metadata for "
+ resource.getLogicalId(), e);
}
}
void clearUpdate(StackResource resource) {
resource.getAttributes().remove(SFN_UPDATE_SNAPSHOT_ATTR);
}
boolean rollbackUpdate(StackResource resource) {
String rawSnapshot = resource.getAttributes().get(SFN_UPDATE_SNAPSHOT_ATTR);
if (rawSnapshot == null) {
return false;
}
try {
JsonNode snapshot = objectMapper.readTree(rawSnapshot);
String previousArn = snapshot.path("physicalId").asText(null);
String replacementArn = snapshot.path("replacementArn").asText(
resource.getPhysicalId());
String replacementRevisionId = snapshot.path("replacementRevisionId")
.asText(null);
if (snapshot.path("replacement").asBoolean(false)
&& replacementArn != null
&& !Objects.equals(previousArn, replacementArn)) {
stepFunctionsService.deleteStateMachineIfRevisionMatches(
replacementArn, replacementRevisionId);
}
StateMachine previous = objectMapper.treeToValue(
snapshot.path("stateMachine"), StateMachine.class);
StateMachine current = findStateMachine(previousArn);
String restoredRevisionId = null;
if (current == null) {
throw new IllegalStateException(
"The original state machine no longer exists: " + previousArn);
}
if (!snapshot.path("replacement").asBoolean(false)) {
if (!stateMachineConfigurationMatches(
current,
previous.getDefinition(),
previous.getRoleArn(),
previous.getLoggingConfiguration(),
previous.getTracingConfiguration(),
previous.getEncryptionConfiguration())) {
stepFunctionsService.updateStateMachine(
previousArn,
new StepFunctionsService.UpdateStateMachineRequest(
previous.getDefinition(),
previous.getRoleArn(),
previous.getLoggingConfiguration(), true,
previous.getTracingConfiguration(), true,
previous.getEncryptionConfiguration(), true,
false,
null));
}
StateMachine restored = stepFunctionsService.describeStateMachine(previousArn);
restoredRevisionId = restored.getRevisionId();
if (!Objects.equals(restored.getTags(), previous.getTags())) {
stepFunctionsService.replaceStateMachineTags(
previousArn, previous.getTags());
}
}
resource.setPhysicalId(previousArn);
resource.getAttributes().clear();
JsonNode previousAttributes = snapshot.path("attributes");
previousAttributes.fields().forEachRemaining(entry ->
resource.getAttributes().put(entry.getKey(), entry.getValue().asText()));
if (restoredRevisionId != null) {
resource.getAttributes().put(
"StateMachineRevisionId", restoredRevisionId);
}
resource.setStatus("UPDATE_COMPLETE");
resource.setStatusReason(null);
return true;
} catch (Exception e) {
throw new IllegalStateException(
"Could not roll back Step Functions state machine "
+ resource.getLogicalId(), e);
}
}
record UpdateCleanupResult(
boolean applicable,
boolean complete,
String previousPhysicalId,
int attempts,
String failureReason) {
}
private String resolveStateMachineDefinition(JsonNode props, CloudFormationTemplateEngine engine) {
if (props == null) {
return null;
throw new AwsException(
"ValidationError",
"A state machine definition is required",
400);
}
String definition = resolveOptional(props, "DefinitionString", engine);
if (definition == null && props.has("Definition") && !props.get("Definition").isNull()) {
definition = engine.resolveNode(props.get("Definition")).toString();
boolean hasDefinitionString =
props.has("DefinitionString")
&& !props.get("DefinitionString").isNull();
boolean hasDefinition =
props.has("Definition")
&& !props.get("Definition").isNull();
boolean hasS3Location =
props.has("DefinitionS3Location")
&& !props.get("DefinitionS3Location").isNull();
int sourceCount = (hasDefinitionString ? 1 : 0)
+ (hasDefinition ? 1 : 0)
+ (hasS3Location ? 1 : 0);
if (sourceCount != 1) {
throw new AwsException(
"ValidationError",
"Specify exactly one of Definition, DefinitionString, or DefinitionS3Location",
400);
}
if (definition == null) {
return null;
boolean definitionFromS3 = false;
String definition;
if (hasDefinitionString) {
definition = resolveOptional(props, "DefinitionString", engine);
} else if (hasDefinition) {
definition = engine.resolveNode(props.get("Definition")).toString();
} else {
JsonNode location = engine.resolveNode(props.get("DefinitionS3Location"));
String bucket = location.path("Bucket").asText(null);
String key = location.path("Key").asText(null);
String version = location.path("Version").asText(null);
if (bucket == null || bucket.isBlank() || key == null || key.isBlank()) {
throw new AwsException(
"ValidationError",
"DefinitionS3Location requires Bucket and Key",
400);
}
S3Object object = s3Service.getObject(bucket, key, version);
definition = new String(object.getData(), StandardCharsets.UTF_8);
definitionFromS3 = true;
}
JsonNode subsNode = props.get("DefinitionSubstitutions");
if (subsNode == null || subsNode.isNull()) {
return definition;
if (subsNode != null && !subsNode.isNull()) {
JsonNode resolvedSubs = engine.resolveNode(subsNode);
Iterator<Map.Entry<String, JsonNode>> entries = resolvedSubs.fields();
while (entries.hasNext()) {
Map.Entry<String, JsonNode> entry = entries.next();
String placeholder = "${" + entry.getKey() + "}";
String value = entry.getValue().isTextual()
? entry.getValue().asText()
: entry.getValue().toString();
definition = definition.replace(placeholder, value);
}
}
JsonNode resolvedSubs = engine.resolveNode(subsNode);
Iterator<Map.Entry<String, JsonNode>> entries = resolvedSubs.fields();
while (entries.hasNext()) {
Map.Entry<String, JsonNode> entry = entries.next();
String placeholder = "${" + entry.getKey() + "}";
String value = entry.getValue().isTextual() ? entry.getValue().asText() : entry.getValue().toString();
definition = definition.replace(placeholder, value);
if (definitionFromS3) {
try {
definition = new CloudFormationYamlParser(objectMapper)
.parse(definition)
.toString();
} catch (Exception e) {
throw new AwsException(
"ValidationError",
"DefinitionS3Location contains invalid JSON or YAML: "
+ e.getMessage(),
400);
}
}
return definition;
}
@@ -5669,7 +6240,8 @@ public class CloudFormationResourceProvisioner {
* Mirrors the naming pattern AWS CloudFormation uses when no explicit name is provided.
*/
private String generatePhysicalName(String stackName, String logicalId, int maxLength, boolean lowercase) {
String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
String suffix = UUID.randomUUID().toString().replace("-", "")
.substring(0, GENERATED_NAME_SUFFIX_LENGTH);
String base = stackName + "-" + logicalId;
if (lowercase) {
base = base.toLowerCase();
@@ -526,7 +526,9 @@ public class CloudFormationService {
private void executeTemplate(Stack stack, String templateBody, Map<String, String> params,
boolean isCreate, String region, String accountId) {
String previousTemplateBody = stack.getTemplateBody();
StackUpdateSnapshot previousState = snapshotForUpdate(stack);
boolean updateCommitted = false;
Set<String> attemptedResourceIds = new LinkedHashSet<>();
try {
JsonNode template = parseTemplate(templateBody);
stack.setOriginalTemplateBody(templateBody);
@@ -588,7 +590,17 @@ public class CloudFormationService {
stack.getResources().put(logicalId, resource);
}
addEvent(stack, logicalId, null, type, "CREATE_IN_PROGRESS", null);
String inProgressStatus = isCreate
? "CREATE_IN_PROGRESS"
: "UPDATE_IN_PROGRESS";
addEvent(
stack,
logicalId,
resource.getPhysicalId(),
type,
inProgressStatus,
null);
attemptedResourceIds.add(logicalId);
if ("AWS::CloudFormation::Stack".equals(type)) {
resource = executeNestedStack(stack, logicalId,
props.isMissingNode() ? null : props,
@@ -598,6 +610,15 @@ public class CloudFormationService {
engine, region, accountId, stack.getStackName(),
resource.getPhysicalId(), resource.getAttributes());
}
resource.setUpdateReplacePolicy(
resDef.path("UpdateReplacePolicy").asText(null));
if (!isCreate) {
if ("CREATE_COMPLETE".equals(resource.getStatus())) {
resource.setStatus("UPDATE_COMPLETE");
} else if ("CREATE_FAILED".equals(resource.getStatus())) {
resource.setStatus("UPDATE_FAILED");
}
}
// Both branches return a fresh StackResource, so the policy is carried over here
// rather than on the instance the loop started with.
resource.setDeletionPolicy(deletionPolicy);
@@ -616,6 +637,12 @@ public class CloudFormationService {
// Provisioners work on a copy of the stored resource metadata. Keep the
// last known-good identity and status when an update attempt fails so a
// later retry or stack deletion still manages the original resource.
// The rollback walker must also know this resource is already restored;
// otherwise an earlier UPDATE_COMPLETE status looks like an unhandled
// mutation and incorrectly turns a safe rollback into ROLLBACK_FAILED.
previousResource.getAttributes().put(
CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR,
"true");
stack.getResources().put(logicalId, previousResource);
}
break;
@@ -626,10 +653,9 @@ public class CloudFormationService {
// A resource failed to provision: stop, and (on create) roll back what we built so a
// corrected re-deploy starts from a clean slate (acceptance criterion #9).
if (failedResource != null) {
if (!isCreate) {
stack.setTemplateBody(previousTemplateBody);
}
rollbackFailedExecution(stack, region, isCreate, failedResource);
rollbackFailedExecution(
stack, region, isCreate, failedResource, previousState,
attemptedResourceIds);
return;
}
@@ -677,6 +703,24 @@ public class CloudFormationService {
exportName, value, stack.getStackName());
});
if (!isCreate) {
updateCommitted = true;
if (hasReplacementUpdates(stack)) {
stack.setStatus("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS");
stack.setLastUpdatedTime(now());
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack",
"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS", null);
// The committed template and new physical IDs must be durable before old
// resources are deleted during replacement cleanup.
persistStack(stack);
}
List<UpdateCleanupFailure> cleanupFailures =
finishCommittedResourceCleanup(stack);
finishCommittedStackUpdate(stack, cleanupFailures);
return;
}
String completeStatus = isCreate ? "CREATE_COMPLETE" : "UPDATE_COMPLETE";
stack.setStatus(completeStatus);
stack.setLastUpdatedTime(now());
@@ -686,31 +730,47 @@ public class CloudFormationService {
LOG.infov("Stack {0} execution complete: {1}", stack.getStackName(), completeStatus);
} catch (Exception e) {
LOG.errorv("Stack {0} execution failed: {1}", stack.getStackName(), e.getMessage());
if (!isCreate) {
stack.setTemplateBody(previousTemplateBody);
if (!isCreate && updateCommitted) {
LOG.errorv(
"Stack {0} update cleanup could not finish: {1}",
stack.getStackName(), e.getMessage());
stack.setStatus("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS");
stack.setStatusReason(e.getMessage());
stack.setLastUpdatedTime(now());
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack",
"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS", e.getMessage());
persistStack(stack);
return;
}
LOG.errorv("Stack {0} execution failed: {1}", stack.getStackName(), e.getMessage());
String failStatus = isCreate ? "CREATE_FAILED" : "UPDATE_FAILED";
stack.setStatus(failStatus);
stack.setStatusReason(e.getMessage());
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", failStatus, e.getMessage());
persistStack(stack);
if (isCreate) {
persistStack(stack);
} else {
rollbackFailedUpdate(
stack, region, previousState, attemptedResourceIds, e.getMessage());
}
}
}
/**
* Handles a resource that failed to provision.
*
* <p>On a <b>create</b>, rolls back by deleting the resources that were successfully created in
* this execution, leaving a clean slate ({@code ROLLBACK_COMPLETE}) so a corrected re-deploy can
* start from scratch. On an <b>update</b>, marks {@code UPDATE_ROLLBACK_COMPLETE}; the caller
* restores the prior template and failed-resource metadata so retries and deletion continue to
* manage the last known-good physical resource. Rolling back side effects from resources that
* completed earlier in the failed update remains out of scope.
* <p>On a <b>create</b>, rolls back by deleting resources created by the failed execution. On
* an <b>update</b>, restores the prior resource, template, output, and export state.
*/
private void rollbackFailedExecution(Stack stack, String region, boolean isCreate,
StackResource failedResource) {
private void rollbackFailedExecution(
Stack stack,
String region,
boolean isCreate,
StackResource failedResource,
StackUpdateSnapshot previousState,
Set<String> attemptedResourceIds) {
String failStatus = isCreate ? "CREATE_FAILED" : "UPDATE_FAILED";
stack.setStatus(failStatus);
stack.setStatusReason(failedResource.getStatusReason());
@@ -740,20 +800,283 @@ public class CloudFormationService {
LOG.errorv("Stack {0} rollback failed: {1}", stack.getStackName(), reason);
}
} else {
if ("true".equals(failedResource.getAttributes().remove(
CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR))) {
failedResource.setStatus("CREATE_COMPLETE");
failedResource.setStatusReason(null);
}
stack.setStatus("UPDATE_ROLLBACK_COMPLETE");
stack.setLastUpdatedTime(now());
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "UPDATE_ROLLBACK_COMPLETE", null);
LOG.infov("Stack {0} update rolled back (UPDATE_ROLLBACK_COMPLETE)", stack.getStackName());
rollbackFailedUpdate(
stack, region, previousState, attemptedResourceIds,
failedResource.getStatusReason());
return;
}
persistStack(stack);
}
private List<UpdateCleanupFailure> finishCommittedResourceCleanup(Stack stack) {
List<UpdateCleanupFailure> failures = new ArrayList<>();
for (StackResource resource : stack.getResources().values()) {
String cleanupPhysicalId = provisioner.updateCleanupPhysicalId(resource);
if (cleanupPhysicalId != null) {
addEvent(
stack,
resource.getLogicalId(),
cleanupPhysicalId,
resource.getResourceType(),
"DELETE_IN_PROGRESS",
null);
}
while (true) {
CloudFormationResourceProvisioner.UpdateCleanupResult result =
provisioner.completeUpdate(resource);
if (!result.applicable()) {
break;
}
if (result.complete()) {
if (cleanupPhysicalId != null) {
addEvent(
stack,
resource.getLogicalId(),
cleanupPhysicalId,
resource.getResourceType(),
"DELETE_COMPLETE",
null);
}
provisioner.clearUpdate(resource);
break;
}
if (result.attempts() < 3) {
continue;
}
String reason = result.failureReason() != null
? result.failureReason()
: "Resource deletion failed during update cleanup";
failures.add(new UpdateCleanupFailure(
resource.getLogicalId(), result.previousPhysicalId(), reason));
addEvent(
stack,
resource.getLogicalId(),
result.previousPhysicalId(),
resource.getResourceType(),
"DELETE_FAILED",
reason);
provisioner.clearUpdate(resource);
break;
}
}
return failures;
}
private void finishCommittedStackUpdate(
Stack stack, List<UpdateCleanupFailure> cleanupFailures) {
String statusReason = null;
if (!cleanupFailures.isEmpty()) {
statusReason = "The following resource(s) could not be deleted during update cleanup: ["
+ cleanupFailures.stream()
.map(failure -> failure.logicalId()
+ " (" + failure.physicalId() + ")")
.collect(java.util.stream.Collectors.joining(", "))
+ "].";
}
stack.setStatus("UPDATE_COMPLETE");
stack.setStatusReason(statusReason);
stack.setLastUpdatedTime(now());
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "UPDATE_COMPLETE", statusReason);
persistStack(stack);
LOG.infov("Stack {0} execution complete: UPDATE_COMPLETE", stack.getStackName());
}
private boolean hasReplacementUpdates(Stack stack) {
return stack.getResources().values().stream()
.anyMatch(provisioner::hasReplacementUpdate);
}
private void rollbackFailedUpdate(
Stack stack,
String region,
StackUpdateSnapshot previousState,
Set<String> attemptedResourceIds,
String failureReason) {
stack.setStatus("UPDATE_ROLLBACK_IN_PROGRESS");
stack.setStatusReason(failureReason);
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "UPDATE_ROLLBACK_IN_PROGRESS", failureReason);
List<String> rollbackFailures = rollbackUpdatedResources(
stack, previousState.resources(), attemptedResourceIds, region);
if (rollbackFailures.isEmpty()) {
stack.setTemplateBody(previousState.templateBody());
}
try {
restoreOutputAndExportState(stack, region, previousState);
} catch (Exception e) {
rollbackFailures.add("Outputs");
LOG.errorv("Could not restore outputs and exports for stack {0}: {1}",
stack.getStackName(), e.getMessage());
}
stack.setLastUpdatedTime(now());
if (rollbackFailures.isEmpty()) {
stack.setStatus("UPDATE_ROLLBACK_COMPLETE");
stack.setStatusReason(null);
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "UPDATE_ROLLBACK_COMPLETE", null);
LOG.infov("Stack {0} update rolled back (UPDATE_ROLLBACK_COMPLETE)",
stack.getStackName());
} else {
String reason = "The following resource(s) failed to roll back: ["
+ String.join(", ", rollbackFailures) + "].";
stack.setStatus("UPDATE_ROLLBACK_FAILED");
stack.setStatusReason(reason);
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "UPDATE_ROLLBACK_FAILED", reason);
LOG.errorv("Stack {0} update rollback failed: {1}", stack.getStackName(), reason);
}
persistStack(stack);
}
private List<String> rollbackUpdatedResources(
Stack stack,
Map<String, StackResource> previousResources,
Set<String> attemptedResourceIds,
String region) {
List<StackResource> resources = new ArrayList<>(stack.getResources().values());
Collections.reverse(resources);
List<String> failures = new ArrayList<>();
List<String> removedResources = new ArrayList<>();
for (StackResource resource : resources) {
if (!attemptedResourceIds.contains(resource.getLogicalId())) {
continue;
}
try {
StackResource previous = previousResources.get(resource.getLogicalId());
if (previous == null) {
boolean rollbackOwned = "true".equals(resource.getAttributes().get(
CfnRollback.ROLLBACK_OWNED_ATTR));
if (resource.getPhysicalId() != null || rollbackOwned) {
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "DELETE_IN_PROGRESS",
"Resource creation cancelled during update rollback");
provisioner.delete(resource, region);
}
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "DELETE_COMPLETE",
"Resource creation cancelled during update rollback");
removedResources.add(resource.getLogicalId());
} else if ("true".equals(resource.getAttributes().remove(
CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR))
|| provisioner.rollbackUpdate(resource)) {
resource.setStatus(previous.getStatus());
resource.setStatusReason(previous.getStatusReason());
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "UPDATE_COMPLETE",
"Resource update rolled back");
} else if (resource.getStatus() != null
&& resource.getStatus().startsWith("UPDATE_")) {
String reason = "Rollback is not implemented for "
+ resource.getResourceType();
failures.add(resource.getLogicalId());
resource.setStatus("UPDATE_FAILED");
resource.setStatusReason(reason);
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "UPDATE_FAILED", reason);
}
} catch (Exception e) {
failures.add(resource.getLogicalId());
resource.setStatus("UPDATE_FAILED");
resource.setStatusReason(e.getMessage());
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "UPDATE_FAILED", e.getMessage());
LOG.errorv("Could not roll back resource {0}: {1}",
resource.getLogicalId(), e.getMessage());
}
}
removedResources.forEach(stack.getResources()::remove);
return failures;
}
private void restoreOutputAndExportState(
Stack stack, String region, StackUpdateSnapshot previousState) {
RuntimeException storageFailure = null;
for (String exportName : new ArrayList<>(stack.getExports().keySet())) {
String key = exportKey(region, exportName);
exports.remove(key);
try {
exportBackend.deleteForAccount(storageAccount, key);
} catch (RuntimeException e) {
storageFailure = appendFailure(storageFailure, e);
}
}
stack.getOutputs().clear();
stack.getOutputs().putAll(previousState.outputs());
stack.getExports().clear();
stack.getExports().putAll(previousState.exports());
stack.getOutputExportNames().clear();
stack.getOutputExportNames().putAll(previousState.outputExportNames());
for (Map.Entry<String, String> entry : previousState.exports().entrySet()) {
String key = exportKey(region, entry.getKey());
exports.put(key, entry.getValue());
try {
exportBackend.putForAccount(storageAccount, key, entry.getValue());
} catch (RuntimeException e) {
storageFailure = appendFailure(storageFailure, e);
}
}
if (storageFailure != null) {
throw storageFailure;
}
}
private static RuntimeException appendFailure(
RuntimeException existing, RuntimeException additional) {
if (existing == null) {
return additional;
}
existing.addSuppressed(additional);
return existing;
}
private StackUpdateSnapshot snapshotForUpdate(Stack stack) {
return new StackUpdateSnapshot(
stack.getTemplateBody(),
new LinkedHashMap<>(stack.getOutputs()),
new LinkedHashMap<>(stack.getExports()),
new LinkedHashMap<>(stack.getOutputExportNames()),
copyResources(stack.getResources()));
}
private Map<String, StackResource> copyResources(
Map<String, StackResource> resources) {
Map<String, StackResource> copies = new LinkedHashMap<>();
resources.forEach((logicalId, resource) ->
copies.put(logicalId, copyResource(resource)));
return copies;
}
private StackResource copyResource(StackResource source) {
StackResource copy = new StackResource();
copy.setLogicalId(source.getLogicalId());
copy.setPhysicalId(source.getPhysicalId());
copy.setResourceType(source.getResourceType());
copy.setStatus(source.getStatus());
copy.setStatusReason(source.getStatusReason());
copy.setDeletionPolicy(source.getDeletionPolicy());
copy.setUpdateReplacePolicy(source.getUpdateReplacePolicy());
copy.setTimestamp(source.getTimestamp());
copy.setAttributes(new HashMap<>(source.getAttributes()));
return copy;
}
private record StackUpdateSnapshot(
String templateBody,
Map<String, String> outputs,
Map<String, String> exports,
Map<String, String> outputExportNames,
Map<String, StackResource> resources) {
}
private record UpdateCleanupFailure(
String logicalId, String physicalId, String failureReason) {
}
/** Deletes every resource created in this execution, in reverse order. */
private List<String> rollbackCreatedResources(Stack stack, String region) {
List<StackResource> resources = new ArrayList<>(stack.getResources().values());
@@ -798,9 +1121,11 @@ public class CloudFormationService {
List<String> failedResources = new ArrayList<>();
for (StackResource resource : resources) {
// CREATE_COMPLETE: first delete attempt. DELETE_FAILED: a previous delete left the
// resource behind (e.g. the bucket was non-empty); AWS re-attempts it on retry.
// CREATE_COMPLETE/UPDATE_COMPLETE: first delete attempt. DELETE_FAILED: a previous
// delete left the resource behind (e.g. the bucket was non-empty); AWS re-attempts
// it on retry.
boolean deletable = "CREATE_COMPLETE".equals(resource.getStatus())
|| "UPDATE_COMPLETE".equals(resource.getStatus())
|| "DELETE_FAILED".equals(resource.getStatus());
if (resource.getPhysicalId() == null || !deletable) {
continue;
@@ -16,6 +16,7 @@ public class StackResource {
private String deletionPolicy;
private String status = "CREATE_IN_PROGRESS";
private String statusReason;
private String updateReplacePolicy;
private Instant timestamp = Instant.now();
private Map<String, String> attributes = new HashMap<>();
@@ -31,6 +32,10 @@ public class StackResource {
public void setStatus(String status) { this.status = status; }
public String getStatusReason() { return statusReason; }
public void setStatusReason(String statusReason) { this.statusReason = statusReason; }
public String getUpdateReplacePolicy() { return updateReplacePolicy; }
public void setUpdateReplacePolicy(String updateReplacePolicy) {
this.updateReplacePolicy = updateReplacePolicy;
}
public Instant getTimestamp() { return timestamp; }
public void setTimestamp(Instant timestamp) { this.timestamp = timestamp; }
public Map<String, String> getAttributes() { return attributes; }
@@ -34,6 +34,7 @@ public class StepFunctionsJsonHandler {
public Response handle(String action, JsonNode request, String region) {
return switch (action) {
case "CreateStateMachine" -> handleCreateStateMachine(request, region);
case "UpdateStateMachine" -> handleUpdateStateMachine(request);
case "DescribeStateMachine" -> handleDescribeStateMachine(request);
case "ListStateMachines" -> handleListStateMachines(request, region);
case "DeleteStateMachine" -> handleDeleteStateMachine(request);
@@ -65,27 +66,71 @@ public class StepFunctionsJsonHandler {
}
private Response handleCreateStateMachine(JsonNode request, String region) {
StateMachine sm = service.createStateMachine(
request.path("name").asText(),
request.path("definition").asText(),
request.path("roleArn").asText(),
request.path("type").asText(null),
boolean publish = parseOptionalBoolean(request, "publish", false);
StepFunctionsService.CreateStateMachineResult result = service.createStateMachine(
requiredText(request, "name"),
requiredText(request, "definition"),
requiredText(request, "roleArn"),
optionalText(request, "type"),
region,
parseTagsArray(request.path("tags"))
parseTagsArray(request.path("tags")),
request.get("loggingConfiguration"),
request.get("tracingConfiguration"),
request.get("encryptionConfiguration"),
publish,
optionalText(request, "versionDescription")
);
StateMachine sm = result.stateMachine();
ObjectNode response = objectMapper.createObjectNode();
response.put("stateMachineArn", sm.getStateMachineArn());
response.put("creationDate", sm.getCreationDate());
// Publishing a version on create is opt-in (publish=true).
if (request.path("publish").asBoolean(false)) {
var version = service.publishStateMachineVersion(sm.getStateMachineArn());
response.put("stateMachineVersionArn", version.getStateMachineVersionArn());
if (result.version() != null) {
response.put(
"stateMachineVersionArn",
result.version().getStateMachineVersionArn());
} else {
response.putNull("stateMachineVersionArn");
}
return Response.ok(response).build();
}
private Response handleUpdateStateMachine(JsonNode request) {
String stateMachineArn = requiredText(request, "stateMachineArn");
String definition = optionalText(request, "definition");
String roleArn = optionalText(request, "roleArn");
// AWS requires at least one updatable field; a bare stateMachineArn returns MissingRequiredParameter.
if (definition == null && roleArn == null) {
throw new AwsException("MissingRequiredParameter",
"Either the definition or the roleArn must be specified.", 400);
}
boolean publish = parseOptionalBoolean(request, "publish", false);
StepFunctionsService.UpdateStateMachineResult result = service.updateStateMachine(
stateMachineArn,
new StepFunctionsService.UpdateStateMachineRequest(
definition,
roleArn,
request.get("loggingConfiguration"), request.has("loggingConfiguration"),
request.get("tracingConfiguration"), request.has("tracingConfiguration"),
request.get("encryptionConfiguration"), request.has("encryptionConfiguration"),
publish,
optionalText(request, "versionDescription")));
StateMachine sm = result.stateMachine();
ObjectNode response = objectMapper.createObjectNode();
response.put("updateDate", sm.getUpdateDate());
response.put("revisionId", sm.getRevisionId());
if (result.version() != null) {
response.put("stateMachineVersionArn", result.version().getStateMachineVersionArn());
} else {
response.putNull("stateMachineVersionArn");
}
return Response.ok(response).build();
}
private Response handlePublishStateMachineVersion(JsonNode request) {
var version = service.publishStateMachineVersion(request.path("stateMachineArn").asText());
var version = service.publishStateMachineVersion(
requiredText(request, "stateMachineArn"),
optionalText(request, "revisionId"),
optionalText(request, "description"));
ObjectNode response = objectMapper.createObjectNode();
response.put("stateMachineVersionArn", version.getStateMachineVersionArn());
response.put("creationDate", version.getCreationDate());
@@ -110,15 +155,40 @@ public class StepFunctionsJsonHandler {
}
private Response handleDescribeStateMachine(JsonNode request) {
StateMachine sm = service.describeStateMachine(request.path("stateMachineArn").asText());
String includedData = optionalText(request, "includedData");
if (includedData != null
&& !"ALL_DATA".equals(includedData)
&& !"METADATA_ONLY".equals(includedData)) {
throw new AwsException(
"ValidationException",
"includedData must be ALL_DATA or METADATA_ONLY.", 400);
}
boolean metadataOnly = "METADATA_ONLY".equals(includedData);
StateMachine sm = service.describeStateMachine(
requiredText(request, "stateMachineArn"));
ObjectNode response = objectMapper.createObjectNode();
response.put("stateMachineArn", sm.getStateMachineArn());
response.put("name", sm.getName());
response.put("definition", sm.getDefinition());
response.put("definition", metadataOnly ? "{}" : sm.getDefinition());
response.put("roleArn", sm.getRoleArn());
response.put("type", sm.getType());
response.put("status", sm.getStatus());
response.put("creationDate", sm.getCreationDate());
if (sm.getDescription() != null) {
response.put("description", sm.getDescription());
}
if (sm.getLoggingConfiguration() != null) {
response.set("loggingConfiguration", sm.getLoggingConfiguration());
}
if (sm.getTracingConfiguration() != null) {
response.set("tracingConfiguration", sm.getTracingConfiguration());
}
if (sm.getEncryptionConfiguration() != null) {
response.set("encryptionConfiguration", sm.getEncryptionConfiguration());
}
if (sm.getRevisionId() != null) {
response.put("revisionId", sm.getRevisionId());
}
return Response.ok(response).build();
}
@@ -390,6 +460,40 @@ public class StepFunctionsJsonHandler {
return tags;
}
private static String requiredText(JsonNode request, String fieldName) {
JsonNode node = request.get(fieldName);
if (node == null || node.isNull()) {
throw new AwsException("MissingRequiredParameter", fieldName + " is required.", 400);
}
if (!node.isTextual()) {
throw new AwsException("ValidationException", fieldName + " must be a string.", 400);
}
return node.asText();
}
private static String optionalText(JsonNode request, String fieldName) {
JsonNode node = request.get(fieldName);
if (node == null || node.isNull()) {
return null;
}
if (!node.isTextual()) {
throw new AwsException("ValidationException", fieldName + " must be a string.", 400);
}
return node.asText();
}
private static boolean parseOptionalBoolean(
JsonNode request, String fieldName, boolean defaultValue) {
JsonNode node = request.get(fieldName);
if (node == null || node.isNull()) {
return defaultValue;
}
if (!node.isBoolean()) {
throw new AwsException("ValidationException", fieldName + " must be a boolean.", 400);
}
return node.asBoolean();
}
/**
* Reads an optional integer field from the JSON request, rejecting wrong types
* with a typed ValidationException. JsonNode.asInt() silently coerces strings,
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.stepfunctions;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -82,34 +83,277 @@ public class StepFunctionsService implements Resettable {
// ──────────────────────────── State Machines ────────────────────────────
public StateMachine createStateMachine(String name, String definition, String roleArn, String type, String region, Map<String, String> tags) {
String arn = regionResolver.buildArn("states", region, "stateMachine:" + name);
if (stateMachineStore.get(arn).isPresent()) {
throw new AwsException("StateMachineAlreadyExists", "State machine already exists: " + arn, 400);
}
public StateMachine createStateMachine(String name, String definition, String roleArn, String type,
String region, Map<String, String> tags) {
return createStateMachine(name, definition, roleArn, type, region, tags, null, null, null);
}
public StateMachine createStateMachine(
String name,
String definition,
String roleArn,
String type,
String region,
Map<String, String> tags,
JsonNode loggingConfiguration,
JsonNode tracingConfiguration,
JsonNode encryptionConfiguration) {
return createStateMachineInternal(
name,
definition,
roleArn,
type,
region,
tags,
loggingConfiguration,
tracingConfiguration,
encryptionConfiguration,
false,
null,
null,
false).stateMachine();
}
public CreateStateMachineResult createStateMachine(
String name,
String definition,
String roleArn,
String type,
String region,
Map<String, String> tags,
JsonNode loggingConfiguration,
JsonNode tracingConfiguration,
JsonNode encryptionConfiguration,
boolean publish,
String versionDescription) {
return createStateMachineInternal(
name,
definition,
roleArn,
type,
region,
tags,
loggingConfiguration,
tracingConfiguration,
encryptionConfiguration,
publish,
versionDescription,
null,
true);
}
public StateMachine createStateMachineWithRevisionId(
String name,
String definition,
String roleArn,
String type,
String region,
Map<String, String> tags,
JsonNode loggingConfiguration,
JsonNode tracingConfiguration,
JsonNode encryptionConfiguration,
String revisionId) {
if (revisionId == null || revisionId.isBlank()) {
throw new IllegalArgumentException("revisionId is required");
}
return createStateMachineInternal(
name,
definition,
roleArn,
type,
region,
tags,
loggingConfiguration,
tracingConfiguration,
encryptionConfiguration,
false,
null,
revisionId,
false).stateMachine();
}
private synchronized CreateStateMachineResult createStateMachineInternal(
String name,
String definition,
String roleArn,
String type,
String region,
Map<String, String> tags,
JsonNode loggingConfiguration,
JsonNode tracingConfiguration,
JsonNode encryptionConfiguration,
boolean publish,
String versionDescription,
String initialRevisionId,
boolean allowIdempotentCreate) {
validateStateMachineName(name);
validateDefinition(definition);
validateRoleArn(roleArn);
validateStateMachineType(type);
validateConfigurations(loggingConfiguration, tracingConfiguration, encryptionConfiguration);
validateVersionDescription(publish, versionDescription);
String effectiveType = type == null || type.isBlank() ? "STANDARD" : type;
JsonNode effectiveLoggingConfiguration = loggingConfiguration != null
? copyNode(loggingConfiguration) : defaultLoggingConfiguration();
JsonNode effectiveTracingConfiguration = tracingConfiguration != null
? copyNode(tracingConfiguration) : defaultTracingConfiguration();
JsonNode effectiveEncryptionConfiguration = encryptionConfiguration != null
? copyNode(encryptionConfiguration) : defaultEncryptionConfiguration();
String arn = regionResolver.buildArn("states", region, "stateMachine:" + name);
Optional<StateMachine> existing = stateMachineStore.get(arn);
if (existing.isPresent()) {
StateMachine stateMachine = existing.get();
if (allowIdempotentCreate
&& isIdempotentCreateRequest(
stateMachine,
definition,
effectiveType,
effectiveLoggingConfiguration,
effectiveTracingConfiguration,
effectiveEncryptionConfiguration,
publish,
versionDescription)) {
return new CreateStateMachineResult(
copyStateMachine(stateMachine),
creationVersion(stateMachine));
}
throw new AwsException(
"StateMachineAlreadyExists",
"State machine already exists: " + arn,
400);
}
StateMachine sm = new StateMachine();
sm.setStateMachineArn(arn);
sm.setName(name);
sm.setDefinition(definition);
sm.setRoleArn(roleArn);
if (type != null && !type.isEmpty()) {
sm.setType(type);
}
sm.setType(effectiveType);
if (tags != null && !tags.isEmpty()) {
sm.getTags().putAll(tags);
}
sm.setRevisionId(initialRevisionId != null
? initialRevisionId
: UUID.randomUUID().toString());
sm.setLoggingConfiguration(effectiveLoggingConfiguration);
sm.setTracingConfiguration(effectiveTracingConfiguration);
sm.setEncryptionConfiguration(effectiveEncryptionConfiguration);
sm.setCreationVersionDescription(versionDescription);
StateMachineVersion version = publish
? addVersion(sm, versionDescription)
: null;
if (version != null) {
sm.setCreationVersionArn(version.getStateMachineVersionArn());
}
stateMachineStore.put(arn, sm);
LOG.infov("Created State Machine: {0}", arn);
return sm;
return new CreateStateMachineResult(copyStateMachine(sm), version);
}
public record CreateStateMachineResult(
StateMachine stateMachine,
StateMachineVersion version) {
}
public record UpdateStateMachineRequest(
String definition,
String roleArn,
JsonNode loggingConfiguration,
boolean loggingConfigurationProvided,
JsonNode tracingConfiguration,
boolean tracingConfigurationProvided,
JsonNode encryptionConfiguration,
boolean encryptionConfigurationProvided,
boolean publish,
String versionDescription) {
}
public record UpdateStateMachineResult(StateMachine stateMachine, StateMachineVersion version) {
}
public synchronized UpdateStateMachineResult updateStateMachine(
String arn, UpdateStateMachineRequest request) {
validateUpdateStateMachineArn(arn);
if (request.definition() == null && request.roleArn() == null) {
throw new AwsException("MissingRequiredParameter",
"Either the definition or the roleArn must be specified.", 400);
}
if (request.definition() != null) {
validateDefinition(request.definition());
}
if (request.roleArn() != null) {
validateRoleArn(request.roleArn());
}
if (request.loggingConfigurationProvided()) {
validateLoggingConfiguration(request.loggingConfiguration());
}
if (request.tracingConfigurationProvided()) {
validateTracingConfiguration(request.tracingConfiguration());
}
if (request.encryptionConfigurationProvided()) {
validateEncryptionConfiguration(request.encryptionConfiguration());
}
validateVersionDescription(request.publish(), request.versionDescription());
StateMachine current = stateMachineStore.get(arn)
.orElseThrow(() -> new AwsException(
"StateMachineDoesNotExist", "State machine does not exist: " + arn, 400));
StateMachine updated = copyStateMachine(current);
if (request.definition() != null) {
updated.setDefinition(request.definition());
}
if (request.roleArn() != null) {
updated.setRoleArn(request.roleArn());
}
if (request.loggingConfigurationProvided()) {
updated.setLoggingConfiguration(copyNode(request.loggingConfiguration()));
}
if (request.tracingConfigurationProvided()) {
updated.setTracingConfiguration(copyNode(request.tracingConfiguration()));
}
if (request.encryptionConfigurationProvided()) {
updated.setEncryptionConfiguration(copyNode(request.encryptionConfiguration()));
}
updated.setRevisionId(UUID.randomUUID().toString());
updated.setUpdateDate(System.currentTimeMillis() / 1000.0);
StateMachineVersion version = request.publish()
? addVersion(updated, request.versionDescription())
: null;
stateMachineStore.put(arn, updated);
LOG.infov("Updated State Machine: {0}", arn);
return new UpdateStateMachineResult(copyStateMachine(updated), version);
}
public StateMachine describeStateMachine(String arn) {
return stateMachineStore.get(arn)
.orElseThrow(() -> new AwsException("StateMachineDoesNotExist", "State machine does not exist", 400));
validateDescribeStateMachineArn(arn);
Optional<StateMachine> stateMachine = stateMachineStore.get(arn);
if (stateMachine.isPresent()) {
return copyStateMachine(stateMachine.get());
}
int versionSeparator = arn != null ? arn.lastIndexOf(':') : -1;
if (versionSeparator > 0 && versionSeparator < arn.length() - 1) {
String versionText = arn.substring(versionSeparator + 1);
if (versionText.chars().allMatch(Character::isDigit)) {
String baseArn = arn.substring(0, versionSeparator);
Optional<StateMachine> baseStateMachine = stateMachineStore.get(baseArn);
if (baseStateMachine.isPresent()) {
return baseStateMachine.get().getVersions().stream()
.filter(version -> arn.equals(version.getStateMachineVersionArn()))
.findFirst()
.map(version -> stateMachineFromVersion(baseStateMachine.get(), version))
.orElseThrow(() -> new AwsException(
"StateMachineDoesNotExist",
"State machine does not exist", 400));
}
}
}
throw new AwsException(
"StateMachineDoesNotExist", "State machine does not exist", 400);
}
public List<StateMachine> listStateMachines(String region) {
@@ -120,13 +364,39 @@ public class StepFunctionsService implements Resettable {
// ── State machine versions ──────────────────────────────────────────────
public StateMachineVersion publishStateMachineVersion(String stateMachineArn) {
StateMachine sm = describeStateMachine(stateMachineArn);
int next = sm.getVersionCounter() + 1;
sm.setVersionCounter(next);
StateMachineVersion version = new StateMachineVersion(
stateMachineArn + ":" + next, next, System.currentTimeMillis() / 1000.0);
sm.getVersions().add(version);
stateMachineStore.put(stateMachineArn, sm);
return publishStateMachineVersion(stateMachineArn, null, null);
}
public synchronized StateMachineVersion publishStateMachineVersion(
String stateMachineArn,
String revisionId,
String description) {
validateStateMachineArn(stateMachineArn);
validateVersionDescription(true, description);
StateMachine current = stateMachineStore.get(stateMachineArn)
.orElseThrow(() -> new AwsException(
"StateMachineDoesNotExist", "State machine does not exist", 400));
if (revisionId != null && !Objects.equals(revisionId, current.getRevisionId())) {
throw new AwsException(
"ConflictException",
"The state machine revision does not match revisionId " + revisionId,
409);
}
StateMachine updated = copyStateMachine(current);
if (updated.getRevisionId() == null) {
updated.setRevisionId(UUID.randomUUID().toString());
}
Optional<StateMachineVersion> existingVersion = updated.getVersions().stream()
.filter(version -> Objects.equals(
updated.getRevisionId(), version.getRevisionId()))
.findFirst();
if (existingVersion.isPresent()) {
return copyVersion(existingVersion.get());
}
StateMachineVersion version = addVersion(updated, description);
stateMachineStore.put(stateMachineArn, updated);
return version;
}
@@ -141,7 +411,8 @@ public class StepFunctionsService implements Resettable {
// second-resolution, so tie-break on the version number (also descending) to keep the order
// correct when several versions are published within the same second — otherwise the
// Terraform provider can latch onto the wrong version ARN.
List<StateMachineVersion> versions = new ArrayList<>(sm.getVersions());
List<StateMachineVersion> versions = new ArrayList<>();
sm.getVersions().forEach(version -> versions.add(copyVersion(version)));
versions.sort(Comparator
.comparingDouble(StateMachineVersion::getCreationDate)
.thenComparingInt(StateMachineVersion::getVersion)
@@ -150,15 +421,18 @@ public class StepFunctionsService implements Resettable {
return List.copyOf(versions);
}
public void deleteStateMachineVersion(String stateMachineVersionArn) {
public synchronized void deleteStateMachineVersion(String stateMachineVersionArn) {
int lastColon = stateMachineVersionArn.lastIndexOf(':');
if (lastColon < 0) {
return;
}
String baseArn = stateMachineVersionArn.substring(0, lastColon);
stateMachineStore.get(baseArn).ifPresent(sm -> {
sm.getVersions().removeIf(v -> stateMachineVersionArn.equals(v.getStateMachineVersionArn()));
stateMachineStore.put(baseArn, sm);
stateMachineStore.get(baseArn).ifPresent(current -> {
StateMachine updated = copyStateMachine(current);
updated.getVersions().removeIf(
version -> stateMachineVersionArn.equals(
version.getStateMachineVersionArn()));
stateMachineStore.put(baseArn, updated);
});
}
@@ -166,6 +440,20 @@ public class StepFunctionsService implements Resettable {
stateMachineStore.delete(arn);
}
public synchronized boolean deleteStateMachineIfRevisionMatches(
String arn, String expectedRevisionId) {
Optional<StateMachine> existing = stateMachineStore.get(arn);
if (existing.isEmpty()) {
return false;
}
if (expectedRevisionId == null
|| !Objects.equals(expectedRevisionId, existing.get().getRevisionId())) {
return false;
}
stateMachineStore.delete(arn);
return true;
}
// ──────────────────────────── Executions ────────────────────────────
public Execution startExecution(String stateMachineArn, String name, String input, String region) {
@@ -418,12 +706,205 @@ public class StepFunctionsService implements Resettable {
throw new AwsException("ResourceNotFound", "Resource not found: " + arn, 400);
}
public synchronized void replaceStateMachineTags(String arn, Map<String, String> tags) {
StateMachine current = stateMachineStore.get(arn)
.orElseThrow(() -> new AwsException(
"StateMachineDoesNotExist", "State machine does not exist: " + arn, 400));
StateMachine updated = copyStateMachine(current);
updated.setTags(new HashMap<>(tags != null ? tags : Map.of()));
stateMachineStore.put(arn, updated);
}
private StateMachineVersion addVersion(StateMachine stateMachine, String description) {
int next = stateMachine.getVersionCounter() + 1;
stateMachine.setVersionCounter(next);
StateMachineVersion version = new StateMachineVersion(
stateMachine.getStateMachineArn() + ":" + next,
next,
System.currentTimeMillis() / 1000.0);
version.setDescription(description);
version.setName(stateMachine.getName());
version.setDefinition(stateMachine.getDefinition());
version.setRoleArn(stateMachine.getRoleArn());
version.setType(stateMachine.getType());
version.setStatus(stateMachine.getStatus());
version.setRevisionId(stateMachine.getRevisionId());
version.setLoggingConfiguration(copyNode(stateMachine.getLoggingConfiguration()));
version.setTracingConfiguration(copyNode(stateMachine.getTracingConfiguration()));
version.setEncryptionConfiguration(copyNode(stateMachine.getEncryptionConfiguration()));
stateMachine.getVersions().add(version);
return copyVersion(version);
}
private StateMachine copyStateMachine(StateMachine source) {
StateMachine copy = new StateMachine();
copy.setStateMachineArn(source.getStateMachineArn());
copy.setName(source.getName());
copy.setDefinition(source.getDefinition());
copy.setRoleArn(source.getRoleArn());
copy.setType(source.getType());
copy.setStatus(source.getStatus());
copy.setCreationDate(source.getCreationDate());
copy.setUpdateDate(source.getUpdateDate());
copy.setRevisionId(source.getRevisionId());
copy.setDescription(source.getDescription());
copy.setLoggingConfiguration(source.getLoggingConfiguration() != null
? copyNode(source.getLoggingConfiguration()) : defaultLoggingConfiguration());
copy.setTracingConfiguration(source.getTracingConfiguration() != null
? copyNode(source.getTracingConfiguration()) : defaultTracingConfiguration());
copy.setEncryptionConfiguration(source.getEncryptionConfiguration() != null
? copyNode(source.getEncryptionConfiguration()) : defaultEncryptionConfiguration());
copy.setTags(new HashMap<>(source.getTags() != null ? source.getTags() : Map.of()));
copy.setCreationVersionArn(source.getCreationVersionArn());
copy.setCreationVersionDescription(source.getCreationVersionDescription());
copy.setVersionCounter(source.getVersionCounter());
List<StateMachineVersion> versions = new ArrayList<>();
for (StateMachineVersion version :
source.getVersions() != null ? source.getVersions() : List.<StateMachineVersion>of()) {
versions.add(copyVersion(version));
}
copy.setVersions(versions);
return copy;
}
private boolean isIdempotentCreateRequest(
StateMachine existing,
String definition,
String type,
JsonNode loggingConfiguration,
JsonNode tracingConfiguration,
JsonNode encryptionConfiguration,
boolean publish,
String versionDescription) {
return Objects.equals(existing.getDefinition(), definition)
&& Objects.equals(existing.getType(), type)
&& Objects.equals(existing.getLoggingConfiguration(), loggingConfiguration)
&& Objects.equals(existing.getTracingConfiguration(), tracingConfiguration)
&& Objects.equals(existing.getEncryptionConfiguration(), encryptionConfiguration)
&& (existing.getCreationVersionArn() != null) == publish
&& Objects.equals(
existing.getCreationVersionDescription(),
versionDescription);
}
private StateMachineVersion creationVersion(StateMachine stateMachine) {
if (stateMachine.getCreationVersionArn() == null) {
return null;
}
return stateMachine.getVersions().stream()
.filter(version -> Objects.equals(
stateMachine.getCreationVersionArn(),
version.getStateMachineVersionArn()))
.findFirst()
.map(this::copyVersion)
.orElseGet(() -> new StateMachineVersion(
stateMachine.getCreationVersionArn(),
1,
stateMachine.getCreationDate()));
}
private StateMachine stateMachineFromVersion(
StateMachine current, StateMachineVersion version) {
StateMachine described = new StateMachine();
described.setStateMachineArn(version.getStateMachineVersionArn());
described.setName(version.getName() != null ? version.getName() : current.getName());
described.setDefinition(version.getDefinition() != null
? version.getDefinition() : current.getDefinition());
described.setRoleArn(version.getRoleArn() != null
? version.getRoleArn() : current.getRoleArn());
described.setType(version.getType() != null ? version.getType() : current.getType());
described.setStatus(version.getStatus() != null
? version.getStatus() : current.getStatus());
described.setCreationDate(version.getCreationDate());
described.setRevisionId(version.getRevisionId() != null
? version.getRevisionId() : current.getRevisionId());
described.setDescription(version.getDescription());
described.setLoggingConfiguration(version.getLoggingConfiguration() != null
? copyNode(version.getLoggingConfiguration())
: copyNode(current.getLoggingConfiguration()));
described.setTracingConfiguration(version.getTracingConfiguration() != null
? copyNode(version.getTracingConfiguration())
: copyNode(current.getTracingConfiguration()));
described.setEncryptionConfiguration(version.getEncryptionConfiguration() != null
? copyNode(version.getEncryptionConfiguration())
: copyNode(current.getEncryptionConfiguration()));
return described;
}
private StateMachineVersion copyVersion(StateMachineVersion source) {
StateMachineVersion copy = new StateMachineVersion(
source.getStateMachineVersionArn(),
source.getVersion(),
source.getCreationDate());
copy.setDescription(source.getDescription());
copy.setName(source.getName());
copy.setDefinition(source.getDefinition());
copy.setRoleArn(source.getRoleArn());
copy.setType(source.getType());
copy.setStatus(source.getStatus());
copy.setRevisionId(source.getRevisionId());
copy.setLoggingConfiguration(copyNode(source.getLoggingConfiguration()));
copy.setTracingConfiguration(copyNode(source.getTracingConfiguration()));
copy.setEncryptionConfiguration(copyNode(source.getEncryptionConfiguration()));
return copy;
}
private record VersionArn(String baseArn, int version) {
}
private static VersionArn parseVersionArn(String arn) {
if (arn == null) {
return null;
}
int separator = arn.lastIndexOf(':');
if (separator < 0 || separator == arn.length() - 1) {
return null;
}
String suffix = arn.substring(separator + 1);
if (!suffix.chars().allMatch(Character::isDigit)) {
return null;
}
try {
return new VersionArn(
arn.substring(0, separator),
Integer.parseInt(suffix));
} catch (NumberFormatException ignored) {
return null;
}
}
private static JsonNode copyNode(JsonNode node) {
return node == null ? null : node.deepCopy();
}
private JsonNode defaultLoggingConfiguration() {
var configuration = objectMapper.createObjectNode();
configuration.put("level", "OFF");
configuration.put("includeExecutionData", false);
configuration.putArray("destinations");
return configuration;
}
private JsonNode defaultTracingConfiguration() {
return objectMapper.createObjectNode().put("enabled", false);
}
private JsonNode defaultEncryptionConfiguration() {
return objectMapper.createObjectNode().put("type", "AWS_OWNED_KEY");
}
// ──────────────────────────── Validation ────────────────────────────
public record Diagnostic(String severity, String code, String message, String location) {}
public record ValidationResult(boolean valid, List<Diagnostic> diagnostics, boolean truncated) {}
private static final int MAX_DEFINITION_LENGTH = 1_048_576;
private static final int MAX_ARN_LENGTH = 256;
private static final int MAX_VERSION_DESCRIPTION_LENGTH = 256;
private static final String INVALID_STATE_MACHINE_NAME_CHARACTERS =
"<>[]{}?*\"#%\\^|~`$&,;:/";
private static final Set<String> STATE_TYPES = Set.of(
"Pass", "Task", "Choice", "Wait", "Succeed", "Fail", "Parallel", "Map");
private static final String PARSE_ERROR_MARKER = "INVALID_JSON_DESCRIPTION:";
// Parse the structured location out of validator flat error strings,
@@ -512,7 +993,246 @@ public class StepFunctionsService implements Resettable {
return new Diagnostic("ERROR", code, message, location);
}
private static void validateStateMachineName(String name) {
boolean invalidCharacter = name != null && name.codePoints().anyMatch(codePoint ->
Character.isWhitespace(codePoint)
|| Character.isISOControl(codePoint)
|| INVALID_STATE_MACHINE_NAME_CHARACTERS.indexOf(codePoint) >= 0);
if (name == null || name.isBlank() || name.length() > 80 || invalidCharacter) {
throw new AwsException(
"InvalidName",
"Invalid state machine name: '" + name + "'",
400);
}
}
private static void validateStateMachineArn(String arn) {
if (arn == null || arn.isBlank() || arn.length() > MAX_ARN_LENGTH) {
throw new AwsException("InvalidArn", "Invalid Arn: '" + arn + "'", 400);
}
try {
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String resource = parsed.resource();
String name = resource != null && resource.startsWith("stateMachine:")
? resource.substring("stateMachine:".length())
: null;
if (!"states".equals(parsed.service())
|| parsed.region().isBlank()
|| parsed.accountId().isBlank()
|| name == null
|| name.isBlank()
|| name.length() > 80
|| name.indexOf(':') >= 0
|| name.chars().anyMatch(Character::isWhitespace)) {
throw new IllegalArgumentException("Invalid state machine ARN");
}
} catch (IllegalArgumentException e) {
throw new AwsException("InvalidArn", "Invalid Arn: '" + arn + "'", 400);
}
}
private static void validateDescribeStateMachineArn(String arn) {
if (arn == null || arn.isBlank() || arn.length() > MAX_ARN_LENGTH) {
throw new AwsException("InvalidArn", "Invalid Arn: '" + arn + "'", 400);
}
try {
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String resource = parsed.resource();
String name = resource != null && resource.startsWith("stateMachine:")
? resource.substring("stateMachine:".length())
: null;
if ("states".equals(parsed.service())
&& name != null
&& name.indexOf('/') >= 0) {
throw new AwsException(
"ValidationException",
"DescribeStateMachine does not accept a qualified Distributed Map ARN.",
400);
}
} catch (IllegalArgumentException e) {
throw new AwsException("InvalidArn", "Invalid Arn: '" + arn + "'", 400);
}
VersionArn versionArn = parseVersionArn(arn);
validateStateMachineArn(
versionArn != null ? versionArn.baseArn() : arn);
}
private static void validateUpdateStateMachineArn(String arn) {
if (arn != null && arn.length() <= MAX_ARN_LENGTH) {
try {
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String resource = parsed.resource();
String name = resource != null && resource.startsWith("stateMachine:")
? resource.substring("stateMachine:".length())
: null;
int qualifierSeparator = name != null ? name.indexOf('/') : -1;
if ("states".equals(parsed.service())
&& !parsed.region().isBlank()
&& !parsed.accountId().isBlank()
&& qualifierSeparator > 0
&& qualifierSeparator < name.length() - 1) {
throw new AwsException("ValidationException",
"UpdateStateMachine does not accept a qualified Distributed Map ARN.",
400);
}
} catch (IllegalArgumentException ignored) {
// The general validator below maps malformed input to InvalidArn.
}
}
validateStateMachineArn(arn);
}
private static void validateRoleArn(String roleArn) {
if (roleArn == null || roleArn.isBlank() || roleArn.length() > MAX_ARN_LENGTH) {
throw new AwsException("InvalidArn", "Invalid roleArn: '" + roleArn + "'", 400);
}
try {
AwsArnUtils.Arn parsed = AwsArnUtils.parse(roleArn);
String resource = parsed.resource();
if (!"iam".equals(parsed.service())
|| !parsed.region().isEmpty()
|| parsed.accountId().isBlank()
|| resource == null
|| !resource.startsWith("role/")
|| resource.length() == "role/".length()
|| roleArn.chars().anyMatch(Character::isWhitespace)) {
throw new IllegalArgumentException("Invalid IAM role ARN");
}
} catch (IllegalArgumentException e) {
throw new AwsException("InvalidArn", "Invalid roleArn: '" + roleArn + "'", 400);
}
}
private static void validateStateMachineType(String type) {
if (type != null && !type.isBlank()
&& !"STANDARD".equals(type) && !"EXPRESS".equals(type)) {
throw new AwsException("StateMachineTypeNotSupported",
"State machine type must be STANDARD or EXPRESS.", 400);
}
}
private static void validateConfigurations(
JsonNode loggingConfiguration,
JsonNode tracingConfiguration,
JsonNode encryptionConfiguration) {
if (loggingConfiguration != null) {
validateLoggingConfiguration(loggingConfiguration);
}
if (tracingConfiguration != null) {
validateTracingConfiguration(tracingConfiguration);
}
if (encryptionConfiguration != null) {
validateEncryptionConfiguration(encryptionConfiguration);
}
}
private static void validateVersionDescription(boolean publish, String description) {
if (description != null && !publish) {
throw new AwsException("ValidationException",
"versionDescription can only be specified when publish is true.", 400);
}
if (description != null && description.length() > MAX_VERSION_DESCRIPTION_LENGTH) {
throw new AwsException("ValidationException",
"versionDescription exceeds maximum length of "
+ MAX_VERSION_DESCRIPTION_LENGTH + " characters.", 400);
}
}
private static void validateLoggingConfiguration(JsonNode configuration) {
if (configuration == null || !configuration.isObject()) {
throw new AwsException("InvalidLoggingConfiguration",
"loggingConfiguration must be an object.", 400);
}
JsonNode levelNode = configuration.get("level");
String level = levelNode == null ? "OFF" : levelNode.asText(null);
if (level == null || !Set.of("ALL", "ERROR", "FATAL", "OFF").contains(level)) {
throw new AwsException("InvalidLoggingConfiguration",
"loggingConfiguration.level must be ALL, ERROR, FATAL, or OFF.", 400);
}
JsonNode includeExecutionData = configuration.get("includeExecutionData");
if (includeExecutionData != null && !includeExecutionData.isBoolean()) {
throw new AwsException("InvalidLoggingConfiguration",
"loggingConfiguration.includeExecutionData must be a boolean.", 400);
}
JsonNode destinations = configuration.get("destinations");
if (destinations != null && (!destinations.isArray() || destinations.size() > 1)) {
throw new AwsException("InvalidLoggingConfiguration",
"loggingConfiguration.destinations must contain at most one destination.", 400);
}
if (!"OFF".equals(level) && (destinations == null || destinations.isEmpty())) {
throw new AwsException("InvalidLoggingConfiguration",
"A logging destination is required when the log level is not OFF.", 400);
}
if (destinations != null) {
for (JsonNode destination : destinations) {
String logGroupArn = destination.path("cloudWatchLogsLogGroup")
.path("logGroupArn").asText(null);
if (logGroupArn == null || logGroupArn.isBlank()) {
throw new AwsException("InvalidLoggingConfiguration",
"Each logging destination must include a CloudWatch Logs logGroupArn.", 400);
}
}
}
}
private static void validateTracingConfiguration(JsonNode configuration) {
if (configuration == null || !configuration.isObject()) {
throw new AwsException("InvalidTracingConfiguration",
"tracingConfiguration must be an object.", 400);
}
JsonNode enabled = configuration.get("enabled");
if (enabled != null && !enabled.isBoolean()) {
throw new AwsException("InvalidTracingConfiguration",
"tracingConfiguration.enabled must be a boolean.", 400);
}
}
private static void validateEncryptionConfiguration(JsonNode configuration) {
if (configuration == null || !configuration.isObject()) {
throw new AwsException("InvalidEncryptionConfiguration",
"encryptionConfiguration must be an object.", 400);
}
JsonNode typeNode = configuration.get("type");
String type = typeNode != null && typeNode.isTextual() ? typeNode.asText() : null;
if (!"AWS_OWNED_KEY".equals(type) && !"CUSTOMER_MANAGED_KMS_KEY".equals(type)) {
throw new AwsException("InvalidEncryptionConfiguration",
"encryptionConfiguration.type must be AWS_OWNED_KEY or CUSTOMER_MANAGED_KMS_KEY.", 400);
}
JsonNode keyId = configuration.get("kmsKeyId");
if (keyId != null
&& (!keyId.isTextual() || keyId.asText().isBlank() || keyId.asText().length() > 2048)) {
throw new AwsException("InvalidEncryptionConfiguration",
"encryptionConfiguration.kmsKeyId must contain between 1 and 2048 characters.", 400);
}
if ("CUSTOMER_MANAGED_KMS_KEY".equals(type) && keyId == null) {
throw new AwsException("InvalidEncryptionConfiguration",
"encryptionConfiguration.kmsKeyId is required for a customer-managed key.", 400);
}
JsonNode reusePeriod = configuration.get("kmsDataKeyReusePeriodSeconds");
if (reusePeriod != null
&& (!reusePeriod.isIntegralNumber()
|| reusePeriod.asInt() < 60
|| reusePeriod.asInt() > 900)) {
throw new AwsException("InvalidEncryptionConfiguration",
"encryptionConfiguration.kmsDataKeyReusePeriodSeconds must be between 60 and 900.", 400);
}
}
private void validateDefinition(String definition) {
if (definition == null || definition.isBlank()) {
throw new AwsException("InvalidDefinition",
"Invalid State Machine Definition: definition must not be empty.", 400);
}
if (definition.length() > MAX_DEFINITION_LENGTH) {
throw new AwsException("ValidationException",
"definition exceeds maximum length of "
+ MAX_DEFINITION_LENGTH + " characters.", 400);
}
List<String> errors = collectValidationErrors(definition);
if (errors.isEmpty()) {
return;
@@ -538,22 +1258,63 @@ public class StepFunctionsService implements Resettable {
return errors;
}
if (def == null || !def.isObject()) {
errors.add("The state machine definition must be a JSON object");
return errors;
}
JsonNode startAtNode = def.get("StartAt");
String startAt = startAtNode != null && startAtNode.isTextual()
? startAtNode.asText()
: null;
if (startAt == null || startAt.isBlank()) {
errors.add("The field 'StartAt' is required and must be a non-empty string");
}
JsonNode states = def.get("States");
if (states == null || !states.isObject() || states.isEmpty()) {
errors.add("The field 'States' is required and must be a non-empty object");
return errors;
}
if (startAt != null && !startAt.isBlank() && !states.has(startAt)) {
errors.add("The value of 'StartAt' must match a state in 'States'");
}
String topLevelQL = def.path("QueryLanguage").asText("JSONPath");
boolean topLevelJsonata = "JSONata".equals(topLevelQL);
JsonNode states = def.path("States");
if (states.isObject()) {
var fields = states.fields();
while (fields.hasNext()) {
var entry = fields.next();
validateState("/States/" + entry.getKey(), entry.getValue(), topLevelJsonata, errors);
}
var fields = states.fields();
while (fields.hasNext()) {
var entry = fields.next();
validateState("/States/" + entry.getKey(), entry.getValue(), topLevelJsonata, errors);
}
return errors;
}
private void validateState(String statePath, JsonNode stateDef,
boolean topLevelJsonata, List<String> errors) {
if (!stateDef.isObject()) {
errors.add("State must be an object at " + statePath);
return;
}
String stateType = stateDef.path("Type").asText(null);
if (stateType == null || !STATE_TYPES.contains(stateType)) {
errors.add("State must declare a valid field 'Type' at " + statePath);
return;
}
boolean terminalType = "Succeed".equals(stateType) || "Fail".equals(stateType);
boolean choiceType = "Choice".equals(stateType);
boolean hasTerminalTransition = stateDef.path("End").asBoolean(false)
|| stateDef.path("Next").isTextual();
if (!terminalType && !choiceType && !hasTerminalTransition) {
errors.add("State must declare either 'Next' or 'End' at " + statePath);
}
if (choiceType
&& (!stateDef.path("Choices").isArray()
|| stateDef.path("Choices").isEmpty())) {
errors.add("Choice state must declare a non-empty field 'Choices' at " + statePath);
}
String stateQL = stateDef.path("QueryLanguage").asText(null);
boolean stateIsJsonata = stateQL != null ? "JSONata".equals(stateQL) : topLevelJsonata;
@@ -567,7 +1328,7 @@ public class StepFunctionsService implements Resettable {
}
}
if ("Map".equals(stateDef.path("Type").asText())) {
if ("Map".equals(stateType)) {
validateMapConcurrency(statePath, stateDef, stateIsJsonata, errors);
if (stateDef.has("ItemReader")) {
validateItemReader(statePath, stateDef, errors);
@@ -578,7 +1339,7 @@ public class StepFunctionsService implements Resettable {
String processorField = stateDef.has("ItemProcessor") ? "ItemProcessor" : "Iterator";
validateNestedStates(stateDef.path(processorField).path("States"),
statePath + "/" + processorField + "/States", topLevelJsonata, errors);
} else if ("Parallel".equals(stateDef.path("Type").asText())) {
} else if ("Parallel".equals(stateType)) {
JsonNode branches = stateDef.path("Branches");
if (branches.isArray()) {
for (int i = 0; i < branches.size(); i++) {
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.stepfunctions.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
@@ -18,7 +19,15 @@ public class StateMachine {
private String type = "STANDARD";
private String status = "ACTIVE";
private double creationDate;
private Double updateDate;
private String revisionId;
private String description;
private JsonNode loggingConfiguration;
private JsonNode tracingConfiguration;
private JsonNode encryptionConfiguration;
private Map<String, String> tags = new HashMap<>();
private String creationVersionArn;
private String creationVersionDescription;
private int versionCounter = 0;
private List<StateMachineVersion> versions = new ArrayList<>();
@@ -47,9 +56,37 @@ public class StateMachine {
public double getCreationDate() { return creationDate; }
public void setCreationDate(double creationDate) { this.creationDate = creationDate; }
public Double getUpdateDate() { return updateDate; }
public void setUpdateDate(Double updateDate) { this.updateDate = updateDate; }
public String getRevisionId() { return revisionId; }
public void setRevisionId(String revisionId) { this.revisionId = revisionId; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public JsonNode getLoggingConfiguration() { return loggingConfiguration; }
public void setLoggingConfiguration(JsonNode loggingConfiguration) { this.loggingConfiguration = loggingConfiguration; }
public JsonNode getTracingConfiguration() { return tracingConfiguration; }
public void setTracingConfiguration(JsonNode tracingConfiguration) { this.tracingConfiguration = tracingConfiguration; }
public JsonNode getEncryptionConfiguration() { return encryptionConfiguration; }
public void setEncryptionConfiguration(JsonNode encryptionConfiguration) { this.encryptionConfiguration = encryptionConfiguration; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public String getCreationVersionArn() { return creationVersionArn; }
public void setCreationVersionArn(String creationVersionArn) {
this.creationVersionArn = creationVersionArn;
}
public String getCreationVersionDescription() { return creationVersionDescription; }
public void setCreationVersionDescription(String creationVersionDescription) {
this.creationVersionDescription = creationVersionDescription;
}
public int getVersionCounter() { return versionCounter; }
public void setVersionCounter(int versionCounter) { this.versionCounter = versionCounter; }
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.stepfunctions.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
/** A published version of a state machine ({@code <stateMachineArn>:<version>}). */
@@ -10,6 +11,16 @@ public class StateMachineVersion {
private String stateMachineVersionArn;
private int version;
private double creationDate;
private String description;
private String name;
private String definition;
private String roleArn;
private String type;
private String status;
private String revisionId;
private JsonNode loggingConfiguration;
private JsonNode tracingConfiguration;
private JsonNode encryptionConfiguration;
public StateMachineVersion() {
}
@@ -28,4 +39,34 @@ public class StateMachineVersion {
public double getCreationDate() { return creationDate; }
public void setCreationDate(double creationDate) { this.creationDate = creationDate; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDefinition() { return definition; }
public void setDefinition(String definition) { this.definition = definition; }
public String getRoleArn() { return roleArn; }
public void setRoleArn(String roleArn) { this.roleArn = roleArn; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getRevisionId() { return revisionId; }
public void setRevisionId(String revisionId) { this.revisionId = revisionId; }
public JsonNode getLoggingConfiguration() { return loggingConfiguration; }
public void setLoggingConfiguration(JsonNode loggingConfiguration) { this.loggingConfiguration = loggingConfiguration; }
public JsonNode getTracingConfiguration() { return tracingConfiguration; }
public void setTracingConfiguration(JsonNode tracingConfiguration) { this.tracingConfiguration = tracingConfiguration; }
public JsonNode getEncryptionConfiguration() { return encryptionConfiguration; }
public void setEncryptionConfiguration(JsonNode encryptionConfiguration) { this.encryptionConfiguration = encryptionConfiguration; }
}
@@ -220,6 +220,31 @@ class CloudFormationEventBusIntegrationTest {
""".formatted(busName);
}
private static String eventBusAndNamedRuleTemplate(String busName, String description) {
return """
{
"Resources": {
"Bus": {
"Type": "AWS::Events::EventBus",
"Properties": {
"Name": "%s",
"Description": "%s"
}
},
"Rule": {
"Type": "AWS::Events::Rule",
"Properties": {
"Name": "%s-rule",
"EventBusName": { "Ref": "Bus" },
"EventPattern": { "source": ["com.example.orders"] },
"State": "ENABLED"
}
}
}
}
""".formatted(busName, description, busName);
}
@Test
void customEventBusIsRegisteredSoRuleReferencingItSucceeds() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -359,7 +384,7 @@ class CloudFormationEventBusIntegrationTest {
String suffix = Long.toString(System.nanoTime(), 36);
String busName = "update-bus-" + suffix;
String stackName = "eventbus-update-" + suffix;
String originalTemplate = eventBusOnlyTemplate(busName, "before");
String originalTemplate = eventBusAndNamedRuleTemplate(busName, "before");
createStack(stackName, originalTemplate);
assertStackStatus(stackName, "CREATE_COMPLETE");
@@ -367,7 +392,7 @@ class CloudFormationEventBusIntegrationTest {
updateStack(stackName, originalTemplate);
assertStackStatus(stackName, "UPDATE_COMPLETE");
updateStack(stackName, eventBusOnlyTemplate(busName, "after"));
updateStack(stackName, eventBusAndNamedRuleTemplate(busName, "after"));
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
given()
@@ -388,6 +413,17 @@ class CloudFormationEventBusIntegrationTest {
deleteStack(stackName);
awaitStackDeleted(stackName);
given()
.contentType("application/x-amz-json-1.1")
.header("Authorization", EVENTS_AUTH)
.header("X-Amz-Target", "AWSEvents.DescribeEventBus")
.body("{\"Name\":\"" + busName + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("ResourceNotFoundException"));
}
@Test
@@ -0,0 +1,254 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsService;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@QuarkusTest
class CloudFormationStepFunctionsCleanupIntegrationTest {
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
@InjectSpy
StepFunctionsService stepFunctionsService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void permanentReplacementCleanupFailureKeepsCommittedUpdateAndWarns() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "sfn-cleanup-warning-" + suffix;
String oldName = "sfn-cleanup-old-" + suffix;
String newName = "sfn-cleanup-new-" + suffix;
String exportName = "sfn-cleanup-export-" + suffix;
String oldArn = stateMachineArn(oldName);
String newArn = stateMachineArn(newName);
createStack(stackName, template(oldName, "old-definition", "old-output", exportName));
Mockito.doThrow(new IllegalStateException("simulated cleanup failure"))
.when(stepFunctionsService)
.deleteStateMachineIfRevisionMatches(eq(oldArn), anyString());
updateStack(stackName, template(newName, "new-definition", "new-output", exportName));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.body(containsString("<StackStatusReason>"))
.body(containsString(oldArn))
.body(containsString("<OutputValue>new-output</OutputValue>"))
.body(not(containsString("<OutputValue>old-output</OutputValue>")));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListExports")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<Name>" + exportName + "</Name>"))
.body(containsString("<Value>new-output</Value>"))
.body(not(containsString("<Value>old-output</Value>")));
assertStateMachine(oldArn, "old-definition");
assertStateMachine(newArn, "new-definition");
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplate")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString(newName))
.body(not(containsString(oldName)));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<PhysicalResourceId>" + oldArn + "</PhysicalResourceId>"))
.body(containsString("<ResourceStatus>DELETE_IN_PROGRESS</ResourceStatus>"))
.body(containsString("<ResourceStatus>DELETE_FAILED</ResourceStatus>"));
verify(stepFunctionsService, times(3))
.deleteStateMachineIfRevisionMatches(eq(oldArn), anyString());
Mockito.doCallRealMethod()
.when(stepFunctionsService)
.deleteStateMachineIfRevisionMatches(eq(oldArn), anyString());
deleteStack(stackName);
stepFunctionsService.deleteStateMachine(oldArn);
}
@Test
void transientReplacementCleanupFailureSucceedsOnThirdAttempt() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "sfn-cleanup-retry-" + suffix;
String oldName = "sfn-cleanup-retry-old-" + suffix;
String newName = "sfn-cleanup-retry-new-" + suffix;
String exportName = "sfn-cleanup-retry-export-" + suffix;
String oldArn = stateMachineArn(oldName);
String newArn = stateMachineArn(newName);
createStack(stackName, template(oldName, "old-definition", "old-output", exportName));
Mockito.doThrow(new IllegalStateException("first cleanup failure"))
.doThrow(new IllegalStateException("second cleanup failure"))
.doCallRealMethod()
.when(stepFunctionsService)
.deleteStateMachineIfRevisionMatches(eq(oldArn), anyString());
updateStack(stackName, template(newName, "new-definition", "new-output", exportName));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.body(not(containsString("<StackStatusReason>")))
.body(containsString("<OutputValue>new-output</OutputValue>"));
assertStateMachineMissing(oldArn);
assertStateMachine(newArn, "new-definition");
verify(stepFunctionsService, times(3))
.deleteStateMachineIfRevisionMatches(eq(oldArn), anyString());
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<PhysicalResourceId>" + oldArn + "</PhysicalResourceId>"))
.body(containsString("<ResourceStatus>DELETE_IN_PROGRESS</ResourceStatus>"))
.body(containsString("<ResourceStatus>DELETE_COMPLETE</ResourceStatus>"))
.body(not(containsString("<ResourceStatus>DELETE_FAILED</ResourceStatus>")));
deleteStack(stackName);
}
private static void createStack(String stackName, String templateBody) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", templateBody)
.when()
.post("/")
.then()
.statusCode(200);
}
private static void updateStack(String stackName, String templateBody) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", templateBody)
.when()
.post("/")
.then()
.statusCode(200);
}
private static void deleteStack(String stackName) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
}
private static void assertStateMachine(String arn, String definitionMarker) {
given()
.header("X-Amz-Target", "AWSStepFunctions.DescribeStateMachine")
.contentType(SFN_CONTENT_TYPE)
.body("{\"stateMachineArn\":\"" + arn + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("definition", containsString(definitionMarker));
}
private static void assertStateMachineMissing(String arn) {
given()
.header("X-Amz-Target", "AWSStepFunctions.DescribeStateMachine")
.contentType(SFN_CONTENT_TYPE)
.body("{\"stateMachineArn\":\"" + arn + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", containsString("StateMachineDoesNotExist"));
}
private static String stateMachineArn(String name) {
return "arn:aws:states:us-east-1:000000000000:stateMachine:" + name;
}
private static String template(
String stateMachineName,
String definitionMarker,
String outputValue,
String exportName) {
return """
{
"Resources": {
"MyStateMachine": {
"Type": "AWS::StepFunctions::StateMachine",
"Properties": {
"StateMachineName": "%s",
"RoleArn": "arn:aws:iam::000000000000:role/cfn-sfn-cleanup-role",
"DefinitionString": "{\\"StartAt\\":\\"Done\\",\\"States\\":{\\"Done\\":{\\"Type\\":\\"Pass\\",\\"Result\\":\\"%s\\",\\"End\\":true}}}"
}
}
},
"Outputs": {
"Marker": {
"Value": "%s",
"Export": {"Name": "%s"}
}
}
}
""".formatted(
stateMachineName, definitionMarker, outputValue, exportName);
}
}
@@ -0,0 +1,354 @@
package io.github.hectorvent.floci.services.stepfunctions;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* UpdateStateMachine — the AWS API action and the behavior CloudFormation relies on when a stack
* update re-provisions an AWS::StepFunctions::StateMachine (previously Floci always called
* CreateStateMachine, which failed with StateMachineAlreadyExists and rolled the stack update back).
*/
@QuarkusTest
class StepFunctionsUpdateStateMachineIntegrationTest {
private static final String CT = "application/x-amz-json-1.0";
private static final String DEF = "{\\\"StartAt\\\":\\\"D\\\",\\\"States\\\":{\\\"D\\\":{\\\"Type\\\":\\\"Pass\\\",\\\"End\\\":true}}}";
private static final String DEF2 = "{\\\"StartAt\\\":\\\"W\\\",\\\"States\\\":{\\\"W\\\":{\\\"Type\\\":\\\"Wait\\\",\\\"Seconds\\\":1,\\\"End\\\":true}}}";
@BeforeAll
static void setup() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static Response call(String target, String body) {
return given().header("X-Amz-Target", "AWSStepFunctions." + target).contentType(CT).body(body).when().post("/");
}
private static String createStateMachine(String name) {
return call("CreateStateMachine",
"{\"name\":\"" + name + "\",\"definition\":\"" + DEF + "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r1\"}")
.then().statusCode(200).extract().jsonPath().getString("stateMachineArn");
}
@Test
void updateChangesDefinitionAndRoleArn() {
String arn = createStateMachine("upd-def-" + System.currentTimeMillis());
Response update = call("UpdateStateMachine",
"{\"stateMachineArn\":\"" + arn + "\",\"definition\":\"" + DEF2 + "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r2\"}")
.then().statusCode(200)
.body("updateDate", notNullValue())
.body("revisionId", notNullValue())
.extract().response();
assertTrue(update.asString().contains("\"stateMachineVersionArn\":null"));
// The update is reflected in DescribeStateMachine.
Response describe = call("DescribeStateMachine", "{\"stateMachineArn\":\"" + arn + "\"}")
.then().statusCode(200)
.body("roleArn", is("arn:aws:iam::000000000000:role/r2"))
.body("definition", containsString("\"Wait\""))
.extract().response();
assertFalse(describe.jsonPath().getMap("").containsKey("updateDate"));
}
@Test
void directUpdatePreservesExistingTags() {
String name = "upd-tags-" + System.currentTimeMillis();
String arn = call("CreateStateMachine",
"{\"name\":\"" + name + "\",\"definition\":\"" + DEF
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r1\","
+ "\"tags\":[{\"key\":\"owner\",\"value\":\"platform\"},"
+ "{\"key\":\"stage\",\"value\":\"test\"}]}")
.then().statusCode(200).extract().jsonPath().getString("stateMachineArn");
call("UpdateStateMachine",
"{\"stateMachineArn\":\"" + arn + "\",\"definition\":\"" + DEF2 + "\"}")
.then().statusCode(200);
call("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")
.then().statusCode(200)
.body("tags.size()", is(2))
.body("tags.find { it.key == 'owner' }.value", is("platform"))
.body("tags.find { it.key == 'stage' }.value", is("test"));
}
@Test
void updateMissingStateMachineReturnsStateMachineDoesNotExist() {
String missing = "arn:aws:states:us-east-1:000000000000:stateMachine:missing-" + System.currentTimeMillis();
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + missing + "\",\"definition\":\"" + DEF + "\"}")
.then().statusCode(400).body(containsString("StateMachineDoesNotExist"));
}
@Test
void updateWithoutDefinitionOrRoleArnReturnsMissingRequiredParameter() {
String arn = createStateMachine("upd-empty-" + System.currentTimeMillis());
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn + "\"}")
.then().statusCode(400).body(containsString("MissingRequiredParameter"));
}
@Test
void updateWithPublishReturnsVersionArn() {
String arn = createStateMachine("upd-pub-" + System.currentTimeMillis());
Response published = call("UpdateStateMachine", """
{
"stateMachineArn":"%s",
"definition":"%s",
"roleArn":"arn:aws:iam::000000000000:role/r2",
"loggingConfiguration":{
"level":"ALL",
"includeExecutionData":true,
"destinations":[{
"cloudWatchLogsLogGroup":{
"logGroupArn":"arn:aws:logs:us-east-1:000000000000:log-group:version:*"
}
}]
},
"tracingConfiguration":{"enabled":true},
"encryptionConfiguration":{
"type":"CUSTOMER_MANAGED_KMS_KEY",
"kmsKeyId":"alias/version-key",
"kmsDataKeyReusePeriodSeconds":120
},
"publish":true,
"versionDescription":"first update"
}
""".formatted(arn, DEF2));
published.then().statusCode(200)
.body("updateDate", notNullValue())
.body("revisionId", notNullValue())
.body("stateMachineVersionArn", containsString(arn + ":1"));
String versionArn = published.jsonPath().getString("stateMachineVersionArn");
String versionRevision = published.jsonPath().getString("revisionId");
call("UpdateStateMachine", """
{
"stateMachineArn":"%s",
"definition":"%s",
"roleArn":"arn:aws:iam::000000000000:role/r3",
"loggingConfiguration":{
"level":"OFF",
"includeExecutionData":false,
"destinations":[]
},
"tracingConfiguration":{"enabled":false},
"encryptionConfiguration":{"type":"AWS_OWNED_KEY"}
}
""".formatted(arn, DEF))
.then().statusCode(200);
call("DescribeStateMachine", "{\"stateMachineArn\":\"" + versionArn + "\"}")
.then().statusCode(200)
.body("stateMachineArn", is(versionArn))
.body("creationDate", notNullValue())
.body("definition", containsString("\"Wait\""))
.body("roleArn", is("arn:aws:iam::000000000000:role/r2"))
.body("revisionId", is(versionRevision))
.body("description", is("first update"))
.body("loggingConfiguration.level", is("ALL"))
.body("loggingConfiguration.includeExecutionData", is(true))
.body("tracingConfiguration.enabled", is(true))
.body("encryptionConfiguration.type", is("CUSTOMER_MANAGED_KMS_KEY"))
.body("encryptionConfiguration.kmsKeyId", is("alias/version-key"))
.body("encryptionConfiguration.kmsDataKeyReusePeriodSeconds", is(120));
call("DescribeStateMachine", "{\"stateMachineArn\":\"" + arn + "\"}")
.then().statusCode(200)
.body("definition", containsString("\"Pass\""))
.body("roleArn", is("arn:aws:iam::000000000000:role/r3"))
.body("loggingConfiguration.level", is("OFF"))
.body("tracingConfiguration.enabled", is(false))
.body("encryptionConfiguration.type", is("AWS_OWNED_KEY"));
call("DeleteStateMachineVersion",
"{\"stateMachineVersionArn\":\"" + versionArn + "\"}")
.then().statusCode(200);
call("DescribeStateMachine", "{\"stateMachineArn\":\"" + versionArn + "\"}")
.then().statusCode(400)
.body(containsString("StateMachineDoesNotExist"));
}
@Test
void updateValidatesRequiredAndMalformedArns() {
call("UpdateStateMachine", "{\"definition\":\"" + DEF2 + "\"}")
.then().statusCode(400).body(containsString("MissingRequiredParameter"));
call("UpdateStateMachine", "{\"stateMachineArn\":\"\",\"definition\":\"" + DEF2 + "\"}")
.then().statusCode(400).body(containsString("InvalidArn"));
call("UpdateStateMachine", "{\"stateMachineArn\":\"not-an-arn\",\"definition\":\""
+ DEF2 + "\"}")
.then().statusCode(400).body(containsString("InvalidArn"));
call("UpdateStateMachine", "{\"stateMachineArn\":42,\"definition\":\"" + DEF2 + "\"}")
.then().statusCode(400).body(containsString("ValidationException"));
String distributedMapArn =
"arn:aws:states:us-east-1:000000000000:stateMachine:machine/map-label";
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + distributedMapArn
+ "\",\"definition\":\"" + DEF2 + "\"}")
.then().statusCode(400).body(containsString("ValidationException"));
}
@Test
void rejectedInputsDoNotMutateTheStateMachine() {
String arn = createStateMachine("upd-invalid-" + System.currentTimeMillis());
String initialRevision = call(
"DescribeStateMachine", "{\"stateMachineArn\":\"" + arn + "\"}")
.then().statusCode(200).extract().jsonPath().getString("revisionId");
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn + "\",\"roleArn\":\"\"}")
.then().statusCode(400).body(containsString("InvalidArn"));
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn
+ "\",\"roleArn\":\"arn:aws:s3:::not-a-role\"}")
.then().statusCode(400).body(containsString("InvalidArn"));
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn + "\",\"definition\":\"\"}")
.then().statusCode(400).body(containsString("InvalidDefinition"));
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn
+ "\",\"definition\":\"{}\"}")
.then().statusCode(400).body(containsString("InvalidDefinition"));
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn
+ "\",\"definition\":\"{\\\"States\\\":{\\\"A\\\":{"
+ "\\\"Type\\\":\\\"Pass\\\",\\\"End\\\":true}}}\"}")
.then().statusCode(400).body(containsString("InvalidDefinition"));
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn
+ "\",\"definition\":\"{\\\"StartAt\\\":\\\"A\\\","
+ "\\\"States\\\":{\\\"A\\\":{\\\"End\\\":true}}}\"}")
.then().statusCode(400).body(containsString("InvalidDefinition"));
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn + "\",\"definition\":\""
+ DEF2 + "\",\"loggingConfiguration\":{\"level\":\"TRACE\"}}")
.then().statusCode(400).body(containsString("InvalidLoggingConfiguration"));
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn + "\",\"definition\":\""
+ DEF2 + "\",\"tracingConfiguration\":{\"enabled\":\"yes\"}}")
.then().statusCode(400).body(containsString("InvalidTracingConfiguration"));
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn + "\",\"definition\":\""
+ DEF2
+ "\",\"encryptionConfiguration\":{\"type\":\"CUSTOMER_MANAGED_KMS_KEY\"}}")
.then().statusCode(400).body(containsString("InvalidEncryptionConfiguration"));
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn + "\",\"definition\":\""
+ DEF2 + "\",\"versionDescription\":\"not published\"}")
.then().statusCode(400).body(containsString("ValidationException"));
Response after = call(
"DescribeStateMachine", "{\"stateMachineArn\":\"" + arn + "\"}");
after.then().statusCode(200)
.body("definition", containsString("\"Pass\""))
.body("roleArn", is("arn:aws:iam::000000000000:role/r1"));
assertEquals(initialRevision, after.jsonPath().getString("revisionId"));
}
@Test
void updateRotatesRevisionAndRoundTripsConfigurations() {
String arn = createStateMachine("upd-config-" + System.currentTimeMillis());
Response initial = call(
"DescribeStateMachine", "{\"stateMachineArn\":\"" + arn + "\"}");
initial.then().statusCode(200)
.body("loggingConfiguration.level", is("OFF"))
.body("loggingConfiguration.includeExecutionData", is(false))
.body("loggingConfiguration.destinations.size()", is(0))
.body("tracingConfiguration.enabled", is(false))
.body("encryptionConfiguration.type", is("AWS_OWNED_KEY"));
String initialRevision = initial.jsonPath().getString("revisionId");
Response update = call("UpdateStateMachine", """
{
"stateMachineArn":"%s",
"definition":"%s",
"loggingConfiguration":{
"level":"ALL",
"includeExecutionData":true,
"destinations":[{
"cloudWatchLogsLogGroup":{
"logGroupArn":"arn:aws:logs:us-east-1:000000000000:log-group:sfn:*"
}
}]
},
"tracingConfiguration":{"enabled":true},
"encryptionConfiguration":{
"type":"CUSTOMER_MANAGED_KMS_KEY",
"kmsKeyId":"alias/sfn-key",
"kmsDataKeyReusePeriodSeconds":120
}
}
""".formatted(arn, DEF2));
update.then().statusCode(200).body("revisionId", notNullValue());
String updatedRevision = update.jsonPath().getString("revisionId");
assertNotEquals(initialRevision, updatedRevision);
call("DescribeStateMachine", "{\"stateMachineArn\":\"" + arn + "\"}")
.then().statusCode(200)
.body("revisionId", is(updatedRevision))
.body("loggingConfiguration.level", is("ALL"))
.body("loggingConfiguration.includeExecutionData", is(true))
.body("tracingConfiguration.enabled", is(true))
.body("encryptionConfiguration.type", is("CUSTOMER_MANAGED_KMS_KEY"))
.body("encryptionConfiguration.kmsKeyId", is("alias/sfn-key"))
.body("encryptionConfiguration.kmsDataKeyReusePeriodSeconds", is(120));
call("DescribeStateMachine",
"{\"stateMachineArn\":\"" + arn + "\",\"includedData\":\"METADATA_ONLY\"}")
.then().statusCode(200)
.body("definition", is("{}"))
.body("encryptionConfiguration.type", is("CUSTOMER_MANAGED_KMS_KEY"));
call("DescribeStateMachine",
"{\"stateMachineArn\":\"" + arn + "\",\"includedData\":\"ALL_DATA\"}")
.then().statusCode(200)
.body("definition", containsString("\"Wait\""));
call("DescribeStateMachine",
"{\"stateMachineArn\":\"" + arn + "\",\"includedData\":\"INVALID\"}")
.then().statusCode(400)
.body(containsString("ValidationException"));
call("DescribeStateMachine",
"{\"stateMachineArn\":\"" + arn + "\",\"includedData\":42}")
.then().statusCode(400)
.body(containsString("ValidationException"));
}
@Test
void createRejectsUnsupportedStateMachineTypeBeforePersistence() {
String name = "invalid-type-" + System.currentTimeMillis();
call("CreateStateMachine",
"{\"name\":\"" + name + "\",\"definition\":\"" + DEF
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r1\","
+ "\"type\":\"BASIC\"}")
.then().statusCode(400)
.body(containsString("StateMachineTypeNotSupported"));
call("DescribeStateMachine", "{\"stateMachineArn\":"
+ "\"arn:aws:states:us-east-1:000000000000:stateMachine:" + name + "\"}")
.then().statusCode(400)
.body(containsString("StateMachineDoesNotExist"));
}
@Test
void describeValidatesRequiredAndQualifiedArns() {
call("DescribeStateMachine", "{}")
.then().statusCode(400)
.body(containsString("MissingRequiredParameter"));
call("DescribeStateMachine", "{\"stateMachineArn\":42}")
.then().statusCode(400)
.body(containsString("ValidationException"));
call("DescribeStateMachine", "{\"stateMachineArn\":\"not-an-arn\"}")
.then().statusCode(400)
.body(containsString("InvalidArn"));
call("DescribeStateMachine", "{\"stateMachineArn\":"
+ "\"arn:aws:states:us-east-1:000000000000:"
+ "stateMachine:machine/map-label\"}")
.then().statusCode(400)
.body(containsString("ValidationException"));
}
}
@@ -11,6 +11,7 @@ import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* State machine version APIs — the Terraform AWS provider calls ListStateMachineVersions after
@@ -58,19 +59,25 @@ class StepFunctionsVersionsIntegrationTest {
}
@Test
void listVersionsAreReturnedNewestFirst() {
void publishIsIdempotentPerRevisionAndVersionsAreReturnedNewestFirst() {
String name = "ver-order-" + System.currentTimeMillis();
String arn = call("CreateStateMachine",
"{\"name\":\"" + name + "\",\"definition\":\"" + DEF + "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r\"}")
.then().statusCode(200).extract().jsonPath().getString("stateMachineArn");
// Publish three versions (1, 2, 3). AWS lists them newest first, and the Terraform provider
// reads the version ARN off this list, so the order must be descending — even though the three
// publishes land within the same (second-resolution) creationDate, the version-number tie-break
// keeps 3 ahead of 2 ahead of 1.
call("PublishStateMachineVersion", "{\"stateMachineArn\":\"" + arn + "\"}").then().statusCode(200);
call("PublishStateMachineVersion", "{\"stateMachineArn\":\"" + arn + "\"}").then().statusCode(200);
call("PublishStateMachineVersion", "{\"stateMachineArn\":\"" + arn + "\"}").then().statusCode(200);
// Re-publishing the same revision is idempotent and returns the existing version.
call("PublishStateMachineVersion", "{\"stateMachineArn\":\"" + arn + "\"}")
.then().statusCode(200).body("stateMachineVersionArn", is(arn + ":1"));
call("PublishStateMachineVersion", "{\"stateMachineArn\":\"" + arn + "\"}")
.then().statusCode(200).body("stateMachineVersionArn", is(arn + ":1"));
// Each update creates a new revision, so publishing those revisions advances the version.
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r2\",\"publish\":true}")
.then().statusCode(200).body("stateMachineVersionArn", is(arn + ":2"));
call("UpdateStateMachine", "{\"stateMachineArn\":\"" + arn
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r3\",\"publish\":true}")
.then().statusCode(200).body("stateMachineVersionArn", is(arn + ":3"));
call("ListStateMachineVersions", "{\"stateMachineArn\":\"" + arn + "\"}")
.then().statusCode(200)
@@ -91,10 +98,139 @@ class StepFunctionsVersionsIntegrationTest {
@Test
void createWithPublishReturnsVersionArn() {
String name = "ver-pub-" + System.currentTimeMillis();
call("CreateStateMachine",
"{\"name\":\"" + name + "\",\"definition\":\"" + DEF + "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r\",\"publish\":true}")
String arn = call("CreateStateMachine",
"{\"name\":\"" + name + "\",\"definition\":\"" + DEF
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r\","
+ "\"publish\":true,\"versionDescription\":\"initial release\"}")
.then().statusCode(200)
.body("stateMachineVersionArn", not(emptyOrNullString()))
.body("stateMachineVersionArn", containsString(":1"));
.body("stateMachineVersionArn", containsString(":1"))
.extract().jsonPath().getString("stateMachineArn");
call("ListStateMachineVersions", "{\"stateMachineArn\":\"" + arn + "\"}")
.then().statusCode(200)
.body("stateMachineVersions.size()", is(1))
.body("stateMachineVersions[0].stateMachineVersionArn", is(arn + ":1"));
call("DescribeStateMachine", "{\"stateMachineArn\":\"" + arn + ":1\"}")
.then().statusCode(200)
.body("description", is("initial release"));
}
@Test
void createWithoutPublishReturnsExplicitNullVersionArn() {
String name = "ver-unpublished-" + System.currentTimeMillis();
Response response = call("CreateStateMachine",
"{\"name\":\"" + name + "\",\"definition\":\"" + DEF
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r\"}")
.then().statusCode(200)
.extract().response();
assertTrue(response.asString().contains("\"stateMachineVersionArn\":null"));
}
@Test
void createIsIdempotentForAwsContractFieldsAndIgnoresRoleAndTags() {
String name = "ver-create-idempotent-" + System.currentTimeMillis();
String originalRequest = "{\"name\":\"" + name + "\",\"definition\":\"" + DEF
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/original\","
+ "\"tags\":[{\"key\":\"owner\",\"value\":\"original\"}],"
+ "\"publish\":true,\"versionDescription\":\"initial release\"}";
String arn = call("CreateStateMachine", originalRequest)
.then().statusCode(200)
.body("stateMachineVersionArn", containsString(":1"))
.extract().jsonPath().getString("stateMachineArn");
call("CreateStateMachine",
"{\"name\":\"" + name + "\",\"definition\":\"" + DEF
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/ignored\","
+ "\"tags\":[{\"key\":\"owner\",\"value\":\"ignored\"}],"
+ "\"publish\":true,\"versionDescription\":\"initial release\"}")
.then().statusCode(200)
.body("stateMachineArn", is(arn))
.body("stateMachineVersionArn", is(arn + ":1"));
call("DescribeStateMachine", "{\"stateMachineArn\":\"" + arn + "\"}")
.then().statusCode(200)
.body("roleArn", is("arn:aws:iam::000000000000:role/original"));
call("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")
.then().statusCode(200)
.body("tags.size()", is(1))
.body("tags[0].key", is("owner"))
.body("tags[0].value", is("original"));
call("CreateStateMachine",
"{\"name\":\"" + name + "\",\"definition\":\"" + DEF
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/original\","
+ "\"publish\":true,\"versionDescription\":\"different\"}")
.then().statusCode(400)
.body(containsString("StateMachineAlreadyExists"));
call("CreateStateMachine",
"{\"name\":\"" + name + "\",\"definition\":\"" + DEF
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/original\","
+ "\"tracingConfiguration\":{\"enabled\":true},"
+ "\"publish\":true,\"versionDescription\":\"initial release\"}")
.then().statusCode(400)
.body(containsString("StateMachineAlreadyExists"));
call("CreateStateMachine",
"{\"name\":\"" + name + "\",\"definition\":\"" + DEF
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/original\"}")
.then().statusCode(400)
.body(containsString("StateMachineAlreadyExists"));
}
@Test
void publishHonorsRevisionAndDescriptionContract() {
String name = "ver-revision-" + System.currentTimeMillis();
String arn = call("CreateStateMachine",
"{\"name\":\"" + name + "\",\"definition\":\"" + DEF
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r\"}")
.then().statusCode(200)
.extract().jsonPath().getString("stateMachineArn");
String revision = call(
"DescribeStateMachine",
"{\"stateMachineArn\":\"" + arn + "\"}")
.then().statusCode(200)
.extract().jsonPath().getString("revisionId");
call("PublishStateMachineVersion",
"{\"stateMachineArn\":\"" + arn + "\",\"revisionId\":\""
+ revision + "\",\"description\":\"first revision\"}")
.then().statusCode(200)
.body("stateMachineVersionArn", is(arn + ":1"));
call("PublishStateMachineVersion",
"{\"stateMachineArn\":\"" + arn + "\",\"revisionId\":\""
+ revision + "\",\"description\":\"ignored replay\"}")
.then().statusCode(200)
.body("stateMachineVersionArn", is(arn + ":1"));
call("DescribeStateMachine", "{\"stateMachineArn\":\"" + arn + ":1\"}")
.then().statusCode(200)
.body("description", is("first revision"));
call("PublishStateMachineVersion",
"{\"stateMachineArn\":\"" + arn
+ "\",\"revisionId\":\"00000000-0000-0000-0000-000000000000\"}")
.then().statusCode(409)
.body(containsString("ConflictException"));
}
@Test
void invalidCreatePublishOptionsAndNamesAreRejectedBeforeStorage() {
String name = "ver-invalid-publish-" + System.currentTimeMillis();
String baseRequest = "{\"name\":\"" + name + "\",\"definition\":\"" + DEF
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r\"";
call("CreateStateMachine",
baseRequest + ",\"versionDescription\":\"requires publish\"}")
.then().statusCode(400)
.body(containsString("ValidationException"));
call("CreateStateMachine", baseRequest + "}")
.then().statusCode(200)
.body("stateMachineArn", containsString(name));
call("CreateStateMachine",
"{\"name\":\"invalid name\",\"definition\":\"" + DEF
+ "\",\"roleArn\":\"arn:aws:iam::000000000000:role/r\"}")
.then().statusCode(400)
.body(containsString("InvalidName"));
}
}