repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

fix(git-safe): bind generated wrapper executables

5e08ba63d1dd3ac3766894bf762900ba3f7852ef

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (7)

extensions/git-safe/README.md

Modified
37 37 - `GIT_SEQUENCE_EDITOR=true`
38 38 - `GIT_MERGE_AUTOEDIT=no`
40 -A session-scoped Git executable wrapper receives parsed arguments from normal Bash calls, `command git`, `env git`, `xargs git`, nested Bash, and unqualified child-process PATH lookup.
40 +A generated Git executable wrapper receives parsed arguments from normal Bash calls, `command git`, `env git`, `xargs git`, nested Bash, and unqualified child-process PATH lookup.
41 +The first Bash call creates it with fixed Node and Git paths; later calls and reloads reuse it.
41 42 It rejects hook-skipping `--no-verify` options, including accepted abbreviations, short `commit -n`, and non-shell alias chains.
42 43 It resets the editor environment immediately before invoking real Git and delegates ordinary commands unchanged.
43 44 Bash `git()` and `git.exe()` functions route direct calls to that wrapper, while narrow preflight checks cover simple literal bypasses.

extensions/git-safe/__tests__/git-policy.test.ts

Modified
1 -import { describe, expect, it } from "vitest";
2 -import { applyGitPolicy, blockedGitCommandReason } from "../git-policy";
1 +import {
2 + chmodSync,
3 + copyFileSync,
4 + mkdtempSync,
5 + readFileSync,
6 + rmSync,
7 + writeFileSync,
8 +} from "node:fs";
9 +import { tmpdir } from "node:os";
10 +import path from "node:path";
11 +import { afterEach, describe, expect, it } from "vitest";
12 +import {
13 + applyGitPolicy,
14 + blockedGitCommandReason,
15 + createGitPolicyRuntime,
16 +} from "../git-policy";
18 +const testDirs: string[] = [];
19 +afterEach(() => {
20 + for (const dir of testDirs.splice(0))
21 + rmSync(dir, { recursive: true, force: true });
22 +});
4 24 describe("git-safe agent Git policy", () => {
5 25 it("blocks literal command-git no-verify bypasses", () => {
47 + it("generates and reuses a wrapper with fixed executables", async () => {
48 + const bin = mkdtempSync(path.join(tmpdir(), "pi-git-policy-bin-"));
49 + testDirs.push(bin);
50 + const git = path.join(
51 + bin,
52 + process.platform === "win32" ? "git.exe" : "git",
53 + );
54 + if (process.platform === "win32") copyFileSync(process.execPath, git);
55 + else {
56 + writeFileSync(git, "#!/bin/sh\nexit 0\n", "utf8");
57 + chmodSync(git, 0o755);
58 + }
60 + const first = await createGitPolicyRuntime({ PATH: bin }, process.platform);
61 + const second = await createGitPolicyRuntime(
62 + { PATH: bin },
63 + process.platform,
64 + );
65 + const wrapper = readFileSync(
66 + path.join(first.wrapperDir, "git-wrapper.cjs"),
67 + "utf8",
68 + );
70 + expect(second).toBe(first);
71 + expect(wrapper).toContain(JSON.stringify(first.realGit));
72 + expect(wrapper).not.toContain("__PI_GIT_SAFE_REAL_GIT__");
73 + });
27 75 it("routes Git, command, and env through the executable wrapper", () => {
28 76 const runtime = { wrapperDir: "/tmp/git policy", realGit: "/usr/bin/git" };
29 77 const wrapped = applyGitPolicy("git status", runtime);
31 79 expect(wrapped).toContain("'/tmp/git policy'");
32 80 expect(wrapped).toContain("'/tmp/git policy/git'");
33 81 expect(wrapped).not.toContain("PI_GIT_SAFE_REAL_GIT");
82 + expect(wrapped).not.toContain("PI_GIT_SAFE_NODE");
34 83 expect(applyGitPolicy(wrapped, runtime)).not.toBe(wrapped);

extensions/git-safe/__tests__/harness.test.ts

Modified
275 275 await expectRejected(command);
277 + if (process.platform === "win32")
278 + await expectRejected(
279 + "MSYS2_ARG_CONV_EXCL='*' cmd.exe /d /c 'git commit --no-verify'",
280 + );
277 281 }, 60_000);
279 283 it("rejects temporary aliases that create no-verify inside Git", async () => {
341 + it("ignores caller-controlled executable overrides", async () => {
342 + await startWithFakeGit();
343 + if (!root) throw new Error("missing test root");
344 + const alternateNode = path.join(root, "alternate-node");
345 + writeFileSync(alternateNode, "#!/bin/sh\nprintf 'OVERRIDE\\n'\n", "utf8");
346 + chmodSync(alternateNode, 0o755);
348 + for (const command of [
349 + `PI_GIT_SAFE_REAL_GIT=${JSON.stringify(process.execPath)} git status`,
350 + `PI_GIT_SAFE_NODE=${JSON.stringify(alternateNode)} git status`,
351 + ]) {
352 + const result = await execute(command);
353 + expect(result.output, command).toContain("FAKE_GIT");
354 + expect(result.output, command).not.toContain("OVERRIDE");
356 + await expectRejected(
357 + `PI_GIT_SAFE_NODE=${JSON.stringify(alternateNode)} PI_GIT_SAFE_REAL_GIT=${JSON.stringify(process.execPath)} git commit --no-verify`,
358 + );
359 + });
337 361 it("permits no-verify when Git treats it as data", async () => {
338 362 await startWithFakeGit();

extensions/git-safe/clone.ts

Modified
24 24 resolve,
26 26 } from "node:path";
27 +import { isMarkerPresent, MARKER_FILE } from "./marker.js";
27 28 import { SpawnExitError, SpawnTimeoutError, spawnExpect } from "./spawn.js";
29 30 // ── Constants ──────────────────────────────────────────────────────────────
32 33 const FILE_COUNT_LIMIT = 10_000;
33 34 const CLONE_TIMEOUT_MS = 60_000; // 60s
34 35 const CHECKOUT_TIMEOUT_MS = 30_000; // 30s
35 -const MARKER_FILE = ".pi-git-safe";
37 37 // ── Types ──────────────────────────────────────────────────────────────────
103 103 await writeFile(join(clonePath, MARKER_FILE), markerContent, "utf-8");
106 -export function isMarkerPresent(clonePath: string): boolean {
107 - return existsSync(join(clonePath, MARKER_FILE));
110 106 // ── Error formatting ───────────────────────────────────────────────────────
112 108 function formatError(

extensions/git-safe/git-policy.ts

Modified
1 -import { constants } from "node:fs";
1 +import { constants, rmSync } from "node:fs";
2 2 import {
3 3 access,
4 4 chmod,
5 5 mkdtemp,
6 6 readFile,
7 7 realpath,
8 - rm,
9 8 writeFile,
10 9 } from "node:fs/promises";
11 10 import { tmpdir } from "node:os";
50 49 return undefined;
53 -export async function createGitPolicyRuntime(): Promise<GitPolicyRuntime> {
54 - const realGit = await findGitExecutable();
52 +const RUNTIME_CACHE = Symbol.for("@bugabinga/pi-ext-git-safe/runtime-cache-v1");
53 +type RuntimeCache = {
54 + promises: Map<string, Promise<GitPolicyRuntime>>;
55 + wrapperDirs: Set<string>;
56 + cleanupRegistered: boolean;
57 +};
58 +type RuntimeGlobal = typeof globalThis & { [RUNTIME_CACHE]?: RuntimeCache };
59 +const runtimeGlobal = globalThis as RuntimeGlobal;
60 +const existingRuntimeCache = runtimeGlobal[RUNTIME_CACHE];
61 +const runtimeCache: RuntimeCache = existingRuntimeCache ?? {
62 + promises: new Map(),
63 + wrapperDirs: new Set(),
64 + cleanupRegistered: false,
65 +};
66 +if (!existingRuntimeCache) runtimeGlobal[RUNTIME_CACHE] = runtimeCache;
67 +if (!runtimeCache.cleanupRegistered) {
68 + runtimeCache.cleanupRegistered = true;
69 + process.once("exit", () => {
70 + for (const wrapperDir of runtimeCache.wrapperDirs) {
71 + try {
72 + rmSync(wrapperDir, { recursive: true, force: true });
73 + } catch {}
74 + }
75 + });
78 +async function generateGitPolicyRuntime(
79 + env: NodeJS.ProcessEnv,
80 + platform: NodeJS.Platform,
81 +): Promise<GitPolicyRuntime> {
82 + const realGit = await findGitExecutable(env, platform);
55 83 if (!realGit) throw new Error("Git executable not found on PATH");
56 84 const wrapperDir = await mkdtemp(join(tmpdir(), "pi-git-safe-policy-"));
57 - const wrapper = join(wrapperDir, "git");
85 + const wrapperScript = join(wrapperDir, "git-wrapper.cjs");
86 + const launcher = join(wrapperDir, "git");
58 87 try {
59 88 const template = await readFile(
60 89 new URL("./git-wrapper.cjs", import.meta.url),
61 90 "utf8",
63 - await writeFile(
64 - wrapper,
65 - template
66 - .replace(/^#![^\r\n]*/u, `#!${bashPath(process.execPath)}`)
67 - .replace('"__PI_GIT_SAFE_REAL_GIT__"', JSON.stringify(realGit)),
68 - "utf8",
69 - );
70 - await chmod(wrapper, 0o755);
71 - await writeFile(
72 - join(wrapperDir, "git.cmd"),
73 - `@echo off\r\n"${process.execPath}" "%~dp0git" %*\r\n`,
74 - "utf8",
75 - );
92 + await Promise.all([
93 + writeFile(
94 + wrapperScript,
95 + template.replace('"__PI_GIT_SAFE_REAL_GIT__"', JSON.stringify(realGit)),
96 + { encoding: "utf8", mode: 0o600 },
97 + ),
98 + writeFile(
99 + launcher,
100 + `#!/bin/sh\nexec ${shellQuote(bashPath(process.execPath))} ${shellQuote(bashPath(wrapperScript))} "$@"\n`,
101 + { encoding: "utf8", mode: 0o500 },
102 + ),
103 + writeFile(
104 + join(wrapperDir, "git.cmd"),
105 + `@echo off\r\n"${process.execPath}" "%~dp0git-wrapper.cjs" %*\r\n`,
106 + { encoding: "utf8", mode: 0o500 },
107 + ),
108 + ]);
109 + await chmod(launcher, 0o500);
110 + runtimeCache.wrapperDirs.add(wrapperDir);
76 111 return { wrapperDir, realGit };
77 112 } catch (error) {
78 - await rm(wrapperDir, { recursive: true, force: true }).catch(() => {});
113 + rmSync(wrapperDir, { recursive: true, force: true });
79 114 throw error;
83 -export async function removeGitPolicyRuntime(
84 - runtime: GitPolicyRuntime | undefined,
85 -): Promise<void> {
86 - if (runtime)
87 - await rm(runtime.wrapperDir, { recursive: true, force: true }).catch(
88 - () => {},
89 - );
118 +export function createGitPolicyRuntime(
119 + env: NodeJS.ProcessEnv = process.env,
120 + platform: NodeJS.Platform = process.platform,
121 +): Promise<GitPolicyRuntime> {
122 + const key = `${platform}\0${process.execPath}\0${env[pathKey(env)] ?? ""}`;
123 + const existing = runtimeCache.promises.get(key);
124 + if (existing) return existing;
125 + const runtime = generateGitPolicyRuntime(env, platform).catch((error) => {
126 + runtimeCache.promises.delete(key);
127 + throw error;
128 + });
129 + runtimeCache.promises.set(key, runtime);
130 + return runtime;
92 133 function shellQuote(value: string): string {

extensions/git-safe/index.ts

Modified
20 20 import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
21 21 import {
22 22 type ExtensionAPI,
23 + type ExtensionContext,
23 24 isToolCallEventType,
24 25 } from "@earendil-works/pi-coding-agent";
25 26 import { Text } from "@earendil-works/pi-tui";
26 27 import { Type } from "typebox";
27 -import { isMarkerPresent, type SafeCloneResult, safeClone } from "./clone.js";
28 +import type { SafeCloneResult } from "./clone.js";
28 29 import {
29 30 applyGitPolicy,
30 31 blockedGitCommandReason,
31 32 createGitPolicyRuntime,
32 33 type GitPolicyRuntime,
33 - removeGitPolicyRuntime,
34 34 } from "./git-policy.js";
35 +import { isMarkerPresent } from "./marker.js";
35 36 import { createMarkers, wrapUntrusted } from "./spotlight.js";
37 38 // ── Git-specific spotlight preamble ────────────────────────────────────────
89 90 export default function gitSafeExtension(pi: ExtensionAPI) {
90 91 // Session-scoped spotlight markers
91 92 const spotlightMarkers = createMarkers({ preamble: GIT_PREAMBLE });
92 - let gitPolicyRegistered = false;
93 - let gitPolicyRuntime: GitPolicyRuntime | undefined;
93 + let generation = 0;
94 + let gitPolicyRuntime: Promise<GitPolicyRuntime | undefined> | undefined;
95 - // ── session_start: install agent Git policy ──────────────────────────
97 - pi.on("session_start", async (_event, ctx) => {
96 + const ensureGitPolicy = (ctx: ExtensionContext) => {
98 97 if (!gitPolicyRuntime) {
99 - try {
100 - gitPolicyRuntime = await createGitPolicyRuntime();
101 - } catch (error) {
102 - if (ctx.hasUI)
103 - ctx.ui.notify(
104 - `git-safe policy disabled: ${error instanceof Error ? error.message : String(error)}`,
105 - "warning",
106 - );
107 - }
108 - }
109 - if (gitPolicyRuntime && !gitPolicyRegistered) {
110 - gitPolicyRegistered = true;
111 - pi.on("tool_call", (event) => {
112 - if (!isToolCallEventType("bash", event) || !gitPolicyRuntime) return;
113 - const reason = blockedGitCommandReason(
114 - event.input.command,
115 - gitPolicyRuntime,
116 - );
117 - if (reason) return { block: true, reason };
118 - event.input.command = applyGitPolicy(
119 - event.input.command,
120 - gitPolicyRuntime,
121 - );
122 - });
98 + const ticket = generation;
99 + gitPolicyRuntime = createGitPolicyRuntime()
100 + .then((runtime) => (ticket === generation ? runtime : undefined))
101 + .catch((error) => {
102 + if (ticket === generation && ctx.hasUI)
103 + ctx.ui.notify(
104 + `git-safe policy disabled: ${error instanceof Error ? error.message : String(error)}`,
105 + "warning",
106 + );
107 + return undefined;
108 + });
110 + return gitPolicyRuntime;
111 + };
113 + pi.on("session_start", () => {
114 + generation++;
115 + gitPolicyRuntime = undefined;
126 - pi.on("session_shutdown", async () => {
127 - await removeGitPolicyRuntime(gitPolicyRuntime);
118 + pi.on("session_shutdown", () => {
119 + generation++;
128 120 gitPolicyRuntime = undefined;
123 + pi.on("tool_call", async (event, ctx) => {
124 + if (!isToolCallEventType("bash", event)) return;
125 + const runtime = await ensureGitPolicy(ctx);
126 + if (!runtime) return;
127 + const reason = blockedGitCommandReason(event.input.command, runtime);
128 + if (reason) return { block: true, reason };
129 + event.input.command = applyGitPolicy(event.input.command, runtime);
130 + });
131 132 // ── tool_result hook on "read": spotlight-wrap cloned content ────────
133 134 pi.on("tool_result", async (event, ctx) => {
281 + const { safeClone } = await import("./clone.js");
280 282 const result = await safeClone(params.url, params.path, {
281 283 branch: params.branch,
282 284 sparse: params.sparse,

extensions/git-safe/marker.ts

Added
new file mode 100644
1 +import { existsSync } from "node:fs";
2 +import { join } from "node:path";
4 +export const MARKER_FILE = ".pi-git-safe";
6 +export function isMarkerPresent(clonePath: string): boolean {
7 + return existsSync(join(clonePath, MARKER_FILE));
8 +}