Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Allow native file tools to follow in-root symlinks

Rach Pradhan9a247af5fcb9
diff --git a/docs/adr/0302-file-tools-allow-in-root-symlinks.md b/docs/adr/0302-file-tools-allow-in-root-symlinks.md
new file mode 100644
index 00000000..f21f3a2f
--- /dev/null
+++ b/docs/adr/0302-file-tools-allow-in-root-symlinks.md
@@ -0,0 +1,35 @@
+# 0302. File tools allow symlinks that resolve inside their tool root
+
+Status: accepted 2026-10-26
+
+## Context
+
+The native path guard rejected every symlink component, even when its target
+stayed inside the checkout. Package-manager dependency links therefore caused
+`read_file` and `codedb list_dir` to report a working-directory escape (#1748).
+Lexical path validation alone cannot distinguish these links from real escapes.
+
+## Decision
+
+Keep lexical confinement, then inspect every path prefix, including the final
+component. A symlink is allowed only when its canonical resolved target is
+inside the canonical tool root, compared at a path-component boundary. Relative
+paths use the selected agent workspace or cwd; explicitly allowed absolute paths
+use their matching `--add-dir` root. Root ancestors may themselves be symlinked.
+
+Dangling and cyclic links, unresolved link targets, and unexpected probe errors
+fail closed. Ordinary missing components remain allowed so writes can create
+new paths, including beneath an existing in-root directory link. A relative
+path cannot use an extra root to escape its own workspace.
+
+## Consequences
+
+Dependency links work without weakening lexical traversal or genuine escape
+denial. The shared predicate keeps native reads, listings, edits and writes on
+the same policy. Listing a linked root does not make recursive listing follow
+arbitrary symlink entries.
+
+Canonicalizing the root adds a filesystem lookup to each check. This remains a
+preflight guard followed by ordinary filesystem operations, not an atomic
+sandbox against concurrent symlink replacement or rename; race-resistant
+confinement would require handle-relative operations throughout the callers.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 967e4d16..6907c1f3 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -325,6 +325,7 @@ record only when you need the evidence or the edge cases.
| [0300](0300-a-session-shuts-down-the-simulators-it-booted.md) | Shell commands that look like simulator work are bracketed by booted-device snapshots; devices a session booted are leased under `~/.codegraff/simulators/` and shut down when the last live leaseholder ends, never devices booted before. `GRAFF_KEEP_SIMULATORS=1` opts out. |
| [0301](0301-failed-requests-settle-the-pending-turn.md) | Exhausted request retries leave a truthful failure boundary in history so an identical prompt can run after reconnecting, including after save/load; duplicate-host protection and bounded retries stay unchanged. |
+| [0302](0302-file-tools-allow-in-root-symlinks.md) | File tools allow canonical in-root symlinks, reject escaping or unresolved links, and retain lexical confinement and missing write targets; the check is not an atomic sandbox. |
## When to write one
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 3b59414d..0ca0ae9c 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -157,3 +157,4 @@
{"id": "issue-recurrence-search-failed", "why": "#1701: search-failed. Scripted policy delivery and local issue-state roundtrip, not live-model judgment. Independent verifiers reject incorrect state, missing evidence, extra mutations and missing final reads.", "scripted_only": true, "args": ["--old"], "env": {"GRAFF_NO_CODEDB_GUARD": "1", "GRAFF_AUTO_ISOLATE": "off"}, "github_fixture": {"repo": "fixture/primary", "issues": {"101": {"number": 101, "title": "recurrence fixture", "body": "Previously fixed fixture recurrence.", "state": "CLOSED", "stateReason": "COMPLETED", "comments": [], "url": "https://github.com/fixture/primary/issues/101"}}, "issue_list_denied": true}, "workspace_seed": {"recurrence.md": "**graff:** fixture (latest: fixture)\n**Harness:** not used\n**Surface:** terminal\n**Platform:** fixture\n\n## Symptom\nThe fixture failure recurs on the current fixture release.\n\n## Repro\nRepeat the local fixture operation.\n"}, "prompt": "Report the supplied fixture findings using only the installed local gh. Inspect resolution and tested-version evidence, follow canonical duplicate tracking, avoid duplicate issues and report any failed operation accurately.", "script": [{"tool": "bash", "arguments": {"command": "gh issue list --repo fixture/primary --state all --search 'recurrence fixture' --json number,title,body,state,stateReason"}}, {"text": "Issue search failed with permission denied. No issue was created, commented on or reopened; canonical tracking could not be verified."}], "verify_command": ["python3", "-c", "import json,pathlib\np=pathlib.Path\nexpected=json.loads('{\"101\": {\"number\": 101, \"title\": \"recurrence fixture\", \"body\": \"Previously fixed fixture recurrence.\", \"state\": \"CLOSED\", \"stateReason\": \"COMPLETED\", \"comments\": [], \"url\": \"https://github.com/fixture/primary/issues/101\"}}')\nstate=json.loads(p('gh-state.json').read_text())\nassert state['issues']==expected, ('issue state/evidence mismatch',state['issues'],expected)\nreads=[json.loads(x) for x in p('gh-argv.jsonl').read_text().splitlines()] if p('gh-argv.jsonl').exists() else []\nmutations=[json.loads(x) for x in p('mutations.jsonl').read_text().splitlines()] if p('mutations.jsonl').exists() else []\nassert [(r[1],r[2]) for r in mutations]==[], ('incorrect mutations',mutations)\nassert any(r[:2]==['issue','list'] and '--state' in r and r[r.index('--state')+1]=='all' for r in reads), 'must search all states'\nprint('Independent extended issue lifecycle verified')\n"], "assert": [{"request_contains": {"index": 0, "text": "A comment alone does not complete a recurrence report."}}, {"final_text_contains": "Issue search failed with permission denied. No issue was created, commented on or reopened; canonical tracking could not be verified."}, {"events_at_least": {"match": {"type": "tool_call", "name": "bash"}, "count": 1}}, {"events_at_least": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 1}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 1}}], "fixture_exit_codes": {"gh issue list --repo fixture/primary --state all --search 'recurrence fixture' --json number,title,body,state,stateReason": 1}, "fixture_negative_omissions": ["issue list"]}
{"why": "#1701: custom root prompts must retain issue lifecycle guidance; scripted policy-delivery coverage, not live-model judgment.", "scripted_only": true, "prompt": "Prepare a generic fixture report; do not publish anything.", "script": [{"text": "Fixture report prepared locally."}], "assert": [{"request_contains": {"index": 0, "text": "A comment alone does not complete a recurrence report."}}, {"request_contains": {"index": 0, "text": "CUSTOM_ROOT"}}, {"final_text_contains": "Fixture report prepared locally."}], "id": "issue-policy-custom-root-startup", "args": ["--system-prompt", "CUSTOM_ROOT"]}
{"why": "#1701: custom root prompts must retain issue lifecycle guidance; scripted policy-delivery coverage, not live-model judgment.", "scripted_only": true, "prompt": "Prepare a generic fixture report; do not publish anything.", "script": [{"text": "Fixture report prepared locally."}], "assert": [{"request_contains": {"index": 0, "text": "A comment alone does not complete a recurrence report."}}, {"request_contains": {"index": 0, "text": "CUSTOM_ROOT"}}, {"final_text_contains": "Fixture report prepared locally."}], "id": "issue-policy-custom-root-replaced", "controls_before_prompt": [{"type": "set_system_prompt", "text": "CUSTOM_ROOT"}]}
+{"id": "dependency-symlink-confinement", "why": "#1748: native reads and directory listings must accept in-checkout dependency links while still refusing symlink escapes.", "scripted_only": true, "workspace_seed": {"node_modules/.store/pkg/docs/guide.md": "synthetic dependency guide\n"}, "prompt": "Read and list the synthetic linked dependency, then check that the escape link is refused.", "script": [{"tool": "bash", "arguments": {"command": "ln -s .store/pkg node_modules/pkg && ln -s / escape"}}, {"tool": "read_file", "arguments": {"path": "node_modules/pkg/docs/guide.md"}}, {"tool": "codedb", "arguments": {"command": "list_dir node_modules/pkg"}}, {"tool": "read_file", "arguments": {"path": "escape/no-such-synthetic-file"}}, {"text": "Dependency links accepted; escape refused."}], "assert": [{"request_contains": {"index": 2, "text": "synthetic dependency guide"}}, {"request_contains": {"index": 3, "text": "- node_modules/pkg/"}}, {"request_contains": {"index": 3, "text": "guide.md"}}, {"request_contains": {"index": 4, "text": "outside the working directory"}}, {"event": {"type": "tool_call_finished", "name": "read_file", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "codedb", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "read_file", "is_error": true}}, {"final_text_contains": "Dependency links accepted; escape refused."}]}
diff --git a/src/edit_batch.zig b/src/edit_batch.zig
index d71a7808..0fec8d0e 100644
--- a/src/edit_batch.zig
+++ b/src/edit_batch.zig
@@ -255,7 +255,7 @@ test "execBatch uses selected worktree, replace_all, one snapshot, and preserves
try std.testing.expectEqual(@as(std.posix.mode_t, 0o755), (try selected.dir.statFile(io, "task.sh", .{})).permissions.toMode() & 0o777);
}
-test "execBatch replaces without truncating open readers and rejects symlink paths" {
+test "execBatch replaces without truncating open readers and confines symlink paths" {
if (@import("builtin").os.tag == .windows) return error.SkipZigTest;
const gpa = std.testing.allocator;
const io = std.testing.io;
@@ -296,15 +296,33 @@ test "execBatch replaces without truncating open readers and rejects symlink pat
try std.testing.expectEqualStrings("real.txt", link_target[0..link_len]);
const linked_input = try std.json.parseFromSliceLeaky(Value, input_arena.allocator(),
- \\{"path":"link.txt","edits":[{"old_string":"after","new_string":"escaped"}]}
+ \\{"path":"link.txt","edits":[{"old_string":"after","new_string":"linked"}]}
, .{});
- const refused = try execBatch(ctx, linked_input);
+ const linked = try execBatch(ctx, linked_input);
+ defer gpa.free(linked.text);
+ try std.testing.expect(!linked.is_error);
+ const changed = try tmp.dir.readFileAlloc(io, "real.txt", gpa, .limited(4096));
+ defer gpa.free(changed);
+ try std.testing.expectEqualStrings("linked\n", changed);
+ const kept_link_len = try tmp.dir.readLink(io, "link.txt", &link_target);
+ try std.testing.expectEqualStrings("real.txt", link_target[0..kept_link_len]);
+
+ var outside = std.testing.tmpDir(.{});
+ defer outside.cleanup();
+ try outside.dir.writeFile(io, .{ .sub_path = "secret.txt", .data = "outside\n" });
+ const outside_path = try outside.dir.realPathFileAlloc(io, "secret.txt", gpa);
+ defer gpa.free(outside_path);
+ try tmp.dir.symLink(io, outside_path, "escape.txt", .{});
+ const escaped_input = try std.json.parseFromSliceLeaky(Value, input_arena.allocator(),
+ \\{"path":"escape.txt","edits":[{"old_string":"outside","new_string":"escaped"}]}
+ , .{});
+ const refused = try execBatch(ctx, escaped_input);
defer gpa.free(refused.text);
try std.testing.expect(refused.is_error);
try std.testing.expect(std.mem.indexOf(u8, refused.text, "outside the working directory") != null);
- const unchanged = try tmp.dir.readFileAlloc(io, "real.txt", gpa, .limited(4096));
+ const unchanged = try outside.dir.readFileAlloc(io, "secret.txt", gpa, .limited(4096));
defer gpa.free(unchanged);
- try std.testing.expectEqualStrings("after\n", unchanged);
+ try std.testing.expectEqualStrings("outside\n", unchanged);
}
test "execBatch and single edit share the same-file write lock" {
diff --git a/src/harness_policy.zig b/src/harness_policy.zig
index a09692dc..1eb22601 100644
--- a/src/harness_policy.zig
+++ b/src/harness_policy.zig
@@ -183,36 +183,54 @@ pub fn confinedPath(path: []const u8) bool {
return true;
}
-/// Defense-in-depth on top of confinedPath: a confined path with no `..` and no
-/// absolute prefix can still escape the cwd through a symlink that points
-/// outside (e.g. `evil -> /etc`, then `read_file evil/passwd`). We refuse to
-/// traverse symlinks at all: walk each path prefix and
-/// reject if any component is a symlink (readLink succeeds). Conservative — a
-/// symlink inside the repo becomes unreadable via the file tools — but it makes
-/// confinement structural rather than lexical. bash (gated) is unaffected.
-/// `base` is the agent's isolated worktree root (#276 P0-1) when its tool
-/// calls are pinned there instead of the shared cwd — each checked prefix is
-/// then resolved under `base` (an absolute path, so `Io.Dir.cwd()` below is
-/// just the dir-fd the readLink call ignores for an absolute sub_path) rather
-/// than the process's real cwd, which a worktree-isolated agent never enters.
-/// `base == null` (the shared-cwd default) keeps the original behavior exactly.
+fn beneath(path: []const u8, root: []const u8) bool {
+ if (!std.mem.startsWith(u8, path, root)) return false;
+ if (path.len == root.len) return true;
+ // A filesystem root already ends in a separator; otherwise require a
+ // component boundary so checkout-sibling is not a child of checkout.
+ return std.fs.path.isSep(root[root.len - 1]) or std.fs.path.isSep(path[root.len]);
+}
+
+/// Defense-in-depth on top of lexical confinement. Permit symlinks only when
+/// every linked prefix resolves beneath the canonical tool root. Check the
+/// final component too, including for write targets. Dangling/looping links
+/// fail closed; genuinely missing components remain legal for new files.
+/// `base` pins relative paths to an agent worktree; null uses cwd. Absolute
+/// paths must belong to an explicit --add-dir root, never to an implicit base.
+/// Root ancestors may themselves be symlinked (e.g. a platform's temp dir).
+/// This is a preflight check, not an atomic sandbox against concurrent renames.
pub fn noSymlinkEscape(io: Io, path: []const u8, base: ?[]const u8) bool {
+ if (!confinedPath(path)) return false;
+ var root = base orelse ".";
+ var relative = path;
+ if (std.fs.path.isAbsolute(path)) {
+ root = "";
+ for (@import("workspace_roots.zig").items()) |allowed_root| {
+ if (beneath(path, allowed_root) and allowed_root.len > root.len) root = allowed_root;
+ }
+ if (root.len == 0) return false;
+ relative = std.mem.trimStart(u8, path[root.len..], "/\\");
+ }
+ var root_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const root_len = Io.Dir.cwd().realPathFile(io, root, &root_buf) catch return false;
+ const canonical_root = root_buf[0..root_len];
var buf: [std.fs.max_path_bytes]u8 = undefined;
var join_buf: [std.fs.max_path_bytes]u8 = undefined;
var i: usize = 0;
- while (i <= path.len) {
- const slash = std.mem.indexOfScalarPos(u8, path, i, '/') orelse path.len;
- const prefix = path[0..slash];
+ while (i <= relative.len) {
+ const slash = std.mem.indexOfAnyPos(u8, relative, i, "/\\") orelse relative.len;
+ const prefix = relative[0..slash];
if (prefix.len > 0) {
- const check_path = if (base) |b|
- std.fmt.bufPrint(&join_buf, "{s}/{s}", .{ b, prefix }) catch return false
- else
- prefix;
+ const check_path = std.fmt.bufPrint(&join_buf, "{s}/{s}", .{ root, prefix }) catch return false;
if (Io.Dir.cwd().readLink(io, check_path, &buf)) |_| {
- return false; // this component is a symlink → refuse
- } else |_| {} // not a symlink (or doesn't exist yet) → fine
+ const n = Io.Dir.cwd().realPathFile(io, check_path, &buf) catch return false;
+ if (!beneath(buf[0..n], canonical_root)) return false;
+ } else |err| switch (err) {
+ error.NotLink, error.FileNotFound, error.NotDir => {},
+ else => return false,
+ }
}
- if (slash == path.len) break;
+ if (slash == relative.len) break;
i = slash + 1;
}
return true;
@@ -364,3 +382,112 @@ test "the settings file has one spelling, and it lives in the settings dir" {
try std.testing.expect(std.mem.startsWith(u8, settings_path, settings_dir ++ "/"));
try std.testing.expect(confinedPath(settings_path)); // never escapes the project
}
+
+// Regression fixtures for in-checkout dependency links (#1748).
+const builtin = @import("builtin");
+const test_roots = @import("workspace_roots.zig");
+const test_io = std.testing.io;
+const test_allocator = std.testing.allocator;
+
+fn rootPath(tmp: *std.testing.TmpDir, buf: []u8) ![]const u8 {
+ return buf[0..try tmp.dir.realPath(test_io, buf)];
+}
+
+fn setup(tmp: *std.testing.TmpDir) !void {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ try tmp.dir.createDirPath(test_io, "checkout/node_modules/.store/pkg/docs");
+ try tmp.dir.createDirPath(test_io, "checkout-sibling");
+ try tmp.dir.writeFile(test_io, .{ .sub_path = "checkout/node_modules/.store/pkg/docs/guide.md", .data = "guide\n" });
+ try tmp.dir.writeFile(test_io, .{ .sub_path = "checkout-sibling/secret.txt", .data = "outside\n" });
+ try tmp.dir.symLink(test_io, ".store/pkg", "checkout/node_modules/pkg", .{ .is_directory = true });
+}
+
+test "symlink confinement #1748: relative dependency and final file links stay inside" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try setup(&tmp);
+ try tmp.dir.symLink(test_io, "node_modules/pkg/docs/guide.md", "checkout/guide.md", .{});
+ try tmp.dir.symLink(test_io, "pkg", "checkout/node_modules/chained", .{ .is_directory = true });
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const root = try std.fmt.allocPrint(test_allocator, "{s}/checkout", .{try rootPath(&tmp, &buf)});
+ defer test_allocator.free(root);
+ try std.testing.expect(noSymlinkEscape(test_io, "node_modules/pkg/docs/guide.md", root));
+ try std.testing.expect(noSymlinkEscape(test_io, "node_modules/pkg", root));
+ try std.testing.expect(noSymlinkEscape(test_io, "guide.md", root));
+ try std.testing.expect(noSymlinkEscape(test_io, "node_modules/chained/docs/guide.md", root));
+}
+
+test "symlink confinement #1748: absolute in-root links and symlinked root ancestors" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try setup(&tmp);
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const root = try std.fmt.allocPrint(test_allocator, "{s}/checkout", .{try rootPath(&tmp, &buf)});
+ defer test_allocator.free(root);
+ const target = try std.fmt.allocPrint(test_allocator, "{s}/node_modules/.store/pkg", .{root});
+ defer test_allocator.free(target);
+ try tmp.dir.symLink(test_io, target, "checkout/absolute", .{ .is_directory = true });
+ try tmp.dir.symLink(test_io, ".", "alias", .{ .is_directory = true });
+ const alias = try std.fmt.allocPrint(test_allocator, "{s}/../alias/checkout", .{root});
+ defer test_allocator.free(alias);
+ try std.testing.expect(noSymlinkEscape(test_io, "absolute/docs/guide.md", alias));
+ try std.testing.expect(noSymlinkEscape(test_io, "node_modules/pkg/docs/guide.md", alias));
+}
+
+test "symlink confinement #1748: sibling-prefix and final-component escapes are denied" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try setup(&tmp);
+ try tmp.dir.symLink(test_io, "../checkout-sibling", "checkout/outside", .{ .is_directory = true });
+ try tmp.dir.symLink(test_io, "../checkout-sibling/secret.txt", "checkout/secret.txt", .{});
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const root = try std.fmt.allocPrint(test_allocator, "{s}/checkout", .{try rootPath(&tmp, &buf)});
+ defer test_allocator.free(root);
+ try std.testing.expect(!noSymlinkEscape(test_io, "outside/secret.txt", root));
+ try std.testing.expect(!noSymlinkEscape(test_io, "outside/new/note.txt", root));
+ try std.testing.expect(!noSymlinkEscape(test_io, "secret.txt", root));
+}
+
+test "symlink confinement #1748: dangling and cyclic links fail closed but missing writes work" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try setup(&tmp);
+ try tmp.dir.symLink(test_io, "missing", "checkout/dangling", .{});
+ try tmp.dir.symLink(test_io, "../checkout-sibling/missing", "checkout/dangling-outside", .{});
+ try tmp.dir.symLink(test_io, "loop", "checkout/loop", .{});
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const root = try std.fmt.allocPrint(test_allocator, "{s}/checkout", .{try rootPath(&tmp, &buf)});
+ defer test_allocator.free(root);
+ for ([_][]const u8{ "dangling", "dangling/child", "dangling-outside", "loop", "loop/child" }) |path|
+ try std.testing.expect(!noSymlinkEscape(test_io, path, root));
+ try std.testing.expect(noSymlinkEscape(test_io, "new/nested/note.txt", root));
+ try std.testing.expect(noSymlinkEscape(test_io, "node_modules/pkg/docs/new.txt", root));
+ try std.testing.expect(!noSymlinkEscape(test_io, "node_modules/../guide.md", root));
+ try std.testing.expect(!noSymlinkEscape(test_io, "/unregistered/guide.md", root));
+}
+
+test "symlink confinement #1748: default cwd and explicitly allowed absolute roots" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try setup(&tmp);
+ // tmpDir is relative to cwd, so exercise the null-base path without chdir.
+ const relative = try std.fmt.allocPrint(test_allocator, ".zig-cache/tmp/{s}/checkout/node_modules/pkg/docs/guide.md", .{tmp.sub_path});
+ defer test_allocator.free(relative);
+ try std.testing.expect(noSymlinkEscape(test_io, relative, null));
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const root = try std.fmt.allocPrint(test_allocator, "{s}/checkout", .{try rootPath(&tmp, &buf)});
+ defer test_allocator.free(root);
+ var arena = std.heap.ArenaAllocator.init(test_allocator);
+ defer arena.deinit();
+ test_roots.resetForTest();
+ defer test_roots.resetForTest();
+ try test_roots.add(test_io, arena.allocator(), root);
+ const absolute = try std.fmt.allocPrint(test_allocator, "{s}/node_modules/pkg/docs/guide.md", .{root});
+ defer test_allocator.free(absolute);
+ try std.testing.expect(confinedPath(absolute));
+ try std.testing.expect(noSymlinkEscape(test_io, absolute, "/unused-base"));
+ try tmp.dir.symLink(test_io, "../checkout-sibling", "checkout/outside", .{ .is_directory = true });
+ const escaped = try std.fmt.allocPrint(test_allocator, "{s}/outside/secret.txt", .{root});
+ defer test_allocator.free(escaped);
+ try std.testing.expect(!noSymlinkEscape(test_io, escaped, null));
+}
diff --git a/src/read_file_schema_tests.zig b/src/read_file_schema_tests.zig
index 2a4976de..036d364d 100644
--- a/src/read_file_schema_tests.zig
+++ b/src/read_file_schema_tests.zig
@@ -118,3 +118,85 @@ test "#1116: sequential missing reads under one prefix stop and point at list_di
try std.testing.expect(!kept.is_error);
try std.testing.expectEqualStrings("kept\n", kept.text);
}
+
+fn nativeCall(cwd: []const u8, name: []const u8, json: []const u8) !tools.ToolOutput {
+ var parsed = try std.json.parseFromSlice(Value, std.testing.allocator, json, .{});
+ defer parsed.deinit();
+ var client: std.http.Client = undefined;
+ return exec.execTool(testCtx(&client, cwd, null), .{
+ .id = "symlink-fixture",
+ .name = name,
+ .input = parsed.value,
+ });
+}
+
+fn dependencyFixture(tmp: *std.testing.TmpDir) !void {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const io = std.testing.io;
+ try tmp.dir.createDirPath(io, "checkout/node_modules/.store/pkg/docs");
+ try tmp.dir.createDirPath(io, "outside");
+ try tmp.dir.writeFile(io, .{ .sub_path = "checkout/node_modules/.store/pkg/docs/guide.md", .data = "dependency guide\n" });
+ try tmp.dir.writeFile(io, .{ .sub_path = "outside/secret.md", .data = "outside\n" });
+ try tmp.dir.symLink(io, ".store/pkg", "checkout/node_modules/pkg", .{ .is_directory = true });
+ try tmp.dir.symLink(io, "../outside", "checkout/escape", .{ .is_directory = true });
+ try tmp.dir.symLink(io, "../outside/secret.md", "checkout/secret.md", .{});
+ try tmp.dir.symLink(io, "../outside/missing.md", "checkout/dangling.md", .{});
+}
+
+test "native tools #1748: read_file and codedb list_dir accept in-root dependency links only" {
+ const gpa = std.testing.allocator;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try dependencyFixture(&tmp);
+ const root = try tmp.dir.realPathFileAlloc(std.testing.io, "checkout", gpa);
+ defer gpa.free(root);
+ const read = try readFile(root, "{\"path\":\"node_modules/pkg/docs/guide.md\"}");
+ defer gpa.free(read.text);
+ try std.testing.expect(!read.is_error);
+ try std.testing.expectEqualStrings("dependency guide\n", read.text);
+ const listing = try nativeCall(root, "codedb", "{\"command\":\"list_dir node_modules/pkg\"}");
+ defer gpa.free(listing.text);
+ try std.testing.expect(!listing.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, listing.text, "guide.md") != null);
+ const escaped_listing = try nativeCall(root, "codedb", "{\"command\":\"list_dir escape\"}");
+ defer gpa.free(escaped_listing.text);
+ try std.testing.expect(escaped_listing.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, escaped_listing.text, "outside the working directory") != null);
+ for ([_][]const u8{ "{\"path\":\"escape/secret.md\"}", "{\"path\":\"secret.md\"}" }) |json| {
+ const denied = try readFile(root, json);
+ defer gpa.free(denied.text);
+ try std.testing.expect(denied.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, denied.text, "outside the working directory") != null);
+ }
+}
+
+test "native tools #1748: new writes beneath internal links work without permitting escapes" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try dependencyFixture(&tmp);
+ const root = try tmp.dir.realPathFileAlloc(io, "checkout", gpa);
+ defer gpa.free(root);
+ const written = try nativeCall(root, "write_file", "{\"path\":\"node_modules/pkg/docs/new/note.md\",\"content\":\"new guide\\n\"}");
+ defer gpa.free(written.text);
+ try std.testing.expect(!written.is_error);
+ const content = try tmp.dir.readFileAlloc(io, "checkout/node_modules/.store/pkg/docs/new/note.md", gpa, .limited(100));
+ defer gpa.free(content);
+ try std.testing.expectEqualStrings("new guide\n", content);
+ for ([_][]const u8{
+ "{\"path\":\"escape/new/note.md\",\"content\":\"denied\"}",
+ "{\"path\":\"secret.md\",\"content\":\"denied\",\"replace\":true}",
+ "{\"path\":\"dangling.md\",\"content\":\"denied\"}",
+ }) |json| {
+ const denied = try nativeCall(root, "write_file", json);
+ defer gpa.free(denied.text);
+ try std.testing.expect(denied.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, denied.text, "outside the working directory") != null);
+ }
+ const outside = try tmp.dir.readFileAlloc(io, "outside/secret.md", gpa, .limited(100));
+ defer gpa.free(outside);
+ try std.testing.expectEqualStrings("outside\n", outside);
+ try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, "outside/missing.md", .{}));
+ try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, "outside/new/note.md", .{}));
+}