feat(config): check the socket target, TCP mappings and bind types, and report unparsable files as JSON

The socket has to land at /var/run/docker.sock in the container, a UDP mapping no longer counts, a long-form bind with a bare name is checked as a path, an env_file makes the storage mode unknown, and a file that cannot be parsed still gets a structured report.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura committed 2026-10-10 23:26:15 -05:00
1 parent 74e017bf05
commit 3160cbf00c
4 files changed
+171 -42

No files matched your search

+4 -3
View File
@@ -723,14 +723,15 @@ its image; a file with a single service is checked whatever its image is):
| Check | Result when it fails |
|---|---|
| The emulator port is mapped (`"4566:4566"`, `"5566:4566"`, `"127.0.0.1:5566:4566"`, a range, or the long form; any host port works) | error |
| `/var/run/docker.sock` is mounted | error where the product needs it, otherwise a warning |
| The emulator port is mapped over TCP (`"4566:4566"`, `"5566:4566"`, `"127.0.0.1:5566:4566"`, a range, or the long form; any host port works) | error |
| A socket is mounted at `/var/run/docker.sock` in the container (the host side may be any socket) | error where the product needs it, otherwise a warning |
| The volume at `/app/data` is writable and not bound to a file | error |
| A volume at `/app/data` comes with `<PREFIX>_STORAGE_MODE=persistent`, and the other way round | warning |
| The image tag is not older than the oldest version this CLI supports (AWS tree) | warning |
It exits 1 when there is an error and 0 otherwise. `-o json` and `-o yaml` print
`file`, `service`, `valid`, `errors` and `warnings`.
`file`, `service`, `valid`, `errors` and `warnings`, also for a file that cannot be parsed. An
`env_file` is not read, so nothing is said about a storage mode it may set.
#### Profiles
@@ -36,8 +36,14 @@ public final class ComposeCheck {
}
}
/** A volume entry, from either the short {@code src:dst[:mode]} or the long form. */
record Mount(String source, String target, boolean readOnly) {}
/** Where the emulator looks for the Docker socket, inside the container. */
static final String DOCKER_SOCK = "/var/run/docker.sock";
/**
* A volume entry, from either the short {@code src:dst[:mode]} or the long form. {@code bind}
* is true when the source is a path on the host rather than a named volume.
*/
record Mount(String source, String target, boolean readOnly, boolean bind) {}
/**
* @param baseDir the Compose file's directory, against which relative bind sources resolve
@@ -79,9 +85,11 @@ public final class ComposeCheck {
Map<String, String> environment = environment(service.path("environment"));
int port = profile.defaultPort();
if (mounts.stream().noneMatch(m -> endsWithDockerSock(m.source()) || endsWithDockerSock(m.target()))) {
// The container side is what the emulator opens; the host side may be any socket (Podman's,
// a rootless Docker's), so only the target is checked.
if (mounts.stream().noneMatch(m -> DOCKER_SOCK.equals(stripTrailingSlash(m.target())))) {
(dockerSockRequired ? errors : warnings)
.add("Missing /var/run/docker.sock volume mount — required for " + dockerSockNeededFor);
.add("Missing " + DOCKER_SOCK + " volume mount — required for " + dockerSockNeededFor);
}
// With host networking the container's ports are the host's; there is nothing to map.
@@ -93,8 +101,11 @@ public final class ComposeCheck {
Mount data = mounts.stream().filter(m -> DATA_DIR.equals(stripTrailingSlash(m.target()))).findFirst().orElse(null);
String storageVar = profile.envVar("STORAGE_MODE");
String storageMode = environment.get(storageVar);
// A value Compose will substitute (${MODE:-persistent}) cannot be judged from here.
boolean storageKnown = storageMode == null || !storageMode.contains("${");
// A value Compose will substitute (${MODE:-persistent}) cannot be judged from here, and
// neither can one an env_file may set: the file is not read.
boolean storageKnown = storageMode == null
? service.path("env_file").isMissingNode() || service.path("env_file").isNull()
: !storageMode.contains("${");
if (data != null && storageKnown && !"persistent".equalsIgnoreCase(storageMode)) {
warnings.add("A volume is mounted at " + DATA_DIR + " but " + storageVar + " is not 'persistent' — "
+ "the emulator keeps its state in memory by default, so the volume stays empty");
@@ -107,7 +118,7 @@ public final class ComposeCheck {
if (data.readOnly()) {
errors.add("The volume at " + DATA_DIR + " is mounted read-only — the emulator cannot save its state there");
}
String notADirectory = fileWhereADirectoryIsNeeded(data.source(), baseDir);
String notADirectory = fileWhereADirectoryIsNeeded(data, baseDir);
if (notADirectory != null) {
errors.add("The volume at " + DATA_DIR + " is bound to " + notADirectory + ", which is a file, not a directory");
}
@@ -151,18 +162,25 @@ public final class ComposeCheck {
public static boolean publishes(JsonNode ports, int port) {
for (JsonNode entry : ports) {
if (entry.isObject()) {
if (entry.path("target").asInt(-1) == port) return true;
if (entry.path("target").asInt(-1) == port && isTcp(entry.path("protocol").asText(""))) return true;
continue;
}
String text = entry.asText("").strip();
int protocol = text.indexOf('/');
if (protocol >= 0) text = text.substring(0, protocol);
int slash = text.indexOf('/');
String protocol = slash >= 0 ? text.substring(slash + 1) : "";
if (slash >= 0) text = text.substring(0, slash);
String container = text.substring(text.lastIndexOf(':') + 1);
if (inRange(container, port)) return true;
if (isTcp(protocol) && inRange(container, port)) return true;
}
return false;
}
// The emulator's endpoint is HTTP: a UDP mapping of the same number does not reach it. An
// entry without a protocol is TCP, as Compose reads it.
private static boolean isTcp(String protocol) {
return protocol.isBlank() || "tcp".equalsIgnoreCase(protocol.strip());
}
private static boolean inRange(String spec, int port) {
try {
int dash = spec.indexOf('-');
@@ -178,28 +196,39 @@ public final class ComposeCheck {
List<Mount> mounts = new ArrayList<>();
for (JsonNode entry : volumes) {
if (entry.isObject()) {
// In the long form the type says what the source is; a bind's is a host path
// even when it is a bare name like 'data'.
mounts.add(new Mount(entry.path("source").asText(""), entry.path("target").asText(""),
entry.path("read_only").asBoolean(false)));
entry.path("read_only").asBoolean(false), "bind".equals(entry.path("type").asText(""))));
continue;
}
String text = entry.asText("");
// A Windows source (C:\data:/app/data) has a colon of its own after the drive letter.
int from = text.length() > 2 && Character.isLetter(text.charAt(0)) && text.charAt(1) == ':'
&& (text.charAt(2) == '\\' || text.charAt(2) == '/') ? 2 : 0;
int from = startsWithDrive(text) ? 2 : 0;
int first = text.indexOf(':', from);
if (first < 0) {
mounts.add(new Mount("", text, false)); // an anonymous volume: only the container path
mounts.add(new Mount("", text, false, false)); // an anonymous volume: only the container path
continue;
}
String source = text.substring(0, first);
String rest = text.substring(first + 1);
int second = rest.indexOf(':');
String target = second < 0 ? rest : rest.substring(0, second);
String mode = second < 0 ? "" : rest.substring(second + 1);
mounts.add(new Mount(text.substring(0, first), target, List.of(mode.split(",")).contains("ro")));
// In the short form a source is a host path when it looks like one; a bare name is a
// named volume.
boolean bind = source.startsWith("/") || source.startsWith(".") || source.startsWith("~")
|| startsWithDrive(source);
mounts.add(new Mount(source, target, List.of(mode.split(",")).contains("ro"), bind));
}
return mounts;
}
private static boolean startsWithDrive(String text) {
return text.length() > 2 && Character.isLetter(text.charAt(0)) && text.charAt(1) == ':'
&& (text.charAt(2) == '\\' || text.charAt(2) == '/');
}
/** A service's {@code environment}, from either the mapping or the {@code KEY=value} list form. */
static Map<String, String> environment(JsonNode environment) {
Map<String, String> values = new LinkedHashMap<>();
@@ -217,20 +246,19 @@ public final class ComposeCheck {
return values;
}
private static boolean endsWithDockerSock(String path) {
return path.endsWith("docker.sock");
}
private static String stripTrailingSlash(String path) {
return path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
}
// Best effort: only a bind source that is a path on this machine and already exists can be
// looked at. A named volume, a ${VARIABLE} or a path that is not there yet says nothing.
private static String fileWhereADirectoryIsNeeded(String source, Path baseDir) {
if (!(source.startsWith("/") || source.startsWith("."))) return null;
// Best effort: only a bind source that already exists on this machine can be looked at. A
// named volume, a ${VARIABLE}, a home-relative path Compose expands itself, or a path that
// is not there yet says nothing.
private static String fileWhereADirectoryIsNeeded(Mount mount, Path baseDir) {
if (!mount.bind() || mount.source().isBlank() || mount.source().contains("${") || mount.source().startsWith("~")) {
return null;
}
try {
Path path = baseDir.resolve(source).normalize();
Path path = baseDir.resolve(mount.source()).normalize();
return Files.isRegularFile(path) ? path.toString() : null;
} catch (InvalidPathException e) {
return null;
@@ -67,18 +67,25 @@ public class ConfigValidateCommand implements Callable<Integer> {
return 1;
}
JsonNode compose;
JsonNode compose = null;
String unreadable = null;
try {
compose = YAML.readTree(content);
if (compose == null || !compose.isObject()) {
unreadable = "Could not read " + composeFile + " as a Compose file: it has no top-level mapping";
}
} catch (IOException e) {
String reason = e.getMessage() == null ? "unreadable" : e.getMessage().lines().findFirst().orElse("unreadable");
printer.error("Could not read " + composeFile + " as YAML: " + reason,
"Fix the file's syntax, or pass another with --file.");
return 1;
unreadable = "Could not read " + composeFile + " as YAML: " + reason;
}
if (compose == null || !compose.isObject()) {
printer.error("Could not read " + composeFile + " as a Compose file: it has no top-level mapping.",
"Fix the file, or pass another with --file.");
if (unreadable != null) {
// Structured output always carries the report, so a script reading it gets 'valid: false'
// and the reason rather than nothing.
if (printer.format() != OutputFormat.text) {
printer.structured(document(composeFile, new ComposeCheck.Report(null, List.of(unreadable), List.of())));
} else {
printer.error(unreadable, "Fix the file's syntax, or pass another with --file.");
}
return 1;
}
@@ -86,13 +93,7 @@ public class ConfigValidateCommand implements Callable<Integer> {
ComposeCheck.Report report = ComposeCheck.analyze(compose, profile, dockerSockRequired, dockerSockNeededFor, baseDir);
if (printer.format() != OutputFormat.text) {
Map<String, Object> out = new LinkedHashMap<>();
out.put("file", composeFile.toString());
out.put("service", report.service());
out.put("valid", report.valid());
out.put("errors", report.errors());
out.put("warnings", report.warnings());
printer.structured(out);
printer.structured(document(composeFile, report));
return report.valid() ? 0 : 1;
}
@@ -118,6 +119,16 @@ public class ConfigValidateCommand implements Callable<Integer> {
return 0;
}
private static Map<String, Object> document(Path composeFile, ComposeCheck.Report report) {
Map<String, Object> out = new LinkedHashMap<>();
out.put("file", composeFile.toString());
out.put("service", report.service());
out.put("valid", report.valid());
out.put("errors", report.errors());
out.put("warnings", report.warnings());
return out;
}
private Path resolveComposeFile() {
if (file != null) return Path.of(file);
for (String name : List.of("docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml")) {
@@ -74,6 +74,40 @@ class ConfigValidateTest {
assertTrue(errors.get(0).startsWith("No port mapping for 4566 found"), errors.get(0));
}
/** The emulator's endpoint is HTTP: a UDP mapping of the same number does not reach it. */
@ParameterizedTest
@ValueSource(strings = {"\"4566:4566/udp\"", "{target: 4566, published: 5566, protocol: udp}", "\"5566:4566/sctp\""})
void aMappingThatIsNotTcpIsAnError(String ports) throws Exception {
List<String> errors = aws(service(ports, "")).errors();
assertEquals(1, errors.size(), errors.toString());
assertTrue(errors.get(0).startsWith("No port mapping for 4566 found"), errors.get(0));
}
@ParameterizedTest
@ValueSource(strings = {"\"4566:4566/TCP\"", "{target: 4566, published: 5566, protocol: tcp}", "{target: 4566}"})
void tcpIsAcceptedHoweverItIsSpelled(String ports) throws Exception {
assertEquals(List.of(), aws(service(ports, "")).errors(), ports);
}
/** What matters is where the socket lands in the container; the host side may be any socket. */
@ParameterizedTest
@ValueSource(strings = {"/run/user/1000/podman/podman.sock:/var/run/docker.sock", "/var/run/docker.sock:/var/run/docker.sock:ro",
"{type: bind, source: /var/run/docker.sock, target: /var/run/docker.sock}"})
void aSocketMountedAtTheExpectedPathIsAccepted(String volume) throws Exception {
assertEquals(List.of(), aws(service("\"4566:4566\"", "").replace("/var/run/docker.sock:/var/run/docker.sock", volume)).errors());
}
@ParameterizedTest
@ValueSource(strings = {"./notdocker.sock:/tmp/notdocker.sock", "/var/run/docker.sock:/tmp/docker.sock",
"{type: bind, source: /var/run/docker.sock, target: /run/docker.sock}"})
void aSocketMountedSomewhereElseDoesNotCount(String volume) throws Exception {
List<String> errors = aws(service("\"4566:4566\"", "").replace("/var/run/docker.sock:/var/run/docker.sock", volume)).errors();
assertEquals(1, errors.size(), errors.toString());
assertTrue(errors.get(0).startsWith("Missing /var/run/docker.sock volume mount"), errors.get(0));
}
@Test
void hostNetworkingNeedsNoPortMapping() throws Exception {
ComposeCheck.Report r = aws("""
@@ -166,6 +200,24 @@ class ConfigValidateTest {
assertEquals(List.of(), r.warnings(), environment);
}
/** An env_file may set the storage mode; it is not read, so nothing is claimed about it. */
@ParameterizedTest
@ValueSource(strings = {" env_file: .env\n", " env_file:\n - .env\n - .env.local\n"})
void anEnvFileMakesTheStorageModeUnknown(String envFile) throws Exception {
ComposeCheck.Report r = aws(service("\"4566:4566\"", " - ./state:/app/data\n" + envFile));
assertEquals(List.of(), r.warnings(), envFile);
}
/** A mode the file itself spells out is still judged, env_file or not. */
@Test
void anExplicitStorageModeIsJudgedEvenWithAnEnvFile() throws Exception {
ComposeCheck.Report r = aws(service("\"4566:4566\"",
" - ./state:/app/data\n env_file: .env\n environment: {FLOCI_STORAGE_MODE: memory}\n"));
assertEquals(1, r.warnings().size(), r.warnings().toString());
}
@Test
void persistentStorageWithoutADataVolumeIsFlagged() throws Exception {
ComposeCheck.Report r = aws(service("\"4566:4566\"", " environment:\n FLOCI_STORAGE_MODE: persistent\n"));
@@ -212,6 +264,24 @@ class ConfigValidateTest {
assertTrue(r.errors().get(0).contains("which is a file, not a directory"), r.errors().get(0));
}
/** In the long form the type says the source is a host path, even when it is a bare name. */
@Test
void aLongFormBindToAFileIsAnErrorEvenWithABareName() throws Exception {
Files.writeString(tempDir.resolve("data"), "not a directory");
ComposeCheck.Report bind = aws(service("\"4566:4566\"",
" - {type: bind, source: data, target: /app/data}\n environment: {FLOCI_STORAGE_MODE: persistent}\n"));
ComposeCheck.Report named = aws(service("\"4566:4566\"",
" - {type: volume, source: data, target: /app/data}\n environment: {FLOCI_STORAGE_MODE: persistent}\n"));
ComposeCheck.Report shortNamed = aws(service("\"4566:4566\"",
" - data:/app/data\n environment: {FLOCI_STORAGE_MODE: persistent}\n"));
assertEquals(1, bind.errors().size(), bind.errors().toString());
assertTrue(bind.errors().get(0).contains("which is a file, not a directory"), bind.errors().get(0));
assertEquals(List.of(), named.errors(), "a named volume called 'data' is not the file");
assertEquals(List.of(), shortNamed.errors(), "nor is the short form's bare name");
}
/** A directory, a path that does not exist yet and a named volume say nothing against the mount. */
@ParameterizedTest
@ValueSource(strings = {"./state", "./not-there-yet", "floci-data", "${DATA_DIR}"})
@@ -360,4 +430,23 @@ class ConfigValidateTest {
assertTrue(r.err().contains("as YAML"), r.err());
assertTrue(r.err().contains("pass another with --file"), r.err());
}
/** A script reading the report gets one for a file that cannot be parsed too. */
@ParameterizedTest
@ValueSource(strings = {"services: [unterminated\n", "- just\n- a list\n", "plain text\n"})
void aFileThatCannotBeReadStillGetsAStructuredReport(String content) throws Exception {
Path file = Files.writeString(tempDir.resolve("compose.yml"), content);
Run r = run("config", "validate", "-f", file.toString(), "-o", "json");
assertEquals(1, r.exit());
JsonNode json = new ObjectMapper().readTree(r.out());
assertEquals(file.toString(), json.path("file").asText());
assertTrue(json.path("service").isNull(), r.out());
assertFalse(json.path("valid").asBoolean());
assertEquals(1, json.path("errors").size());
assertTrue(json.path("errors").get(0).asText().startsWith("Could not read "), r.out());
assertEquals(0, json.path("warnings").size());
assertEquals("", r.err());
}
}