feat(leaks): compile safe custom regex settings
e5a630f6610824d2f3157118e02e7428011da6a1
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: dd071511bc5d
bugabingas pi extensions
e5a630f6610824d2f3157118e02e7428011da6a1
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+331 / −6 text lines
new file mode 100644+155 / −0 text lines
import { describe, expect, it } from "vitest";import { __test } from "../index.ts";const fixtureSecret = "foo_secret_fixture_value_123456789";describe("leaks settings and custom regex", () => { it("accepts only leaks.regex", () => { const loaded = __test.loadLeaksSettings({ leaks: { enabled: false, keywords: ["nope"], exclude: ["nope"], secretFiles: ["nope"], regex: [{ pattern: "foo_[a-z]+", label: "FOO_TOKEN" }], }, }); expect(loaded.settings).toEqual({ regex: [{ pattern: "foo_[a-z]+", label: "FOO_TOKEN" }], }); expect(JSON.stringify(loaded.settings)).not.toContain("enabled"); expect(JSON.stringify(loaded.settings)).not.toContain("secretFiles"); }); it("warns for unsupported regex entry fields and ignores flags", () => { const loaded = __test.loadLeaksSettings({ leaks: { regex: [ { pattern: "foo_[a-z]+", label: "FOO_TOKEN", flags: "i", extra: true }, ], }, }); expect(loaded.warnings.map((warning) => warning.code)).toEqual([ "settings.regex.unsupported-field", "settings.regex.flags", ]); expect(loaded.settings.regex[0]).toEqual({ pattern: "foo_[a-z]+", label: "FOO_TOKEN", }); }); it("accepts 512-character patterns and rejects 513-character patterns", () => { const accepted = __test.compileCustomRegex({ regex: [{ pattern: "a".repeat(512), label: "LONG_TOKEN" }], }); const rejected = __test.compileCustomRegex({ regex: [{ pattern: "a".repeat(513), label: "LONG_TOKEN" }], }); expect(accepted.rules).toHaveLength(1); expect(rejected.rules).toHaveLength(0); expect(rejected.invalidRegexCount).toBe(1); }); it("accepts strict labels and falls back for missing or invalid labels", () => { const compiled = __test.compileCustomRegex({ regex: [ { pattern: "foo_[a-z]+", label: "FOO_TOKEN" }, { pattern: "bar_[a-z]+" }, { pattern: "baz_[a-z]+", label: "bad-label" }, ], }); expect(compiled.rules.map((rule) => rule.label)).toEqual([ "FOO_TOKEN", "CUSTOM_REGEX", "CUSTOM_REGEX", ]); expect(compiled.warnings.map((warning) => warning.code)).toEqual([ "settings.regex.missing-label", "settings.regex.invalid-label", ]); }); it("rejects invalid regex syntax", () => { const compiled = __test.compileCustomRegex({ regex: [{ pattern: "(", label: "BROKEN" }], }); expect(compiled.rules).toEqual([]); expect(compiled.invalidRegexCount).toBe(1); expect(compiled.warnings[0].code).toBe("settings.regex.syntax"); }); it("redacts full match for zero captures", () => { const engine = new __test.LeaksEngine({ settings: { regex: [{ pattern: "foo_secret_fixture_value_[0-9]+", label: "FOO_TOKEN" }], }, }); const result = engine.redactText(`send ${fixtureSecret}`, "provider"); expect(result.text).not.toContain(fixtureSecret); expect(result.labels).toEqual(["FOO_TOKEN"]); }); it("redacts group 1 for one capture", () => { const engine = new __test.LeaksEngine({ settings: { regex: [{ pattern: "token=(foo_secret_fixture_value_[0-9]+)", label: "FOO_TOKEN" }], }, }); const result = engine.redactText(`token=${fixtureSecret}`, "provider"); expect(result.text).toContain("token="); expect(result.text).not.toContain(fixtureSecret); }); it("redacts group 1 for multiple captures and warns", () => { const engine = new __test.LeaksEngine({ settings: { regex: [{ pattern: "(foo_secret_fixture_value_[0-9]+)-(tail)", label: "FOO_TOKEN" }], }, }); const result = engine.redactText(`${fixtureSecret}-tail`, "provider"); expect(result.text).toMatch(/^__LEAK_FOO_TOKEN_[a-f0-9]{12}__-tail$/); expect(engine.stats().warnings.map((warning) => warning.code)).toContain( "settings.regex.multiple-captures", ); }); it("rejects cheap unsafe regex constructs", () => { const patterns = [ "(foo)\\1", "(?=foo)foo", "(foo+)+", "(foo|bar)+", "foo(|bar)", ".*secret.*", ]; const compiled = __test.compileCustomRegex({ regex: patterns.map((pattern) => ({ pattern, label: "UNSAFE" })), }); expect(compiled.rules).toHaveLength(0); expect(compiled.invalidRegexCount).toBe(patterns.length); expect(compiled.warnings.every((warning) => warning.code === "settings.regex.unsafe")).toBe(true); }); it("keeps warning text secret-free", () => { const compiled = __test.compileCustomRegex({ regex: [{ pattern: `(${fixtureSecret}`, label: "BROKEN" }], }); expect(compiled.warnings.map((warning) => warning.message).join("\n")).not.toContain( fixtureSecret, ); });});+12 / −0 text lines
+24 / −6 text lines
new file mode 100644+140 / −0 text lines
import { isPlainObject } from "./safety.ts";import type { CustomRegexInput, LeaksSettings, SecretSpan, WarningRecord } from "./types.ts";export type LoadedSettings = { settings: LeaksSettings; warnings: WarningRecord[];};export type CompiledCustomRule = { pattern: string; regex: RegExp; label: string; captureGroup: number;};export type CompiledCustomRegex = { rules: CompiledCustomRule[]; warnings: WarningRecord[]; invalidRegexCount: number;};const LABEL_RE = /^[A-Z0-9_]{1,64}$/;export function loadLeaksSettings(raw: unknown): LoadedSettings { const warnings: WarningRecord[] = []; const leaks = isPlainObject(raw) && isPlainObject(raw.leaks) ? raw.leaks : {}; const input = Array.isArray(leaks.regex) ? leaks.regex : []; const regex: CustomRegexInput[] = []; for (const entry of input) { if (!isPlainObject(entry)) continue; const unsupported = Object.keys(entry).filter((key) => key !== "pattern" && key !== "label" && key !== "flags"); if (unsupported.length > 0) warnings.push(warn("settings.regex.unsupported-field", "unsupported regex setting fields ignored")); if ("flags" in entry) warnings.push(warn("settings.regex.flags", "regex flags are not supported and were ignored")); regex.push({ pattern: entry.pattern, label: entry.label }); } return { settings: { regex }, warnings };}export function compileCustomRegex(settings: LeaksSettings): CompiledCustomRegex { const rules: CompiledCustomRule[] = []; const warnings: WarningRecord[] = []; let invalidRegexCount = 0; for (const entry of settings.regex) { if (typeof entry.pattern !== "string" || entry.pattern.length === 0) { warnings.push(warn("settings.regex.missing-pattern", "custom regex pattern missing")); invalidRegexCount++; continue; } if (entry.pattern.length > 512) { warnings.push(warn("settings.regex.pattern-too-long", "custom regex pattern too long")); invalidRegexCount++; continue; } if (isUnsafeRegex(entry.pattern)) { warnings.push(warn("settings.regex.unsafe", "custom regex rejected by safety checks")); invalidRegexCount++; continue; } let label = "CUSTOM_REGEX"; if (typeof entry.label !== "string" || entry.label.length === 0) { warnings.push(warn("settings.regex.missing-label", "custom regex label missing; using CUSTOM_REGEX")); } else if (!LABEL_RE.test(entry.label)) { warnings.push(warn("settings.regex.invalid-label", "custom regex label invalid; using CUSTOM_REGEX")); } else { label = entry.label; } const captures = countCaptures(entry.pattern); if (captures > 1) warnings.push(warn("settings.regex.multiple-captures", "custom regex has multiple captures; using group 1")); try { rules.push({ pattern: entry.pattern, regex: new RegExp(entry.pattern, "dg"), label, captureGroup: captures === 0 ? 0 : 1, }); } catch { warnings.push(warn("settings.regex.syntax", "custom regex syntax invalid")); invalidRegexCount++; } } return { rules, warnings, invalidRegexCount };}export function customRegexSpans(text: string, rules: CompiledCustomRule[]): SecretSpan[] { const spans: SecretSpan[] = []; for (const rule of rules) { rule.regex.lastIndex = 0; let match: RegExpExecArray | null; while ((match = rule.regex.exec(text))) { const range = match.indices?.[rule.captureGroup]; const value = match[rule.captureGroup]; if (range && typeof value === "string" && value.length > 0) { spans.push({ start: range[0], end: range[1], value, labels: [{ tag: rule.label, priority: 30, source: "custom" }], kind: "custom", confidence: 80, wholeSpan: false, }); } if (match[0] === "") rule.regex.lastIndex++; } } return spans;}export function countCaptures(pattern: string): number { let count = 0; for (let index = 0; index < pattern.length; index++) { if (pattern[index] !== "(" || escaped(pattern, index)) continue; if (pattern[index + 1] === "?") continue; count++; } return count;}export function isUnsafeRegex(pattern: string): boolean { if (/\\[1-9]/.test(pattern)) return true; if (/\(\?<[^=!]|\(\?[=!<]/.test(pattern)) return true; if (/\([^)]*[+*][^)]*\)[+*{]/.test(pattern)) return true; if (/\([^)]*\|[^)]*\)[+*{]/.test(pattern)) return true; if (/(^|\()\||\|(\)|$)/.test(pattern)) return true; if (/\.\*/.test(pattern)) return true; return false;}function escaped(text: string, index: number) { let count = 0; for (let pos = index - 1; pos >= 0 && text[pos] === "\\"; pos--) count++; return count % 2 === 1;}function warn(code: string, message: string): WarningRecord { return { code, message, severity: "warning" };}