import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; import { join } from "node:path"; import test, { type TestContext } from "node:test"; import pathRules from "../index.ts"; type Input = { path?: string; command?: string; pattern?: string; remote?: string }; type TextContent = { type: "text"; text: string }; interface ToolEvent { toolName: string; input: Input; content?: TextContent[]; isError?: boolean; } interface HandlerResult { block?: boolean; reason?: string; content?: TextContent[]; isError?: boolean; } type Handler = (event: ToolEvent, ctx: { cwd: string }) => HandlerResult | undefined; // The workspaces extension's answer: every path under a `workspace` directory belongs to a // workspace of the repository whose main checkout is the `main` directory next to it. function resolveWorkspace(request: { cwd: string; root?: string; workspace?: string }) { const match = /^(.*)\/workspace(?:\/|$)/.exec(request.cwd); if (match) { request.root = `${match[1]}/main`; request.workspace = `${match[1]}/workspace`; } } function setup(t: TestContext, rules: { deny?: string[]; denyWrite?: string[]; allow?: string[] }) { const agentDir = mkdtempSync(join(tmpdir(), "pi-path-rules-")); const previous = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = agentDir; t.after(() => { if (previous === undefined) { delete process.env.PI_CODING_AGENT_DIR; } else { process.env.PI_CODING_AGENT_DIR = previous; } rmSync(agentDir, { recursive: true, force: true }); }); const configPath = join(agentDir, "extensions", "path-rules", "config.json"); mkdirSync(join(configPath, ".."), { recursive: true }); writeFileSync(configPath, JSON.stringify(rules)); const handlers = new Map(); const pi = { on: (name: string, handler: Handler) => handlers.set(name, handler), events: { emit: (name: string, data: { cwd: string }) => name === "workspaces:resolve" && resolveWorkspace(data), }, }; // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- The extension only registers event handlers. pathRules(pi as never); return { configPath, handlers }; } test("file tools honor deny rules and allow exceptions", (t) => { const { configPath, handlers } = setup(t, { deny: ["*.env", "*.env.*", "~/.keys/*"], allow: ["*.env.example"], }); const check = (toolName: string, input: Input) => handlers.get("tool_call")?.({ toolName, input }, { cwd: "/project" }); assert.deepEqual(check("read", { path: ".env" }), { block: true, reason: 'Path rule "*.env" denies access to /project/.env.', }); assert.equal(check("edit", { path: "@config/.env.local" })?.block, true); assert.equal(check("write", { path: "~/.keys/signing" })?.block, true); assert.match(check("ls", { path: "~/.keys/signing" })?.reason ?? "", new RegExp(homedir())); assert.equal(check("grep", { path: ".env", remote: "lab" })?.block, true); assert.equal(check("read", { path: ".env", remote: "lab" }), undefined); assert.equal(check("write", { path: "~/.keys/signing", remote: "lab" }), undefined); assert.equal(check("copy", { path: "~/.keys/signing", remote: "lab" })?.block, true); assert.equal(check("read", { path: ".env.example" }), undefined); assert.equal(check("read", { path: "notes.md" }), undefined); assert.equal(check("bash", { command: "cat .env" }), undefined); writeFileSync(configPath, JSON.stringify({ deny: "*.env" })); assert.match(check("read", { path: "notes.md" })?.reason ?? "", /path-rules config is invalid/); }); test("write rules block only edit and write", (t) => { const { handlers } = setup(t, { denyWrite: ["*/guard/config.json"] }); const check = (toolName: string, path: string) => handlers.get("tool_call")?.({ toolName, input: { path } }, { cwd: "/project" }); assert.equal(check("edit", "guard/config.json")?.block, true); assert.equal(check("write", "/other/guard/config.json")?.block, true); assert.equal(check("read", "guard/config.json"), undefined); assert.equal(check("grep", "guard/config.json"), undefined); assert.equal(check("write", "guard/notes.md"), undefined); }); test("file tools check the target of a symlink", (t) => { const dir = realpathSync(mkdtempSync(join(tmpdir(), "pi-path-rules-link-"))); t.after(() => rmSync(dir, { recursive: true, force: true })); mkdirSync(join(dir, "private")); writeFileSync(join(dir, "private", "token"), "value\n"); symlinkSync(join(dir, "private", "token"), join(dir, "notes.txt")); symlinkSync(join(dir, "private"), join(dir, "linked")); const { handlers } = setup(t, { deny: [`${dir}/private/*`] }); const check = (toolName: string, path: string) => handlers.get("tool_call")?.({ toolName, input: { path } }, { cwd: dir }); assert.equal(check("read", "notes.txt")?.block, true); assert.equal(check("write", "linked/new.txt")?.block, true); assert.equal(check("write", "new.txt"), undefined); }); test("files in another workspace get the rules of the main checkout", (t) => { const { handlers } = setup(t, { denyWrite: ["/repo/main/config.json"] }); const check = (path: string) => handlers.get("tool_call")?.({ toolName: "edit", input: { path } }, { cwd: "/" }); assert.equal(check("/repo/workspace/config.json")?.block, true); assert.equal(check("/repo/main/config.json")?.block, true); assert.equal(check("/repo/workspace/notes.txt"), undefined); }); test("grep output from denied files in a searched directory is removed", (t) => { const dir = mkdtempSync(join(tmpdir(), "pi-path-rules-grep-")); t.after(() => rmSync(dir, { recursive: true, force: true })); mkdirSync(join(dir, "secrets")); mkdirSync(join(dir, "src")); const { handlers } = setup(t, { deny: ["*.env", `${dir}/secrets/*`] }); const grep = (path: string | undefined, text: string) => handlers.get("tool_result")?.( { toolName: "grep", input: { pattern: "KEY", path }, content: [{ type: "text", text }], isError: false, }, { cwd: dir }, ); const result = grep( undefined, [ "src/app.ts:3: const KEY = load();", ".env:1: KEY=secret", "src/.env-2- OTHER=value", "", "[5 matches limit reached]", ].join("\n"), ); assert.deepEqual(result?.content, [ { type: "text", text: "src/app.ts:3: const KEY = load();\n\n[5 matches limit reached]" }, { type: "text", text: "[Path rules removed 2 lines from denied files.]" }, ]); assert.equal(grep("secrets", "id_key:1: PRIVATE KEY")?.content?.[0]?.text, ""); assert.equal(grep("src", "app.ts:3: const KEY = load();"), undefined); });