import { accessSync, chmodSync, constants, copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { createBashTool } from "@earendil-works/pi-coding-agent"; import { afterEach, describe, expect, it } from "vitest"; import { createTestSession, type TestSession, withProcessEnv, } from "../../../test/harness"; type BashEvent = { type: "tool_call"; toolName: "bash"; toolCallId: string; input: { command: string }; }; function gitSafePath(): string { return path.resolve(import.meta.dirname, "../index.ts"); } function rtkPath(): string { return path.resolve(import.meta.dirname, "../../rtk/index.ts"); } function bashShebang(): string { if (process.platform === "win32") return "#!/usr/bin/env bash"; const candidates = [ process.env.SHELL, ...(process.env.PATH ?? "") .split(path.delimiter) .filter(Boolean) .map((directory) => path.join(directory, "bash")), "/bin/bash", ]; for (const candidate of candidates) { if (!candidate || path.basename(candidate) !== "bash") continue; try { accessSync(candidate, constants.X_OK); return `#!${candidate}`; } catch {} } throw new Error("bash executable not found"); } function installFakeGit(root: string): { bin: string; executable: string } { const bin = path.join(root, "fake-bin"); mkdirSync(bin); if (process.platform === "win32") { const gitExe = path.join(bin, "git.exe"); copyFileSync(process.execPath, gitExe); const implementation = path.join(root, "fake-git.cjs"); writeFileSync( implementation, [ 'const path = require("node:path");', "const command = path.basename(process.argv[1]);", "const args = process.argv.slice(2);", "if (command === 'config' && args.includes('--get')) process.exit(1);", "process.stdout.write('FAKE_GIT\\n');", "process.stdout.write(`ARGS:<${[command, ...args].join('><')}>\\n`);", "process.stdout.write(`EDITOR=<${process.env.GIT_EDITOR ?? ''}> SEQUENCE=<${process.env.GIT_SEQUENCE_EDITOR ?? ''}> MERGE=<${process.env.GIT_MERGE_AUTOEDIT ?? ''}>\\n`);", "", ].join("\n"), "utf8", ); for (const command of [ "add", "am", "commit", "config", "grep", "merge", "note", "nv", "pull", "push", "rebase", "status", "var", ]) { writeFileSync( path.join(root, command), `require(${JSON.stringify(implementation)});\n`, "utf8", ); } return { bin, executable: gitExe }; } const git = path.join(bin, "git"); writeFileSync( git, [ bashShebang(), "if [[ \"$*\" == '--list-cmds=builtins' ]]; then printf 'status\\n'; exit 0; fi", "if [[ \"$*\" == *'config --get alias.'* ]]; then exit 1; fi", "printf 'FAKE_GIT\\n'", "printf 'ARGS:'", "printf '<%s>' \"$@\"", 'printf \'\\nEDITOR=<%s> SEQUENCE=<%s> MERGE=<%s>\\n\' "$GIT_EDITOR" "$GIT_SEQUENCE_EDITOR" "$GIT_MERGE_AUTOEDIT"', "", ].join("\n"), "utf8", ); chmodSync(git, 0o755); return { bin, executable: git }; } function installFakeRtk(bin: string): void { const rtk = path.join(bin, "rtk"); writeFileSync( rtk, [ bashShebang(), "if [[ \"$1\" == '--version' ]]; then printf 'rtk 0.42.4\\n'; exit 0; fi", "if [[ \"$1\" == 'rewrite' && \"$2\" == 'git commit --no-verify' ]]; then printf 'rtk git commit --no-verify\\n'; exit 0; fi", "if [[ \"$1\" == 'rewrite' && \"$2\" == 'git status' ]]; then printf 'rtk git status\\n'; exit 0; fi", 'if [[ "$1" == \'git\' ]]; then shift; exec git "$@"; fi', "exit 1", "", ].join("\n"), "utf8", ); chmodSync(rtk, 0o755); } function bashEvent(command: string): BashEvent { return { type: "tool_call", toolName: "bash", toolCallId: crypto.randomUUID(), input: { command }, }; } describe("git-safe pi-test-harness", () => { let t: TestSession | undefined; let root: string | undefined; let fakeGit: string | undefined; afterEach(() => { t?.dispose(); if (root) rmSync(root, { recursive: true, force: true }); t = undefined; root = undefined; fakeGit = undefined; }); async function startWithFakeGit(useRtk = false): Promise { root = mkdtempSync(path.join(tmpdir(), "pi-git-safe-test-")); const installed = installFakeGit(root); if (useRtk) installFakeRtk(installed.bin); fakeGit = installed.executable; t = await createTestSession({ cwd: root, env: { PATH: `${installed.bin}${path.delimiter}${process.env.PATH}` }, extensions: useRtk ? [gitSafePath(), rtkPath()] : [gitSafePath()], }); } async function execute(command: string) { if (!t) throw new Error("missing test session"); const event = bashEvent(command); const blocked = await t.session.extensionRunner.emitToolCall( event as never, ); if (blocked) return { blocked, output: "" }; const tool = createBashTool(t.cwd); try { const result = await withProcessEnv(t.env, () => tool.execute( event.toolCallId, event.input, new AbortController().signal, undefined, ), ); const output = result.content .flatMap((part) => (part.type === "text" ? [part.text] : [])) .join("\n"); return { blocked, output }; } catch (error) { return { blocked, output: error instanceof Error ? error.message : String(error), }; } } async function expectRejected(command: string): Promise { const result = await execute(command); expect(result.output, command).toContain("git-safe blocked --no-verify"); expect(result.output, command).not.toContain("FAKE_GIT"); } it("loads in real Pi extension runtime", async () => { t = await createTestSession({ extensions: [gitSafePath()] }); expect(t.session.extensionRunner.extensions).toHaveLength(1); }); it("recovers a marked clone lazily when read", async () => { root = mkdtempSync(path.join(tmpdir(), "pi-git-safe-read-")); const clone = path.join(root, "owner", "repo"); const file = path.join(clone, "README.md"); mkdirSync(clone, { recursive: true }); writeFileSync(path.join(clone, ".pi-git-safe"), "{}", "utf8"); writeFileSync(file, "untrusted instructions", "utf8"); t = await createTestSession({ cwd: root, extensions: [gitSafePath()] }); const result = await t.session.extensionRunner.emitToolResult({ type: "tool_result", toolName: "read", toolCallId: crypto.randomUUID(), input: { path: file }, content: [{ type: "text", text: "untrusted instructions" }], isError: false, } as never); expect(result?.content[0]).toMatchObject({ type: "text" }); expect( result?.content[0]?.type === "text" && result.content[0].text, ).toContain("UNTRUSTED DATA"); expect( result?.content[0]?.type === "text" && result.content[0].text, ).toContain("untrusted instructions"); }); it("sets noninteractive editor variables while ordinary Git still runs", async () => { await startWithFakeGit(); const result = await execute("git status"); expect(result.blocked).toBeUndefined(); expect(result.output).toContain("FAKE_GIT"); expect(result.output).toContain("ARGS:"); expect(result.output).toContain("EDITOR= SEQUENCE= MERGE="); }); it("rejects no-verify after shell expansion and indirect PATH lookup", async () => { await startWithFakeGit(); for (const command of [ 'flag=--no-verify; git commit "$flag"', "git am --no-v patch.mbox", "git am -n patch.mbox", 'command git commit --no-"verify"', "command -p git -C . commit --no-verify", "env git push --no-verify", "env --uns PATH git commit --no-verify", "bash -p -c 'git rebase --no-verify'", "bash -c 'command git commit --no-verify'", "unset -f git; git commit --no-verify", "printf '%s\\0' commit --no-verify | xargs -0 git", "printf '%s\\0' commit --no-verify | xargs -0 git.exe", "printf '%s\\0' commit --no-verify | xargs -0 --max-a 2 git.exe", "git commit -n", "git commit --no-verif", "git commit --untracked-files --no-verify", "git push --signed --no-verify", "git rebase --rebase-merges --no-verify main", "git pull --no-verify", ]) { await expectRejected(command); } if (process.platform === "win32") await expectRejected( "MSYS2_ARG_CONV_EXCL='*' cmd.exe /d /c 'git commit --no-verify'", ); }, 60_000); it("rejects temporary aliases that create no-verify inside Git", async () => { await startWithFakeGit(); for (const command of [ "git -c 'alias.nv=commit --no-verify' nv", `git -c "alias.nv=commit -m '' --no-verify" nv`, "git -c 'alias.nv=--no-pager commit --no-verify' nv", "git -c 'alias.x=-c alias.y=commit y --no-verify' x", "git -calias.nv='commit --no-verify' nv", "git -c 'alias.nv=commit -n' nv", "git -c 'alias.nv=commit \"--no-verify\"' nv", "git -c alias.ci=commit ci --no-verify", "NV='commit --no-verify' git --config-env=alias.nv=NV nv", "GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=alias.nv GIT_CONFIG_VALUE_0='commit --no-verify' git nv", ]) { await expectRejected(command); } const chain = Array.from( { length: 12 }, (_, index) => `-c alias.a${index}=a${index + 1}`, ).join(" "); await expectRejected(`git ${chain} -c 'alias.a12=commit --no-verify' a0`); }); it("restores editor protection at the executable boundary", async () => { await startWithFakeGit(); for (const command of [ "GIT_EDITOR=vim git commit", "GIT_SEQUENCE_EDITOR=vim git rebase -i HEAD~1", "env -u GIT_EDITOR -u GIT_SEQUENCE_EDITOR -u GIT_MERGE_AUTOEDIT git commit", "GIT_EDITOR=vim command -p git commit", ]) { const result = await execute(command); expect(result.output).toContain("FAKE_GIT"); expect(result.output).toContain( "EDITOR= SEQUENCE= MERGE=", ); } }); it("preserves editor queries without opening an editor", async () => { await startWithFakeGit(); const result = await execute("git var GIT_EDITOR"); expect(result.output).toContain("FAKE_GIT"); expect(result.output).toContain("EDITOR=<> SEQUENCE=<> MERGE=<>"); }); it("does not trust an agent-supplied policy marker", async () => { await startWithFakeGit(); await expectRejected( "# pi-git-safe-policy-v1\\ngit commit --no-verify".replace("\\n", "\n"), ); }); it("ignores caller-controlled executable overrides", async () => { await startWithFakeGit(); if (!root) throw new Error("missing test root"); const alternateNode = path.join(root, "alternate-node"); writeFileSync(alternateNode, "#!/bin/sh\nprintf 'OVERRIDE\\n'\n", "utf8"); chmodSync(alternateNode, 0o755); for (const command of [ `PI_GIT_SAFE_REAL_GIT=${JSON.stringify(process.execPath)} git status`, `PI_GIT_SAFE_NODE=${JSON.stringify(alternateNode)} git status`, ]) { const result = await execute(command); expect(result.output, command).toContain("FAKE_GIT"); expect(result.output, command).not.toContain("OVERRIDE"); } await expectRejected( `PI_GIT_SAFE_NODE=${JSON.stringify(alternateNode)} PI_GIT_SAFE_REAL_GIT=${JSON.stringify(process.execPath)} git commit --no-verify`, ); }); it("permits no-verify when Git treats it as data", async () => { await startWithFakeGit(); const commands = [ "git add -- --no-verify", "git grep -e --no-verify", "git commit -m --no-verify", "git commit -am --no-verify", "git commit -uno", "git commit -t/dev/null", "git commit --mess --no-verify", "git commit -m safe --end-of-options --no-verify", "git commit -Sn -m signed", "git merge --into-name --no-verify topic", "git merge -F --no-verify topic", "git am --resolvemsg --no-verify patch.mbox", "git rebase --trailer --no-verify trunk", "git pull --no-rebase -o --no-verify", "git -c 'alias.nv=commit --no-verify' status", "git -c 'alias.note=!printf %s --no-verify' note", "command git merge --no-verify-signatures topic", "command git commit -m 'Document --no-verify usage'", 'env -i PATH="$PATH" git status', "GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=alias.nv GIT_CONFIG_VALUE_0='commit --no-verify' git -c alias.nv=status nv", "GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=alias.commit GIT_CONFIG_VALUE_0='rebase --no-verify' git commit -m safe", ]; if (process.platform !== "win32") { commands.push( "GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=alias.status GIT_CONFIG_VALUE_0='commit --no-verify' git status", ); } for (const command of commands) { const result = await execute(command); expect(result.blocked, command).toBeUndefined(); if (process.platform !== "win32" || !command.includes("git -c ")) { expect(result.output, command).toContain("FAKE_GIT"); } } }, 60_000); it("blocks literal command-git bypasses before execution", async () => { await startWithFakeGit(); const result = await execute("command git commit --no-verify"); expect(result.blocked).toMatchObject({ block: true }); expect(result.blocked?.reason).toContain("git-safe blocked --no-verify"); }); it("rejects literal absolute Git paths", async () => { await startWithFakeGit(); if (!fakeGit) throw new Error("missing fake Git path"); for (const command of ["commit", "pull"]) { const result = await execute( `${JSON.stringify(fakeGit)} ${command} --no-verify`, ); expect(result.blocked).toMatchObject({ block: true }); } }); it("keeps policy active after RTK rewrites Git", async () => { await startWithFakeGit(true); await expectRejected("git commit --no-verify"); const ordinary = await execute("git status"); expect(ordinary.output).toContain("FAKE_GIT"); expect(ordinary.output).toContain("ARGS:"); }); });