From 74e017bf05951d46cdf995599dbc5252963f4e0c Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 10 Oct 2026 23:07:18 -0500 Subject: [PATCH] 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 --- README.md | 14 + .../cli/commands/config/ComposeCheck.java | 239 ++++++++++++ .../config/ConfigValidateCommand.java | 75 ++-- .../cli/doctor/checks/ImageVersionCheck.java | 3 +- .../io/floci/cli/unit/ConfigValidateTest.java | 363 ++++++++++++++++++ 5 files changed, 662 insertions(+), 32 deletions(-) create mode 100644 src/main/java/io/floci/cli/commands/config/ComposeCheck.java create mode 100644 src/test/java/io/floci/cli/unit/ConfigValidateTest.java diff --git a/README.md b/README.md index 9f1d2d4..cb00c79 100644 --- a/README.md +++ b/README.md @@ -718,6 +718,20 @@ 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 (`"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 volume at `/app/data` is writable and not bound to a file | error | +| A volume at `/app/data` comes with `_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`. + #### Profiles Profiles are stored in `~/.floci/profiles/.yaml`. Pass `--profile ` to any command to diff --git a/src/main/java/io/floci/cli/commands/config/ComposeCheck.java b/src/main/java/io/floci/cli/commands/config/ComposeCheck.java new file mode 100644 index 0000000..2403753 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/config/ComposeCheck.java @@ -0,0 +1,239 @@ +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 errors, List warnings) { + + public boolean valid() { + return errors.isEmpty(); + } + } + + /** A volume entry, from either the short {@code src:dst[:mode]} or the long form. */ + record Mount(String source, String target, boolean readOnly) {} + + /** + * @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 errors = new ArrayList<>(); + List 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 found = null; + for (Map.Entry 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 mounts = mounts(service.path("volumes")); + Map environment = environment(service.path("environment")); + int port = profile.defaultPort(); + + if (mounts.stream().noneMatch(m -> endsWithDockerSock(m.source()) || endsWithDockerSock(m.target()))) { + (dockerSockRequired ? errors : warnings) + .add("Missing /var/run/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. + boolean storageKnown = storageMode == null || !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.source(), 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) return true; + continue; + } + String text = entry.asText("").strip(); + int protocol = text.indexOf('/'); + if (protocol >= 0) text = text.substring(0, protocol); + String container = text.substring(text.lastIndexOf(':') + 1); + if (inRange(container, port)) return true; + } + return false; + } + + 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 mounts(JsonNode volumes) { + List mounts = new ArrayList<>(); + for (JsonNode entry : volumes) { + if (entry.isObject()) { + mounts.add(new Mount(entry.path("source").asText(""), entry.path("target").asText(""), + entry.path("read_only").asBoolean(false))); + 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 first = text.indexOf(':', from); + if (first < 0) { + mounts.add(new Mount("", text, false)); // an anonymous volume: only the container path + continue; + } + 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"))); + } + return mounts; + } + + /** A service's {@code environment}, from either the mapping or the {@code KEY=value} list form. */ + static Map environment(JsonNode environment) { + Map values = new LinkedHashMap<>(); + if (environment.isObject()) { + for (Map.Entry 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 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; + try { + Path path = baseDir.resolve(source).normalize(); + return Files.isRegularFile(path) ? path.toString() : null; + } catch (InvalidPathException e) { + return null; + } + } +} diff --git a/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java index b8c2915..cdb585a 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java @@ -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 { + private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory()); + protected final ProductProfile profile; private final boolean dockerSockRequired; private final String dockerSockNeededFor; @@ -61,45 +67,52 @@ public class ConfigValidateCommand implements Callable { return 1; } - printer.println(Ansi.bold("Validating") + " " + composeFile); + JsonNode compose; + try { + compose = YAML.readTree(content); + } 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; + } + 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."); + return 1; + } + + Path baseDir = composeFile.toAbsolutePath().getParent(); + ComposeCheck.Report report = ComposeCheck.analyze(compose, profile, dockerSockRequired, dockerSockNeededFor, baseDir); + + if (printer.format() != OutputFormat.text) { + Map 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); + return report.valid() ? 0 : 1; + } + + printer.println(Ansi.bold("Validating") + " " + composeFile + + (report.service() == null ? "" : Ansi.gray(" (service: " + report.service() + ")"))); printer.println(""); - List issues = new ArrayList<>(); - List 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; diff --git a/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java b/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java index 6cc1936..f267a41 100644 --- a/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java @@ -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"); diff --git a/src/test/java/io/floci/cli/unit/ConfigValidateTest.java b/src/test/java/io/floci/cli/unit/ConfigValidateTest.java new file mode 100644 index 0000000..4f84d83 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/ConfigValidateTest.java @@ -0,0 +1,363 @@ +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 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)); + } + + @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); + } + + @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)); + } + + /** 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()); + } +}