repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(leaks): report redaction metadata

4b5050ca518b04507af2857278754ee2f77a9b00

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (6)

+129 / −12 text lines

Diff layout

CHANGELOG.md

Modified

+2 / −0 text lines

163163 secret-internal transformations, high performance and correctness on every
164164 message, fail-open tolerance for faulty regex input, and human-friendly status
165165 and notifications without exposing secrets
166- Report leaks provider redaction paths, labels, and placeholders in safe
167 metadata and show unbounded path/label details in redaction notifications
167169## 0.0.3

extensions/leaks/__tests__/unit.test.ts

Modified

+48 / −0 text lines

2121 value: 1,
2222 changed: false,
2323 count: 0,
24 redactions: [],
2425 });
2526 expect(engine.redactDeep(null, "provider")).toEqual({
2627 value: null,
2728 changed: false,
2829 count: 0,
30 redactions: [],
2931 });
3032 const image = { type: "image", data: fixtureSecret };
3133 expect(engine.redactDeep(image, "provider").value).toEqual(image);
3840 }
3941 });
43 it("reports provider redaction paths and labels without secret bytes", () => {
44 const sensitiveValue = "alpha-secret";
45 const engine = new __test.LeaksEngine({
46 detectors: [
47 (text) => {
48 const start = text.indexOf(sensitiveValue);
49 if (start === -1) return [];
50 return [
51 {
52 start,
53 end: start + sensitiveValue.length,
54 value: sensitiveValue,
55 labels: [
56 {
57 tag: "ALPHA_SECRET",
58 priority: 99,
59 source: "custom",
60 },
61 ],
62 kind: "custom",
63 confidence: 99,
64 wholeSpan: false,
65 },
66 ];
67 },
68 ],
69 });
71 const result = engine.redactDeep(
72 { messages: [{ content: `send ${sensitiveValue}` }] },
73 "provider",
74 );
76 expect(JSON.stringify(result.value)).not.toContain(sensitiveValue);
77 expect(result.redactions).toEqual([
78 {
79 path: "messages[0].content",
80 labels: ["ALPHA_SECRET"],
81 placeholders: [
82 expect.stringMatching(/^__LEAK_ALPHA_SECRET_[a-f0-9]{12}__$/),
83 ],
84 },
85 ]);
86 expect(JSON.stringify(result.redactions)).not.toContain(sensitiveValue);
87 });
4189 it("fails open when a detector throws", () => {
4290 const engine = new __test.LeaksEngine({
4391 detectors: [

extensions/leaks/__tests__/ux.test.ts

Modified

+24 / −0 text lines

3030 ).toHaveLength(1);
3131 });
33 it("notification reports every provider redaction path and label", async () => {
34 const sensitiveValue = "tdd-secret-value-" + "x".repeat(32);
35 t = await createTestSession({
36 extensions: [extPath()],
37 env: { ["ALPHA_" + "SECRET"]: sensitiveValue },
38 });
39 await t.session.extensionRunner.emitBeforeProviderRequest({
40 messages: [
41 { content: `first ${sensitiveValue}` },
42 { content: `second ${sensitiveValue}` },
43 ],
44 });
46 const notice =
47 t.events
48 .uiCallsFor("notify")
49 .map((call) => String(call.args[0]))
50 .find((item) => item.includes("leaks redacted")) ?? "";
51 expect(notice).toContain("leaks redacted 2 provider value(s)");
52 expect(notice).toContain("messages[0].content: ENV_KEY");
53 expect(notice).toContain("messages[1].content: ENV_KEY");
54 expect(notice).not.toContain(sensitiveValue);
55 });
3357 it("status reports required safe fields", async () => {
3458 t = await createTestSession({ extensions: [extPath()] });
3559 await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret });

extensions/leaks/src/engine.ts

Modified

+34 / −7 text lines

2020 EngineStats,
2121 LeaksSettings,
2222 RedactionOrigin,
23 RedactionRecord,
2324 RedactionResult,
2425 SecretSpan,
2526 WarningRecord,
7980 "detector failure; redaction pass left unchanged",
8081 );
8182 if (origin === "provider") this.lastProviderRedactionCount = 0;
82 return { text, count: 0, labels: [], placeholders: [] };
83 return {
84 text,
85 count: 0,
86 labels: [],
87 placeholders: [],
88 redactions: [],
89 };
8390 }
8491 }
8794 let redacted = text;
8895 const placeholders: string[] = [];
8996 const labels: string[] = [];
97 const redactions: RedactionRecord[] = [];
9098 for (const span of selected) {
99 const spanLabels = span.labels.map((label) => label.tag);
91100 const placeholder = this.placeholders.create(span.value, span.labels);
92101 redacted = `${redacted.slice(0, span.start)}${placeholder}${redacted.slice(span.end)}`;
93102 placeholders.push(placeholder);
94 labels.push(...span.labels.map((label) => label.tag));
103 labels.push(...spanLabels);
104 redactions.push({
105 path: "",
106 labels: spanLabels,
107 placeholders: [placeholder],
108 });
95109 }
97111 const count = selected.length;
107121 .replace(/_[a-f0-9]{12}(?:_\d+)?__$/, ""),
108122 );
109123 }
110 return { text: redacted, count, labels, placeholders };
124 return { text: redacted, count, labels, placeholders, redactions };
111125 }
113127 redactDeep<T>(
173187 restore: boolean,
174188 ): DeepRedactionResult<T> {
175189 const seen = new WeakMap<object, unknown>();
190 const redactions: RedactionRecord[] = [];
176191 let count = 0;
177192 let changed = false;
178 const visit = (value: unknown, depth: number): unknown => {
193 const visit = (value: unknown, depth: number, trace: string): unknown => {
179194 if (typeof value === "string") {
180195 if (restore) {
181196 const next = this.restoreText(value);
188203 const result = this.redactText(value, origin);
189204 if (result.text !== value) changed = true;
190205 count += result.count;
206 for (const item of result.redactions)
207 redactions.push({ ...item, path: trace || "$" });
191208 return result.text;
192209 }
193210 if (value === null || typeof value !== "object") return value;
203220 if (Array.isArray(value)) {
204221 const copy: unknown[] = [];
205222 seen.set(value, copy);
206 for (const item of value) copy.push(visit(item, depth + 1));
223 for (let index = 0; index < value.length; index++)
224 copy.push(visit(value[index], depth + 1, `${trace}[${index}]`));
207225 if (copy.some((item, index) => item !== value[index])) changed = true;
208226 return copy;
209227 }
212230 const copy: Record<string, unknown> = {};
213231 seen.set(value, copy);
214232 for (const [key, item] of Object.entries(source))
215 copy[key] = visit(item, depth + 1);
233 copy[key] = visit(item, depth + 1, childPath(trace, key));
216234 if (Object.keys(copy).some((key) => copy[key] !== source[key]))
217235 changed = true;
218236 return copy;
219237 };
220 return { value: visit(input, 0) as T, changed, count };
238 const value = visit(input, 0, "") as T;
239 if (origin === "provider" && !restore)
240 this.lastProviderRedactionCount = count;
241 return { value, changed, count, redactions };
221242 }
223244 private warnOnce(code: string, message: string) {
230251 this.warnings.push(warning);
231252 }
255function childPath(parent: string, key: string) {
256 if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key))
257 return parent ? `${parent}.${key}` : key;
258 return `${parent}[${JSON.stringify(key)}]`;
259}

extensions/leaks/src/pi.ts

Modified

+13 / −5 text lines

2020 const result = engine.redactDeep(event.payload, "provider");
2121 if (ctx.hasUI) {
2222 ctx.ui.setStatus("leaks", `leaks on | last ${result.count}`);
23 if (result.count > 0)
24 ctx.ui.notify(
25 `leaks redacted ${result.count} provider value(s)`,
26 "info",
27 );
23 if (result.count > 0) ctx.ui.notify(formatNotice(result), "info");
2824 }
2925 return result.value;
3026 });
8884 }
87function formatNotice(result: {
88 count: number;
89 redactions: Array<{ path: string; labels: string[] }>;
90}) {
91 return [
92 `leaks redacted ${result.count} provider value(s)`,
93 ...result.redactions.map(
94 (redaction) => `${redaction.path}: ${redaction.labels.join(", ")}`,
95 ),
96 ].join("\n");
97}
9199function formatStatus(engine: LeaksEngine) {
92100 const stats = engine.stats();
93101 return [

extensions/leaks/src/types.ts

Modified

+8 / −0 text lines

4040export type RedactionOrigin = "context" | "provider" | "diagnostic";
42export type RedactionRecord = {
43 path: string;
44 labels: string[];
45 placeholders: string[];
46};
4248export type RedactionResult = {
4349 text: string;
4450 count: number;
4551 labels: string[];
4652 placeholders: string[];
53 redactions: RedactionRecord[];
4754};
4956export type DeepRedactionResult<T = unknown> = {
5057 value: T;
5158 changed: boolean;
5259 count: number;
60 redactions: RedactionRecord[];
5361};
5563export type EngineStats = {