mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-22 21:50:47 -05:00
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>
This commit is contained in:
2 files changed
+184
-9
No files matched your search
@@ -1,15 +1,24 @@
|
||||
package io.floci.cli.commands.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.MissingNode;
|
||||
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
|
||||
@@ -21,25 +30,86 @@ import java.util.Iterator;
|
||||
*/
|
||||
public final class YamlTree {
|
||||
|
||||
private static final ObjectMapper TREES = new ObjectMapper();
|
||||
/**
|
||||
* 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;
|
||||
|
||||
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, with a one-line reason
|
||||
* @throws IOException when the text is not YAML, or expands to more than {@link #MAX_NODES}
|
||||
* nodes, 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, and the
|
||||
// default LoaderOptions bound how far aliases may expand.
|
||||
Iterator<Object> documents = new Yaml(new SafeConstructor(new LoaderOptions())).loadAll(yaml).iterator();
|
||||
Object first = documents.hasNext() ? documents.next() : null;
|
||||
return first == null ? MissingNode.getInstance() : TREES.valueToTree(first);
|
||||
// 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});
|
||||
}
|
||||
|
||||
// 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 {
|
||||
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));
|
||||
}
|
||||
return object;
|
||||
}
|
||||
if (value instanceof Collection<?> items) {
|
||||
ArrayNode array = NODES.arrayNode();
|
||||
for (Object item : items) {
|
||||
array.add(tree(item, budget));
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -477,6 +477,111 @@ class ConfigValidateTest {
|
||||
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());
|
||||
}
|
||||
|
||||
/** 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"));
|
||||
|
||||
Reference in new issue
Block a user