fix(cloudformation): reject resources that depend on each other in a cycle (#5208)

* fix(cloudformation): reject resources that depend on each other in a cycle

A template whose resources form a dependency cycle was created anyway: the
topological sort appended the resources it could not order and created them in
template order. CloudFormation rejects such a template with a ValidationError
naming the resources, before any of them is created.

The sort now throws that error when resources remain unsorted, and the
synchronous pre-check that runs before CreateStack, UpdateStack and
CreateChangeSet calls the sort instead of repeating its dependency checks, so
the request fails before any stack state is created.

* fix(cloudformation): keep dependency order when deleting a stack saved with a cyclic template

A stack saved before circular templates were rejected can still carry one.
Deleting it hit the new circular-dependency error while ordering its resources,
so the delete fell back to insertion order for every resource and could remove
a resource before one still using it. The delete now orders what it can and
places the circular resources after it, as before.

* fix(cloudformation): order resources that depend on a cycle when deleting a saved stack

A resource that depends on a dependency cycle cannot be ordered either, so the
delete of a stack saved with a cyclic template ranked such resources in
template order and could remove a target group before the listener using it.
When the sort stalls it now releases a resource on the cycle itself and goes on,
so everything that depends on the cycle keeps its dependency order.

* fix(cloudformation): delete linked dependency cycles in dependency order

When a saved stack's template has a cycle that depends on another cycle, the
sort could release a resource of the dependent cycle before the cycle it uses
was placed, so the delete removed that cycle's resources first. When the sort
stalls it now releases a resource from the first strongly connected component
Tarjan's algorithm completes over the resources left, which depends on no other
cycle.

* fix(cloudformation): order a saved cyclic stack in one pass and name only the cycle

Breaking one cycle at a time searched again at every stall and recursed, so a
long dependency chain could exhaust the thread's stack and stop the delete of a
stack saved with a cyclic template. The resources left at a stall are now
ordered in one pass by their strongly connected components, dependencies
first, with an iterative Tarjan search. The circular-dependency error names only
the components that are cycles, not resources that merely depend on one.

* test(cloudformation): cover circular dependency rejection with the AWS SDK

* test(cloudformation): assert only the cycle's resources in the SDK test's message
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-10-07 16:39:14 -04:00
1 parent 0f94d6213c
commit 13738f89de
6 files changed
+466 -32

No files matched your search

@@ -131,7 +131,7 @@ class AwsIncludeProcessor {
* count: AWS documents that a snippet may not itself use {@code AWS::Include}, not that it may
* carry no other transform. Package-private: also used by {@code CloudFormationService} to
* report {@code AWS::Include} in {@code GetTemplateSummary}'s {@code DeclaredTransforms} and to
* skip {@code validateConditionDependencies} for a template the merge has not run against yet.
* skip {@code validateResourceDependencies} for a template the merge has not run against yet.
*/
boolean containsAwsInclude(JsonNode node) {
if (node.isObject()) {
@@ -355,13 +355,13 @@ public class CloudFormationService implements ResourceProvider {
// of throwing, so this failure is reported by the change set, not by a 400 on creation.
String samTransformFailureReason = samTransformFailureReason(stackName, resolvedTemplate);
// Reject an unresolvable condition dependency graph up front, before any stack state is
// Reject an unresolvable or circular dependency graph up front, before any stack state is
// created, so CreateStack/UpdateStack fail synchronously the way real CloudFormation does.
// Unconditional: validateConditionDependencies already returns immediately for any
// Unconditional: validateResourceDependencies already returns immediately for any
// template declaring the SAM transform, whether or not that transform succeeded, so
// gating this call on samTransformFailureReason == null duplicates that check for no
// effect.
validateConditionDependencies(resolvedTemplate, parameters, region, accountId);
validateResourceDependencies(resolvedTemplate, parameters, region, accountId);
// A CREATE change set against a name that already has a stack of any status - including
// ROLLBACK_COMPLETE - is a real conflict: AWS requires an explicit DeleteStack before a
@@ -498,7 +498,7 @@ public class CloudFormationService implements ResourceProvider {
try {
template = parseTemplate(templateBody);
} catch (Exception e) {
// Template parse failures are reported by validateConditionDependencies and by
// Template parse failures are reported by validateResourceDependencies and by
// execution itself, with their own messages; not this transform-specific one.
return null;
}
@@ -2326,7 +2326,9 @@ public class CloudFormationService implements ResourceProvider {
}
Map<String, Boolean> conditions = resolveConditions(
template, stack.parametersSnapshot(), stack, region, regionResolver.getAccountId());
List<String> creationOrder = topologicalSort(resources, conditions);
// A stack saved before circular templates were rejected may still have one; order it
// by its dependencies anyway rather than giving up.
List<String> creationOrder = creationOrder(resources, conditions).sorted();
Map<String, Integer> rank = new HashMap<>();
for (int i = 0; i < creationOrder.size(); i++) {
rank.put(creationOrder.get(i), i);
@@ -2506,16 +2508,17 @@ public class CloudFormationService implements ResourceProvider {
/**
* 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.
* depends on a resource excluded by a false condition, or when resources depend on each other
* in a cycle. Real CloudFormation rejects such a template synchronously ("Template format
* error: Unresolved resource dependencies [...]" or "Circular dependency between resources:
* [...]") rather than skipping the dependent or picking an arbitrary order, so mirror that.
* Malformed or SAM templates are left for the execution path, which surfaces their own errors.
* A template carrying an unexpanded {@code Fn::Transform}/{@code AWS::Include} is left for the
* same reason: a {@code Conditions} section spliced in from a snippet is invisible here, since
* the merge has not run yet, and treating it as absent would fail a template whose dependency
* graph the execution path resolves correctly.
*/
private void validateConditionDependencies(String templateBody, Map<String, String> params,
private void validateResourceDependencies(String templateBody, Map<String, String> params,
String region, String accountId) {
JsonNode template;
try {
@@ -2537,23 +2540,8 @@ public class CloudFormationService implements ResourceProvider {
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);
}
// Throws the ValidationError for either case; the order itself is computed again on execution.
topologicalSort(resources, conditions);
}
private boolean evaluateCondition(JsonNode expr, Map<String, String> params,
@@ -3069,6 +3057,25 @@ public class CloudFormationService implements ResourceProvider {
}
private List<String> topologicalSort(JsonNode resources, Map<String, Boolean> conditions) {
// A resource left unsorted is in a dependency cycle or depends on one, so no creation
// order exists; AWS rejects such a template instead of creating it in an arbitrary order.
CreationOrder order = creationOrder(resources, conditions);
if (!order.circular().isEmpty()) {
throw new AwsException("ValidationError",
"Circular dependency between resources: [" + String.join(", ", order.circular()) + "]", 400);
}
return order.sorted();
}
/**
* The template's resources, dependencies first, and those in a dependency cycle. Resources in or
* depending on a cycle are still placed in {@code sorted}, each cycle after the cycles it depends
* on, so every dependency outside a cycle keeps its order.
*/
private record CreationOrder(List<String> sorted, Set<String> circular) {
}
private CreationOrder creationOrder(JsonNode resources, Map<String, Boolean> conditions) {
Set<String> allIds = new LinkedHashSet<>();
resources.fieldNames().forEachRemaining(allIds::add);
@@ -3128,13 +3135,81 @@ public class CloudFormationService implements ResourceProvider {
}
}
for (String id : activeIds) {
if (!sorted.contains(id)) {
sorted.add(id);
// Every resource left waits on another one left. Ordering their strongly connected
// components dependencies first still respects every dependency outside a cycle; only the
// components that are cycles themselves are circular.
Set<String> circular = new LinkedHashSet<>();
if (sorted.size() < activeIds.size()) {
Set<String> placed = new HashSet<>(sorted);
for (List<String> component : componentsDependenciesFirst(activeIds, placed, dependencies)) {
sorted.addAll(component);
String first = component.get(0);
if (component.size() > 1 || dependencies.get(first).contains(first)) {
circular.addAll(component);
}
}
}
return new CreationOrder(sorted, circular);
}
return sorted;
/**
* The strongly connected components of the resources not yet placed, each after every component
* it depends on: Tarjan's algorithm completes a component only once those are complete. The
* search keeps its own stack so a long dependency chain cannot exhaust the thread's.
*/
private static List<List<String>> componentsDependenciesFirst(Set<String> activeIds, Set<String> placed,
Map<String, Set<String>> dependencies) {
Map<String, Integer> index = new HashMap<>();
Map<String, Integer> lowLink = new HashMap<>();
Deque<String> open = new ArrayDeque<>();
Set<String> onOpen = new HashSet<>();
List<List<String>> components = new ArrayList<>();
Deque<Map.Entry<String, Iterator<String>>> path = new ArrayDeque<>();
for (String root : activeIds) {
if (placed.contains(root) || index.containsKey(root)) {
continue;
}
String next = root;
while (next != null || !path.isEmpty()) {
if (next != null) {
index.put(next, index.size());
lowLink.put(next, index.get(next));
open.push(next);
onOpen.add(next);
path.push(Map.entry(next, dependencies.get(next).iterator()));
next = null;
}
String id = path.peek().getKey();
Iterator<String> deps = path.peek().getValue();
if (deps.hasNext()) {
String dep = deps.next();
if (!dependencies.containsKey(dep) || placed.contains(dep)) {
continue;
}
if (!index.containsKey(dep)) {
next = dep;
} else if (onOpen.contains(dep)) {
lowLink.merge(id, index.get(dep), Math::min);
}
continue;
}
path.pop();
if (!path.isEmpty()) {
lowLink.merge(path.peek().getKey(), lowLink.get(id), Math::min);
}
if (lowLink.get(id).equals(index.get(id))) {
List<String> component = new ArrayList<>();
String member;
do {
member = open.pop();
onOpen.remove(member);
component.add(member);
} while (!member.equals(id));
components.add(component);
}
}
}
return components;
}
private static final Pattern SUB_VAR_PATTERN = Pattern.compile("\\$\\{([^}]+)}");