repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(leaks): add volatile placeholder store

8bc9ecd09ee0e597d23c49fe1fa0dee2e563e308

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

+299 / −15 text lines

Diff layout

extensions/leaks/__tests__/placeholders.test.ts

Added
new file mode 100644

+124 / −0 text lines

1import { describe, expect, it } from "vitest";
2import { __test } from "../index.ts";
3import type { SpanLabel } from "../src/types.ts";
4
5const secretA = "placeholder-fixture-secret-A-123456";
6const secretB = "placeholder-fixture-secret-B-123456";
7
8function label(tag: string, priority: number, source: SpanLabel["source"]): SpanLabel {
9 return { tag, priority, source };
10}
12describe("leaks placeholder store", () => {
13 it("creates tagged HMAC12 placeholders", () => {
14 const store = new __test.PlaceholderStore();
15 const placeholder = store.create(secretA, [label("API_KEY", 10, "dotenv")]);
17 expect(placeholder).toMatch(/^__LEAK_API_KEY_[a-f0-9]{12}__$/);
18 expect(placeholder).not.toContain(secretA);
19 });
21 it("uses random per-store HMAC keys", () => {
22 const left = new __test.PlaceholderStore().create(secretA, [
23 label("TOKEN", 10, "dotenv"),
24 ]);
25 const right = new __test.PlaceholderStore().create(secretA, [
26 label("TOKEN", 10, "dotenv"),
27 ]);
29 expect(left).not.toBe(right);
30 });
32 it("keeps same-value placeholders stable and freezes tags", () => {
33 const store = new __test.PlaceholderStore();
34 const first = store.create(secretA, [label("FIRST", 10, "dotenv")]);
35 const second = store.create(secretA, [label("SECOND", 90, "builtin")]);
37 expect(second).toBe(first);
38 expect(second).toContain("FIRST");
39 expect(second).not.toContain("SECOND");
40 });
42 it("orders tags by semantic priority and caps tag count and length", () => {
43 const store = new __test.PlaceholderStore({ digest: () => "0123456789ab" });
44 const placeholder = store.create(secretA, [
45 label("GENERIC", 50, "generic"),
46 label("BUILTIN", 40, "builtin"),
47 label("CUSTOM", 30, "custom"),
48 label("STRUCTURE", 20, "structure"),
49 label("ENV_KEY", 10, "env"),
50 label("EXTRA", 60, "generic"),
51 label("x".repeat(80), 5, "dotenv"),
52 ]);
54 expect(placeholder).toBe(
55 `__LEAK_${"X".repeat(64)}_ENV_KEY_STRUCTURE_CUSTOM_BUILTIN_GENERIC_0123456789ab__`,
56 );
57 });
59 it("adds collision suffixes when HMAC collides", () => {
60 const store = new __test.PlaceholderStore({ digest: () => "abcdef123456" });
62 const first = store.create(secretA, [label("TOKEN", 10, "dotenv")]);
63 const second = store.create(secretB, [label("TOKEN", 10, "dotenv")]);
65 expect(first).toBe("__LEAK_TOKEN_abcdef123456__");
66 expect(second).toBe("__LEAK_TOKEN_abcdef123456_2__");
67 });
69 it("caps restorable mappings at 8192 and warns once", () => {
70 const warnings: string[] = [];
71 const store = new __test.PlaceholderStore({
72 digest: (value) =>
73 Number(value.match(/\d+$/)?.[0] ?? 999999)
74 .toString(16)
75 .padStart(12, "0"),
76 onWarning: (warning) => warnings.push(warning.message),
77 });
78 for (let index = 0; index < 8192; index++) {
79 store.create(`cap-fixture-${index}`, [label("TOKEN", 10, "dotenv")]);
80 }
82 const overflow = store.create(secretA, [label("TOKEN", 10, "dotenv")]);
83 const overflowAgain = store.create(secretB, [label("TOKEN", 10, "dotenv")]);
85 expect(store.stats().mappingCount).toBe(8192);
86 expect(overflow).toMatch(/^__LEAK_TOKEN_[a-f0-9]{12}__$/);
87 expect(store.restore(overflow)).toBe(overflow);
88 expect(overflowAgain).not.toBe(overflow);
89 expect(warnings).toEqual(["placeholder mapping cap reached; new placeholders are not restorable"]);
90 });
92 it("restores only exact placeholders", () => {
93 const store = new __test.PlaceholderStore({ digest: () => "bbbbbbbbbbbb" });
94 const placeholder = store.create(secretA, [label("TOKEN", 10, "dotenv")]);
96 expect(store.restore(`run ${placeholder}`)).toBe(`run ${secretA}`);
97 expect(store.restore(`run ${placeholder.slice(0, -2)}`)).not.toContain(secretA);
98 });
100 it("engine redacts selected spans through the store", () => {
101 const engine = new __test.LeaksEngine({
102 detectors: [
103 (text) => [
104 {
105 start: text.indexOf(secretA),
106 end: text.indexOf(secretA) + secretA.length,
107 value: secretA,
108 labels: [label("TOKEN", 10, "dotenv")],
109 kind: "exact",
110 confidence: 100,
111 wholeSpan: false,
112 },
113 ],
114 ],
115 });
117 const redacted = engine.redactText(`send ${secretA}`, "provider");
119 expect(redacted.text).not.toContain(secretA);
120 expect(redacted.count).toBe(1);
121 expect(engine.restoreText(redacted.text)).toBe(`send ${secretA}`);
122 expect(engine.stats().mappingCount).toBe(1);
123 });
124});

extensions/leaks/index.ts

Modified

+2 / −0 text lines

11import { LeaksEngine } from "./src/engine.ts";
2import { PlaceholderStore } from "./src/placeholders.ts";
23import {
34 isExistingPlaceholder,
45 isPlainObject,
1213export const __test = {
1314 LeaksEngine,
15 PlaceholderStore,
1416 RUNTIME_SETTING_KEYS,
1517 isExistingPlaceholder,
1618 isPlainObject,

extensions/leaks/src/engine.ts

Modified

+54 / −15 text lines

1import { PlaceholderStore } from "./placeholders.ts";
12import type {
23 DeepRedactionResult,
34 Detector,
56 LeaksSettings,
67 RedactionOrigin,
78 RedactionResult,
9 SecretSpan,
810 WarningRecord,
911} from "./types.ts";
@@ -19,8 +21,13 @@ LeaksEngine
1921 private readonly detectors: Detector[];
2022 private readonly warnings: WarningRecord[] = [];
2123 private readonly warningKeys = new Set<string>();
24 private readonly placeholders = new PlaceholderStore({
25 onWarning: (warning) => this.addWarning(warning),
26 });
2227 private lastProviderRedactionCount = 0;
2328 private totalProviderRedactionCount = 0;
29 private recentLabels: string[] = [];
30 private latestTags: string[] = [];
2532 constructor(options: LeaksEngineOptions = {}) {
2633 this.settings = { regex: options.settings?.regex ?? [] };
3138 reload(_cwd = process.cwd(), _settings = this.settings, _env = process.env) {}
3340 redactText(text: string, origin: RedactionOrigin = "provider"): RedactionResult {
34 const failed = this.detectors.some((detector) => {
41 let spans: SecretSpan[] = [];
42 for (const detector of this.detectors) {
3543 try {
36 detector(text);
37 return false;
44 spans = spans.concat(detector(text));
3845 } catch {
3946 this.warnOnce("detector.failure", "detector failure; redaction pass left unchanged");
40 return true;
47 if (origin === "provider") this.lastProviderRedactionCount = 0;
48 return { text, count: 0, labels: [], placeholders: [] };
4149 }
42 });
43 const result = { text, count: 0, labels: [], placeholders: [] };
44 if (origin === "provider") this.lastProviderRedactionCount = 0;
45 if (failed) return result;
46 return result;
50 }
52 const selected = spans
53 .filter((span) => span.start >= 0 && span.end > span.start && span.end <= text.length)
54 .toSorted((left, right) => right.start - left.start);
55 let redacted = text;
56 const placeholders: string[] = [];
57 const labels: string[] = [];
58 for (const span of selected) {
59 const placeholder = this.placeholders.create(span.value, span.labels);
60 redacted = `${redacted.slice(0, span.start)}${placeholder}${redacted.slice(span.end)}`;
61 placeholders.push(placeholder);
62 labels.push(...span.labels.map((label) => label.tag));
63 }
65 const count = selected.length;
66 if (origin === "provider") {
67 this.lastProviderRedactionCount = count;
68 this.totalProviderRedactionCount += count;
69 }
70 if (labels.length > 0) this.recentLabels = labels.slice(-12);
71 if (placeholders.length > 0) {
72 this.latestTags = placeholders.map((placeholder) =>
73 placeholder.replace(/^__LEAK_?/, "").replace(/_[a-f0-9]{12}(?:_\d+)?__$/, ""),
74 );
75 }
76 return { text: redacted, count, labels, placeholders };
4777 }
4979 redactDeep<T>(value: T, origin: RedactionOrigin = "provider"): DeepRedactionResult<T> {
5787 }
5989 restoreText(text: string) {
60 return text;
90 return this.placeholders.restore(text);
6191 }
6393 restoreDeep<T>(value: T): DeepRedactionResult<T> {
64 return { value, changed: false, count: 0 };
94 if (typeof value !== "string") return { value, changed: false, count: 0 };
95 const restored = this.restoreText(value);
96 return { value: restored as T, changed: restored !== value, count: restored === value ? 0 : 1 };
6597 }
6799 clear() {
100 this.placeholders.clear();
68101 this.lastProviderRedactionCount = 0;
102 this.recentLabels = [];
103 this.latestTags = [];
69104 }
71106 stats(): EngineStats {
77112 warningCount: this.warnings.length,
78113 invalidRegexCount: 0,
79114 learnedCount: 0,
80 mappingCount: 0,
115 mappingCount: this.placeholders.stats().mappingCount,
81116 lastProviderRedactionCount: this.lastProviderRedactionCount,
82117 totalProviderRedactionCount: this.totalProviderRedactionCount,
83 recentLabels: [],
84 latestTags: [],
118 recentLabels: [...this.recentLabels],
119 latestTags: [...this.latestTags],
85120 warnings: [...this.warnings],
86121 };
87122 }
@@ -89,6 +124,10 @@ Old: warnOnce; new: LeaksEngine
89124 private warnOnce(code: string, message: string) {
90125 if (this.warningKeys.has(code)) return;
91126 this.warningKeys.add(code);
92 this.warnings.push({ code, message, severity: "warning" });
127 this.addWarning({ code, message, severity: "warning" });
128 }
130 private addWarning(warning: WarningRecord) {
131 this.warnings.push(warning);
93132 }

extensions/leaks/src/placeholders.ts

Added
new file mode 100644

+119 / −0 text lines

1import { createHmac, randomBytes } from "node:crypto";
2import { sanitizeTag } from "./safety.ts";
3import type { SpanLabel, WarningRecord } from "./types.ts";
4
5const CAP = 8192;
6const PLACEHOLDER_RE = /__LEAK(?:_[A-Z0-9]{1,64})*_[a-f0-9]{12}(?:_\d+)?__/g;
7const SOURCE_RANK: Record<SpanLabel["source"], number> = {
8 dotenv: 0,
9 env: 0,
10 structure: 1,
11 custom: 2,
12 builtin: 3,
13 generic: 4,
14};
16type PlaceholderStoreOptions = {
17 digest?: (value: string) => string;
18 onWarning?: (warning: WarningRecord) => void;
19};
21export class PlaceholderStore {
22 private readonly key = randomBytes(32);
23 private readonly digestOverride?: (value: string) => string;
24 private readonly onWarning?: (warning: WarningRecord) => void;
25 private readonly secretToPlaceholder = new Map<string, string>();
26 private readonly placeholderToSecret = new Map<string, string>();
27 private readonly overflowPlaceholders = new Set<string>();
28 private warnedCap = false;
29 private overflowNonce = 1;
31 constructor(options: PlaceholderStoreOptions = {}) {
32 this.digestOverride = options.digest;
33 this.onWarning = options.onWarning;
34 }
36 create(value: string, labels: SpanLabel[]): string {
37 const known = this.secretToPlaceholder.get(value);
38 if (known) return known;
40 const base = this.format(value, labels);
41 if (this.secretToPlaceholder.size >= CAP) {
42 this.warnCap();
43 return this.nonRestorable(base);
44 }
46 const placeholder = this.nextAvailable(base);
47 this.secretToPlaceholder.set(value, placeholder);
48 this.placeholderToSecret.set(placeholder, value);
49 return placeholder;
50 }
52 restore(text: string): string {
53 return text.replace(PLACEHOLDER_RE, (placeholder) => {
54 return this.placeholderToSecret.get(placeholder) ?? placeholder;
55 });
56 }
58 clear() {
59 this.secretToPlaceholder.clear();
60 this.placeholderToSecret.clear();
61 this.overflowPlaceholders.clear();
62 this.warnedCap = false;
63 this.overflowNonce = 1;
64 }
66 stats() {
67 return { mappingCount: this.secretToPlaceholder.size };
68 }
70 private format(value: string, labels: SpanLabel[]) {
71 const tags = labels
72 .toSorted((left, right) => {
73 const rank = SOURCE_RANK[left.source] - SOURCE_RANK[right.source];
74 if (rank !== 0) return rank;
75 return left.priority - right.priority;
76 })
77 .map((label) => sanitizeTag(label.tag))
78 .filter((tag, index, all) => all.indexOf(tag) === index)
79 .slice(0, 6);
80 const tagText = tags.length === 0 ? "" : `_${tags.join("_")}`;
81 return `__LEAK${tagText}_${this.digest(value)}__`;
82 }
84 private digest(value: string) {
85 const raw = this.digestOverride?.(value) ?? createHmac("sha256", this.key).update(value).digest("hex");
86 return raw.toLowerCase().replace(/[^a-f0-9]/g, "0").slice(0, 12).padEnd(12, "0");
87 }
89 private nextAvailable(base: string) {
90 if (!this.placeholderToSecret.has(base)) return base;
91 let index = 2;
92 while (true) {
93 const candidate = base.replace(/__$/, `_${index}__`);
94 if (!this.placeholderToSecret.has(candidate)) return candidate;
95 index++;
96 }
97 }
99 private nonRestorable(base: string) {
100 let candidate = base;
101 while (this.placeholderToSecret.has(candidate) || this.overflowPlaceholders.has(candidate)) {
102 this.overflowNonce++;
103 candidate = base.replace(/__$/, `_${this.overflowNonce}__`);
104 }
105 this.overflowPlaceholders.add(candidate);
106 this.overflowNonce++;
107 return candidate;
108 }
110 private warnCap() {
111 if (this.warnedCap) return;
112 this.warnedCap = true;
113 this.onWarning?.({
114 code: "placeholder.cap",
115 message: "placeholder mapping cap reached; new placeholders are not restorable",
116 severity: "warning",
117 });
118 }
119}