Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

fix(docker): never run a compose file from the working directory

KageBinaryb71a33313811
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 9d28312c..ce9e9e9b 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -305,6 +305,8 @@ jobs:
|| { echo "::error::cli/dist/cli/main.js missing from staging — the tarball would contain no CLI at all"; exit 1; }
test -f "$STAGING/cli/package.json" && test -d "$STAGING/cli/node_modules" \
|| { echo "::error::cli/package.json or cli/node_modules missing from staging — the CLI would not start"; exit 1; }
+ test -f "$STAGING/cli/dist/docker-compose.standalone.yml" \
+ || { echo "::error::cli/dist/docker-compose.standalone.yml missing from staging — ix docker start would have no backend compose file"; exit 1; }
cp -rL ix-cli/scripts/render-logo.mjs ix-cli/scripts/render-logo.d.mts "$STAGING/cli/scripts/"
cp -rL ix-cli/assets/logo.png "$STAGING/cli/assets/"
test -f "$STAGING/cli/scripts/render-logo.mjs" && test -f "$STAGING/cli/assets/logo.png" \
diff --git a/Formula/ix.rb b/Formula/ix.rb
index 37db1b21..1278fefe 100644
--- a/Formula/ix.rb
+++ b/Formula/ix.rb
@@ -28,6 +28,9 @@ class Ix < Formula
# Run tsc directly — npm run build would redundantly rebuild core-ingestion
# via build-core-ingestion.mjs, which triggers native module compilation
system "npx", "tsc"
+ # The backend compose file `ix docker start` writes to ~/.ix/backend/.
+ # npm run build copies it into dist/; this build skips npm run build.
+ cp "../docker-compose.standalone.yml", "dist/docker-compose.standalone.yml"
# Install the compiled CLI and its dependencies
libexec.install "dist", "node_modules", "package.json"
diff --git a/ix-cli/package.json b/ix-cli/package.json
index 669517d0..e6552adf 100644
--- a/ix-cli/package.json
+++ b/ix-cli/package.json
@@ -16,7 +16,7 @@
"node": ">=22.0.0"
},
"scripts": {
- "build": "node scripts/build-core-ingestion.mjs && node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
+ "build": "node scripts/build-core-ingestion.mjs && node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json && node -e \"require('fs').copyFileSync('../docker-compose.standalone.yml','dist/docker-compose.standalone.yml')\"",
"test": "node scripts/build-core-ingestion.mjs && vitest run && node test/parser.smoke.mjs",
"test:unit": "vitest run",
"test:coverage": "vitest run --coverage",
diff --git a/ix-cli/src/cli/__tests__/docker-compose-source.test.ts b/ix-cli/src/cli/__tests__/docker-compose-source.test.ts
new file mode 100644
index 00000000..4cf19d92
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/docker-compose-source.test.ts
@@ -0,0 +1,108 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { Command } from "commander";
+
+/**
+ * `ix docker start` used to fall back to ./docker-compose.yml when
+ * ~/.ix/backend had none, so running it inside an untrusted repository ran
+ * whatever services that repository declared. The backend compose file now
+ * comes only from the copy the CLI ships.
+ */
+
+const REPO_COMPOSE = resolve(fileURLToPath(new URL("../../../../docker-compose.standalone.yml", import.meta.url)));
+
+let t: string;
+let saved: Record<string, string | undefined>;
+
+beforeEach(() => {
+ vi.resetModules();
+ t = mkdtempSync(join(tmpdir(), "ix-docker-src-"));
+ saved = {
+ PATH: process.env.PATH,
+ IX_HOME: process.env.IX_HOME,
+ IX_BUNDLED_COMPOSE: process.env.IX_BUNDLED_COMPOSE,
+ CWD: process.cwd(),
+ };
+ // docker records every call; `compose ... up` marks the backend as started.
+ // curl answers the health probes: unhealthy until `up` ran.
+ mkdirSync(join(t, "bin"));
+ writeFileSync(join(t, "bin", "docker"), `#!/bin/sh\necho "$*" >> "${t}/docker.log"\ncase "$*" in *" up "*) touch "${t}/up" ;; esac\nexit 0\n`);
+ writeFileSync(join(t, "bin", "curl"), `#!/bin/sh\n[ -f "${t}/up" ]\n`);
+ chmodSync(join(t, "bin", "docker"), 0o755);
+ chmodSync(join(t, "bin", "curl"), 0o755);
+ process.env.PATH = `${join(t, "bin")}:${process.env.PATH}`;
+ process.env.IX_HOME = join(t, "ix-home");
+ // A repository carrying its own compose file, as an attacker's would.
+ mkdirSync(join(t, "repo"));
+ writeFileSync(join(t, "repo", "docker-compose.yml"), "services:\n evil:\n image: evil\n");
+ process.chdir(join(t, "repo"));
+});
+
+afterEach(() => {
+ process.chdir(saved.CWD!);
+ for (const k of ["PATH", "IX_HOME", "IX_BUNDLED_COMPOSE"]) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+ vi.restoreAllMocks();
+ rmSync(t, { recursive: true, force: true });
+});
+
+async function dockerStart(): Promise<void> {
+ const { registerDockerCommand } = await import("../commands/docker.js");
+ const program = new Command().exitOverride();
+ registerDockerCommand(program);
+ await program.parseAsync(["docker", "start"], { from: "user" });
+}
+
+const log = () => (existsSync(join(t, "docker.log")) ? readFileSync(join(t, "docker.log"), "utf8") : "");
+
+describe("ix docker start: where the compose file comes from", () => {
+ it.skipIf(process.platform === "win32")("writes the shipped compose file and never runs the repository's", async () => {
+ process.env.IX_BUNDLED_COMPOSE = REPO_COMPOSE;
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ vi.spyOn(process.stdout, "write").mockImplementation(() => true);
+
+ await dockerStart();
+
+ const local = join(t, "ix-home", "backend", "docker-compose.yml");
+ expect(readFileSync(local, "utf8")).toBe(readFileSync(REPO_COMPOSE, "utf8"));
+ expect(log()).toContain(`compose -f ${local} up -d --pull always`);
+ expect(log()).not.toContain(join(t, "repo"));
+ });
+
+ it.skipIf(process.platform === "win32")("fails with a message and runs nothing when no compose file ships", async () => {
+ process.env.IX_BUNDLED_COMPOSE = "";
+ const errors: string[] = [];
+ vi.spyOn(console, "error").mockImplementation((...a: unknown[]) => { errors.push(a.join(" ")); });
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
+ throw new Error(`exit ${code}`);
+ }) as never);
+
+ await expect(dockerStart()).rejects.toThrow("exit 1");
+ expect(errors.join("\n")).toMatch(/No backend compose file/);
+ expect(log()).not.toMatch(/compose/);
+ });
+});
+
+describe("isIxArangoVolume", () => {
+ const labels = (project: string, volume: string) =>
+ new Map([["com.docker.compose.project", project], ["com.docker.compose.volume", volume]]);
+
+ it("matches only the Ix backends' own ArangoDB volume", async () => {
+ const { isIxArangoVolume } = await import("../commands/docker.js");
+ expect(isIxArangoVolume(labels("backend", "arangodb-data"))).toBe(true);
+ expect(isIxArangoVolume(labels("ix", "arangodb-data"))).toBe(true);
+ // Other stacks on the same machine, which --remove-all-data used to delete.
+ expect(isIxArangoVolume(labels("ix-bench", "arangodb-data"))).toBe(false);
+ expect(isIxArangoVolume(labels("ix-personal", "arangodb-data"))).toBe(false);
+ expect(isIxArangoVolume(labels("ix-e2e", "arangodb-data"))).toBe(false);
+ expect(isIxArangoVolume(labels("backend", "arango-backup"))).toBe(false);
+ });
+});
diff --git a/ix-cli/src/cli/commands/docker.ts b/ix-cli/src/cli/commands/docker.ts
index 28fc4e03..0f18478d 100644
--- a/ix-cli/src/cli/commands/docker.ts
+++ b/ix-cli/src/cli/commands/docker.ts
@@ -3,9 +3,10 @@
import { Command } from "commander";
import { execFileSync, spawn } from "child_process";
import { createInterface } from "readline";
-import { existsSync, mkdirSync } from "fs";
-import { join } from "path";
+import { copyFileSync, existsSync, mkdirSync } from "fs";
+import { dirname, join } from "path";
import { homedir } from "os";
+import { fileURLToPath } from "url";
import { stampBackendVersionAfterPull } from "./upgrade.js";
const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");
@@ -13,14 +14,70 @@ const COMPOSE_DIR = join(IX_HOME, "backend");
const LOCAL_COMPOSE = join(COMPOSE_DIR, "docker-compose.yml");
const HEALTH_URL = "http://localhost:8090/v1/health";
const ARANGO_URL = "http://localhost:8529/_api/version";
-const GITHUB_RAW =
- "https://raw.githubusercontent.com/ix-infrastructure/Ix/main";
+/**
+ * The compose file this CLI release ships. `npm run build` copies the repo's
+ * docker-compose.standalone.yml to dist/, which the release tarball carries;
+ * a source checkout also finds it at the repo root, four levels above this
+ * file. Both are located from the CLI's own install, never from the cwd.
+ */
+function bundledComposeFile(): string | null {
+ if (process.env.NODE_ENV === "test" && process.env.IX_BUNDLED_COMPOSE !== undefined) {
+ return process.env.IX_BUNDLED_COMPOSE && existsSync(process.env.IX_BUNDLED_COMPOSE)
+ ? process.env.IX_BUNDLED_COMPOSE
+ : null;
+ }
+ const here = dirname(fileURLToPath(import.meta.url));
+ for (const candidate of [
+ join(here, "..", "..", "docker-compose.standalone.yml"),
+ join(here, "..", "..", "..", "..", "docker-compose.standalone.yml"),
+ ]) {
+ if (existsSync(candidate)) return candidate;
+ }
+ return null;
+}
+
+/**
+ * The backend's compose file, ~/.ix/backend/docker-compose.yml, written from
+ * the copy this CLI ships when it is missing. Never a docker-compose.yml from
+ * the working directory: `ix docker start` inside an untrusted repository
+ * would otherwise run whatever services that repository's compose file
+ * declares. And never a download from the `main` branch, which may not match
+ * the installed CLI.
+ */
function findComposeFile(): string | null {
if (existsSync(LOCAL_COMPOSE)) return LOCAL_COMPOSE;
- const repoCompose = join(process.cwd(), "docker-compose.yml");
- if (existsSync(repoCompose)) return repoCompose;
- return null;
+ const bundled = bundledComposeFile();
+ if (!bundled) return null;
+ try {
+ mkdirSync(COMPOSE_DIR, { recursive: true });
+ copyFileSync(bundled, LOCAL_COMPOSE);
+ return LOCAL_COMPOSE;
+ } catch {
+ return null;
+ }
+}
+
+function reportMissingCompose(): void {
+ console.error(`[error] No backend compose file at ${LOCAL_COMPOSE}, and this CLI install does not ship one.`);
+ console.error(" Reinstall or run 'ix upgrade' to restore it.");
+}
+
+/** Compose projects whose volumes are Ix backend data: ix docker's own, and a repo checkout run directly. */
+const IX_COMPOSE_PROJECTS = new Set(["backend", "ix"]);
+
+/**
+ * Is this volume an Ix backend's ArangoDB data? Exact compose project and
+ * volume names. The previous test (project starting with "ix", volume
+ * containing "arango") also matched other stacks' databases on the same
+ * machine (ix-bench, a personal or test backend), which --remove-all-data
+ * then deleted.
+ */
+export function isIxArangoVolume(labels: Map<string, string>): boolean {
+ return (
+ IX_COMPOSE_PROJECTS.has(labels.get("com.docker.compose.project") ?? "") &&
+ labels.get("com.docker.compose.volume") === "arangodb-data"
+ );
}
function findIxArangoVolumes(): string[] {
@@ -42,10 +99,7 @@ function findIxArangoVolumes(): string[] {
if (eq > 0) labelMap.set(pair.slice(0, eq), pair.slice(eq + 1));
}
- const project = labelMap.get("com.docker.compose.project") ?? "";
- const volume = labelMap.get("com.docker.compose.volume") ?? "";
-
- return project.startsWith("ix") && volume.includes("arango");
+ return isIxArangoVolume(labelMap);
}).map((line) => line.split("|", 1)[0]);
} catch {
return [];
@@ -91,19 +145,8 @@ export function registerDockerCommand(program: Command): void {
.alias("up")
.description("Start the IX backend (ArangoDB + Memory Layer)")
.action(async () => {
- // Always ensure standalone compose file exists so stop/restart work from any directory
- if (!existsSync(LOCAL_COMPOSE)) {
- try {
- mkdirSync(COMPOSE_DIR, { recursive: true });
- execFileSync(
- "curl",
- ["-fsSL", `${GITHUB_RAW}/docker-compose.standalone.yml`, "-o", LOCAL_COMPOSE],
- { stdio: "ignore" }
- );
- } catch {
- // Non-critical — start can still work from repo dir
- }
- }
+ // Written before anything else, so stop/restart/logs work from any directory.
+ const composeFile = findComposeFile();
if (isHealthy()) {
console.log("[ok] Backend is already running and healthy");
@@ -118,23 +161,9 @@ export function registerDockerCommand(program: Command): void {
process.exit(1);
}
- let composeFile = findComposeFile();
-
if (!composeFile) {
- console.log("Downloading docker-compose.yml...");
- try {
- mkdirSync(COMPOSE_DIR, { recursive: true });
- execFileSync(
- "curl",
- ["-fsSL", `${GITHUB_RAW}/docker-compose.standalone.yml`, "-o", LOCAL_COMPOSE],
- { stdio: "inherit" }
- );
- composeFile = LOCAL_COMPOSE;
- console.log(`[ok] Saved to ${COMPOSE_DIR}`);
- } catch {
- console.error("[error] Failed to download docker-compose.yml");
- process.exit(1);
- }
+ reportMissingCompose();
+ process.exit(1);
}
console.log("Starting backend services...");
@@ -153,8 +182,8 @@ export function registerDockerCommand(program: Command): void {
// when `ix upgrade` runs, so starting the backend any other way leaves a
// file naming an older release and the update notice fires on every
// command for ever. The compose file is passed because it decides whether
- // that premise holds at all: this falls back to any docker-compose.yml in
- // the working directory, which may pin a tag, a digest, or a local build.
+ // that premise holds at all: a user may have edited it to pin a tag, a
+ // digest, or a local build.
// Awaited so the stamp is on disk before the command returns, and it
// cannot fail the start: the helper swallows its own errors.
await stampBackendVersionAfterPull(composeFile);
@@ -187,8 +216,7 @@ export function registerDockerCommand(program: Command): void {
.action(async (opts) => {
const composeFile = findComposeFile();
if (!composeFile) {
- console.error("[error] No docker-compose.yml found.");
- console.error(" Run 'ix docker start' first, or run from the Ix repo.");
+ reportMissingCompose();
process.exit(1);
}
@@ -300,7 +328,7 @@ export function registerDockerCommand(program: Command): void {
.action((opts) => {
const composeFile = findComposeFile();
if (!composeFile) {
- console.error("[error] No docker-compose.yml found.");
+ reportMissingCompose();
process.exit(1);
}
@@ -316,7 +344,7 @@ export function registerDockerCommand(program: Command): void {
.action(() => {
const composeFile = findComposeFile();
if (!composeFile) {
- console.error("[error] No docker-compose.yml found.");
+ reportMissingCompose();
process.exit(1);
}