repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

test(leaks): cover provider redaction

c76522ab0f23157b084910078287b7a4e1df3324

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

+107 / −10 text lines

Diff layout

extensions/leaks/__tests__/harness.test.ts

Modified

+13 / −1 text lines

22import { mkdirSync, writeFileSync } from "node:fs";
33import os from "node:os";
44import path from "node:path";
5import { createTestSession, type TestSession } from "@marcfargas/pi-test-harness";
5import { createTestSession, says, when, type TestSession } from "@marcfargas/pi-test-harness";
77function extPath() {
88 return path.resolve(import.meta.dir, "../index.ts");
8484 expect(JSON.stringify(result)).toMatch(/__LEAK_[a-f0-9]{12}__/);
8585 });
87 it("redacts during a mocked agent run", async () => {
88 t = await createTestSession({ extensions: [extPath()], mockTools: {} });
89 const value = "sk-or-v1-" + "9".repeat(64);
91 await t.run(when(`Decide if this is sensitive: ${value}`, [says("done")]));
93 const command = t.session.extensionRunner.extensions[0].commands.get("leaks");
94 await command.handler("status", t.session.extensionRunner.createContext());
95 const notices = t.events.uiCallsFor("notify").map((c) => String(c.args[0]));
96 expect(notices.some((m) => m.includes("mappings: 1"))).toBe(true);
97 });
8799 it("command status/test/clear/reload run through real command registry", async () => {
88100 t = await createTestSession({ extensions: [extPath()], mockUI: { confirm: true } });
89101 const command = t.session.extensionRunner.extensions[0].commands.get("leaks");

extensions/leaks/__tests__/real/minimax.test.ts

Added
new file mode 100644

+86 / −0 text lines

1import { describe, expect, it } from "bun:test";
2import fs from "node:fs";
3import os from "node:os";
4import path from "node:path";
5import {
6 AuthStorage,
7 createAgentSession,
8 DefaultResourceLoader,
9 ModelRegistry,
10 SessionManager,
11 SettingsManager,
12} from "@earendil-works/pi-coding-agent";
13import { getModel } from "@earendil-works/pi-ai";
15const real = process.env.LEAKS_REAL === "1";
16const d = real ? describe : describe.skip;
18d("real MiniMax integration", () => {
19 it("redacts provider-bound token before a real MiniMax request", async () => {
20 const temp = fs.mkdtempSync(path.join(os.tmpdir(), "leaks-real-"));
21 const cwd = path.join(temp, "cwd");
22 const agentDir = path.join(temp, "agent");
23 fs.mkdirSync(cwd, { recursive: true });
24 fs.mkdirSync(agentDir, { recursive: true });
26 const leaksPath = path.resolve(import.meta.dir, "../../index.ts");
27 const settingsManager = SettingsManager.inMemory({
28 defaultProvider: "minimax",
29 defaultModel: "MiniMax-M2.7-highspeed",
30 defaultThinkingLevel: "off",
31 leaks: { enabled: true, secretFiles: [] },
32 });
34 const loader = new DefaultResourceLoader({
35 cwd,
36 agentDir,
37 settingsManager,
38 noExtensions: true,
39 noSkills: true,
40 noPromptTemplates: true,
41 noThemes: true,
42 noContextFiles: true,
43 additionalExtensionPaths: [leaksPath],
44 });
45 await loader.reload();
47 const authStorage = AuthStorage.create();
48 const modelRegistry = ModelRegistry.create(authStorage);
49 const model = getModel("minimax", "MiniMax-M2.7-highspeed");
50 const assistantTexts: string[] = [];
52 const { session, extensionsResult } = await createAgentSession({
53 cwd,
54 agentDir,
55 authStorage,
56 modelRegistry,
57 model,
58 thinkingLevel: "off",
59 sessionManager: SessionManager.inMemory(),
60 settingsManager,
61 resourceLoader: loader,
62 noTools: "all",
63 });
65 try {
66 expect(extensionsResult.extensions.map((e) => e.path)).toEqual([leaksPath]);
67 session.subscribe((event) => {
68 if (event.type !== "message_end") return;
69 const msg = event.message;
70 if (msg.role !== "assistant") return;
71 assistantTexts.push(JSON.stringify(msg.content));
72 });
74 const fake = "sk-or-v1-" + "1".repeat(64);
75 await session.prompt(`Look only at the bracket content. Does it start with sk-or-v1-? Answer exactly YES or NO. [${fake}]`);
76 await session.agent.waitForIdle();
78 const answer = assistantTexts.join("\n").toUpperCase();
79 expect(answer).toContain("NO");
80 expect(answer).not.toContain("YES");
81 } finally {
82 session.dispose();
83 fs.rmSync(temp, { recursive: true, force: true });
84 }
85 }, 120000);
86});

extensions/leaks/__tests__/unit.test.ts

Modified

+5 / −3 text lines

7474 const engine = new __test.LeaksEngine(__test.normalizeSettings({ secretFiles: [] }));
7575 engine.reload(process.cwd(), engine.settings);
7676 const strong = "aB9_qP2xZ7mN4rT8vL0s";
77 const res = engine.redactText(`password = changeme token = ${strong}`);
77 const hex = "4f9c2a7b8d1e3f604a9c2a7b8d1e3f60";
78 const res = engine.redactText(`password = changeme token = ${strong} api_key = ${hex} secret_key = ${hex}`);
7980 expect(res.text).toContain("password = changeme");
81 expect(res.text).toContain(`api_key = ${hex}`);
8082 expect(res.text).not.toContain(strong);
81 expect(res.matches).toHaveLength(1);
82 expect(res.matches[0].label).toBe("generic-assignment-secret");
83 expect(res.matches).toHaveLength(2);
84 expect(res.matches.map((m) => m.label)).toEqual(["generic-assignment-secret", "generic-assignment-secret"]);
8385 });
8587 it("restores placeholders deeply", () => {

extensions/leaks/index.ts

Modified

+3 / −6 text lines

3131const DEFAULT_EXCLUDE = ["localhost", "127.0.0.1", "0.0.0.0", "example.com"];
3232const PLACEHOLDER_RE = /__LEAK_[a-f0-9]{12}(?:_\d+)?__/g;
34const BOUNDARY = String.raw`(?:^|[^A-Za-z0-9_])`;
35const END = String.raw`(?=$|[^A-Za-z0-9_])`;
3734const BUILTIN_RULES: Array<Omit<CompiledRule, "re" | "priority"> & { pattern: string; flags?: string }> = [
3835 { id: "openai", pattern: String.raw`\bsk-(?:(?:proj|svcacct|service|admin)-[A-Za-z0-9_-]+|[A-Za-z0-9]+)T3BlbkFJ[A-Za-z0-9_-]+\b` },
3936 { id: "anthropic", pattern: String.raw`\bsk-ant-(?:admin01|api03)-[A-Za-z0-9_-]{93}AA\b` },
303300 const end = start + captured.length;
304301 if (exclude.has(captured) || isPlaceholder(captured)) continue;
305302 if (rule.minEntropy && shannon(captured) < rule.minEntropy) continue;
306 if (rule.generic && isGenericReject(captured)) continue;
303 if (rule.generic && isGenericReject(captured, full)) continue;
307304 found.push({ start, end, original: captured, label: rule.id, priority: rule.priority });
308305 }
309306 }
341338 return /^__LEAK_[a-f0-9]{12}(?:_\d+)?__$/.test(s);
344function isGenericReject(s: string): boolean {
341function isGenericReject(s: string, context = ""): boolean {
345342 const v = s.trim();
346343 if (/^(?:true|false|null|undefined)$/i.test(v)) return true;
347344 if (/^\$[A-Za-z_][A-Za-z0-9_]*$/.test(v)) return true;
350347 if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v)) return true;
351348 if (/^https?:\/\//i.test(v)) return true;
352349 if (/^(?:\.{0,2}\/|~\/|[A-Za-z]:\\|\/)[\w./\\-]+$/.test(v)) return true;
353 if (/^[a-f0-9]{32,128}$/i.test(v)) return true;
350 if (/^[a-f0-9]{32,128}$/i.test(v) && !/\b(?:password|passwd|secret(?:[_-]?key)?|token|credential|auth(?:[_-]?token)?)\b/i.test(context)) return true;
354351 return false;