Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(cloudformation): honor resource-level conditions (#2255)

z9rtm8ef71d693029
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 100c5463c2..dba8a3e914 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
@@ -143,8 +143,30 @@ public class CloudFormationService {
String templateBody, String templateUrl,
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region) {
+ return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
+ parameters, capabilities, tags, region, regionResolver.getAccountId());
+ }
+
+ /**
+ * Creates a change set whose condition-dependency preflight is evaluated in {@code accountId}'s
+ * context. This matters for StackSet deployments: {@code createChangeSet} runs in the
+ * administrator request scope, but the instance is executed in the target account, so a
+ * condition using {@code AWS::AccountId} must be preflighted against the same target account the
+ * execution will use. Otherwise a resource that is active in the target account is wrongly seen
+ * as excluded and its dependents fail with a spurious "Unresolved resource dependencies" error.
+ * This parameter changes only the preflight context; change-set and stack identifiers created here
+ * remain scoped to the caller account, and the execution account is supplied separately.
+ */
+ public ChangeSet createChangeSet(String stackName, String changeSetName, String changeSetType,
+ String templateBody, String templateUrl,
+ Map<String, String> parameters, List<String> capabilities,
+ Map<String, String> tags, String region, String accountId) {
String resolvedTemplate = resolveTemplate(templateBody, templateUrl);
+ // Reject an unresolvable condition dependency graph up front, before any stack state is
+ // created, so CreateStack/UpdateStack fail synchronously the way real CloudFormation does.
+ validateConditionDependencies(resolvedTemplate, parameters, region, accountId);
+
// Detect first creation atomically: the mapping function runs at most once per key, so the
// flag is only set for the thread that actually creates the stack (no double-recording under
// concurrent CreateChangeSet calls).
@@ -715,19 +737,21 @@ public class CloudFormationService {
// resources are deleted during replacement cleanup.
persistStack(stack);
}
+ // Both cleanup paths feed the single final status/reason writer.
List<UpdateCleanupFailure> cleanupFailures =
- finishCommittedResourceCleanup(stack);
+ new ArrayList<>(deleteInactiveConditionResources(
+ stack, resources, conditions, region));
+ cleanupFailures.addAll(finishCommittedResourceCleanup(stack));
finishCommittedStackUpdate(stack, cleanupFailures);
return;
}
- String completeStatus = isCreate ? "CREATE_COMPLETE" : "UPDATE_COMPLETE";
- stack.setStatus(completeStatus);
+ stack.setStatus("CREATE_COMPLETE");
stack.setLastUpdatedTime(now());
addEvent(stack, stack.getStackName(), stack.getStackId(),
- "AWS::CloudFormation::Stack", completeStatus, null);
+ "AWS::CloudFormation::Stack", "CREATE_COMPLETE", null);
persistStack(stack);
- LOG.infov("Stack {0} execution complete: {1}", stack.getStackName(), completeStatus);
+ LOG.infov("Stack {0} execution complete: CREATE_COMPLETE", stack.getStackName());
} catch (Exception e) {
if (!isCreate && updateCommitted) {
@@ -1114,6 +1138,69 @@ public class CloudFormationService {
return failedResources;
}
+ /**
+ * Removes resources that were provisioned by an earlier execution but whose resource-level
+ * {@code Condition} is false in the current template. Physical deletion honors the resource's
+ * deletion policy. A failed physical deletion leaves the resource in the underlying service and
+ * keeps it under stack management as {@code DELETE_FAILED}, so a later {@code DeleteStack} or
+ * {@code UpdateStack} can retry the cleanup instead of orphaning the backing resource.
+ * Resources removed from the template entirely are outside this condition-specific cleanup.
+ *
+ * @return one {@link UpdateCleanupFailure} per resource whose physical deletion failed
+ */
+ private List<UpdateCleanupFailure> deleteInactiveConditionResources(Stack stack, JsonNode resources,
+ Map<String, Boolean> conditions, String region) {
+ if (!resources.isObject()) {
+ return List.of();
+ }
+
+ List<UpdateCleanupFailure> failures = new ArrayList<>();
+ List<StackResource> ordered = new ArrayList<>(stack.getResources().values());
+ Collections.reverse(ordered);
+ for (StackResource resource : ordered) {
+ JsonNode resDef = resources.get(resource.getLogicalId());
+ if (resDef == null) {
+ continue;
+ }
+ String condition = resDef.path("Condition").asText(null);
+ if (condition == null || conditions.getOrDefault(condition, false)) {
+ continue;
+ }
+
+ if (resource.getPhysicalId() == null || skipRetainedResource(stack, resource, false)) {
+ stack.getResources().remove(resource.getLogicalId());
+ continue;
+ }
+
+ addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
+ resource.getResourceType(), "DELETE_IN_PROGRESS", null);
+ try {
+ provisioner.delete(resource, region);
+ addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
+ resource.getResourceType(), "DELETE_COMPLETE", null);
+ stack.getResources().remove(resource.getLogicalId());
+ } catch (Exception e) {
+ String reason = e.getMessage() != null
+ ? e.getMessage()
+ : "Resource deletion failed during update cleanup";
+ failures.add(new UpdateCleanupFailure(
+ resource.getLogicalId(), resource.getPhysicalId(), reason));
+ // Keep the resource under stack management as DELETE_FAILED. Removing it here would
+ // drop it from DescribeStackResources while the backing resource still exists,
+ // orphaning it and preventing a later DeleteStack/UpdateStack from retrying cleanup.
+ resource.setStatus("DELETE_FAILED");
+ resource.setStatusReason(reason);
+ addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
+ resource.getResourceType(), "DELETE_FAILED", reason);
+ LOG.warnv("Failed to delete condition-disabled {0} ({1}) in stack {2}: {3}",
+ resource.getResourceType(), resource.getPhysicalId(),
+ stack.getStackName(), reason);
+ }
+ }
+
+ return failures;
+ }
+
private void deleteStackResources(Stack stack, String region) {
try {
List<StackResource> resources = new ArrayList<>(stack.getResources().values());
@@ -1222,6 +1309,54 @@ public class CloudFormationService {
return conditions;
}
+ /**
+ * Fails a create/update before any stack state is mutated when a resource that will be created
+ * depends on a resource excluded by a false condition. Real CloudFormation rejects such a
+ * template synchronously ("Template format error: Unresolved resource dependencies [...]")
+ * rather than silently skipping the dependent, so mirror that instead of dropping the resource.
+ * Malformed or SAM templates are left for the execution path, which surfaces their own errors.
+ */
+ private void validateConditionDependencies(String templateBody, Map<String, String> params,
+ String region, String accountId) {
+ JsonNode template;
+ try {
+ template = parseTemplate(templateBody);
+ } catch (Exception e) {
+ LOG.debugv("Skipping condition-dependency validation; template did not parse: {0}",
+ e.getMessage());
+ return;
+ }
+ if (samTransformProcessor.hasSamTransform(template)) {
+ return;
+ }
+ JsonNode resources = template.path("Resources");
+ if (!resources.isObject()) {
+ return;
+ }
+
+ Map<String, String> resolvedParams = resolveDefaultParameters(template, params);
+ Map<String, Boolean> conditions =
+ resolveConditions(template, resolvedParams, null, region, accountId);
+
+ Set<String> allIds = new LinkedHashSet<>();
+ resources.fieldNames().forEachRemaining(allIds::add);
+ Set<String> activeIds = new LinkedHashSet<>();
+ Map<String, Set<String>> dependencies = new HashMap<>();
+ for (String logicalId : allIds) {
+ JsonNode resDef = resources.get(logicalId);
+ String condition = resDef.path("Condition").asText(null);
+ if (condition == null || conditions.getOrDefault(condition, false)) {
+ activeIds.add(logicalId);
+ }
+ dependencies.put(logicalId, collectResourceDependencies(resDef, allIds, conditions));
+ }
+
+ Set<String> unresolved = unresolvedConditionDependencies(activeIds, allIds, dependencies);
+ if (!unresolved.isEmpty()) {
+ throw unresolvedDependenciesError(unresolved);
+ }
+ }
+
private boolean evaluateCondition(JsonNode expr, Map<String, String> params,
Map<String, Boolean> conditions, String region, String accountId) {
if (expr == null || expr.isNull()) {
@@ -1560,31 +1695,29 @@ public class CloudFormationService {
resources.fieldNames().forEachRemaining(allIds::add);
Map<String, Set<String>> dependencies = new HashMap<>();
+ Set<String> activeIds = new LinkedHashSet<>();
for (String logicalId : allIds) {
JsonNode resDef = resources.get(logicalId);
-
String condition = resDef.path("Condition").asText(null);
- if (condition != null && !conditions.getOrDefault(condition, false)) {
- continue;
- }
-
- Set<String> deps = new LinkedHashSet<>();
- collectDependencies(resDef.path("Properties"), allIds, deps);
-
- JsonNode dependsOn = resDef.path("DependsOn");
- if (dependsOn.isTextual()) {
- deps.add(dependsOn.asText());
- } else if (dependsOn.isArray()) {
- for (JsonNode d : dependsOn) {
- deps.add(d.asText());
- }
+ if (condition == null || conditions.getOrDefault(condition, false)) {
+ activeIds.add(logicalId);
}
+ dependencies.put(logicalId, collectResourceDependencies(resDef, allIds, conditions));
+ }
- dependencies.put(logicalId, deps);
+ // AWS rejects a template whose created resources depend on a resource excluded by a false
+ // condition rather than silently skipping the dependent (verified against real
+ // CloudFormation: CreateStack fails synchronously with "Unresolved resource dependencies").
+ // Fn::If-guarded references are safe because collectDependencies only walks the selected
+ // branch, so a false-branch reference is never recorded as a dependency.
+ Set<String> unresolved = unresolvedConditionDependencies(activeIds, allIds, dependencies);
+ if (!unresolved.isEmpty()) {
+ throw unresolvedDependenciesError(unresolved);
}
+ dependencies.keySet().retainAll(activeIds);
Map<String, Integer> inDegree = new HashMap<>();
- for (String id : allIds) {
+ for (String id : activeIds) {
inDegree.put(id, 0);
}
for (var entry : dependencies.entrySet()) {
@@ -1596,7 +1729,7 @@ public class CloudFormationService {
}
Deque<String> queue = new ArrayDeque<>();
- for (String id : allIds) {
+ for (String id : activeIds) {
if (inDegree.get(id) == 0) {
queue.add(id);
}
@@ -1617,7 +1750,7 @@ public class CloudFormationService {
}
}
- for (String id : allIds) {
+ for (String id : activeIds) {
if (!sorted.contains(id)) {
sorted.add(id);
}
@@ -1628,7 +1761,53 @@ public class CloudFormationService {
private static final Pattern SUB_VAR_PATTERN = Pattern.compile("\\$\\{([^}]+)}");
- private void collectDependencies(JsonNode node, Set<String> allIds, Set<String> deps) {
+ /**
+ * Collects the logical IDs this resource depends on, both through its {@code Properties}
+ * (Ref/GetAtt/Fn::Sub, and the selected branch of Fn::If) and its explicit {@code DependsOn}.
+ */
+ private Set<String> collectResourceDependencies(JsonNode resDef, Set<String> allIds,
+ Map<String, Boolean> conditions) {
+ Set<String> deps = new LinkedHashSet<>();
+ collectDependencies(resDef.path("Properties"), allIds, deps, conditions);
+
+ JsonNode dependsOn = resDef.path("DependsOn");
+ if (dependsOn.isTextual()) {
+ deps.add(dependsOn.asText());
+ } else if (dependsOn.isArray()) {
+ for (JsonNode d : dependsOn) {
+ deps.add(d.asText());
+ }
+ }
+ return deps;
+ }
+
+ /**
+ * Returns the logical IDs of resources that are excluded by a false condition yet are still
+ * depended upon by a resource that will be created. An empty set means the dependency graph is
+ * resolvable for the current condition values.
+ */
+ private Set<String> unresolvedConditionDependencies(Set<String> activeIds, Set<String> allIds,
+ Map<String, Set<String>> dependencies) {
+ Set<String> unresolved = new LinkedHashSet<>();
+ for (String logicalId : activeIds) {
+ for (String dependency : dependencies.get(logicalId)) {
+ if (allIds.contains(dependency) && !activeIds.contains(dependency)) {
+ unresolved.add(dependency);
+ }
+ }
+ }
+ return unresolved;
+ }
+
+ private AwsException unresolvedDependenciesError(Set<String> unresolved) {
+ return new AwsException("ValidationError",
+ "Template format error: Unresolved resource dependencies ["
+ + String.join(", ", unresolved)
+ + "] in the Resources block of the template", 400);
+ }
+
+ private void collectDependencies(JsonNode node, Set<String> allIds, Set<String> deps,
+ Map<String, Boolean> conditions) {
if (node == null || node.isNull() || node.isMissingNode()) {
return;
}
@@ -1653,19 +1832,28 @@ public class CloudFormationService {
}
return;
}
+ if (node.has("Fn::If")) {
+ JsonNode fnIf = node.get("Fn::If");
+ if (fnIf.isArray() && fnIf.size() == 3) {
+ boolean condition = conditions.getOrDefault(fnIf.get(0).asText(), false);
+ collectDependencies(fnIf.get(condition ? 1 : 2), allIds, deps, conditions);
+ return;
+ }
+ }
if (node.has("Fn::Sub")) {
- collectSubDependencies(node.get("Fn::Sub"), allIds, deps);
+ collectSubDependencies(node.get("Fn::Sub"), allIds, deps, conditions);
return;
}
- node.fields().forEachRemaining(e -> collectDependencies(e.getValue(), allIds, deps));
+ node.fields().forEachRemaining(e -> collectDependencies(e.getValue(), allIds, deps, conditions));
} else if (node.isArray()) {
for (JsonNode item : node) {
- collectDependencies(item, allIds, deps);
+ collectDependencies(item, allIds, deps, conditions);
}
}
}
- private void collectSubDependencies(JsonNode sub, Set<String> allIds, Set<String> deps) {
+ private void collectSubDependencies(JsonNode sub, Set<String> allIds, Set<String> deps,
+ Map<String, Boolean> conditions) {
String template;
Set<String> explicitVars = new HashSet<>();
@@ -1675,7 +1863,7 @@ public class CloudFormationService {
template = sub.get(0).asText();
if (sub.size() >= 2 && sub.get(1).isObject()) {
sub.get(1).fieldNames().forEachRemaining(explicitVars::add);
- collectDependencies(sub.get(1), allIds, deps);
+ collectDependencies(sub.get(1), allIds, deps, conditions);
}
} else {
return;
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java
index c9b9a3ae40..71ce40b8dd 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java
@@ -149,6 +149,15 @@ public class StackSetService {
throw new AwsException("ValidationError",
"Accounts and Regions must each contain at least one value", 400);
}
+ if (accounts.stream().anyMatch(account -> account == null || !account.matches("[0-9]{12}"))) {
+ throw new AwsException("ValidationError",
+ "1 validation error detected: Value '" + accounts
+ + "' at 'accounts' failed to satisfy constraint: Member must satisfy constraint: "
+ + "[Member must have length less than or equal to 12, Member must have length "
+ + "greater than or equal to 12, Member must satisfy regular expression pattern: "
+ + "^[0-9]{12}$]",
+ 400);
+ }
List<StackInstance> deployed = new ArrayList<>();
for (String account : accounts) {
for (String region : regions) {
@@ -243,8 +252,11 @@ public class StackSetService {
private StackInstance deployInstance(StackSet ss, String account, String region,
String changeSetName, String changeSetType) {
String stackName = instanceStackName(ss.getStackSetName(), account);
+ // Preflight the change set in the target account so AWS::AccountId-based conditions are
+ // evaluated against the same account the instance executes in (createChangeSet otherwise runs
+ // in the administrator request scope).
cfnService.createChangeSet(stackName, changeSetName, changeSetType, ss.getTemplateBody(), null,
- ss.getParameters(), ss.getCapabilities(), ss.getTags(), region);
+ ss.getParameters(), ss.getCapabilities(), ss.getTags(), region, account);
await(cfnService.executeChangeSet(stackName, changeSetName, region, account));
StackInstance inst = new StackInstance();
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceConditionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceConditionIntegrationTest.java
new file mode 100644
index 0000000000..d54ffe54ac
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceConditionIntegrationTest.java
@@ -0,0 +1,983 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+
+import static io.restassured.RestAssured.given;
+import static org.awaitility.Awaitility.await;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.not;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+@QuarkusTest
+class CloudFormationResourceConditionIntegrationTest {
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void createStack_skipsResourceWhenResourceLevelConditionIsFalse() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cond-resource-" + suffix;
+ String skippedQueueName = "should-not-exist-" + suffix;
+ String pickedQueueName = "false-branch-" + suffix;
+ String trueBranchQueueName = "true-branch-" + suffix;
+
+ String template = """
+ {
+ "Conditions": {
+ "IsFalse": { "Fn::Equals": ["a", "b"] }
+ },
+ "Resources": {
+ "SkippedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Condition": "IsFalse",
+ "Properties": { "QueueName": "%s" }
+ },
+ "PickedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {
+ "QueueName": { "Fn::If": ["IsFalse", "%s", "%s"] }
+ }
+ }
+ }
+ }
+ """.formatted(skippedQueueName, trueBranchQueueName, pickedQueueName);
+
+ createStack(stackName, template);
+ try {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueUrl")
+ .formParam("QueueName", pickedQueueName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString(pickedQueueName));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueUrl")
+ .formParam("QueueName", skippedQueueName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("AWS.SimpleQueueService.NonExistentQueue"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackResources")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<LogicalResourceId>PickedQueue</LogicalResourceId>"))
+ .body(not(containsString("<LogicalResourceId>SkippedQueue</LogicalResourceId>")));
+ } finally {
+ deleteStack(stackName);
+ }
+ }
+
+ @Test
+ void updateStack_deletesResourceWhenConditionTurnsFalse() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cond-update-" + suffix;
+ String queueName = "condition-update-" + suffix;
+
+ String enabledTemplate = """
+ {
+ "Conditions": {
+ "Enabled": { "Fn::Equals": ["enabled", "enabled"] }
+ },
+ "Resources": {
+ "OptionalQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Condition": "Enabled",
+ "Properties": { "QueueName": "%s" }
+ }
+ }
+ }
+ """.formatted(queueName);
+ String disabledTemplate = """
+ {
+ "Conditions": {
+ "Enabled": { "Fn::Equals": ["enabled", "disabled"] }
+ },
+ "Resources": {
+ "OptionalQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Condition": "Enabled",
+ "Properties": { "QueueName": "%s" }
+ }
+ }
+ }
+ """.formatted(queueName);
+
+ createStack(stackName, enabledTemplate);
+ try {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueUrl")
+ .formParam("QueueName", queueName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString(queueName));
+
+ updateStack(stackName, disabledTemplate);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueUrl")
+ .formParam("QueueName", queueName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("AWS.SimpleQueueService.NonExistentQueue"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackResources")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(not(containsString("<LogicalResourceId>OptionalQueue</LogicalResourceId>")));
+ } finally {
+ deleteStack(stackName);
+ }
+ }
+
+ @Test
+ void updateStack_whenConditionDeletionFails_keepsResourceTrackedAsDeleteFailed() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cond-delete-fail-" + suffix;
+ String bucketName = "condition-delete-fail-" + suffix;
+
+ String enabledTemplate = """
+ {
+ "Conditions": {
+ "Enabled": { "Fn::Equals": ["enabled", "enabled"] }
+ },
+ "Resources": {
+ "OptionalBucket": {
+ "Type": "AWS::S3::Bucket",
+ "Condition": "Enabled",
+ "Properties": { "BucketName": "%s" }
+ }
+ }
+ }
+ """.formatted(bucketName);
+ String disabledTemplate = """
+ {
+ "Conditions": {
+ "Enabled": { "Fn::Equals": ["enabled", "disabled"] }
+ },
+ "Resources": {
+ "OptionalBucket": {
+ "Type": "AWS::S3::Bucket",
+ "Condition": "Enabled",
+ "Properties": { "BucketName": "%s" }
+ }
+ }
+ }
+ """.formatted(bucketName);
+
+ createStack(stackName, enabledTemplate);
+ try {
+ given()
+ .header("Host", bucketName + ".localhost")
+ .when()
+ .get("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("text/plain")
+ .body("prevent condition-disabled bucket deletion")
+ .when()
+ .put("/" + bucketName + "/object.txt")
+ .then()
+ .statusCode(200);
+
+ updateStack(stackName, disabledTemplate);
+
+ 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("OptionalBucket"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackResources")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ // The cleanup delete failed (bucket non-empty), so the resource must remain under
+ // stack management as DELETE_FAILED instead of being dropped and orphaned.
+ .body(containsString("<LogicalResourceId>OptionalBucket</LogicalResourceId>"))
+ .body(containsString("<ResourceStatus>DELETE_FAILED</ResourceStatus>"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackEvents")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<LogicalResourceId>OptionalBucket</LogicalResourceId>"))
+ .body(containsString("<ResourceStatus>DELETE_FAILED</ResourceStatus>"))
+ .body(containsString("<ResourceStatusReason>"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetTemplate")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("[&quot;enabled&quot;, &quot;disabled&quot;]"))
+ .body(not(containsString("[&quot;enabled&quot;, &quot;enabled&quot;]")));
+
+ given()
+ .header("Host", bucketName + ".localhost")
+ .when()
+ .get("/")
+ .then()
+ .statusCode(200);
+ } finally {
+ given().header("Host", bucketName + ".localhost").delete("/object.txt");
+ deleteStack(stackName);
+ awaitStackGone(stackName);
+ }
+ }
+
+ @Test
+ void createStack_failsWhenResourceDependsOnConditionFalseResourceViaDependsOn() {
+ // Verified against real AWS: CreateStack is rejected synchronously with
+ // "Template format error: Unresolved resource dependencies [SkippedQueue]" — CloudFormation
+ // does NOT create a DependsOn dependent (or the stack) when its target is condition-false.
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cond-dep-on-" + suffix;
+ String skippedQueueName = "skipped-" + suffix;
+ String dependentQueueName = "dependent-" + suffix;
+
+ String template = """
+ {
+ "Conditions": {
+ "IsFalse": { "Fn::Equals": ["a", "b"] }
+ },
+ "Resources": {
+ "SkippedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Condition": "IsFalse",
+ "Properties": { "QueueName": "%s" }
+ },
+ "DependentQueue": {
+ "Type": "AWS::SQS::Queue",
+ "DependsOn": "SkippedQueue",
+ "Properties": { "QueueName": "%s" }
+ }
+ }
+ }
+ """.formatted(skippedQueueName, dependentQueueName);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))
+ .body("ErrorResponse.Error.Message", containsString("Unresolved resource dependencies"))
+ .body("ErrorResponse.Error.Message", containsString("SkippedQueue"));
+
+ // No stack is left behind, and the dependent queue was never provisioned.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueUrl")
+ .formParam("QueueName", dependentQueueName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("AWS.SimpleQueueService.NonExistentQueue"));
+ }
+
+ @Test
+ void createStack_failsWhenResourceReferencesConditionFalseResourceViaRef() {
+ // Verified against real AWS: an unguarded Ref/Fn::Sub to a condition-false resource is also
+ // rejected with "Unresolved resource dependencies [SkippedQueue]".
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cond-ref-" + suffix;
+ String skippedQueueName = "skipped-ref-" + suffix;
+ String dependentQueueName = "dependent-ref-" + suffix;
+
+ String template = """
+ {
+ "Conditions": {
+ "IsFalse": { "Fn::Equals": ["a", "b"] }
+ },
+ "Resources": {
+ "SkippedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Condition": "IsFalse",
+ "Properties": { "QueueName": "%s" }
+ },
+ "DependentQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {
+ "QueueName": { "Fn::Sub": "${SkippedQueue}-%s" }
+ }
+ }
+ }
+ }
+ """.formatted(skippedQueueName, dependentQueueName);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))
+ .body("ErrorResponse.Error.Message", containsString("Unresolved resource dependencies"))
+ .body("ErrorResponse.Error.Message", containsString("SkippedQueue"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"));
+ }
+
+ @Test
+ void createStack_createsResourceWhenFnIfGuardsConditionFalseReference() {
+ // Verified against real AWS: when Fn::If selects the branch that does NOT reference the
+ // condition-false resource, there is no real dependency, so the dependent resource is
+ // created and the stack completes.
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cond-fnif-" + suffix;
+ String skippedQueueName = "skipped-fnif-" + suffix;
+ String fallbackQueueName = "fallback-fnif-" + suffix;
+
+ String template = """
+ {
+ "Conditions": {
+ "IsFalse": { "Fn::Equals": ["a", "b"] }
+ },
+ "Resources": {
+ "SkippedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Condition": "IsFalse",
+ "Properties": { "QueueName": "%s" }
+ },
+ "DependentQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {
+ "QueueName": { "Fn::If": ["IsFalse", { "Ref": "SkippedQueue" }, "%s"] }
+ }
+ }
+ }
+ }
+ """.formatted(skippedQueueName, fallbackQueueName);
+
+ createStack(stackName, template);
+ try {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueUrl")
+ .formParam("QueueName", fallbackQueueName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString(fallbackQueueName));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackResources")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<LogicalResourceId>DependentQueue</LogicalResourceId>"))
+ .body(not(containsString("<LogicalResourceId>SkippedQueue</LogicalResourceId>")));
+ } finally {
+ deleteStack(stackName);
+ }
+ }
+
+ @Test
+ void updateStack_createsPreviouslySkippedResourceWhenConditionTurnsTrue() {
+ // Issue #2168 follow-up, verified against real AWS: create with the condition false, then
+ // update with it true. AWS re-provisions the previously-skipped resource, and PickedQueue's
+ // Fn::If now resolves to the true branch. (AWS also *replaces* PickedQueue and deletes the
+ // old physical queue during cleanup because SQS QueueName is immutable; that generic
+ // replacement-cleanup behavior is out of scope here and is asserted only for the new name.)
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-2168-" + suffix;
+ String skippedQueueName = "should-not-exist-" + suffix;
+ String falseBranchName = "false-branch-" + suffix;
+ String trueBranchName = "true-branch-" + suffix;
+
+ String falseTemplate = """
+ {
+ "Conditions": { "IsFalse": { "Fn::Equals": ["a", "b"] } },
+ "Resources": {
+ "SkippedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Condition": "IsFalse",
+ "Properties": { "QueueName": "%s" }
+ },
+ "PickedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {
+ "QueueName": { "Fn::If": ["IsFalse", "%s", "%s"] }
+ }
+ }
+ }
+ }
+ """.formatted(skippedQueueName, trueBranchName, falseBranchName);
+ String trueTemplate = """
+ {
+ "Conditions": { "IsFalse": { "Fn::Equals": ["a", "a"] } },
+ "Resources": {
+ "SkippedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Condition": "IsFalse",
+ "Properties": { "QueueName": "%s" }
+ },
+ "PickedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {
+ "QueueName": { "Fn::If": ["IsFalse", "%s", "%s"] }
+ }
+ }
+ }
+ }
+ """.formatted(skippedQueueName, trueBranchName, falseBranchName);
+
+ createStack(stackName, falseTemplate);
+ try {
+ // Baseline: PickedQueue resolves to the false branch; SkippedQueue is not created.
+ getQueueUrl(falseBranchName).then().statusCode(200).body(containsString(falseBranchName));
+ getQueueUrl(skippedQueueName).then().statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("AWS.SimpleQueueService.NonExistentQueue"));
+
+ updateStack(stackName, trueTemplate);
+
+ // The previously-skipped resource is created once its condition turns true.
+ getQueueUrl(skippedQueueName).then().statusCode(200).body(containsString(skippedQueueName));
+ // PickedQueue's Fn::If now resolves to the true branch.
+ getQueueUrl(trueBranchName).then().statusCode(200).body(containsString(trueBranchName));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackResources")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<LogicalResourceId>SkippedQueue</LogicalResourceId>"))
+ .body(containsString("<LogicalResourceId>PickedQueue</LogicalResourceId>"));
+ } finally {
+ deleteStack(stackName);
+ }
+ }
+
+ private static io.restassured.response.Response getQueueUrl(String queueName) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueUrl")
+ .formParam("QueueName", queueName)
+ .when()
+ .post("/");
+ }
+
+ @Test
+ void createStack_failsWhenResourceReferencesConditionFalseResourceViaGetAtt() {
+ // Verified against real AWS: an unguarded Fn::GetAtt to a condition-false resource is
+ // rejected the same way as Ref/Fn::Sub ("Unresolved resource dependencies [SkippedQueue]").
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cond-getatt-" + suffix;
+ String skippedQueueName = "skipped-getatt-" + suffix;
+ String dependentQueueName = "dependent-getatt-" + suffix;
+
+ String template = """
+ {
+ "Conditions": {
+ "IsFalse": { "Fn::Equals": ["a", "b"] }
+ },
+ "Resources": {
+ "SkippedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Condition": "IsFalse",
+ "Properties": { "QueueName": "%s" }
+ },
+ "DependentQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {
+ "QueueName": { "Fn::GetAtt": ["SkippedQueue", "QueueName"] }
+ }
+ }
+ }
+ }
+ """.formatted(skippedQueueName, dependentQueueName);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))
+ .body("ErrorResponse.Error.Message", containsString("Unresolved resource dependencies"))
+ .body("ErrorResponse.Error.Message", containsString("SkippedQueue"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"));
+
+ getQueueUrl(dependentQueueName).then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("AWS.SimpleQueueService.NonExistentQueue"));
+ }
+
+ @Test
+ void createStack_failsWhenDependsOnArrayContainsConditionFalseResource() {
+ // The DependsOn array form must be rejected identically to the string form when any listed
+ // target is excluded by a false Condition.
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cond-dep-arr-" + suffix;
+ String presentQueueName = "present-arr-" + suffix;
+ String skippedQueueName = "skipped-arr-" + suffix;
+ String dependentQueueName = "dependent-arr-" + suffix;
+
+ String template = """
+ {
+ "Conditions": {
+ "IsFalse": { "Fn::Equals": ["a", "b"] }
+ },
+ "Resources": {
+ "PresentQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": { "QueueName": "%s" }
+ },
+ "SkippedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Condition": "IsFalse",
+ "Properties": { "QueueName": "%s" }
+ },
+ "DependentQueue": {
+ "Type": "AWS::SQS::Queue",
+ "DependsOn": ["PresentQueue", "SkippedQueue"],
+ "Properties": { "QueueName": "%s" }
+ }
+ }
+ }
+ """.formatted(presentQueueName, skippedQueueName, dependentQueueName);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))
+ .body("ErrorResponse.Error.Message", containsString("Unresolved resource dependencies"))
+ .body("ErrorResponse.Error.Message", containsString("SkippedQueue"));
+
+ // The whole template is rejected before any resource is provisioned.
+ getQueueUrl(presentQueueName).then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("AWS.SimpleQueueService.NonExistentQueue"));
+ getQueueUrl(dependentQueueName).then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("AWS.SimpleQueueService.NonExistentQueue"));
+ }
+
+ @Test
+ void updateStack_failsWhenResourceDependsOnConditionFalseResourceAndLeavesStackUnchanged() {
+ // The same synchronous validation that guards CreateStack must guard UpdateStack: an invalid
+ // condition-dependency graph is rejected before any stack state is mutated, so the existing
+ // stack and its resources are left intact.
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cond-upd-dep-" + suffix;
+ String keepQueueName = "keep-dep-" + suffix;
+ String skippedQueueName = "skipped-upd-dep-" + suffix;
+ String dependentQueueName = "dependent-upd-dep-" + suffix;
+
+ String initialTemplate = """
+ {
+ "Resources": {
+ "KeepQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": { "QueueName": "%s" }
+ }
+ }
+ }
+ """.formatted(keepQueueName);
+ String invalidTemplate = """
+ {
+ "Conditions": {
+ "IsFalse": { "Fn::Equals": ["a", "b"] }
+ },
+ "Resources": {
+ "KeepQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": { "QueueName": "%s" }
+ },
+ "SkippedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Condition": "IsFalse",
+ "Properties": { "QueueName": "%s" }
+ },
+ "DependentQueue": {
+ "Type": "AWS::SQS::Queue",
+ "DependsOn": "SkippedQueue",
+ "Properties": { "QueueName": "%s" }
+ }
+ }
+ }
+ """.formatted(keepQueueName, skippedQueueName, dependentQueueName);
+
+ createStack(stackName, initialTemplate);
+ try {
+ getQueueUrl(keepQueueName).then().statusCode(200).body(containsString(keepQueueName));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", invalidTemplate)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))
+ .body("ErrorResponse.Error.Message", containsString("Unresolved resource dependencies"))
+ .body("ErrorResponse.Error.Message", containsString("SkippedQueue"));
+
+ // The existing stack is untouched: still UPDATE-able, still holding only KeepQueue.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackResources")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<LogicalResourceId>KeepQueue</LogicalResourceId>"))
+ .body(not(containsString("<LogicalResourceId>DependentQueue</LogicalResourceId>")))
+ .body(not(containsString("<LogicalResourceId>SkippedQueue</LogicalResourceId>")));
+
+ // The stored template was not replaced by the rejected one.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetTemplate")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(not(containsString("SkippedQueue")));
+
+ getQueueUrl(keepQueueName).then().statusCode(200).body(containsString(keepQueueName));
+ getQueueUrl(dependentQueueName).then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("AWS.SimpleQueueService.NonExistentQueue"));
+ } finally {
+ deleteStack(stackName);
+ }
+ }
+
+ @Test
+ void updateStack_failsWhenResourceReferencesConditionFalseResourceViaRefAndLeavesStackUnchanged() {
+ // Same as above but through an unguarded Ref/Fn::Sub reference rather than DependsOn.
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cond-upd-ref-" + suffix;
+ String keepQueueName = "keep-ref-" + suffix;
+ String skippedQueueName = "skipped-upd-ref-" + suffix;
+ String dependentQueueName = "dependent-upd-ref-" + suffix;
+
+ String initialTemplate = """
+ {
+ "Resources": {
+ "KeepQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": { "QueueName": "%s" }
+ }
+ }
+ }
+ """.formatted(keepQueueName);
+ String invalidTemplate = """
+ {
+ "Conditions": {
+ "IsFalse": { "Fn::Equals": ["a", "b"] }
+ },
+ "Resources": {
+ "KeepQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": { "QueueName": "%s" }
+ },
+ "SkippedQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Condition": "IsFalse",
+ "Properties": { "QueueName": "%s" }
+ },
+ "DependentQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {
+ "QueueName": { "Fn::Sub": "${SkippedQueue}-%s" }
+ }
+ }
+ }
+ }
+ """.formatted(keepQueueName, skippedQueueName, dependentQueueName);
+
+ createStack(stackName, initialTemplate);
+ try {
+ getQueueUrl(keepQueueName).then().statusCode(200).body(containsString(keepQueueName));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", invalidTemplate)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))
+ .body("ErrorResponse.Error.Message", containsString("Unresolved resource dependencies"))
+ .body("ErrorResponse.Error.Message", containsString("SkippedQueue"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
+
+ getQueueUrl(keepQueueName).then().statusCode(200).body(containsString(keepQueueName));
+ getQueueUrl(dependentQueueName).then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("AWS.SimpleQueueService.NonExistentQueue"));
+ } finally {
+ deleteStack(stackName);
+ }
+ }
+
+ @Test
+ void deleteStack_afterConditionDeletionFailure_retriesAndReclaimsResource() {
+ // When a condition-driven cleanup delete fails (bucket non-empty), the resource stays under
+ // stack management as DELETE_FAILED. Once the blocker is cleared, a later DeleteStack must
+ // retry the deletion and reclaim the backing resource instead of leaving it orphaned.
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cond-del-orphan-" + suffix;
+ String bucketName = "condition-orphan-" + suffix;
+
+ String enabledTemplate = """
+ {
+ "Conditions": {
+ "Enabled": { "Fn::Equals": ["enabled", "enabled"] }
+ },
+ "Resources": {
+ "OptionalBucket": {
+ "Type": "AWS::S3::Bucket",
+ "Condition": "Enabled",
+ "Properties": { "BucketName": "%s" }
+ }
+ }
+ }
+ """.formatted(bucketName);
+ String disabledTemplate = """
+ {
+ "Conditions": {
+ "Enabled": { "Fn::Equals": ["enabled", "disabled"] }
+ },
+ "Resources": {
+ "OptionalBucket": {
+ "Type": "AWS::S3::Bucket",
+ "Condition": "Enabled",
+ "Properties": { "BucketName": "%s" }
+ }
+ }
+ }
+ """.formatted(bucketName);
+
+ createStack(stackName, enabledTemplate);
+ try {
+ given().header("Host", bucketName + ".localhost").when().get("/").then().statusCode(200);
+ given()
+ .contentType("text/plain")
+ .body("prevent condition-disabled bucket deletion")
+ .when()
+ .put("/" + bucketName + "/object.txt")
+ .then()
+ .statusCode(200);
+
+ // Cleanup delete fails (bucket non-empty), but the update still completes; the bucket
+ // stays under stack management as DELETE_FAILED.
+ updateStack(stackName, disabledTemplate);
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackResources")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<LogicalResourceId>OptionalBucket</LogicalResourceId>"))
+ .body(containsString("<ResourceStatus>DELETE_FAILED</ResourceStatus>"));
+
+ // Clear the blocker, then DeleteStack must retry the still-tracked DELETE_FAILED resource
+ // and reclaim the backing bucket rather than orphaning it.
+ given().header("Host", bucketName + ".localhost").delete("/object.txt").then().statusCode(204);
+ deleteStack(stackName);
+ awaitStackGone(stackName);
+ given().header("Host", bucketName + ".localhost").when().get("/").then().statusCode(404);
+ } finally {
+ given().header("Host", bucketName + ".localhost").delete("/object.txt");
+ given().header("Host", bucketName + ".localhost").delete("/");
+ deleteStack(stackName);
+ }
+ }
+
+ 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)
+ .body(containsString("<StackId>"));
+ }
+
+ 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)
+ .body(containsString("<StackId>"));
+ }
+
+ 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 awaitStackGone(String stackName) {
+ await()
+ .atMost(Duration.ofSeconds(30))
+ .pollInterval(Duration.ofMillis(50))
+ .untilAsserted(() -> {
+ String body = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when().post("/").then().extract().asString();
+ if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
+ fail("stack delete failed: " + body);
+ }
+ assertTrue(body.contains("does not exist"), "stack still exists: " + body);
+ });
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java
index c1086390d4..ffb8bb7eba 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java
@@ -35,6 +35,24 @@ class CloudFormationStackSetsIntegrationTest {
""".formatted(queueName);
}
+ /**
+ * A template whose {@code ConditionalQueue} is created only in {@code conditionAccount} (via an
+ * {@code AWS::AccountId} condition) and whose {@code DependentQueue} depends on it. Deploying it
+ * into {@code conditionAccount} must succeed; deploying it elsewhere must fail preflight because
+ * the dependent then references a condition-excluded resource.
+ */
+ private static String conditionalDependentTemplate(String conditionAccount, String conditionalQueue,
+ String dependentQueue) {
+ return """
+ {"Conditions":{"IsTarget":{"Fn::Equals":[{"Ref":"AWS::AccountId"},"%s"]}},
+ "Resources":{
+ "ConditionalQueue":{"Type":"AWS::SQS::Queue","Condition":"IsTarget",
+ "Properties":{"QueueName":"%s"}},
+ "DependentQueue":{"Type":"AWS::SQS::Queue","DependsOn":"ConditionalQueue",
+ "Properties":{"QueueName":"%s"}}}}
+ """.formatted(conditionAccount, conditionalQueue, dependentQueue);
+ }
+
private void assertQueueVisible(String account, String queueName) {
given()
.contentType("application/x-www-form-urlencoded")
@@ -485,4 +503,172 @@ class CloudFormationStackSetsIntegrationTest {
.then().statusCode(200)
.body(containsString("<Status>FAILED</Status>"));
}
+
+ @Test
+ void stackSetConditionPreflightUsesTargetAccountOnCreateInstances() {
+ // Regression: condition-dependency preflight for a StackSet instance must run in the target
+ // account, not the administrator account. Here ConditionalQueue is active only in ACCOUNT_B
+ // (via AWS::AccountId) and DependentQueue depends on it. createChangeSet runs in the admin
+ // request scope, so evaluating the condition against the admin account would wrongly treat
+ // ConditionalQueue as excluded and fail the dependent with "Unresolved resource dependencies".
+ String setName = "cond-create-" + UUID.randomUUID().toString().substring(0, 8);
+ String conditional = "cond-q-" + UUID.randomUUID().toString().substring(0, 8);
+ String dependent = "dep-q-" + UUID.randomUUID().toString().substring(0, 8);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackSet")
+ .formParam("StackSetName", setName)
+ .formParam("TemplateBody", conditionalDependentTemplate(ACCOUNT_B, conditional, dependent))
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200).body(containsString("<StackSetId>"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackInstances")
+ .formParam("StackSetName", setName)
+ .formParam("Accounts.member.1", ACCOUNT_B)
+ .formParam("Regions.member.1", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200).body(containsString("<OperationId>"));
+
+ // Both resources materialize in the target account because the condition is true there.
+ assertQueueVisible(ACCOUNT_B, conditional);
+ assertQueueVisible(ACCOUNT_B, dependent);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackInstance")
+ .formParam("StackSetName", setName)
+ .formParam("StackInstanceAccount", ACCOUNT_B)
+ .formParam("StackInstanceRegion", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<DetailedStatus>SUCCEEDED</DetailedStatus>"));
+ }
+
+ @Test
+ void stackSetConditionPreflightUsesTargetAccountOnUpdateStackSet() {
+ // UpdateStackSet re-applies through the same deployInstance path, so the target-account
+ // preflight must hold there too.
+ String setName = "cond-update-" + UUID.randomUUID().toString().substring(0, 8);
+ String initialQueue = "init-q-" + UUID.randomUUID().toString().substring(0, 8);
+ String conditional = "cond-u-" + UUID.randomUUID().toString().substring(0, 8);
+ String dependent = "dep-u-" + UUID.randomUUID().toString().substring(0, 8);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackSet")
+ .formParam("StackSetName", setName)
+ .formParam("TemplateBody", queueTemplate(initialQueue))
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackInstances")
+ .formParam("StackSetName", setName)
+ .formParam("Accounts.member.1", ACCOUNT_B)
+ .formParam("Regions.member.1", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+ assertQueueVisible(ACCOUNT_B, initialQueue);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStackSet")
+ .formParam("StackSetName", setName)
+ .formParam("TemplateBody", conditionalDependentTemplate(ACCOUNT_B, conditional, dependent))
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200).body(containsString("<OperationId>"));
+
+ // The updated template's condition is true in the target account, so both resources exist.
+ assertQueueVisible(ACCOUNT_B, conditional);
+ assertQueueVisible(ACCOUNT_B, dependent);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ListStackSetOperations")
+ .formParam("StackSetName", setName)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<Action>UPDATE</Action>"))
+ .body(containsString("<Status>SUCCEEDED</Status>"));
+ }
+
+ @Test
+ void stackSetConditionPreflightFailsWhenTargetAccountExcludesDependency() {
+ // The mirror image: when the condition is false in the target account, the dependent
+ // references a condition-excluded resource, so preflight must reject the instance in the
+ // target account's context (HTTP 400 ValidationError), not silently succeed.
+ String setName = "cond-neg-" + UUID.randomUUID().toString().substring(0, 8);
+ String conditional = "cond-n-" + UUID.randomUUID().toString().substring(0, 8);
+ String dependent = "dep-n-" + UUID.randomUUID().toString().substring(0, 8);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackSet")
+ .formParam("StackSetName", setName)
+ // Condition is true only in ACCOUNT_B, but we deploy into ACCOUNT_C.
+ .formParam("TemplateBody", conditionalDependentTemplate(ACCOUNT_B, conditional, dependent))
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackInstances")
+ .formParam("StackSetName", setName)
+ .formParam("Accounts.member.1", ACCOUNT_C)
+ .formParam("Regions.member.1", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(400)
+ .body(containsString("ValidationError"))
+ .body(containsString("Unresolved resource dependencies"))
+ .body(containsString("ConditionalQueue"));
+
+ // Nothing was provisioned in the excluded target account.
+ assertQueueAbsent(ACCOUNT_C, conditional);
+ assertQueueAbsent(ACCOUNT_C, dependent);
+ }
+
+ @Test
+ void createStackInstancesRejectsInvalidAccountBeforeDeployment() {
+ String setName = "invalid-account-" + UUID.randomUUID().toString().substring(0, 8);
+ String queue = "invalid-account-q-" + UUID.randomUUID().toString().substring(0, 8);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackSet")
+ .formParam("StackSetName", setName)
+ .formParam("TemplateBody", queueTemplate(queue))
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackInstances")
+ .formParam("StackSetName", setName)
+ .formParam("Accounts.member.1", ACCOUNT_B)
+ .formParam("Accounts.member.2", "")
+ .formParam("Regions.member.1", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(400)
+ .body(containsString("ValidationError"))
+ .body(containsString("Value &apos;[" + ACCOUNT_B + ", ]&apos; at &apos;accounts&apos;"))
+ .body(containsString("^[0-9]{12}$"));
+
+ // AWS validates every account before deploying any instance in the request.
+ assertQueueAbsent(ACCOUNT_B, queue);
+ }
}