Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
fix(read): report invalid and denied reads (#553)
Hiro-Chiba0a5d12f0a9cd
diff --git a/ix-cli/src/cli/__tests__/read-containment.test.ts b/ix-cli/src/cli/__tests__/read-containment.test.tsindex 77fd5676..d60bbccc 100644--- a/ix-cli/src/cli/__tests__/read-containment.test.ts+++ b/ix-cli/src/cli/__tests__/read-containment.test.ts@@ -17,6 +17,7 @@ let workspace: string;let outside: string;let savedHome: string | undefined;let savedProfile: string | undefined;+let savedExitCode: number | string | undefined;beforeEach(() => {home = mkdtempSync(join(tmpdir(), "ix-read-home-"));@@ -24,6 +25,8 @@ beforeEach(() => {outside = mkdtempSync(join(tmpdir(), "ix-read-outside-"));savedHome = process.env.HOME;savedProfile = process.env.USERPROFILE;+ savedExitCode = process.exitCode;+ process.exitCode = undefined;process.env.HOME = home;process.env.USERPROFILE = home;@@ -40,6 +43,7 @@ beforeEach(() => {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;+ process.exitCode = savedExitCode;for (const dir of [home, workspace, outside]) rmSync(dir, { recursive: true, force: true });});@@ -124,7 +128,7 @@ describe("isReadablePath", () => {// 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 }> {+ async function runRead(target: string, root: string, format = "json"): Promise<{ out: string; err: string }> {const out: string[] = [];const err: string[] = [];const log = vi.spyOn(console, "log").mockImplementation((...a) => { out.push(a.join(" ")); });@@ -133,7 +137,7 @@ describe("ix read enforces the boundary", () => {const program = new Command();program.exitOverride();registerReadCommand(program);- await program.parseAsync(["read", target, "--root", root, "--format", "json"], { from: "user" });+ await program.parseAsync(["read", target, "--root", root, "--format", format], { from: "user" });return { out: out.join("\n"), err: err.join("") };} finally {log.mockRestore();@@ -146,20 +150,49 @@ describe("ix read enforces the boundary", () => {expect(out).toContain("export const answer = 42;");});- it("refuses a file outside it, and emits no content", async () => {+ it("refuses a file outside it without emitting source 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(JSON.parse(out)).toMatchObject({ error: "path_outside_workspace" });+ expect(process.exitCode).toBe(1);+ expect(err).toBe("");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");+ const { out } = await runRead(link, workspace);+ expect(JSON.parse(out)).toMatchObject({ error: "path_outside_workspace" });+ expect(process.exitCode).toBe(1);expect(out).not.toContain("SENTINEL");});++ it.each(["src/main.ts:0-0", "src/main.ts:5-2"])("rejects invalid line range %s", async (target) => {+ const { out } = await runRead(target, workspace);+ expect(JSON.parse(out)).toMatchObject({ error: "invalid_line_range" });+ expect(process.exitCode).toBe(1);+ expect(out).not.toContain("export const answer");+ });++ // The text branch is the only one that still names the boundary, and routing+ // the machine formats to stdout left it as the sole caller of readableRoots().+ // Nothing else covers it, so a change to either would go unnoticed.+ it("names the boundary on stderr for text output, and still emits no content", async () => {+ const { out, err } = await runRead(join(outside, "secret.txt"), workspace, "text");++ expect(err).toContain("Refusing to read file outside the workspace");+ expect(err).toContain("allowed root:");+ expect(err).toContain(workspace);+ expect(process.exitCode).toBe(1);+ expect(out).toBe("");+ expect(err).not.toContain("SENTINEL");+ });++ it("reports an invalid line range on stderr for text output", async () => {+ const { out, err } = await runRead("src/main.ts:5-2", workspace, "text");++ expect(err).toContain("Invalid line range");+ expect(process.exitCode).toBe(1);+ expect(out).not.toContain("export const answer");+ });});diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.tsindex 4479b725..527d9e9e 100644--- a/ix-cli/src/cli/commands/read.ts+++ b/ix-cli/src/cli/commands/read.ts@@ -8,7 +8,7 @@ import { resolveEntityFull, activeReadScope, ensureReadScope } from "../resolve.import { stderr } from "../stderr.js";import { isFileStale } from "../stale.js";import { relativePath } from "../format.js";-import { llmLine, printLlmLines } from "../llm.js";+import { llmError, llmLine, printLlmLines } from "../llm.js";import { parsePickOption } from "../options.js";import { reportUnresolvedTarget } from "../ui.js";@@ -44,18 +44,37 @@ function checkStale(filePath: string): boolean {* 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.+ * Returns true when the read may proceed. On refusal it reports a structured+ * machine error, or prints the reason and allowed roots for text output.*/-function guardReadable(absPath: string, explicitRoot: string | undefined, what: string): boolean {+function guardReadable(absPath: string, explicitRoot: string | undefined, what: string, format: 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."));+ const message = `Refusing to read ${what} outside the workspace: ${absPath}`;+ if (format === "json") {+ console.log(JSON.stringify({ error: "path_outside_workspace", message }, null, 2));+ } else if (format === "llm") {+ console.log(llmError("path_outside_workspace", message));+ } else {+ stderr(chalk.red(message));+ 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."));+ }+ process.exitCode = 1;return false;}+function reportInvalidLineRange(target: string, format: string): void {+ const message = `Invalid line range in "${target}". Line numbers must start at 1 and the end must not precede the start.`;+ if (format === "json") {+ console.log(JSON.stringify({ error: "invalid_line_range", message }, null, 2));+ } else if (format === "llm") {+ console.log(llmError("invalid_line_range", message));+ } else {+ stderr(chalk.red(message));+ }+ process.exitCode = 1;+}+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");@@ -203,11 +222,15 @@ Examples:const rawTarget = lineRangeMatch ? lineRangeMatch[1] : target;const rangeStart = lineRangeMatch ? parseInt(lineRangeMatch[2], 10) : undefined;const rangeEnd = lineRangeMatch ? parseInt(lineRangeMatch[3], 10) : undefined;+ if (rangeStart !== undefined && rangeEnd !== undefined && (rangeStart < 1 || rangeEnd < rangeStart)) {+ reportInvalidLineRange(target, opts.format);+ return;+ }// --- 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;+ if (!guardReadable(resolvedPath, opts.root, "file", opts.format)) return;const stale = checkStale(resolvedPath);const { content, lineStart, lineEnd } = readFileRange(resolvedPath, rangeStart, rangeEnd);const result: ReadResult = {@@ -232,7 +255,7 @@ Examples: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;+ if (!guardReadable(matchPath, opts.root, "graph file match", opts.format)) return;const stale = checkStale(matchPath);const { content, lineStart, lineEnd } = readFileRange(matchPath, rangeStart, rangeEnd);const result: ReadResult = {@@ -272,7 +295,7 @@ Examples: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;+ if (!guardReadable(absSourceUri, opts.root, "symbol source", opts.format)) 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");