repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(leaks): enforce provider-bound redaction hooks

a5ffb355ae7e913ef5e211a8ed17974131c3b30d

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (3)

+128 / −118 text lines

Diff layout

extensions/leaks/__tests__/harness.test.ts

Modified

+41 / −117 text lines

22import os from "node:os";
33import path from "node:path";
44import { afterEach, describe, expect, it } from "vitest";
5import {
6 createTestSession,
7 says,
8 type TestSession,
9 when,
10} from "../../../test/harness";
5import { createTestSession, type TestSession } from "../../../test/harness";
127function extPath() {
138 return path.resolve(import.meta.dirname, "../index.ts");
149}
16describe("leaks pi-test-harness", () => {
11const secret = "sk-or-v1-" + "d".repeat(64);
12const dotenvSecret = ["dotenv", "fixture", "secret", "123456789"].join("-");
14describe("leaks Pi provider boundary hooks", () => {
1715 let t: TestSession | undefined;
1816 afterEach(() => {
1917 t?.dispose();
2018 t = undefined;
2119 });
23 it("loads in real Pi extension runtime", async () => {
21 it("loads in real Pi runtime with one command and no tools", async () => {
2422 t = await createTestSession({ extensions: [extPath()] });
25 expect(t.session.extensionRunner.extensions).toHaveLength(1);
26 expect(t.session.extensionRunner.extensions[0].path).toBe(extPath());
27 expect([
28 ...t.session.extensionRunner.extensions[0].commands.keys(),
29 ]).toContain("leaks");
23 const extension = t.session.extensionRunner.extensions[0];
25 expect(extension.path).toBe(extPath());
26 expect([...extension.commands.keys()]).toEqual(["leaks"]);
27 expect([...extension.tools.keys()]).toEqual([]);
3028 });
32 it("redacts provider payload and records mappings", async () => {
30 it("redacts context copies without mutating originals", async () => {
3331 t = await createTestSession({ extensions: [extPath()] });
34 const value = "sk-or-v1-" + "d".repeat(64);
32 const messages = [{ role: "user", content: `send ${secret}` }];
36 const result = await t.session.extensionRunner.emitBeforeProviderRequest({
37 messages: [{ role: "user", content: `send ${value}` }],
38 });
34 const result = await t.session.extensionRunner.emitContext(messages as never);
40 const text = JSON.stringify(result);
41 expect(text).not.toContain(value);
42 expect(text).toMatch(/__LEAK_[a-f0-9]{12}__/);
36 expect(JSON.stringify(result)).not.toContain(secret);
37 expect(JSON.stringify(result)).toMatch(/__LEAK_[A-Z0-9_]+_[a-f0-9]{12}__/);
38 expect(messages[0].content).toContain(secret);
4339 });
45 it("redacts context message copies without mutating originals", async () => {
41 it("redacts provider payload authoritatively and preserves auth headers", async () => {
4642 t = await createTestSession({ extensions: [extPath()] });
47 const value = "ghp_" + "E".repeat(36);
48 const messages = [
49 {
50 role: "toolResult",
51 content: [{ type: "text", text: `output ${value}` }],
52 },
53 ];
55 const result = await t.session.extensionRunner.emitContext(
56 messages as never,
57 );
59 expect(JSON.stringify(result)).not.toContain(value);
60 expect(messages[0].content[0].text).toContain(value);
61 });
63 it("restores tool args before execution", async () => {
64 t = await createTestSession({ extensions: [extPath()] });
65 const value = "sk-or-v1-" + "e".repeat(64);
66 const redacted = await t.session.extensionRunner.emitBeforeProviderRequest({
67 text: value,
68 });
69 const placeholder = JSON.stringify(redacted).match(
70 /__LEAK_[a-f0-9]{12}__/,
71 )?.[0];
72 expect(placeholder).toBeTruthy();
74 const event = {
75 type: "tool_call",
76 toolName: "bash",
77 toolCallId: "call-1",
78 input: { command: `echo ${placeholder}` },
43 const payload = {
44 headers: { authorization: "Bearer provider-auth-header" },
45 messages: [{ role: "user", content: `send ${secret}` }],
7946 };
80 await t.session.extensionRunner.emitToolCall(event as never);
82 expect(event.input.command).toBe(`echo ${value}`);
48 const result = await t.session.extensionRunner.emitBeforeProviderRequest(payload);
50 expect(JSON.stringify(result)).not.toContain(secret);
51 expect((result as typeof payload).headers.authorization).toBe("Bearer provider-auth-header");
8352 });
85 it("restores finalized assistant messages", async () => {
54 it("restores tool args and finalized assistant messages locally", async () => {
8655 t = await createTestSession({ extensions: [extPath()] });
87 const value = "sk-or-v1-" + "f".repeat(64);
88 const redacted = await t.session.extensionRunner.emitBeforeProviderRequest({
89 text: value,
90 });
91 const placeholder = JSON.stringify(redacted).match(
92 /__LEAK_[a-f0-9]{12}__/,
93 )?.[0];
56 const redacted = await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret });
57 const placeholder = JSON.stringify(redacted).match(/__LEAK_[A-Z0-9_]+_[a-f0-9]{12}__/)?.[0];
9458 expect(placeholder).toBeTruthy();
96 const result = await t.session.extensionRunner.emitMessageEnd({
97 type: "message_end",
98 message: {
99 role: "assistant",
100 content: [{ type: "text", text: `saw ${placeholder}` }],
101 },
102 } as never);
60 const event = { type: "tool_call", toolName: "bash", toolCallId: "1", input: { command: `echo ${placeholder}` } };
61 await t.session.extensionRunner.emitToolCall(event as never);
62 expect(event.input.command).toBe(`echo ${secret}`);
104 expect(JSON.stringify(result)).toContain(value);
64 const message = await t.session.extensionRunner.emitMessageEnd({
65 type: "message_end",
66 message: { role: "assistant", content: [{ type: "text", text: `saw ${placeholder}` }] },
67 } as never);
68 expect(JSON.stringify(message)).toContain(secret);
10569 });
107 it("loads secret file values from Pi cwd", async () => {
71 it("loads dotenv values from Pi cwd without persisting mappings", async () => {
10872 const cwd = path.join(os.tmpdir(), `leaks-harness-${Date.now()}`);
10973 mkdirSync(cwd, { recursive: true });
110 writeFileSync(
111 path.join(cwd, ".env"),
112 "VALUE=from-dotenv-123456789\n",
113 "utf8",
114 );
74 writeFileSync(path.join(cwd, ".env"), `TOKEN=${dotenvSecret}\n`, "utf8");
11575 t = await createTestSession({ cwd, extensions: [extPath()] });
117 const result = await t.session.extensionRunner.emitBeforeProviderRequest({
118 text: "from-dotenv-123456789",
119 });
77 const result = await t.session.extensionRunner.emitBeforeProviderRequest({ text: dotenvSecret });
121 expect(JSON.stringify(result)).not.toContain("from-dotenv-123456789");
122 expect(JSON.stringify(result)).toMatch(/__LEAK_[a-f0-9]{12}__/);
123 });
125 it("redacts during a mocked agent run", async () => {
126 t = await createTestSession({ extensions: [extPath()], mockTools: {} });
127 const value = "sk-or-v1-" + "9".repeat(64);
129 await t.run(when(`Decide if this is sensitive: ${value}`, [says("done")]));
131 const command =
132 t.session.extensionRunner.extensions[0].commands.get("leaks");
133 await command.handler("status", t.session.extensionRunner.createContext());
134 const notices = t.events.uiCallsFor("notify").map((c) => String(c.args[0]));
135 expect(notices.some((m) => m.includes("mappings: 1"))).toBe(true);
136 });
138 it("command status/test/clear/reload run through real command registry", async () => {
139 t = await createTestSession({
140 extensions: [extPath()],
141 mockUI: { confirm: true },
142 });
143 const command =
144 t.session.extensionRunner.extensions[0].commands.get("leaks");
145 const ctx = t.session.extensionRunner.createContext();
147 await command.handler("status", ctx);
148 await command.handler("test " + "sk-or-v1-" + "a".repeat(64), ctx);
149 await command.handler("reload", ctx);
150 await command.handler("clear", ctx);
152 const notices = t.events.uiCallsFor("notify").map((c) => String(c.args[0]));
153 expect(notices.some((m) => m.includes("leaks on"))).toBe(true);
154 expect(notices.some((m) => m.includes("openrouter: 1"))).toBe(true);
155 expect(notices.some((m) => m.includes("leaks reloaded"))).toBe(true);
156 expect(notices.some((m) => m.includes("leaks cleared"))).toBe(true);
79 expect(JSON.stringify(result)).not.toContain(dotenvSecret);
80 expect(JSON.stringify(t.session.sessionManager.getEntries())).not.toContain("LEAK_");
15781 });
15882});

extensions/leaks/index.ts

Modified

+2 / −1 text lines

99 parseDotenv,
1010} from "./src/dotenv.ts";
1111import { LeaksEngine } from "./src/engine.ts";
12import leaks from "./src/pi.ts";
1213import { PlaceholderStore } from "./src/placeholders.ts";
1314import { selectSecretSpans } from "./src/selector.ts";
1415import {
7273 sanitizeTag,
7374};
75export default function leaks(_pi: unknown) {}
76export default leaks;

extensions/leaks/src/pi.ts

Added
new file mode 100644

+85 / −0 text lines

1import { existsSync, readFileSync } from "node:fs";
2import path from "node:path";
3import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4import { LeaksEngine } from "./engine.ts";
5import { loadLeaksSettings } from "./settings.ts";
6
7export default function leaks(pi: ExtensionAPI) {
8 const engine = new LeaksEngine();
9
10 pi.on("session_start", async (_event, ctx) => {
11 engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env);
12 if (ctx.hasUI) ctx.ui.setStatus("leaks", "leaks on | last 0");
13 });
15 pi.on("context", async (event) => {
16 return { messages: engine.redactDeep(event.messages, "context").value };
17 });
19 pi.on("before_provider_request", async (event, ctx) => {
20 const result = engine.redactDeep(event.payload, "provider");
21 if (ctx.hasUI) ctx.ui.setStatus("leaks", `leaks on | last ${result.count}`);
22 return result.value;
23 });
25 pi.on("tool_call", async (event) => {
26 const input = (event as { input?: unknown }).input;
27 if (input !== undefined) (event as { input: unknown }).input = engine.restoreDeep(input).value;
28 });
30 pi.on("message_end", async (event) => {
31 const restored = engine.restoreDeep(event.message).value;
32 return { message: restored };
33 });
35 pi.registerCommand("leaks", {
36 description: "Inspect and control provider-bound redaction",
37 async handler(args, ctx) {
38 const command = args.trim();
39 if (command === "status" || command === "") {
40 ctx.ui.notify(formatStatus(engine), "info");
41 return;
42 }
43 if (command === "reload") {
44 engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env);
45 ctx.ui.notify("leaks reloaded", "info");
46 return;
47 }
48 if (command === "clear") {
49 engine.clear();
50 ctx.ui.notify("leaks cleared", "info");
51 return;
52 }
53 if (command.startsWith("test ")) {
54 const result = engine.redactText(command.slice(5), "diagnostic");
55 ctx.ui.notify(`matches: ${result.count}\n${result.text}`, "info");
56 return;
57 }
58 ctx.ui.notify("usage: /leaks status|reload|test <text>|clear", "warning");
59 },
60 });
61}
63function readSettings(cwd: string) {
64 const file = path.join(cwd, ".pi", "settings.json");
65 if (!existsSync(file)) return { regex: [] };
66 try {
67 return loadLeaksSettings(JSON.parse(readFileSync(file, "utf8"))).settings;
68 } catch {
69 return { regex: [] };
70 }
71}
73function formatStatus(engine: LeaksEngine) {
74 const stats = engine.stats();
75 return [
76 "leaks on",
77 `built-in rules: ${stats.builtInRuleCount}`,
78 `custom regex: ${stats.customRegexCount}`,
79 `invalid regex: ${stats.invalidRegexCount}`,
80 `learned: ${stats.learnedCount}`,
81 `mappings: ${stats.mappingCount}`,
82 `last provider redactions: ${stats.lastProviderRedactionCount}`,
83 `total provider redactions: ${stats.totalProviderRedactionCount}`,
84 ].join("\n");
85}