From 03d33350a7da40fcc85d68b1b5dd3e2286ae91c0 Mon Sep 17 00:00:00 2001 From: Niels Kootstra <545768+nkootstra@users.noreply.github.com> Date: Wed, 16 Sep 2026 00:35:53 +0200 Subject: [PATCH] fix(cloudformation): claim change set atomically before execution (#3564) * fix(cloudformation): claim change set atomically before execution ExecuteChangeSet checked that a change set was AVAILABLE and executed it as two separate steps, with no lock held in between. Two concurrent ExecuteChangeSet requests for the same change set could both pass the AVAILABLE check before either flipped the status, so both would submit the template for provisioning and create every resource in the stack twice. The internal 4-arg executeChangeSet that CreateStack/UpdateStack call directly had the same race against an external ExecuteChangeSet call for the same change set, for example "initial-create" right after CreateStack creates it. Unify both entry points behind one atomic claim, claimAndSubmitExecution, using the same ConcurrentHashMap#compute() idiom createChangeSet already uses for its own check-then-insert race. The request path requires ExecutionStatus AVAILABLE, matching AWS; the internal path only refuses a change set whose execution has already started or finished, so a failed SAM transform can still reach CREATE_FAILED. Inside the same claim, every other change set on the stack is deleted, matching AWS's documented ExecuteChangeSet behavior that executing a change set deletes every other change set on that stack. After the background execution finishes, the claimed change set's ExecutionStatus is set to a terminal EXECUTE_COMPLETE or EXECUTE_FAILED so DescribeChangeSet stops reporting EXECUTE_IN_PROGRESS forever. The rejection message now reports the execution status that actually caused the rejection instead of the change set's unrelated Status field. * fix(cloudformation): mark pending change sets obsolete on direct stack updates --- .../cloudformation/CloudFormationService.java | 103 ++++-- ...teChangeSetConcurrencyIntegrationTest.java | 307 ++++++++++++++++++ 2 files changed, 379 insertions(+), 31 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationExecuteChangeSetConcurrencyIntegrationTest.java diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index c86fb2e2f0..6ed211d358 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -620,19 +620,7 @@ public class CloudFormationService implements ResourceProvider { * that failure surfaces on those paths, and floci must still expose it there. */ public Future> executeChangeSetForRequest(String stackName, String changeSetName, String region) { - Stack stack = getStackOrThrow(stackName, region, regionResolver.getAccountId()); - ChangeSet cs = stack.getChangeSets().get(resolveChangeSetName( - changeSetName, region, regionResolver.getAccountId())); - if (cs == null) { - throw new AwsException("ChangeSetNotFoundException", - "ChangeSet [" + changeSetName + "] does not exist", 400); - } - if (!"AVAILABLE".equals(cs.getExecutionStatus())) { - throw new AwsException("InvalidChangeSetStatus", - "ChangeSet [" + cs.getChangeSetId() + "] cannot be executed in its current " - + "status of [" + cs.getStatus() + "]", 400); - } - return executeChangeSet(stackName, changeSetName, region, regionResolver.getAccountId()); + return claimAndSubmitExecution(stackName, changeSetName, region, regionResolver.getAccountId(), true); } /** @@ -643,33 +631,86 @@ public class CloudFormationService implements ResourceProvider { * are materialized under a synthetic request scope bound to {@code accountId} so a single-stack * deployment lands in the caller's account, and a StackSet instance lands in its target account. * - *
Unlike {@link #executeChangeSetForRequest}, this does not refuse a non-{@code AVAILABLE} - * change set: {@code CreateStack}/{@code UpdateStack} call this directly right after creating - * their own change set, and must still reach {@code CREATE_FAILED} (or its update equivalent) - * when that change set failed, for example from a failed SAM transform. + *
Unlike {@link #executeChangeSetForRequest}, this does not require the change set to be
+ * {@code AVAILABLE}: {@code CreateStack}/{@code UpdateStack} call this directly right after
+ * creating their own change set, and must still reach {@code CREATE_FAILED} (or its update
+ * equivalent) when that change set failed, for example from a failed SAM transform. It still
+ * refuses one that is already executing or has already executed.
*/
public Future> executeChangeSet(String stackName, String changeSetName, String region, String accountId) {
- Stack stack = getStackOrThrow(stackName, region, accountId);
- ChangeSet cs = stack.getChangeSets().get(resolveChangeSetName(changeSetName, region, accountId));
- if (cs == null) {
- throw new AwsException("ChangeSetNotFoundException",
- "ChangeSet [" + changeSetName + "] does not exist", 400);
- }
+ return claimAndSubmitExecution(stackName, changeSetName, region, accountId, false);
+ }
- boolean isCreate = "CREATE".equalsIgnoreCase(cs.getChangeSetType()) ||
- "CREATE_IN_PROGRESS".equals(stack.getStatus());
+ private record ClaimedExecution(ChangeSet changeSet, boolean isCreate) {}
- stack.setStatus(isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS");
- stack.setLastUpdatedTime(now());
- addEvent(stack, stack.getStackName(), stack.getStackId(),
- "AWS::CloudFormation::Stack", isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS", null);
+ // compute() holds the stack's per-key lock for the whole claim, so only one racing execution can win.
+ private Future> claimAndSubmitExecution(String stackNameOrArn, String changeSetName, String region,
+ String accountId, boolean requireAvailable) {
+ String canonicalStackName = getStackOrThrow(stackNameOrArn, region, accountId).getStackName();
+ String resolvedChangeSetName = resolveChangeSetName(changeSetName, region, accountId);
+
+ ClaimedExecution[] claimed = new ClaimedExecution[1];
+ Stack stack = stacks.compute(stackKey(accountId, canonicalStackName, region), (k, existing) -> {
+ if (existing == null) {
+ throw new AwsException("ValidationError",
+ "Stack with id " + stackNameOrArn + " does not exist", 400);
+ }
+ ChangeSet cs = existing.getChangeSets().get(resolvedChangeSetName);
+ if (cs == null) {
+ throw new AwsException("ChangeSetNotFoundException",
+ "ChangeSet [" + changeSetName + "] does not exist", 400);
+ }
+ String executionStatus = cs.getExecutionStatus();
+ boolean eligible = requireAvailable
+ ? "AVAILABLE".equals(executionStatus)
+ : executionStatus == null || !executionStatus.startsWith("EXECUTE_");
+ if (!eligible) {
+ throw invalidChangeSetStatus(cs);
+ }
+ boolean isCreate = "CREATE".equalsIgnoreCase(cs.getChangeSetType()) ||
+ "CREATE_IN_PROGRESS".equals(existing.getStatus());
+ cs.setExecutionStatus("EXECUTE_IN_PROGRESS");
+ if (requireAvailable) {
+ // CloudFormation deletes every other change set on the stack once one of them executes.
+ existing.getChangeSets().values().removeIf(other -> other != cs);
+ } else {
+ for (ChangeSet other : existing.getChangeSets().values()) {
+ if (other != cs && "AVAILABLE".equals(other.getExecutionStatus())) {
+ other.setExecutionStatus("OBSOLETE");
+ }
+ }
+ }
+ existing.setStatus(isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS");
+ existing.setLastUpdatedTime(now());
+ addEvent(existing, existing.getStackName(), existing.getStackId(),
+ "AWS::CloudFormation::Stack", isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS", null);
+ claimed[0] = new ClaimedExecution(cs, isCreate);
+ return existing;
+ });
persistStack(stack);
+ return submitExecution(stack, claimed[0].changeSet(), claimed[0].isCreate(), region, accountId);
+ }
+
+ private AwsException invalidChangeSetStatus(ChangeSet cs) {
+ String detail = "FAILED".equals(cs.getStatus())
+ ? "status of [" + cs.getStatus() + "]"
+ : "execution status of [" + cs.getExecutionStatus() + "]";
+ return new AwsException("InvalidChangeSetStatus",
+ "ChangeSet [" + cs.getChangeSetId() + "] cannot be executed in its current " + detail, 400);
+ }
+
+ private Future> submitExecution(Stack stack, ChangeSet cs, boolean isCreate, String region, String accountId) {
String templateBody = cs.getTemplateBody();
MapInvalidChangeSetStatus"));
+ assertTrue(rejectedBody.contains("execution status of [EXECUTE_IN_PROGRESS]")
+ || rejectedBody.contains("execution status of [EXECUTE_COMPLETE]"), rejectedBody);
+
+ waitForStackStatus(stackName, "CREATE_COMPLETE");
+ assertEquals(1, countTopicsWithPrefix(stackName + "-Topic-"), "expected exactly one topic provisioned");
+ }
+
+ @Test
+ void executeChangeSet_afterCompletion_rejectsSecondExecution() {
+ String stackName = uniqueStackName("reexec");
+ createChangeSet(stackName, "initial", "CREATE", topicTemplate("Topic")).then().statusCode(200);
+ executeChangeSet(stackName, "initial").then().statusCode(200);
+ waitForStackStatus(stackName, "CREATE_COMPLETE");
+
+ assertEquals("EXECUTE_COMPLETE", describeChangeSetExecutionStatus(stackName, "initial"));
+
+ Response second = executeChangeSet(stackName, "initial");
+ second.then().statusCode(400).body(containsString("InvalidChangeSetStatus"));
+ assertThat(second.asString(), containsString("execution status of [EXECUTE_COMPLETE]"));
+
+ assertEquals(1, countTopicsWithPrefix(stackName + "-Topic-"));
+ }
+
+ @Test
+ void executeChangeSet_deletesOtherChangeSetsOnTheStack() {
+ String stackName = uniqueStackName("delete-siblings");
+ createChangeSet(stackName, "initial", "CREATE", topicTemplate("Base")).then().statusCode(200);
+ executeChangeSet(stackName, "initial").then().statusCode(200);
+ waitForStackStatus(stackName, "CREATE_COMPLETE");
+
+ createChangeSet(stackName, "update-a", "UPDATE", twoTopicTemplate("Base", "TopicA")).then().statusCode(200);
+ createChangeSet(stackName, "update-b", "UPDATE", twoTopicTemplate("Base", "TopicB")).then().statusCode(200);
+
+ executeChangeSet(stackName, "update-a").then().statusCode(200);
+ waitForStackStatus(stackName, "UPDATE_COMPLETE");
+
+ describeChangeSet(stackName, "update-b").then().statusCode(400)
+ .body(containsString("ChangeSetNotFoundException"));
+ executeChangeSet(stackName, "update-b").then().statusCode(400)
+ .body(containsString("ChangeSetNotFoundException"));
+
+ assertEquals("EXECUTE_COMPLETE", describeChangeSetExecutionStatus(stackName, "update-a"));
+
+ assertEquals(1, countTopicsWithPrefix(stackName + "-TopicA-"));
+ assertEquals(0, countTopicsWithPrefix(stackName + "-TopicB-"));
+ }
+
+ @Test
+ void executeChangeSet_afterCreateStack_rejectsInitialCreateChangeSet() {
+ String stackName = uniqueStackName("internal");
+ createStack(stackName, topicTemplate("Topic"));
+
+ Response rejected = executeChangeSet(stackName, "initial-create");
+ rejected.then().statusCode(400).body(containsString("InvalidChangeSetStatus"));
+ assertThat(rejected.asString(), containsString("execution status of [EXECUTE_"));
+ }
+
+ @Test
+ void updateStack_marksPendingChangeSetsObsolete() {
+ String stackName = uniqueStackName("obsolete");
+ createStack(stackName, topicTemplate("Base"));
+ waitForStackStatus(stackName, "CREATE_COMPLETE");
+ createChangeSet(stackName, "pending", "UPDATE", twoTopicTemplate("Base", "TopicA")).then().statusCode(200);
+
+ updateStack(stackName, twoTopicTemplate("Base", "TopicB"));
+ waitForStackStatus(stackName, "UPDATE_COMPLETE");
+
+ assertEquals("OBSOLETE", describeChangeSetExecutionStatus(stackName, "pending"));
+ Response rejected = executeChangeSet(stackName, "pending");
+ rejected.then().statusCode(400).body(containsString("InvalidChangeSetStatus"));
+ assertThat(rejected.asString(), containsString("execution status of [OBSOLETE]"));
+ assertEquals(0, countTopicsWithPrefix(stackName + "-TopicA-"));
+ }
+
+ private String uniqueStackName(String prefix) {
+ String name = "cfn-execute-" + prefix + "-" + Long.toString(System.nanoTime(), 36);
+ stacksToDelete.add(name);
+ return name;
+ }
+
+ private static String topicTemplate(String logicalId) {
+ return """
+ Resources:
+ %s:
+ Type: AWS::SNS::Topic
+ """.formatted(logicalId);
+ }
+
+ private static String twoTopicTemplate(String logicalId1, String logicalId2) {
+ return """
+ Resources:
+ %s:
+ Type: AWS::SNS::Topic
+ %s:
+ Type: AWS::SNS::Topic
+ """.formatted(logicalId1, logicalId2);
+ }
+
+ private static Response createChangeSet(String stackName, String changeSetName, String changeSetType, String template) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateChangeSet")
+ .formParam("StackName", stackName)
+ .formParam("ChangeSetName", changeSetName)
+ .formParam("ChangeSetType", changeSetType)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/");
+ }
+
+ private static void createStack(String stackName, String template) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private static void updateStack(String stackName, String template) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private static Response executeChangeSet(String stackName, String changeSetName) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ExecuteChangeSet")
+ .formParam("StackName", stackName)
+ .formParam("ChangeSetName", changeSetName)
+ .when()
+ .post("/");
+ }
+
+ private static Response describeChangeSet(String stackName, String changeSetName) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeChangeSet")
+ .formParam("StackName", stackName)
+ .formParam("ChangeSetName", changeSetName)
+ .when()
+ .post("/");
+ }
+
+ private static String describeChangeSetExecutionStatus(String stackName, String changeSetName) {
+ return describeChangeSet(stackName, changeSetName)
+ .then()
+ .statusCode(200)
+ .extract()
+ .xmlPath()
+ .getString("DescribeChangeSetResponse.DescribeChangeSetResult.ExecutionStatus");
+ }
+
+ private static long countTopicsWithPrefix(String prefix) {
+ List