feat(config): validate Compose files by their structure, with -o json and three more checks (#61)

* feat(config): validate Compose files by their structure, with -o json and three more checks

config validate now parses the Compose file and checks the emulator's own service: any host port mapped to the emulator port is accepted (5566:4566 was rejected), -o json and -o yaml report the findings, and it flags a read-only or file-bound data volume, a data volume without persistent storage mode (and the reverse), and an image tag older than the supported minimum.

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

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

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-11 09:01:14 -05:00
1 parent 4a9a9b5a4a
commit 6b06382516
5 files changed
+791 -32

No files matched your search

+15
View File
@@ -729,6 +729,21 @@ Each product tree has its own `config show|validate|profile` (`floci gcp config
uses that product's defaults; `config default-product` is available through bare `floci config`
and `floci aws config`, but not through the GCP, Azure, or OCI config trees.
`config validate` reads the Compose file and checks the service that runs the emulator (found by
its image; a file with a single service is checked whatever its image is):
| Check | Result when it fails |
|---|---|
| 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`, 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
Profiles are stored in `~/.floci/profiles/<name>.yaml`. Pass `--profile <name>` to any command to
@@ -0,0 +1,267 @@
package io.floci.cli.commands.config;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.cli.ProductProfile;
import io.floci.cli.doctor.checks.ImageVersionCheck;
import io.floci.cli.update.Version;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* What {@code config validate} finds in a Compose file. It reads the parsed document and looks
* at the one service that runs the product's emulator, so a port or a volume on some other
* service is never taken for the emulator's.
*/
public final class ComposeCheck {
/** The directory the emulator keeps its state in, inside the container. */
static final String DATA_DIR = "/app/data";
private ComposeCheck() {}
/**
* The findings for one file. {@code service} is the Compose service that was checked, or null
* when none could be told apart as the emulator's.
*/
public record Report(String service, List<String> errors, List<String> warnings) {
public boolean valid() {
return errors.isEmpty();
}
}
/** 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
*/
public static Report analyze(JsonNode compose, ProductProfile profile, boolean dockerSockRequired,
String dockerSockNeededFor, Path baseDir) {
List<String> errors = new ArrayList<>();
List<String> warnings = new ArrayList<>();
JsonNode services = compose.path("services");
if (!services.isObject() || services.isEmpty()) {
errors.add("No services found: a Compose file needs a 'services' section with the "
+ profile.displayName() + " service in it");
return new Report(null, errors, warnings);
}
String ghcrImage = "ghcr.io/floci-io/" + profile.image().substring(profile.image().indexOf('/') + 1);
Map.Entry<String, JsonNode> found = null;
for (Map.Entry<String, JsonNode> service : services.properties()) {
String repository = repositoryOf(service.getValue().path("image").asText(""));
if (repository.equals(profile.image()) || repository.equals("docker.io/" + profile.image())
|| repository.equals(ghcrImage)) {
found = service;
break;
}
}
if (found == null) {
warnings.add(profile.displayName() + " image reference not detected — ensure your service uses "
+ profile.image() + " or " + ghcrImage);
// With one service there is no doubt which one is meant (a locally built image, a
// mirror); with several, checking the wrong one would only mislead.
if (services.size() != 1) {
return new Report(null, errors, warnings);
}
found = services.properties().iterator().next();
}
JsonNode service = found.getValue();
List<Mount> mounts = mounts(service.path("volumes"));
Map<String, String> environment = environment(service.path("environment"));
int port = profile.defaultPort();
// 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 " + DOCKER_SOCK + " volume mount — required for " + dockerSockNeededFor);
}
// With host networking the container's ports are the host's; there is nothing to map.
if (!"host".equals(service.path("network_mode").asText("")) && !publishes(service.path("ports"), port)) {
errors.add("No port mapping for " + port + " found — " + profile.displayName() + " listens on " + port
+ " inside the container; map any host port to it, for example \"" + port + ":" + port + "\"");
}
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, 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");
}
if (data == null && "persistent".equalsIgnoreCase(storageMode)) {
warnings.add(storageVar + " is 'persistent' but nothing is mounted at " + DATA_DIR
+ " — the state is lost when the container is removed");
}
if (data != null) {
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, baseDir);
if (notADirectory != null) {
errors.add("The volume at " + DATA_DIR + " is bound to " + notADirectory + ", which is a file, not a directory");
}
}
String tag = tagOf(service.path("image").asText(""));
// The minimum is the AWS emulator's; the other emulators are versioned on their own lines.
if ("aws".equals(profile.name()) && Version.isValid(tag)
&& !ImageVersionCheck.meetsMinimum(tag, ImageVersionCheck.MIN_VERSION)) {
warnings.add("Image tag " + tag + " is older than " + ImageVersionCheck.MIN_VERSION
+ ", the oldest version this CLI supports — use a newer tag");
}
return new Report(found.getKey(), errors, warnings);
}
/** {@code registry/name:tag@digest} without its tag and digest. */
public static String repositoryOf(String image) {
String reference = image.strip();
int digest = reference.indexOf('@');
if (digest >= 0) reference = reference.substring(0, digest);
int colon = reference.lastIndexOf(':');
// A colon before the last slash is a registry port, not a tag.
return colon > reference.lastIndexOf('/') ? reference.substring(0, colon) : reference;
}
/** The tag of an image reference, or an empty string when it has none. */
public static String tagOf(String image) {
String reference = image.strip();
int digest = reference.indexOf('@');
if (digest >= 0) reference = reference.substring(0, digest);
int colon = reference.lastIndexOf(':');
return colon > reference.lastIndexOf('/') ? reference.substring(colon + 1) : "";
}
/**
* Whether one of a service's {@code ports} entries reaches {@code port} inside the container,
* whatever the host side is: {@code 4566}, {@code "4566:4566"}, {@code "5566:4566"},
* {@code "127.0.0.1:5566:4566/tcp"}, a range that contains it, or the long form's {@code target}.
*/
public static boolean publishes(JsonNode ports, int port) {
for (JsonNode entry : ports) {
if (entry.isObject()) {
if (entry.path("target").asInt(-1) == port && isTcp(entry.path("protocol").asText(""))) return true;
continue;
}
String text = entry.asText("").strip();
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 (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('-');
if (dash < 0) return Integer.parseInt(spec.strip()) == port;
return Integer.parseInt(spec.substring(0, dash).strip()) <= port
&& port <= Integer.parseInt(spec.substring(dash + 1).strip());
} catch (NumberFormatException e) {
return false; // a ${VARIABLE} or something else that is not a number
}
}
static List<Mount> mounts(JsonNode volumes) {
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), "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 = startsWithDrive(text) ? 2 : 0;
int first = text.indexOf(':', from);
if (first < 0) {
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);
// 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<>();
if (environment.isObject()) {
for (Map.Entry<String, JsonNode> entry : environment.properties()) {
values.put(entry.getKey(), entry.getValue().asText(""));
}
} else {
for (JsonNode entry : environment) {
String text = entry.asText("");
int equals = text.indexOf('=');
if (equals > 0) values.put(text.substring(0, equals), text.substring(equals + 1));
}
}
return values;
}
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 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(mount.source()).normalize();
return Files.isRegularFile(path) ? path.toString() : null;
} catch (InvalidPathException e) {
return null;
}
}
}
@@ -1,18 +1,22 @@
package io.floci.cli.commands.config;
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.ProductProfile;
import io.floci.cli.output.Ansi;
import io.floci.cli.output.OutputFormat;
import io.floci.cli.output.Printer;
import picocli.CommandLine.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.regex.Pattern;
@Command(
name = "validate",
@@ -21,6 +25,8 @@ import java.util.regex.Pattern;
)
public class ConfigValidateCommand implements Callable<Integer> {
private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory());
protected final ProductProfile profile;
private final boolean dockerSockRequired;
private final String dockerSockNeededFor;
@@ -61,50 +67,68 @@ public class ConfigValidateCommand implements Callable<Integer> {
return 1;
}
printer.println(Ansi.bold("Validating") + " " + composeFile);
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");
unreadable = "Could not read " + composeFile + " as YAML: " + reason;
}
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;
}
Path baseDir = composeFile.toAbsolutePath().getParent();
ComposeCheck.Report report = ComposeCheck.analyze(compose, profile, dockerSockRequired, dockerSockNeededFor, baseDir);
if (printer.format() != OutputFormat.text) {
printer.structured(document(composeFile, report));
return report.valid() ? 0 : 1;
}
printer.println(Ansi.bold("Validating") + " " + composeFile
+ (report.service() == null ? "" : Ansi.gray(" (service: " + report.service() + ")")));
printer.println("");
List<String> issues = new ArrayList<>();
List<String> warnings = new ArrayList<>();
// Check for docker.sock mount (an error where the product needs it for core services)
if (!content.contains("/var/run/docker.sock")) {
(dockerSockRequired ? issues : warnings)
.add("Missing /var/run/docker.sock volume mount — required for " + dockerSockNeededFor);
}
// Check port mapping
int port = profile.defaultPort();
if (!Pattern.compile(port + "\\s*:\\s*" + port).matcher(content).find()) {
issues.add("Port mapping " + port + ":" + port + " not found — " + profile.displayName()
+ " listens on " + port + " by default");
}
// Check for the product image
String ghcrImage = "ghcr.io/floci-io/" + profile.image().substring(profile.image().indexOf('/') + 1);
if (!content.contains(profile.image()) && !content.contains(ghcrImage)) {
warnings.add(profile.displayName() + " image reference not detected — ensure your service uses "
+ profile.image() + " or " + ghcrImage);
}
for (String issue : issues) {
for (String issue : report.errors()) {
printer.println(" " + Ansi.red("✗") + " " + issue);
}
for (String warn : warnings) {
for (String warn : report.warnings()) {
printer.println(" " + Ansi.yellow("⚠") + " " + warn);
}
if (issues.isEmpty() && warnings.isEmpty()) {
if (report.errors().isEmpty() && report.warnings().isEmpty()) {
printer.println(" " + Ansi.green("✓") + " Compose file looks good");
}
printer.println("");
if (!issues.isEmpty()) {
printer.println(issues.size() + " error(s) found.");
if (!report.valid()) {
printer.println(report.errors().size() + " error(s) found.");
return 1;
}
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")) {
@@ -15,7 +15,8 @@ public class ImageVersionCheck implements Check {
private final String image;
private final DockerClient docker;
private static final String MIN_VERSION = "1.5.0";
/** The oldest server version this CLI supports. */
public static final String MIN_VERSION = "1.5.0";
public ImageVersionCheck() {
this("floci/floci");
@@ -0,0 +1,452 @@
package io.floci.cli.unit;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.floci.cli.FlociCli;
import io.floci.cli.ProductProfile;
import io.floci.cli.commands.config.ComposeCheck;
import io.floci.cli.config.ProfileStore;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/** BL-055: config validate reads the Compose file's structure and checks the emulator's own service. */
class ConfigValidateTest {
private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory());
private static final String NEEDED_FOR = "Lambda, EC2";
@TempDir
Path tempDir;
private ComposeCheck.Report aws(String compose) throws Exception {
return ComposeCheck.analyze(YAML.readTree(compose), ProductProfile.AWS, true, NEEDED_FOR, tempDir);
}
private static String service(String ports, String extra) {
return """
services:
floci:
image: floci/floci:latest
ports:
- %s
volumes:
- /var/run/docker.sock:/var/run/docker.sock
%s""".formatted(ports, extra);
}
@Test
void aCompleteServiceHasNothingToReport() throws Exception {
ComposeCheck.Report r = aws(service("\"4566:4566\"", ""));
assertEquals("floci", r.service());
assertEquals(List.of(), r.errors());
assertEquals(List.of(), r.warnings());
assertTrue(r.valid());
}
/** Any host port works: only the container side has to be the emulator's port. */
@ParameterizedTest
@ValueSource(strings = {"\"4566:4566\"", "\"5566:4566\"", "\"127.0.0.1:5566:4566\"", "\"5566:4566/tcp\"",
"4566", "\"4566\"", "\"14510-14600:4510-4600\"", "{target: 4566, published: 5566}",
"{target: 4566, published: \"5566\", protocol: tcp}"})
void everyWayOfMappingTheEmulatorPortIsAccepted(String ports) throws Exception {
assertEquals(List.of(), aws(service(ports, "")).errors(), ports);
}
@ParameterizedTest
@ValueSource(strings = {"\"4566:8080\"", "\"8080:8080\"", "\"45660:45660\"", "8080", "{target: 8080, published: 4566}",
"\"${HOST_PORT}:${CONTAINER_PORT}\""})
void aMappingThatDoesNotReachTheEmulatorPortIsAnError(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));
}
/** 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("""
services:
floci:
image: floci/floci:latest
network_mode: host
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
""");
assertEquals(List.of(), r.errors());
}
/** Another service's port or socket mount must not satisfy the emulator's checks. */
@Test
void onlyTheEmulatorsOwnServiceCounts() throws Exception {
ComposeCheck.Report r = aws("""
services:
proxy:
image: nginx
ports: ["4566:4566"]
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
floci:
image: ghcr.io/floci-io/floci:1.6.0
""");
assertEquals("floci", r.service());
assertEquals(2, r.errors().size(), r.errors().toString());
assertTrue(r.errors().get(0).contains("docker.sock"), r.errors().toString());
assertTrue(r.errors().get(1).contains("No port mapping for 4566"), r.errors().toString());
}
@Test
void theSocketIsOnlyAWarningWhereTheProductDoesNotNeedIt() throws Exception {
JsonNode compose = YAML.readTree("""
services:
gcp:
image: floci/floci-gcp:latest
ports: ["4588:4588"]
""");
ComposeCheck.Report r = ComposeCheck.analyze(compose, ProductProfile.GCP, false, "Cloud Run", tempDir);
assertTrue(r.valid());
assertEquals(1, r.warnings().size());
assertTrue(r.warnings().get(0).contains("docker.sock"), r.warnings().toString());
}
@Test
void theLongVolumeFormIsRead() throws Exception {
ComposeCheck.Report r = aws("""
services:
floci:
image: floci/floci
ports: ["4566:4566"]
volumes:
- type: bind
source: /var/run/docker.sock
target: /var/run/docker.sock
""");
assertEquals(List.of(), r.errors());
}
// ---- storage mode and the data volume ----------------------------------------------------
@Test
void aDataVolumeWithoutPersistentStorageIsFlagged() throws Exception {
ComposeCheck.Report r = aws(service("\"4566:4566\"", " - ./data:/app/data\n"));
assertTrue(r.valid());
assertEquals(1, r.warnings().size(), r.warnings().toString());
assertTrue(r.warnings().get(0).contains("FLOCI_STORAGE_MODE is not 'persistent'"), r.warnings().get(0));
}
@ParameterizedTest
@ValueSource(strings = {"""
environment:
FLOCI_STORAGE_MODE: persistent
""", """
environment:
- FLOCI_STORAGE_MODE=persistent
""", """
environment:
FLOCI_STORAGE_MODE: ${MODE:-memory}
"""})
void aDataVolumeWithPersistentStorageIsFine(String environment) throws Exception {
ComposeCheck.Report r = aws(service("\"4566:4566\"", " - floci-data:/app/data\n" + environment));
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"));
assertEquals(1, r.warnings().size(), r.warnings().toString());
assertTrue(r.warnings().get(0).contains("nothing is mounted at /app/data"), r.warnings().get(0));
}
@Test
void theStorageVariableIsTheProductsOwn() throws Exception {
JsonNode compose = YAML.readTree("""
services:
oci:
image: floci/floci-oci:latest
ports: ["4599:4599"]
volumes: ["./state:/app/data", "/var/run/docker.sock:/var/run/docker.sock"]
environment:
FLOCI_STORAGE_MODE: persistent
""");
ComposeCheck.Report r = ComposeCheck.analyze(compose, ProductProfile.OCI, true, "Functions", tempDir);
assertTrue(r.warnings().get(0).contains("FLOCI_OCI_STORAGE_MODE is not 'persistent'"), r.warnings().toString());
}
@ParameterizedTest
@ValueSource(strings = {" - ./data:/app/data:ro\n", " - floci-data:/app/data/:ro,z\n",
" - {type: bind, source: ./data, target: /app/data, read_only: true}\n"})
void aReadOnlyDataVolumeIsAnError(String volume) throws Exception {
ComposeCheck.Report r = aws(service("\"4566:4566\"", volume + " 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 aDataVolumeBoundToAFileIsAnError() throws Exception {
Files.writeString(tempDir.resolve("data"), "not a directory");
ComposeCheck.Report r = aws(service("\"4566:4566\"",
" - ./data:/app/data\n environment: {FLOCI_STORAGE_MODE: persistent}\n"));
assertEquals(1, r.errors().size(), r.errors().toString());
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}"})
void otherDataSourcesAreNotJudged(String source) throws Exception {
Files.createDirectories(tempDir.resolve("state"));
ComposeCheck.Report r = aws(service("\"4566:4566\"",
" - " + source + ":/app/data\n environment: {FLOCI_STORAGE_MODE: persistent}\n"));
assertEquals(List.of(), r.errors(), source);
}
// ---- image ---------------------------------------------------------------------------------
@Test
void anImageOlderThanTheSupportedMinimumIsFlagged() throws Exception {
ComposeCheck.Report r = aws(service("\"4566:4566\"", "").replace("floci/floci:latest", "floci/floci:1.4.2"));
assertTrue(r.valid());
assertEquals(1, r.warnings().size(), r.warnings().toString());
assertTrue(r.warnings().get(0).contains("Image tag 1.4.2 is older than 1.5.0"), r.warnings().get(0));
}
@ParameterizedTest
@ValueSource(strings = {"floci/floci", "floci/floci:latest", "floci/floci:1.5.0", "floci/floci:2.0.1",
"ghcr.io/floci-io/floci:1.6.0", "docker.io/floci/floci:1.6.0", "floci/floci:1.6.0@sha256:abc", "floci/floci:nightly"})
void supportedOrUnversionedImagesAreNotFlagged(String image) throws Exception {
ComposeCheck.Report r = aws(service("\"4566:4566\"", "").replace("floci/floci:latest", image));
assertEquals("floci", r.service(), image);
assertEquals(List.of(), r.warnings(), image);
}
@Test
void repositoriesAndTagsAreSplitAtTheRightColon() {
assertEquals("registry.local:5000/floci/floci", ComposeCheck.repositoryOf("registry.local:5000/floci/floci:1.6.0"));
assertEquals("1.6.0", ComposeCheck.tagOf("registry.local:5000/floci/floci:1.6.0"));
assertEquals("registry.local:5000/floci/floci", ComposeCheck.repositoryOf("registry.local:5000/floci/floci"));
assertEquals("", ComposeCheck.tagOf("registry.local:5000/floci/floci"));
}
/** One service and no recognisable image (built locally, mirrored): it is still the one to check. */
@Test
void aSingleServiceIsCheckedEvenWithoutARecognisedImage() throws Exception {
ComposeCheck.Report r = aws("""
services:
emulator:
build: .
""");
assertEquals("emulator", r.service());
assertEquals(2, r.errors().size(), r.errors().toString());
assertTrue(r.warnings().get(0).contains("image reference not detected"), r.warnings().toString());
}
/** Several services and none recognisable: checking one at random would only mislead. */
@Test
void severalServicesWithoutARecognisedImageAreNotGuessedAt() throws Exception {
ComposeCheck.Report r = aws("""
services:
web: {image: nginx}
db: {image: postgres}
""");
assertNull(r.service());
assertEquals(List.of(), r.errors());
assertEquals(1, r.warnings().size());
}
@Test
void aFileWithoutServicesIsAnError() throws Exception {
ComposeCheck.Report r = aws("version: '3'\n");
assertFalse(r.valid());
assertTrue(r.errors().get(0).startsWith("No services found"), r.errors().toString());
}
// ---- the command ---------------------------------------------------------------------------
private record Run(int exit, String out, String err) {}
private Run run(String... args) {
PrintStream out = System.out;
PrintStream err = System.err;
ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
System.setOut(new PrintStream(outBuf));
System.setErr(new PrintStream(errBuf));
try {
int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir.resolve("profiles"))).execute(args);
return new Run(exit, outBuf.toString(), errBuf.toString());
} finally {
System.setOut(out);
System.setErr(err);
}
}
@Test
void jsonOutputCarriesTheFindingsAndTheExitCode() throws Exception {
Path file = Files.writeString(tempDir.resolve("compose.yml"), """
services:
floci:
image: floci/floci:1.4.0
ports: ["4566:8080"]
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
""");
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());
assertEquals("floci", json.path("service").asText());
assertFalse(json.path("valid").asBoolean());
assertEquals(1, json.path("errors").size());
assertEquals(1, json.path("warnings").size());
assertFalse(r.out().contains("Validating"), "no text banner in structured output");
}
@Test
void aValidFileExitsZeroInEveryTree() throws Exception {
Path file = Files.writeString(tempDir.resolve("compose.yml"), """
services:
gcp:
image: floci/floci-gcp:latest
ports: ["14588:4588"]
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
""");
Run text = run("gcp", "config", "validate", "-f", file.toString());
Run yaml = run("gcp", "config", "validate", "-f", file.toString(), "-o", "yaml");
assertEquals(0, text.exit(), text.out() + text.err());
assertTrue(text.out().contains("Compose file looks good"), text.out());
assertEquals(0, yaml.exit());
assertTrue(yaml.out().contains("valid: true"), yaml.out());
}
@Test
void aFileThatIsNotYamlIsReportedWithANextStep() throws Exception {
Path file = Files.writeString(tempDir.resolve("compose.yml"), "services: [unterminated\n");
Run r = run("config", "validate", "-f", file.toString());
assertEquals(1, r.exit());
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());
}
}