fix(config): report a self-referencing alias instead of overflowing the stack in config validate

A recursive alias is a collection that contains itself. The reader now stops at 64 levels of nesting and reports the file, so the command still prints its validation report.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura committed 2026-10-11 10:27:18 -05:00
1 parent bdaade5f8f
commit 0c4dc28d96
2 files changed
+53 -6

No files matched your search

@@ -37,6 +37,13 @@ public final class YamlTree {
*/
static final int MAX_NODES = 100_000;
/**
* The deepest nesting a document may have. A recursive alias ({@code x: &a [*a]}) is a list
* that contains itself: without a limit, copying it would recurse until the stack overflows,
* long before the node budget is spent. Real Compose files are a handful of levels deep.
*/
static final int MAX_DEPTH = 64;
private static final JsonNodeFactory NODES = JsonNodeFactory.instance;
private YamlTree() {}
@@ -65,8 +72,8 @@ public final class YamlTree {
/**
* The first document of {@code yaml}; a missing node for an empty one.
*
* @throws IOException when the text is not YAML, or expands to more than {@link #MAX_NODES}
* nodes, with a one-line reason
* @throws IOException when the text is not YAML, expands to more than {@link #MAX_NODES}
* nodes or nests deeper than {@link #MAX_DEPTH}, with a one-line reason
*/
public static JsonNode read(String yaml) throws IOException {
Object first;
@@ -81,12 +88,16 @@ public final class YamlTree {
String reason = e.getMessage() == null ? "not valid YAML" : e.getMessage().lines().findFirst().orElse("not valid YAML");
throw new IOException(reason);
}
return first == null ? NODES.missingNode() : tree(first, new int[] {MAX_NODES});
return first == null ? NODES.missingNode() : tree(first, new int[] {MAX_NODES}, 0);
}
// SnakeYAML hands back shared objects for aliases; the tree gets a copy at each use, counted
// against the budget so the copying cannot run away.
private static JsonNode tree(Object value, int[] budget) throws IOException {
private static JsonNode tree(Object value, int[] budget, int depth) throws IOException {
if (depth > MAX_DEPTH) {
throw new IOException("the document is nested more than " + MAX_DEPTH
+ " levels deep, or an alias refers to itself");
}
if (--budget[0] < 0) {
throw new IOException("the document has more than " + MAX_NODES + " values once its aliases are expanded");
}
@@ -94,14 +105,14 @@ public final class YamlTree {
if (value instanceof Map<?, ?> map) {
ObjectNode object = NODES.objectNode();
for (Map.Entry<?, ?> entry : map.entrySet()) {
object.set(String.valueOf(entry.getKey()), tree(entry.getValue(), budget));
object.set(String.valueOf(entry.getKey()), tree(entry.getValue(), budget, depth + 1));
}
return object;
}
if (value instanceof Collection<?> items) {
ArrayNode array = NODES.arrayNode();
for (Object item : items) {
array.add(tree(item, budget));
array.add(tree(item, budget, depth + 1));
}
return array;
}
@@ -515,6 +515,42 @@ class ConfigValidateTest {
assertTrue(json.path("errors").get(0).asText().contains("once its aliases are expanded"), r.out());
}
/**
* An alias that refers to itself is a collection containing itself. It is reported like any
* other unreadable file, not left to overflow the stack.
*/
@ParameterizedTest
@ValueSource(strings = {"x: &a [*a]\n", "x: &a {self: *a}\n", "x: &a [[[*a]]]\nservices: {}\n"})
void aRecursiveAliasIsReportedNotFollowed(String yaml) {
IOException e = assertThrows(IOException.class, () -> YamlTree.read(yaml));
assertTrue(e.getMessage().contains("an alias refers to itself"), e.getMessage());
}
@Test
void theCommandReportsARecursiveAlias() throws Exception {
Path file = Files.writeString(tempDir.resolve("compose.yml"), "x-loop: &a [*a]\nservices: {}\n");
Run json = run("config", "validate", "-f", file.toString(), "-o", "json");
Run text = run("config", "validate", "-f", file.toString());
assertEquals(1, json.exit());
assertFalse(new ObjectMapper().readTree(json.out()).path("valid").asBoolean());
assertTrue(json.out().contains("an alias refers to itself"), json.out());
assertEquals(1, text.exit());
assertTrue(text.err().contains("an alias refers to itself"), text.err());
assertFalse(text.err().contains("StackOverflow"), text.err());
}
/** Ordinary nesting, well past what a Compose file uses, is still read. */
@Test
void deepButFiniteNestingIsRead() throws Exception {
StringBuilder yaml = new StringBuilder("a: ");
yaml.append("[".repeat(40)).append("x").append("]".repeat(40)).append("\n");
assertTrue(YamlTree.read(yaml.toString()).path("a").isArray());
}
/** A real Compose file with many aliases stays far below the budget. */
@Test
void manyOrdinaryAliasesAreFine() throws Exception {