fix(config): accept Compose files that use YAML anchors and merge keys in config validate (#65)

* fix(config): accept Compose files that use YAML anchors and merge keys in config validate

config validate read the file without resolving anchors, aliases or merge keys, so a service built from an anchor looked empty and a valid file got two errors and exit 1. The file is now read with its anchors resolved, the way Compose reads it. snakeyaml was already on the classpath through Jackson's YAML module and is now declared, since it is used directly.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* fix(config): bound alias expansion and read Compose scalars as YAML 1.2 in config validate

A few nested aliases can describe millions of values; the reader now stops at 100000 and reports the file instead of using up memory. Only true and false are booleans, so a service named on, off, yes or no keeps its name.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* 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>

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-11 21:12:20 -05:00
1 parent 885e49f81a
commit 68d28d49ef
4 files changed
+452 -8

No files matched your search

+8
View File
@@ -50,6 +50,14 @@
<artifactId>jackson-dataformat-yaml</artifactId> <artifactId>jackson-dataformat-yaml</artifactId>
<version>${jackson.version}</version> <version>${jackson.version}</version>
</dependency> </dependency>
<!-- Already on the classpath through jackson-dataformat-yaml, which is built on it; declared
because config validate uses it directly to resolve anchors and merge keys. Keep the
version the one Jackson's YAML module brings in. -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>2.3</version>
</dependency>
<!-- Testing --> <!-- Testing -->
<dependency> <dependency>
@@ -1,8 +1,6 @@
package io.floci.cli.commands.config; package io.floci.cli.commands.config;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.floci.cli.GlobalOptions; import io.floci.cli.GlobalOptions;
import io.floci.cli.ProductProfile; import io.floci.cli.ProductProfile;
import io.floci.cli.output.Ansi; import io.floci.cli.output.Ansi;
@@ -26,8 +24,6 @@ import java.util.concurrent.Callable;
) )
public class ConfigValidateCommand implements Callable<Integer> { public class ConfigValidateCommand implements Callable<Integer> {
private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory());
protected final ProductProfile profile; protected final ProductProfile profile;
private final boolean dockerSockRequired; private final boolean dockerSockRequired;
private final String dockerSockNeededFor; private final String dockerSockNeededFor;
@@ -71,7 +67,7 @@ public class ConfigValidateCommand implements Callable<Integer> {
JsonNode compose = null; JsonNode compose = null;
String unreadable = null; String unreadable = null;
try { try {
compose = YAML.readTree(content); compose = YamlTree.read(content);
if (compose == null || !compose.isObject()) { if (compose == null || !compose.isObject()) {
unreadable = "Could not read " + composeFile + " as a Compose file: it has no top-level mapping"; unreadable = "Could not read " + composeFile + " as a Compose file: it has no top-level mapping";
} }
@@ -0,0 +1,126 @@
package io.floci.cli.commands.config;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import org.yaml.snakeyaml.resolver.Resolver;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Reads a YAML document into a tree with its anchors, aliases and merge keys resolved, the way a
* YAML consumer such as Compose sees it. Jackson's own {@code readTree} leaves them unresolved:
* {@code volumes: *common} arrives as the string "common" and {@code <<: *base} as a field named
* {@code <<}, so a service built from an anchor looks empty. Its parser also drops anchors on
* scalars ({@code image: &img ...}), so they cannot be resolved on top of it either; SnakeYAML,
* which Jackson's YAML module is built on, does all three.
*/
public final class YamlTree {
/**
* The most nodes a document may have once its aliases are expanded. An alias costs nothing in
* the file and a whole copy in the tree, so a few nested aliases describe millions of nodes;
* no Compose file comes near this, and stopping here keeps such a file from using up memory.
*/
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() {}
/**
* Scalar typing as Compose reads it (YAML 1.2): only {@code true} and {@code false} are
* booleans. SnakeYAML's default follows YAML 1.1, where {@code yes}, {@code no}, {@code on}
* and {@code off} are booleans too, which would rename a service called {@code on} to
* {@code true}. Timestamps are left as text for the same reason: nothing here wants a date.
*/
private static final class ComposeResolver extends Resolver {
private static final Pattern TRUE_OR_FALSE = Pattern.compile("^(?:true|True|TRUE|false|False|FALSE)$");
@Override
protected void addImplicitResolvers() {
addImplicitResolver(Tag.BOOL, TRUE_OR_FALSE, "tTfF");
addImplicitResolver(Tag.INT, INT, "-+0123456789");
addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789.");
addImplicitResolver(Tag.MERGE, MERGE, "<");
addImplicitResolver(Tag.NULL, NULL, "~nN\0");
addImplicitResolver(Tag.NULL, EMPTY, null);
}
}
/**
* The first document of {@code yaml}; a missing node for an empty one.
*
* @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;
try {
// SafeConstructor builds only maps, lists and scalars, never arbitrary classes.
LoaderOptions options = new LoaderOptions();
DumperOptions unused = new DumperOptions();
Yaml reader = new Yaml(new SafeConstructor(options), new Representer(unused), unused, options, new ComposeResolver());
Iterator<Object> documents = reader.loadAll(yaml).iterator();
first = documents.hasNext() ? documents.next() : null;
} catch (YAMLException | IllegalArgumentException e) {
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}, 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, 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");
}
if (value == null) return NODES.nullNode();
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, depth + 1));
}
return object;
}
if (value instanceof Collection<?> items) {
ArrayNode array = NODES.arrayNode();
for (Object item : items) {
array.add(tree(item, budget, depth + 1));
}
return array;
}
if (value instanceof Boolean flag) return NODES.booleanNode(flag);
if (value instanceof Integer number) return NODES.numberNode(number);
if (value instanceof Long number) return NODES.numberNode(number);
if (value instanceof BigInteger number) return NODES.numberNode(number);
if (value instanceof Double number) return NODES.numberNode(number);
return NODES.textNode(String.valueOf(value));
}
}
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.floci.cli.FlociCli; import io.floci.cli.FlociCli;
import io.floci.cli.ProductProfile; import io.floci.cli.ProductProfile;
import io.floci.cli.commands.config.ComposeCheck; import io.floci.cli.commands.config.ComposeCheck;
import io.floci.cli.commands.config.YamlTree;
import io.floci.cli.config.ProfileStore; import io.floci.cli.config.ProfileStore;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
@@ -13,6 +14,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource; import org.junit.jupiter.params.provider.ValueSource;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
@@ -30,7 +32,7 @@ class ConfigValidateTest {
Path tempDir; Path tempDir;
private ComposeCheck.Report aws(String compose) throws Exception { private ComposeCheck.Report aws(String compose) throws Exception {
return ComposeCheck.analyze(YAML.readTree(compose), ProductProfile.AWS, true, NEEDED_FOR, tempDir); return ComposeCheck.analyze(YamlTree.read(compose), ProductProfile.AWS, true, NEEDED_FOR, tempDir);
} }
private static String service(String ports, String extra) { private static String service(String ports, String extra) {
@@ -142,7 +144,7 @@ class ConfigValidateTest {
@Test @Test
void theSocketIsOnlyAWarningWhereTheProductDoesNotNeedIt() throws Exception { void theSocketIsOnlyAWarningWhereTheProductDoesNotNeedIt() throws Exception {
JsonNode compose = YAML.readTree(""" JsonNode compose = YamlTree.read("""
services: services:
gcp: gcp:
image: floci/floci-gcp:latest image: floci/floci-gcp:latest
@@ -228,7 +230,7 @@ class ConfigValidateTest {
@Test @Test
void theStorageVariableIsTheProductsOwn() throws Exception { void theStorageVariableIsTheProductsOwn() throws Exception {
JsonNode compose = YAML.readTree(""" JsonNode compose = YamlTree.read("""
services: services:
oci: oci:
image: floci/floci-oci:latest image: floci/floci-oci:latest
@@ -359,6 +361,318 @@ class ConfigValidateTest {
assertTrue(r.errors().get(0).startsWith("No services found"), r.errors().toString()); assertTrue(r.errors().get(0).startsWith("No services found"), r.errors().toString());
} }
// ---- anchors, aliases and merge keys ---------------------------------------------------------
/** BL-085: a service built from an anchor with a merge key is read the way Compose reads it. */
@Test
void aServiceBuiltFromAnAnchorIsReadInFull() throws Exception {
ComposeCheck.Report r = aws("""
x-floci: &floci
image: floci/floci:latest
ports:
- "4566:4566"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
services:
floci:
<<: *floci
""");
assertEquals("floci", r.service());
assertEquals(List.of(), r.errors());
assertEquals(List.of(), r.warnings());
}
@Test
void anAliasedListIsReadAsTheList() throws Exception {
ComposeCheck.Report r = aws("""
x-volumes: &v
- /var/run/docker.sock:/var/run/docker.sock
x-ports: &p ["5566:4566"]
services:
floci:
image: floci/floci:latest
ports: *p
volumes: *v
""");
assertEquals(List.of(), r.errors());
}
/** A key written in the service wins over the one a merge brings in, wherever '<<' stands. */
@Test
void anExplicitKeyOverridesTheMergedOne() throws Exception {
ComposeCheck.Report r = aws("""
x-base: &base
image: nginx
ports: ["8080:8080"]
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
services:
floci:
image: floci/floci:latest
ports: ["4566:4566"]
<<: *base
""");
assertEquals("floci", r.service());
assertEquals(List.of(), r.errors());
}
@Test
void aMergeOfSeveralMappingsTakesTheEarlierOneFirst() throws Exception {
JsonNode tree = YamlTree.read("""
a: &a {x: 1, y: 1}
b: &b {y: 2, z: 2}
c:
<<: [*a, *b]
z: 3
""");
assertEquals(1, tree.path("c").path("x").asInt());
assertEquals(1, tree.path("c").path("y").asInt());
assertEquals(3, tree.path("c").path("z").asInt());
assertFalse(tree.path("c").has("<<"));
}
/** An alias is a copy: what is checked for one service does not leak into the anchor's owner. */
@Test
void anAnchoredServiceCanBeReusedByAnother() throws Exception {
ComposeCheck.Report r = aws("""
services:
floci: &main
image: floci/floci:latest
ports: ["4566:4566"]
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
floci-b:
<<: *main
ports: ["14566:4566"]
""");
assertEquals("floci", r.service());
assertEquals(List.of(), r.errors());
}
@Test
void scalarsKeepTheirTypesAndPlainDocumentsReadAsBefore() throws Exception {
JsonNode tree = YamlTree.read("""
name: floci
port: 4566
ratio: 1.5
enabled: true
nothing: null
tag: "1.6.0"
list: [1, "two", {three: 3}]
anchored: &s shared
again: *s
""");
assertEquals("floci", tree.path("name").asText());
assertTrue(tree.path("port").isIntegralNumber());
assertEquals(4566, tree.path("port").asInt());
assertEquals(1.5, tree.path("ratio").asDouble());
assertTrue(tree.path("enabled").isBoolean());
assertTrue(tree.path("nothing").isNull());
assertTrue(tree.path("tag").isTextual());
assertEquals(3, tree.path("list").get(2).path("three").asInt());
assertEquals("shared", tree.path("again").asText());
}
/**
* Sixteen levels, three aliases each: 48 aliases, under the parser's own limit, and 43 million
* values once expanded. The reader stops at its budget instead of building that tree.
*/
@Test
void aFileThatExpandsToMillionsOfValuesIsRefusedQuickly() {
StringBuilder bomb = new StringBuilder("x-0: &l0 [a, b, c]\n");
for (int level = 1; level <= 16; level++) {
bomb.append("x-").append(level).append(": &l").append(level)
.append(" [*l").append(level - 1).append(", *l").append(level - 1).append(", *l").append(level - 1).append("]\n");
}
bomb.append("services:\n floci:\n image: floci/floci:latest\n");
long start = System.nanoTime();
IOException e = assertThrows(IOException.class, () -> YamlTree.read(bomb.toString()));
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
assertTrue(e.getMessage().contains("once its aliases are expanded"), e.getMessage());
assertTrue(elapsedMs < 5_000, "took " + elapsedMs + " ms");
}
@Test
void theCommandReportsSuchAFileInsteadOfRunningOutOfMemory() throws Exception {
StringBuilder bomb = new StringBuilder("x-0: &l0 [a, b, c]\n");
for (int level = 1; level <= 16; level++) {
bomb.append("x-").append(level).append(": &l").append(level)
.append(" [*l").append(level - 1).append(", *l").append(level - 1).append(", *l").append(level - 1).append("]\n");
}
Path file = Files.writeString(tempDir.resolve("compose.yml"), bomb + "services: {}\n");
Run r = run("config", "validate", "-f", file.toString(), "-o", "json");
assertEquals(1, r.exit());
JsonNode json = new ObjectMapper().readTree(r.out());
assertFalse(json.path("valid").asBoolean());
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 {
StringBuilder compose = new StringBuilder("x-env: &env {A: 1, B: 2, C: 3}\nservices:\n");
for (int i = 0; i < 40; i++) {
compose.append(" svc").append(i).append(":\n image: busybox\n environment: *env\n");
}
compose.append(" floci:\n image: floci/floci:latest\n ports: [\"4566:4566\"]\n"
+ " volumes: [\"/var/run/docker.sock:/var/run/docker.sock\"]\n");
ComposeCheck.Report r = aws(compose.toString());
assertEquals("floci", r.service());
assertEquals(List.of(), r.errors());
}
/**
* Compose reads YAML 1.2, where only true and false are booleans. A service or key called
* on, off, yes or no keeps its spelling instead of turning into true or false.
*/
@ParameterizedTest
@ValueSource(strings = {"on", "off", "yes", "no", "y", "n", "On", "NO"})
void aServiceNamedLikeAYaml11BooleanKeepsItsName(String name) throws Exception {
ComposeCheck.Report r = aws("""
services:
%s:
image: floci/floci:latest
ports: ["4566:4566"]
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
""".formatted(name));
assertEquals(name, r.service());
assertEquals(List.of(), r.errors());
}
@Test
void onlyTrueAndFalseAreBooleans() throws Exception {
JsonNode tree = YamlTree.read("""
a: true
b: False
c: yes
d: off
e: 2024-01-01
f: 0x1F
g: ~
""");
assertTrue(tree.path("a").isBoolean() && tree.path("a").asBoolean());
assertTrue(tree.path("b").isBoolean() && !tree.path("b").asBoolean());
assertEquals("yes", tree.path("c").asText());
assertTrue(tree.path("c").isTextual());
assertEquals("off", tree.path("d").asText());
assertEquals("2024-01-01", tree.path("e").asText());
assertTrue(tree.path("f").isIntegralNumber());
assertTrue(tree.path("g").isNull());
}
/** read_only written as true still makes a data volume read-only. */
@Test
void aBooleanValueIsStillABoolean() throws Exception {
ComposeCheck.Report r = aws(service("\"4566:4566\"",
" - {type: bind, source: ./data, target: /app/data, read_only: true}\n environment: {FLOCI_STORAGE_MODE: persistent}\n"));
assertEquals(1, r.errors().size(), r.errors().toString());
assertTrue(r.errors().get(0).contains("mounted read-only"), r.errors().get(0));
}
@Test
void anAliasWithoutItsAnchorIsAParseError() {
assertThrows(IOException.class, () -> YamlTree.read("services:\n floci: *missing\n"));
}
@Test
void anEmptyDocumentIsMissing() throws Exception {
assertTrue(YamlTree.read("").isMissingNode());
assertTrue(YamlTree.read("# only a comment\n").isMissingNode());
}
/** An anchor on a plain value, such as a shared image tag, resolves like any other. */
@Test
void anAnchorOnAScalarResolves() throws Exception {
ComposeCheck.Report r = aws("""
x-image: &image floci/floci:1.6.0
x-port: &port "4566:4566"
services:
floci:
image: *image
ports: [*port]
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
""");
assertEquals("floci", r.service());
assertEquals(List.of(), r.errors());
assertEquals(List.of(), r.warnings());
}
/** Through the command: the file from the report exits 0. */
@Test
void theCommandAcceptsAComposeFileWithAnchors() throws Exception {
Path file = Files.writeString(tempDir.resolve("compose.yml"), """
x-floci: &floci
image: floci/floci:latest
volumes: &sock
- /var/run/docker.sock:/var/run/docker.sock
services:
floci:
<<: *floci
ports: ["4566:4566"]
worker:
image: busybox
volumes: *sock
""");
Run r = run("config", "validate", "-f", file.toString(), "-o", "json");
assertEquals(0, r.exit(), r.out() + r.err());
JsonNode json = new ObjectMapper().readTree(r.out());
assertTrue(json.path("valid").asBoolean(), r.out());
assertEquals("floci", json.path("service").asText());
assertEquals(0, json.path("errors").size());
}
// ---- the command --------------------------------------------------------------------------- // ---- the command ---------------------------------------------------------------------------
private record Run(int exit, String out, String err) {} private record Run(int exit, String out, String err) {}