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
Modified37 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";
9 +import { tmpdir }
from "node:os";
10 +import path
from "node:path";
11 +import { afterEach, describe, expect, it }
from "vitest";
14 + blockedGitCommandReason,
15 + createGitPolicyRuntime,
16 +}
from "../git-policy";
18 +const testDirs
: string[]
= [];
20 + for (
const dir
of testDirs.
splice(
0))
21 + rmSync(dir, { recursive:
true, force:
true });
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-"));
50 + const git
= path.
join(
52 + process.
platform === "win32" ? "git.exe" : "git",
54 + if (
process.
platform === "win32")
copyFileSync(
process.
execPath, git);
56 + writeFileSync(git,
"#!/bin/sh\nexit 0\n",
"utf8");
57 + chmodSync(git,
0o755);
60 + const first
= await createGitPolicyRuntime({ PATH: bin },
process.
platform);
61 + const second
= await createGitPolicyRuntime(
65 + const wrapper
= readFileSync(
66 + path.
join(first.wrapperDir,
"git-wrapper.cjs"),
70 + expect(second).
toBe(first);
71 + expect(wrapper).
toContain(
JSON.
stringify(first.realGit));
72 + expect(wrapper).not.
toContain(
"__PI_GIT_SAFE_REAL_GIT__");
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
Modified275 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'",
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`,
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`,
337 361 it(
"permits no-verify when Git treats it as data",
async ()
=> {
338 362 await startWithFakeGit();
extensions/git-safe/clone.ts
Modified 26 26 } from
"node:path";
27 +import { isMarkerPresent, MARKER_FILE }
from "./marker.js";
27 28 import { SpawnExitError, SpawnTimeoutError, spawnExpect }
from "./spawn.js";
32 33 const FILE_COUNT_LIMIT
= 10_000;
33 34 const CLONE_TIMEOUT_MS
= 60_000;
34 35 const CHECKOUT_TIMEOUT_MS
= 30_000;
35 -const MARKER_FILE
= ".pi-git-safe";
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));
112 108 function formatError(
extensions/git-safe/git-policy.ts
Modified 1 -import { constants }
from "node:fs";
1 +import { constants, rmSync }
from "node:fs";
10 9 }
from "node:fs/promises";
11 10 import { tmpdir }
from "node:os";
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;
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,
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) {
72 + rmSync(wrapperDir, { recursive:
true, force:
true });
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");
59 88 const template
= await readFile(
60 89 new URL(
"./git-wrapper.cjs",
import.
meta.url),
66 - .
replace(
/^#![^\r\n]*/u,
`#!${bashPath(process.execPath)}`)
67 - .
replace(
'"__PI_GIT_SAFE_REAL_GIT__"',
JSON.
stringify(realGit)),
70 - await chmod(wrapper,
0o755);
72 - join(wrapperDir,
"git.cmd"),
73 - `@echo off\r\n"${process.execPath}" "%~dp0git" %*\r\n`,
95 + template.
replace(
'"__PI_GIT_SAFE_REAL_GIT__"',
JSON.
stringify(realGit)),
96 + { encoding:
"utf8", mode:
0o600 },
100 + `#!/bin/sh\nexec ${shellQuote(bashPath(process.execPath))} ${shellQuote(bashPath(wrapperScript))} "$@"\n`,
101 + { encoding:
"utf8", mode:
0o500 },
104 + join(wrapperDir,
"git.cmd"),
105 + `@echo off\r\n"${process.execPath}" "%~dp0git-wrapper.cjs" %*\r\n`,
106 + { encoding:
"utf8", mode:
0o500 },
109 + await chmod(launcher,
0o500);
110 + runtimeCache.wrapperDirs.
add(wrapperDir);
76 111 return { wrapperDir, realGit };
78 - await rm(wrapperDir, { recursive:
true, force:
true }).
catch(()
=> {});
113 + rmSync(wrapperDir, { recursive:
true, force:
true });
83 -export async function removeGitPolicyRuntime(
84 - runtime
: GitPolicyRuntime | undefined,
87 - await rm(runtime.wrapperDir, { recursive:
true, force:
true }).
catch(
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);
129 + runtimeCache.promises.
set(key, 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";
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";
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";
89 90 export default function gitSafeExtension(pi
: ExtensionAPI) {
91 92 const spotlightMarkers
= createMarkers({ preamble: GIT_PREAMBLE });
92 - let gitPolicyRegistered
= false;
93 - let gitPolicyRuntime
: GitPolicyRuntime | undefined;
94 + let gitPolicyRuntime
: Promise<
GitPolicyRuntime | undefined>
| undefined;
97 - pi.
on(
"session_start",
async (_event, ctx)
=> {
96 + const ensureGitPolicy = (ctx
: ExtensionContext)
=> {
98 97 if (
!gitPolicyRuntime) {
100 - gitPolicyRuntime
= await createGitPolicyRuntime();
104 - `git-safe policy disabled: ${error instanceof Error ? error.message : String(error)}`,
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,
117 - if (reason)
return { block:
true, reason };
118 - event.
input.command
= applyGitPolicy(
119 - event.
input.command,
98 + const ticket
= generation;
99 + gitPolicyRuntime
= createGitPolicyRuntime()
100 + .
then((runtime)
=> (ticket
=== generation
? runtime
: undefined))
101 + .
catch((error)
=> {
102 + if (ticket
=== generation
&& ctx.hasUI)
104 + `git-safe policy disabled: ${error instanceof Error ? error.message : String(error)}`,
110 + return gitPolicyRuntime;
113 + pi.
on(
"session_start", ()
=> {
115 + gitPolicyRuntime
= undefined;
126 - pi.
on(
"session_shutdown",
async ()
=> {
127 - await removeGitPolicyRuntime(gitPolicyRuntime);
118 + pi.
on(
"session_shutdown", ()
=> {
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);
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
Addednew 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));