feat(leaks): enforce provider-bound redaction hooks
a5ffb355ae7e913ef5e211a8ed17974131c3b30d
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: 486e0cdd2e79
bugabingas pi extensions
a5ffb355ae7e913ef5e211a8ed17974131c3b30d
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+128 / −118 text lines
+41 / −117 text lines
import { createTestSession, type TestSession } from "../../../test/harness";describe("leaks pi-test-harness", () => { it("loads in real Pi extension runtime", async () => { it("loads in real Pi runtime with one command and no tools", async () => { it("redacts provider payload and records mappings", async () => { it("redacts context copies without mutating originals", async () => { const value = "sk-or-v1-" + "d".repeat(64); const messages = [{ role: "user", content: `send ${secret}` }]; const result = await t.session.extensionRunner.emitBeforeProviderRequest({ messages: [{ role: "user", content: `send ${value}` }], }); const result = await t.session.extensionRunner.emitContext(messages as never); it("redacts context message copies without mutating originals", async () => { it("redacts provider payload authoritatively and preserves auth headers", async () => { const value = "ghp_" + "E".repeat(36); const messages = [ { role: "toolResult", content: [{ type: "text", text: `output ${value}` }], }, ]; const result = await t.session.extensionRunner.emitContext( messages as never, ); expect(JSON.stringify(result)).not.toContain(value); expect(messages[0].content[0].text).toContain(value); }); it("restores tool args before execution", async () => { t = await createTestSession({ extensions: [extPath()] }); const value = "sk-or-v1-" + "e".repeat(64); const redacted = await t.session.extensionRunner.emitBeforeProviderRequest({ text: value, }); const placeholder = JSON.stringify(redacted).match( /__LEAK_[a-f0-9]{12}__/, )?.[0]; expect(placeholder).toBeTruthy(); const event = { type: "tool_call", toolName: "bash", toolCallId: "call-1", input: { command: `echo ${placeholder}` }, await t.session.extensionRunner.emitToolCall(event as never); expect(event.input.command).toBe(`echo ${value}`); it("restores finalized assistant messages", async () => { it("restores tool args and finalized assistant messages locally", async () => { expect(JSON.stringify(result)).toContain(value); it("loads secret file values from Pi cwd", async () => { it("loads dotenv values from Pi cwd without persisting mappings", async () => { writeFileSync(path.join(cwd, ".env"), `TOKEN=${dotenvSecret}\n`, "utf8"); const result = await t.session.extensionRunner.emitBeforeProviderRequest({ text: "from-dotenv-123456789", }); const result = await t.session.extensionRunner.emitBeforeProviderRequest({ text: dotenvSecret }); expect(JSON.stringify(result)).not.toContain("from-dotenv-123456789"); expect(JSON.stringify(result)).toMatch(/__LEAK_[a-f0-9]{12}__/); }); it("redacts during a mocked agent run", async () => { t = await createTestSession({ extensions: [extPath()], mockTools: {} }); const value = "sk-or-v1-" + "9".repeat(64); await t.run(when(`Decide if this is sensitive: ${value}`, [says("done")])); const command = t.session.extensionRunner.extensions[0].commands.get("leaks"); await command.handler("status", t.session.extensionRunner.createContext()); const notices = t.events.uiCallsFor("notify").map((c) => String(c.args[0])); expect(notices.some((m) => m.includes("mappings: 1"))).toBe(true); }); it("command status/test/clear/reload run through real command registry", async () => { t = await createTestSession({ extensions: [extPath()], mockUI: { confirm: true }, }); const command = t.session.extensionRunner.extensions[0].commands.get("leaks"); const ctx = t.session.extensionRunner.createContext(); await command.handler("status", ctx); await command.handler("test " + "sk-or-v1-" + "a".repeat(64), ctx); await command.handler("reload", ctx); await command.handler("clear", ctx); const notices = t.events.uiCallsFor("notify").map((c) => String(c.args[0])); expect(notices.some((m) => m.includes("leaks on"))).toBe(true); expect(notices.some((m) => m.includes("openrouter: 1"))).toBe(true); expect(notices.some((m) => m.includes("leaks reloaded"))).toBe(true); expect(notices.some((m) => m.includes("leaks cleared"))).toBe(true);+2 / −1 text lines
import leaks from "./src/pi.ts";new file mode 100644+85 / −0 text lines
import { existsSync, readFileSync } from "node:fs";import path from "node:path";import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";import { LeaksEngine } from "./engine.ts";import { loadLeaksSettings } from "./settings.ts";export default function leaks(pi: ExtensionAPI) { const engine = new LeaksEngine(); pi.on("session_start", async (_event, ctx) => { engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env); if (ctx.hasUI) ctx.ui.setStatus("leaks", "leaks on | last 0"); }); pi.on("context", async (event) => { return { messages: engine.redactDeep(event.messages, "context").value }; }); pi.on("before_provider_request", async (event, ctx) => { const result = engine.redactDeep(event.payload, "provider"); if (ctx.hasUI) ctx.ui.setStatus("leaks", `leaks on | last ${result.count}`); return result.value; }); pi.on("tool_call", async (event) => { const input = (event as { input?: unknown }).input; if (input !== undefined) (event as { input: unknown }).input = engine.restoreDeep(input).value; }); pi.on("message_end", async (event) => { const restored = engine.restoreDeep(event.message).value; return { message: restored }; }); pi.registerCommand("leaks", { description: "Inspect and control provider-bound redaction", async handler(args, ctx) { const command = args.trim(); if (command === "status" || command === "") { ctx.ui.notify(formatStatus(engine), "info"); return; } if (command === "reload") { engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env); ctx.ui.notify("leaks reloaded", "info"); return; } if (command === "clear") { engine.clear(); ctx.ui.notify("leaks cleared", "info"); return; } if (command.startsWith("test ")) { const result = engine.redactText(command.slice(5), "diagnostic"); ctx.ui.notify(`matches: ${result.count}\n${result.text}`, "info"); return; } ctx.ui.notify("usage: /leaks status|reload|test <text>|clear", "warning"); }, });}function readSettings(cwd: string) { const file = path.join(cwd, ".pi", "settings.json"); if (!existsSync(file)) return { regex: [] }; try { return loadLeaksSettings(JSON.parse(readFileSync(file, "utf8"))).settings; } catch { return { regex: [] }; }}function formatStatus(engine: LeaksEngine) { const stats = engine.stats(); return [ "leaks on", `built-in rules: ${stats.builtInRuleCount}`, `custom regex: ${stats.customRegexCount}`, `invalid regex: ${stats.invalidRegexCount}`, `learned: ${stats.learnedCount}`, `mappings: ${stats.mappingCount}`, `last provider redactions: ${stats.lastProviderRedactionCount}`, `total provider redactions: ${stats.totalProviderRedactionCount}`, ].join("\n");}