Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(read): contain ix read to the workspace roots (#424)

KageBinaryee5aa78ec1b9
diff --git a/ix-cli/src/cli/__tests__/read-containment.test.ts b/ix-cli/src/cli/__tests__/read-containment.test.ts
new file mode 100644
index 00000000..77fd5676
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/read-containment.test.ts
@@ -0,0 +1,165 @@
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { Command } from "commander";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { isPathInside, isReadablePath, readableRoots } from "../config.js";
+import { registerReadCommand } from "../commands/read.js";
+
+// `ix read` used to hand back any absolute path that existed on disk: no
+// workspace containment, no graph lookup. These cover the boundary itself
+// rather than the command, so they hold regardless of which of the four
+// resolution steps reaches the filesystem.
+
+let home: string;
+let workspace: string;
+let outside: string;
+let savedHome: string | undefined;
+let savedProfile: string | undefined;
+
+beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), "ix-read-home-"));
+ workspace = mkdtempSync(join(tmpdir(), "ix-read-ws-"));
+ outside = mkdtempSync(join(tmpdir(), "ix-read-outside-"));
+ savedHome = process.env.HOME;
+ savedProfile = process.env.USERPROFILE;
+ process.env.HOME = home;
+ process.env.USERPROFILE = home;
+
+ mkdirSync(join(home, ".ix"), { recursive: true });
+ writeFileSync(
+ join(home, ".ix", "config.yaml"),
+ ["endpoint: http://localhost:8090", "format: text", ""].join("\n"),
+ );
+ mkdirSync(join(workspace, "src"), { recursive: true });
+ writeFileSync(join(workspace, "src", "main.ts"), "export const answer = 42;\n");
+ writeFileSync(join(outside, "secret.txt"), "SENTINEL\n");
+});
+
+afterEach(() => {
+ if (savedHome === undefined) delete process.env.HOME; else process.env.HOME = savedHome;
+ if (savedProfile === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = savedProfile;
+ for (const dir of [home, workspace, outside]) rmSync(dir, { recursive: true, force: true });
+});
+
+describe("isPathInside", () => {
+ it("accepts the root itself and anything under it", () => {
+ expect(isPathInside(workspace, workspace)).toBe(true);
+ expect(isPathInside(workspace, join(workspace, "src", "main.ts"))).toBe(true);
+ });
+
+ it("rejects a sibling whose path shares a string prefix with the root", () => {
+ // The bug a startsWith() containment check would have: `/ws-evil` is not
+ // inside `/ws`, but its path does start with it.
+ expect(isPathInside("/home/ws", "/home/ws-evil/secret")).toBe(false);
+ });
+
+ it("rejects traversal out of the root", () => {
+ expect(isPathInside(workspace, join(workspace, "..", "elsewhere"))).toBe(false);
+ expect(isPathInside(workspace, outside)).toBe(false);
+ });
+});
+
+describe("isReadablePath", () => {
+ it("allows a file inside the workspace passed as --root", () => {
+ expect(isReadablePath(join(workspace, "src", "main.ts"), workspace)).toBe(true);
+ });
+
+ it("refuses an absolute path outside every readable root", () => {
+ expect(isReadablePath(join(outside, "secret.txt"), workspace)).toBe(false);
+ });
+
+ it("refuses a traversal that climbs out of the workspace", () => {
+ expect(isReadablePath(join(workspace, "..", "..", "etc", "passwd"), workspace)).toBe(false);
+ });
+
+ it("refuses a symlink planted inside the workspace that points outside it", () => {
+ const link = join(workspace, "src", "escape.txt");
+ symlinkSync(join(outside, "secret.txt"), link);
+ // Lexically the link is inside the workspace; only resolving it reveals
+ // that reading it hands back a file that is not.
+ expect(isPathInside(workspace, link)).toBe(true);
+ expect(isReadablePath(link, workspace)).toBe(false);
+ });
+
+ it("still allows an ordinary read when the workspace root is itself a symlink", () => {
+ // Resolving only the candidate would break this: the real file sits under
+ // the link's target, which is not lexically inside the root the caller gave.
+ const linkedRoot = join(outside, "linked-root");
+ symlinkSync(workspace, linkedRoot);
+ expect(isReadablePath(join(linkedRoot, "src", "main.ts"), linkedRoot)).toBe(true);
+ });
+
+ it("allows a file in another registered workspace", () => {
+ const other = mkdtempSync(join(tmpdir(), "ix-read-other-"));
+ try {
+ writeFileSync(join(other, "shared.ts"), "export const shared = 1;\n");
+ writeFileSync(
+ join(home, ".ix", "config.yaml"),
+ [
+ "endpoint: http://localhost:8090",
+ "format: text",
+ "workspaces:",
+ " - workspace_id: '1'",
+ " workspace_name: other",
+ ` root_path: ${other}`,
+ " default: false",
+ "",
+ ].join("\n"),
+ );
+
+ // Reads legitimately span registered workspaces (a stitched system,
+ // ix view --all), and every one of them is a path the user configured.
+ expect(readableRoots(workspace).map(r => resolve(r))).toContain(resolve(other));
+ expect(isReadablePath(join(other, "shared.ts"), workspace)).toBe(true);
+ expect(isReadablePath(join(outside, "secret.txt"), workspace)).toBe(false);
+ } finally {
+ rmSync(other, { recursive: true, force: true });
+ }
+ });
+});
+
+// The cases above pin the boundary. These pin that `ix read` is actually behind
+// it — delete the guard call sites and everything above still passes, because a
+// helper nobody calls is still a correct helper.
+describe("ix read enforces the boundary", () => {
+ async function runRead(target: string, root: string): Promise<{ out: string; err: string }> {
+ const out: string[] = [];
+ const err: string[] = [];
+ const log = vi.spyOn(console, "log").mockImplementation((...a) => { out.push(a.join(" ")); });
+ const write = vi.spyOn(process.stderr, "write").mockImplementation(((s: string) => { err.push(String(s)); return true; }) as never);
+ try {
+ const program = new Command();
+ program.exitOverride();
+ registerReadCommand(program);
+ await program.parseAsync(["read", target, "--root", root, "--format", "json"], { from: "user" });
+ return { out: out.join("\n"), err: err.join("") };
+ } finally {
+ log.mockRestore();
+ write.mockRestore();
+ }
+ }
+
+ it("reads a file inside the workspace", async () => {
+ const { out } = await runRead(join(workspace, "src", "main.ts"), workspace);
+ expect(out).toContain("export const answer = 42;");
+ });
+
+ it("refuses a file outside it, and emits no content", async () => {
+ const { out, err } = await runRead(join(outside, "secret.txt"), workspace);
+ // The refusal names the boundary; an agent that cannot see it just retries.
+ expect(err).toContain("Refusing to read file outside the workspace");
+ expect(err).toContain("allowed root:");
+ expect(out).not.toContain("SENTINEL");
+ expect(out).toBe("");
+ });
+
+ it("refuses a symlink inside the workspace that points outside it", async () => {
+ const link = join(workspace, "src", "escape.txt");
+ symlinkSync(join(outside, "secret.txt"), link);
+ const { out, err } = await runRead(link, workspace);
+ expect(err).toContain("Refusing to read file outside the workspace");
+ expect(out).not.toContain("SENTINEL");
+ });
+});
diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.ts
index b979ecfe..1e024576 100644
--- a/ix-cli/src/cli/commands/read.ts
+++ b/ix-cli/src/cli/commands/read.ts
@@ -3,7 +3,7 @@ import * as path from "node:path";
import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
-import { absoluteFromSourceUri, getEndpoint, resolveWorkspaceRoot } from "../config.js";
+import { absoluteFromSourceUri, getEndpoint, isReadablePath, readableRoots, resolveWorkspaceRoot } from "../config.js";
import { resolveEntityFull, activeReadScope, ensureReadScope } from "../resolve.js";
import { stderr } from "../stderr.js";
import { isFileStale } from "../stale.js";
@@ -49,6 +49,28 @@ function checkStale(filePath: string): boolean {
try { return isFileStale(filePath); } catch { return false; }
}
+/**
+ * Refuse a file outside every readable workspace root, and say so.
+ *
+ * `ix read` resolves its target four ways, and three of them can end at an
+ * arbitrary absolute path: the caller passes one directly, or the graph hands
+ * back a `source_uri` that is already absolute. Nothing downstream re-checked
+ * it, so `ix read /etc/shadow` read `/etc/shadow` — no workspace involved, no
+ * backend involved. That matters most through `ix mcp`, where the caller is an
+ * agent and the target is a string it chose.
+ *
+ * Returns true when the read may proceed. On refusal it prints the reason and
+ * the roots that WOULD have been allowed, because "denied" with no boundary is
+ * indistinguishable from a broken install.
+ */
+function guardReadable(absPath: string, explicitRoot: string | undefined, what: string): boolean {
+ if (isReadablePath(absPath, explicitRoot)) return true;
+ stderr(chalk.red(`Refusing to read ${what} outside the workspace: ${absPath}`));
+ for (const root of readableRoots(explicitRoot)) stderr(chalk.dim(` allowed root: ${root}`));
+ stderr(chalk.dim(" Use --root to read from a different workspace, or ix init to register one."));
+ return false;
+}
+
function readFileRange(filePath: string, start?: number, end?: number): { content: string; lineStart: number; lineEnd: number } {
const raw = fs.readFileSync(filePath, "utf-8");
const lines = raw.split("\n");
@@ -200,6 +222,7 @@ Examples:
// --- Step 2: Try exact file path ---
const resolvedPath = path.isAbsolute(rawTarget) ? rawTarget : path.resolve(root, rawTarget);
if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isFile()) {
+ if (!guardReadable(resolvedPath, opts.root, "file")) return;
const stale = checkStale(resolvedPath);
const { content, lineStart, lineEnd } = readFileRange(resolvedPath, rangeStart, rangeEnd);
const result: ReadResult = {
@@ -222,6 +245,9 @@ Examples:
if (filenameMatches.length === 1) {
const matchPath = filenameMatches[0].path;
if (matchPath && fs.existsSync(matchPath)) {
+ // The path came back from the graph rather than the caller, so this
+ // guard is what stops a backend from naming a file off the disk.
+ if (!guardReadable(matchPath, opts.root, "graph file match")) return;
const stale = checkStale(matchPath);
const { content, lineStart, lineEnd } = readFileRange(matchPath, rangeStart, rangeEnd);
const result: ReadResult = {
@@ -259,6 +285,9 @@ Examples:
// If the source file exists, extract the symbol's lines
if (absSourceUri && fs.existsSync(absSourceUri)) {
+ // absoluteFromSourceUri passes an already-absolute source_uri through
+ // untouched, so a graph row can still point anywhere on the disk.
+ if (!guardReadable(absSourceUri, opts.root, "symbol source")) return;
const lineStart = node.attrs?.lineStart ?? node.attrs?.line_start ?? 1;
const lineEnd = node.attrs?.lineEnd ?? node.attrs?.line_end;
const fileContent = fs.readFileSync(absSourceUri, "utf-8");
diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.ts
index f0136978..c1e69bc4 100644
--- a/ix-cli/src/cli/config.ts
+++ b/ix-cli/src/cli/config.ts
@@ -1,4 +1,4 @@
-import { readFileSync, writeFileSync, existsSync, rmSync, chmodSync, renameSync } from "node:fs";
+import { readFileSync, writeFileSync, existsSync, rmSync, chmodSync, renameSync, realpathSync } from "node:fs";
import { isAbsolute, join, relative, resolve as resolvePath, sep } from "node:path";
import { homedir } from "node:os";
import { createHash } from "node:crypto";
@@ -133,19 +133,58 @@ export function loadWorkspaces(): WorkspaceConfig[] {
return config.workspaces ?? []; // workspace_id already normalized to string in loadConfig
}
+/**
+ * Is `candidate` `root` itself, or somewhere underneath it?
+ *
+ * The `relative()` form is the one this file already used to pick a workspace
+ * for a cwd. It handles the two cases a `startsWith` prefix test gets wrong: a
+ * `..` traversal comes back with leading `..` segments, and on Windows a path on
+ * a different drive comes back absolute. Both sides are resolved first so a
+ * relative input cannot slip past.
+ */
+export function isPathInside(root: string, candidate: string): boolean {
+ const rel = relative(resolvePath(root), resolvePath(candidate));
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
+}
+
+/**
+ * The roots a read command may open a file from: the workspace this invocation
+ * resolves to, plus every workspace the user has registered with `ix init`.
+ *
+ * Registered workspaces are included because reads legitimately span them — a
+ * stitched system, or `ix view --all` — and every one of them is a path the user
+ * put in their own config. What is NOT in the list is the rest of the disk.
+ */
+export function readableRoots(explicitRoot?: string): string[] {
+ const roots = [resolveWorkspaceRoot(explicitRoot), ...loadWorkspaces().map(w => w.root_path)];
+ return [...new Set(roots.filter(Boolean).map(r => resolvePath(r)))];
+}
+
+/**
+ * May `ix read` open this file?
+ *
+ * Symlinks are resolved on both sides before comparing, so a link planted inside
+ * a workspace cannot be used to hand back a file outside it. Resolving both sides
+ * is what keeps that from backfiring: workspace roots are themselves often
+ * symlinks (macOS `/tmp`, a checkout reached through one), and comparing a real
+ * path against a symlinked root would reject perfectly ordinary reads.
+ * `realpathSync` is best-effort — if either side cannot be resolved, the lexical
+ * path stands in, which is the same answer for everything that is not a link.
+ */
+export function isReadablePath(candidate: string, explicitRoot?: string): boolean {
+ const real = (p: string) => { try { return realpathSync(p); } catch { return resolvePath(p); } };
+ const realCandidate = real(candidate);
+ return readableRoots(explicitRoot).some(
+ root => isPathInside(root, candidate) && isPathInside(real(root), realCandidate),
+ );
+}
+
export function selectWorkspaceForCwd(
workspaces: WorkspaceConfig[],
cwd: string,
): WorkspaceConfig | undefined {
- const resolvedCwd = resolvePath(cwd);
return workspaces
- .filter((workspace) => {
- const relativePath = relative(resolvePath(workspace.root_path), resolvedCwd);
- return (
- relativePath === "" ||
- (relativePath !== ".." && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath))
- );
- })
+ .filter(workspace => isPathInside(workspace.root_path, cwd))
.sort((a, b) => b.root_path.length - a.root_path.length)[0];
}