repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(leaks): compile safe custom regex settings

e5a630f6610824d2f3157118e02e7428011da6a1

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

+331 / −6 text lines

Diff layout

extensions/leaks/__tests__/settings.test.ts

Added
new file mode 100644

+155 / −0 text lines

1import { describe, expect, it } from "vitest";
2import { __test } from "../index.ts";
3
4const fixtureSecret = "foo_secret_fixture_value_123456789";
5
6describe("leaks settings and custom regex", () => {
7 it("accepts only leaks.regex", () => {
8 const loaded = __test.loadLeaksSettings({
9 leaks: {
10 enabled: false,
11 keywords: ["nope"],
12 exclude: ["nope"],
13 secretFiles: ["nope"],
14 regex: [{ pattern: "foo_[a-z]+", label: "FOO_TOKEN" }],
15 },
16 });
18 expect(loaded.settings).toEqual({
19 regex: [{ pattern: "foo_[a-z]+", label: "FOO_TOKEN" }],
20 });
21 expect(JSON.stringify(loaded.settings)).not.toContain("enabled");
22 expect(JSON.stringify(loaded.settings)).not.toContain("secretFiles");
23 });
25 it("warns for unsupported regex entry fields and ignores flags", () => {
26 const loaded = __test.loadLeaksSettings({
27 leaks: {
28 regex: [
29 { pattern: "foo_[a-z]+", label: "FOO_TOKEN", flags: "i", extra: true },
30 ],
31 },
32 });
34 expect(loaded.warnings.map((warning) => warning.code)).toEqual([
35 "settings.regex.unsupported-field",
36 "settings.regex.flags",
37 ]);
38 expect(loaded.settings.regex[0]).toEqual({
39 pattern: "foo_[a-z]+",
40 label: "FOO_TOKEN",
41 });
42 });
44 it("accepts 512-character patterns and rejects 513-character patterns", () => {
45 const accepted = __test.compileCustomRegex({
46 regex: [{ pattern: "a".repeat(512), label: "LONG_TOKEN" }],
47 });
48 const rejected = __test.compileCustomRegex({
49 regex: [{ pattern: "a".repeat(513), label: "LONG_TOKEN" }],
50 });
52 expect(accepted.rules).toHaveLength(1);
53 expect(rejected.rules).toHaveLength(0);
54 expect(rejected.invalidRegexCount).toBe(1);
55 });
57 it("accepts strict labels and falls back for missing or invalid labels", () => {
58 const compiled = __test.compileCustomRegex({
59 regex: [
60 { pattern: "foo_[a-z]+", label: "FOO_TOKEN" },
61 { pattern: "bar_[a-z]+" },
62 { pattern: "baz_[a-z]+", label: "bad-label" },
63 ],
64 });
66 expect(compiled.rules.map((rule) => rule.label)).toEqual([
67 "FOO_TOKEN",
68 "CUSTOM_REGEX",
69 "CUSTOM_REGEX",
70 ]);
71 expect(compiled.warnings.map((warning) => warning.code)).toEqual([
72 "settings.regex.missing-label",
73 "settings.regex.invalid-label",
74 ]);
75 });
77 it("rejects invalid regex syntax", () => {
78 const compiled = __test.compileCustomRegex({
79 regex: [{ pattern: "(", label: "BROKEN" }],
80 });
82 expect(compiled.rules).toEqual([]);
83 expect(compiled.invalidRegexCount).toBe(1);
84 expect(compiled.warnings[0].code).toBe("settings.regex.syntax");
85 });
87 it("redacts full match for zero captures", () => {
88 const engine = new __test.LeaksEngine({
89 settings: {
90 regex: [{ pattern: "foo_secret_fixture_value_[0-9]+", label: "FOO_TOKEN" }],
91 },
92 });
94 const result = engine.redactText(`send ${fixtureSecret}`, "provider");
96 expect(result.text).not.toContain(fixtureSecret);
97 expect(result.labels).toEqual(["FOO_TOKEN"]);
98 });
100 it("redacts group 1 for one capture", () => {
101 const engine = new __test.LeaksEngine({
102 settings: {
103 regex: [{ pattern: "token=(foo_secret_fixture_value_[0-9]+)", label: "FOO_TOKEN" }],
104 },
105 });
107 const result = engine.redactText(`token=${fixtureSecret}`, "provider");
109 expect(result.text).toContain("token=");
110 expect(result.text).not.toContain(fixtureSecret);
111 });
113 it("redacts group 1 for multiple captures and warns", () => {
114 const engine = new __test.LeaksEngine({
115 settings: {
116 regex: [{ pattern: "(foo_secret_fixture_value_[0-9]+)-(tail)", label: "FOO_TOKEN" }],
117 },
118 });
120 const result = engine.redactText(`${fixtureSecret}-tail`, "provider");
122 expect(result.text).toMatch(/^__LEAK_FOO_TOKEN_[a-f0-9]{12}__-tail$/);
123 expect(engine.stats().warnings.map((warning) => warning.code)).toContain(
124 "settings.regex.multiple-captures",
125 );
126 });
128 it("rejects cheap unsafe regex constructs", () => {
129 const patterns = [
130 "(foo)\\1",
131 "(?=foo)foo",
132 "(foo+)+",
133 "(foo|bar)+",
134 "foo(|bar)",
135 ".*secret.*",
136 ];
137 const compiled = __test.compileCustomRegex({
138 regex: patterns.map((pattern) => ({ pattern, label: "UNSAFE" })),
139 });
141 expect(compiled.rules).toHaveLength(0);
142 expect(compiled.invalidRegexCount).toBe(patterns.length);
143 expect(compiled.warnings.every((warning) => warning.code === "settings.regex.unsafe")).toBe(true);
144 });
146 it("keeps warning text secret-free", () => {
147 const compiled = __test.compileCustomRegex({
148 regex: [{ pattern: `(${fixtureSecret}`, label: "BROKEN" }],
149 });
151 expect(compiled.warnings.map((warning) => warning.message).join("\n")).not.toContain(
152 fixtureSecret,
153 );
154 });
155});

extensions/leaks/index.ts

Modified

+12 / −0 text lines

11import { LeaksEngine } from "./src/engine.ts";
22import { PlaceholderStore } from "./src/placeholders.ts";
33import { selectSecretSpans } from "./src/selector.ts";
4import {
5 compileCustomRegex,
6 countCaptures,
7 customRegexSpans,
8 isUnsafeRegex,
9 loadLeaksSettings,
10} from "./src/settings.ts";
411import {
512 isExistingPlaceholder,
613 isPlainObject,
1623 PlaceholderStore,
1724 RUNTIME_SETTING_KEYS,
1825 selectSecretSpans,
26 loadLeaksSettings,
27 compileCustomRegex,
28 customRegexSpans,
29 countCaptures,
30 isUnsafeRegex,
1931 isExistingPlaceholder,
2032 isPlainObject,
2133 isWeakValue,

extensions/leaks/src/engine.ts

Modified

+24 / −6 text lines

11import { PlaceholderStore } from "./placeholders.ts";
22import { selectSecretSpans } from "./selector.ts";
3import {
4 compileCustomRegex,
5 customRegexSpans,
6 type CompiledCustomRule,
7} from "./settings.ts";
38import type {
49 DeepRedactionResult,
510 Detector,
1823};
2025export class LeaksEngine {
21 readonly settings: LeaksSettings;
26 settings: LeaksSettings;
2227 private readonly detectors: Detector[];
2328 private readonly warnings: WarningRecord[] = [];
2429 private readonly warningKeys = new Set<string>();
2530 private readonly placeholders = new PlaceholderStore({
2631 onWarning: (warning) => this.addWarning(warning),
2732 });
33 private customRules: CompiledCustomRule[] = [];
34 private invalidRegexCount = 0;
2835 private lastProviderRedactionCount = 0;
2936 private totalProviderRedactionCount = 0;
3037 private recentLabels: string[] = [];
3441 this.settings = { regex: options.settings?.regex ?? [] };
3542 this.detectors = options.detectors ?? [];
3643 void options.env;
44 this.compileSettings();
3745 }
39 reload(_cwd = process.cwd(), _settings = this.settings, _env = process.env) {}
47 reload(_cwd = process.cwd(), settings = this.settings, _env = process.env) {
48 this.settings = { regex: settings.regex ?? [] };
49 this.compileSettings();
50 }
4152 redactText(text: string, origin: RedactionOrigin = "provider"): RedactionResult {
42 let spans: SecretSpan[] = [];
53 let spans: SecretSpan[] = customRegexSpans(text, this.customRules);
4354 for (const detector of this.detectors) {
4455 try {
4556 spans = spans.concat(detector(text));
106117 return {
107118 active: true,
108119 builtInRuleCount: 0,
109 customRegexCount: this.settings.regex.length,
110 regexWarningCount: 0,
120 customRegexCount: this.customRules.length,
121 regexWarningCount: this.warnings.filter((warning) => warning.code.startsWith("settings.regex.")).length,
111122 warningCount: this.warnings.length,
112 invalidRegexCount: 0,
123 invalidRegexCount: this.invalidRegexCount,
113124 learnedCount: 0,
114125 mappingCount: this.placeholders.stats().mappingCount,
115126 lastProviderRedactionCount: this.lastProviderRedactionCount,
120131 };
121132 }
134 private compileSettings() {
135 const compiled = compileCustomRegex(this.settings);
136 this.customRules = compiled.rules;
137 this.invalidRegexCount = compiled.invalidRegexCount;
138 for (const warning of compiled.warnings) this.addWarning(warning);
139 }
123141 private warnOnce(code: string, message: string) {
124142 if (this.warningKeys.has(code)) return;
125143 this.warningKeys.add(code);

extensions/leaks/src/settings.ts

Added
new file mode 100644

+140 / −0 text lines

1import { isPlainObject } from "./safety.ts";
2import type { CustomRegexInput, LeaksSettings, SecretSpan, WarningRecord } from "./types.ts";
3
4export type LoadedSettings = {
5 settings: LeaksSettings;
6 warnings: WarningRecord[];
7};
8
9export type CompiledCustomRule = {
10 pattern: string;
11 regex: RegExp;
12 label: string;
13 captureGroup: number;
14};
16export type CompiledCustomRegex = {
17 rules: CompiledCustomRule[];
18 warnings: WarningRecord[];
19 invalidRegexCount: number;
20};
22const LABEL_RE = /^[A-Z0-9_]{1,64}$/;
24export function loadLeaksSettings(raw: unknown): LoadedSettings {
25 const warnings: WarningRecord[] = [];
26 const leaks = isPlainObject(raw) && isPlainObject(raw.leaks) ? raw.leaks : {};
27 const input = Array.isArray(leaks.regex) ? leaks.regex : [];
28 const regex: CustomRegexInput[] = [];
29 for (const entry of input) {
30 if (!isPlainObject(entry)) continue;
31 const unsupported = Object.keys(entry).filter((key) => key !== "pattern" && key !== "label" && key !== "flags");
32 if (unsupported.length > 0) warnings.push(warn("settings.regex.unsupported-field", "unsupported regex setting fields ignored"));
33 if ("flags" in entry) warnings.push(warn("settings.regex.flags", "regex flags are not supported and were ignored"));
34 regex.push({ pattern: entry.pattern, label: entry.label });
35 }
36 return { settings: { regex }, warnings };
37}
39export function compileCustomRegex(settings: LeaksSettings): CompiledCustomRegex {
40 const rules: CompiledCustomRule[] = [];
41 const warnings: WarningRecord[] = [];
42 let invalidRegexCount = 0;
43 for (const entry of settings.regex) {
44 if (typeof entry.pattern !== "string" || entry.pattern.length === 0) {
45 warnings.push(warn("settings.regex.missing-pattern", "custom regex pattern missing"));
46 invalidRegexCount++;
47 continue;
48 }
49 if (entry.pattern.length > 512) {
50 warnings.push(warn("settings.regex.pattern-too-long", "custom regex pattern too long"));
51 invalidRegexCount++;
52 continue;
53 }
54 if (isUnsafeRegex(entry.pattern)) {
55 warnings.push(warn("settings.regex.unsafe", "custom regex rejected by safety checks"));
56 invalidRegexCount++;
57 continue;
58 }
60 let label = "CUSTOM_REGEX";
61 if (typeof entry.label !== "string" || entry.label.length === 0) {
62 warnings.push(warn("settings.regex.missing-label", "custom regex label missing; using CUSTOM_REGEX"));
63 } else if (!LABEL_RE.test(entry.label)) {
64 warnings.push(warn("settings.regex.invalid-label", "custom regex label invalid; using CUSTOM_REGEX"));
65 } else {
66 label = entry.label;
67 }
69 const captures = countCaptures(entry.pattern);
70 if (captures > 1) warnings.push(warn("settings.regex.multiple-captures", "custom regex has multiple captures; using group 1"));
72 try {
73 rules.push({
74 pattern: entry.pattern,
75 regex: new RegExp(entry.pattern, "dg"),
76 label,
77 captureGroup: captures === 0 ? 0 : 1,
78 });
79 } catch {
80 warnings.push(warn("settings.regex.syntax", "custom regex syntax invalid"));
81 invalidRegexCount++;
82 }
83 }
84 return { rules, warnings, invalidRegexCount };
85}
87export function customRegexSpans(text: string, rules: CompiledCustomRule[]): SecretSpan[] {
88 const spans: SecretSpan[] = [];
89 for (const rule of rules) {
90 rule.regex.lastIndex = 0;
91 let match: RegExpExecArray | null;
92 while ((match = rule.regex.exec(text))) {
93 const range = match.indices?.[rule.captureGroup];
94 const value = match[rule.captureGroup];
95 if (range && typeof value === "string" && value.length > 0) {
96 spans.push({
97 start: range[0],
98 end: range[1],
99 value,
100 labels: [{ tag: rule.label, priority: 30, source: "custom" }],
101 kind: "custom",
102 confidence: 80,
103 wholeSpan: false,
104 });
105 }
106 if (match[0] === "") rule.regex.lastIndex++;
107 }
108 }
109 return spans;
110}
112export function countCaptures(pattern: string): number {
113 let count = 0;
114 for (let index = 0; index < pattern.length; index++) {
115 if (pattern[index] !== "(" || escaped(pattern, index)) continue;
116 if (pattern[index + 1] === "?") continue;
117 count++;
118 }
119 return count;
120}
122export function isUnsafeRegex(pattern: string): boolean {
123 if (/\\[1-9]/.test(pattern)) return true;
124 if (/\(\?<[^=!]|\(\?[=!<]/.test(pattern)) return true;
125 if (/\([^)]*[+*][^)]*\)[+*{]/.test(pattern)) return true;
126 if (/\([^)]*\|[^)]*\)[+*{]/.test(pattern)) return true;
127 if (/(^|\()\||\|(\)|$)/.test(pattern)) return true;
128 if (/\.\*/.test(pattern)) return true;
129 return false;
130}
132function escaped(text: string, index: number) {
133 let count = 0;
134 for (let pos = index - 1; pos >= 0 && text[pos] === "\\"; pos--) count++;
135 return count % 2 === 1;
136}
138function warn(code: string, message: string): WarningRecord {
139 return { code, message, severity: "warning" };
140}