Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(secret-scan-perf): every input-size budget is a CPU-time scaling ratio against a 10x smaller input
garrytancc61c0da7a68
diff --git a/test/secret-scan-perf.test.ts b/test/secret-scan-perf.test.tsindex 90ae8c11b0..1b12b8c550 100644--- a/test/secret-scan-perf.test.ts+++ b/test/secret-scan-perf.test.ts@@ -11,9 +11,18 @@* tail: ~8 s (~30 s at 23 MB); redacting a 1 MB transcript with ~5k unique* values: ~3 s; the echo pass as ONE escaped-alternation RegExp over 64* claimed 4 KB bearer values sharing a 4000-char prefix ahead of a 1 MB tail- * of the prefix character: ~24 s). The thresholds sit 2-50x above the fixed- * timings and 10-1000x below the broken ones, so they bind on a regression- * without flaking on a loaded CI box.+ * of the prefix character: ~24 s).+ *+ * Each of those broken forms did per-item work that grew with the input, so+ * most cases below time the same input shape at two sizes SCALE (10x) apart,+ * back to back in this process, and require the larger to cost under+ * MAX_RATIO (30x) the smaller: linear work reads about 10x, the broken forms+ * about 100x. Both sides are process CPU time, which load on a shared CI VM+ * does not inflate, where an absolute wall-clock budget counted it (409 ms+ * against 400 at 32 busy slots). The echo-pass cases and the `high_entropy_assignment` case keep+ * absolute bounds: their inputs are capped (64 dictionary values,+ * ECHO_MAX_VALUE_CHARS, 4096-char values), so what they guard is a constant+ * factor, which a size ratio cannot see.** Every credential-shaped value is synthetic and runtime-joined from >= 2* fragments; constant names keep scanner keywords away from the `=`.@@ -37,29 +46,56 @@ function elapsedMs(fn: () => void): number {return performance.now() - t0;}+const SCALE = 10;+const MAX_RATIO = 30;+const RATIO_TIMEOUT_MS = 60_000;++function cpuMs(fn: () => void): number {+ const start = process.cpuUsage();+ fn();+ const used = process.cpuUsage(start);+ return (used.user + used.system) / 1000;+}++/**+ * cpu(large) / cpu(small) for one call on inputs SCALE apart, timed back to back in this process. Process CPU+ * time, not wall clock: a run that waits for a busy CPU accrues none, so load on a shared VM moves neither side+ * (under 6 busy loops at nice 10, wall-clock ratios of the same pair ranged 0-376x, CPU-time ratios 5-18x).+ * `small` runs SCALE times per window so its sub-millisecond time is well above the clock's resolution. The best+ * of up to 3 pairs, stopping at the first under MAX_RATIO; a regression that grows with the input is over+ * MAX_RATIO in every pair. The caller's correctness run warms `large`.+ */+function scalingRatio(small: () => unknown, large: () => unknown): number {+ small();+ let best = Infinity;+ for (let pair = 0; pair < 3 && !(best < MAX_RATIO); pair++) {+ const t = cpuMs(() => { for (let k = 0; k < SCALE; k++) small(); }) / SCALE;+ best = Math.min(best, cpuMs(() => { large(); }) / Math.max(t, 0.05));+ }+ return best;+}+const OPAQUE = ['opaque', 'Token0123456789abcdefXYZ'].join('');const USERINFO = ['alice-example', ':', 's3cr3t', '@'].join('');const PG_URL_CREDS = ['postgres://', USERINFO].join('');const PG_URL = PG_URL_CREDS + 'db.example.com:5432/app';-/** One minified JSON line of credential-less redis URLs (~248k chars). */-function redisJsonLine(extraElement = ''): string {- const items = Array.from({ length: 8000 }, (_, i) => `{"u":"redis://localhost:${6379 + (i % 7)}"}`);+/** One minified JSON line of `count` credential-less redis URLs (8000: ~248k chars). */+function redisJsonLine(count: number, extraElement = ''): string {+ const items = Array.from({ length: count }, (_, i) => `{"u":"redis://localhost:${6379 + (i % 7)}"}`);if (extraElement) items.push(extraElement);return `[${items.join(',')}]`;}describe('db_url_credentials is linear on long lines', () => {- test('(i) 8000 credential-less redis URLs on one JSON line: 0 findings, < 200ms', () => {- const line = redisJsonLine();+ test('(i) 8000 credential-less redis URLs on one JSON line: 0 findings; 10x the URLs costs < 30x the time', () => {+ const line = redisJsonLine(8000), small = redisJsonLine(8000 / SCALE);expect(line.length).toBeGreaterThan(160_000);- let findings: unknown[] = [];- const ms = elapsedMs(() => { findings = scanText(line); });- expect(findings).toEqual([]);- expect(ms).toBeLessThan(200);- });+ expect(scanText(line)).toEqual([]);+ expect(scalingRatio(() => scanText(small), () => scanText(line))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);- test('(i-b) the same line WITH an @ elsewhere (the cheap precheck passes): still 0 findings, < 200ms', () => {+ test('(i-b) the same line WITH an @ elsewhere (the cheap precheck passes): still 0 findings; 10x the URLs costs < 30x the time', () => {// An email address means the `@` precheck cannot skip the pattern — this// pins the bounded quantifiers on their own, not the precheck. It also// pins the FALSE POSITIVE the unbounded form had: the run from the last@@ -67,70 +103,63 @@ describe('db_url_credentials is linear on long lines', () => {// db_url_credentials finding, because string delimiters were legal// password characters. Second element: the same shape through the// USER segment (`cache"},{"contact":"ops` + `:oncall@`).- const line = redisJsonLine('{"owner":"[email protected]"},{"u":"redis://cache"},{"contact":"ops:[email protected]"}');- let findings: unknown[] = [];- const ms = elapsedMs(() => { findings = scanText(line); });- expect(findings).toEqual([]);- expect(ms).toBeLessThan(200);- });-- test('(ii) 160k chars of repeated `redis://:` (no @): < 200ms', () => {- const line = 'redis://:'.repeat(17_778);+ const extra = '{"owner":"[email protected]"},{"u":"redis://cache"},{"contact":"ops:[email protected]"}';+ const line = redisJsonLine(8000, extra), small = redisJsonLine(8000 / SCALE, extra);+ expect(scanText(line)).toEqual([]);+ expect(scalingRatio(() => scanText(small), () => scanText(line))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);++ test('(ii) 160k chars of repeated `redis://:` (no @): 0 findings; 10x the run costs < 30x the time', () => {+ const line = 'redis://:'.repeat(17_778), small = 'redis://:'.repeat(1_778);expect(line.length).toBeGreaterThan(160_000);- let findings: unknown[] = [];- const ms = elapsedMs(() => { findings = scanText(line); });- expect(findings).toEqual([]);- expect(ms).toBeLessThan(200);- });+ expect(scanText(line)).toEqual([]);+ expect(scalingRatio(() => scanText(small), () => scanText(line))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);- test('(ii-b) 160k chars of repeated `redis://:` followed by a single @: one bounded finding, < 200ms', () => {+ test('(ii-b) 160k chars of repeated `redis://:` followed by a single @: one bounded finding; 10x the run costs < 30x the time', () => {// `/` is a legal password character (base64 passwords are pasted// unescaped), so the ≤256 chars of `redis://:` runs ahead of the `@` read// as `user="" password="redis://:redis://:…"` — ONE credential-shaped// finding whose value ends at the `@`, not one per scheme occurrence and// not a run to the end of the line. The timing is the pin; the count// shows the bound is doing the work.- const line = 'redis://:'.repeat(17_778) + '@';- let findings: ReturnType<typeof scanText> = [];- const ms = elapsedMs(() => { findings = scanText(line); });- expect(findings.map((f) => f.pattern)).toEqual(['db_url_credentials']);- expect(ms).toBeLessThan(200);- });+ const line = 'redis://:'.repeat(17_778) + '@', small = 'redis://:'.repeat(1_778) + '@';+ expect(scanText(line).map((f) => f.pattern)).toEqual(['db_url_credentials']);+ expect(scanText(small).map((f) => f.pattern)).toEqual(['db_url_credentials']);+ expect(scalingRatio(() => scanText(small), () => scanText(line))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);});describe('preview + corpus redaction are linear in hits on one line', () => {- const bearerLine = Array.from({ length: 5000 }, () => `Bearer ${OPAQUE}`).join(' ');+ const bearers = (n: number) => Array.from({ length: n }, () => `Bearer ${OPAQUE}`).join(' ');+ const bearerLine = bearers(5000), smallLine = bearers(5000 / SCALE);- test('(iii) 5000 Bearer tokens on one 190k line: scanText < 1500ms, one finding per occurrence', () => {+ test('(iii) 5000 Bearer tokens on one 190k line: one finding per occurrence; 10x the tokens costs < 30x the time', () => {expect(bearerLine.length).toBeGreaterThan(160_000);- let findings: ReturnType<typeof scanText> = [];- const ms = elapsedMs(() => { findings = scanText(bearerLine); });+ const findings = scanText(bearerLine);expect(findings.length).toBe(5000);expect(findings.every((f) => f.pattern === 'bearer')).toBe(true);expect(JSON.stringify(findings).includes(OPAQUE)).toBe(false);- expect(ms).toBeLessThan(1500);- });+ expect(scalingRatio(() => scanText(smallLine), () => scanText(bearerLine))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);- test('(iii-b) redactFindings over the same line: < 1500ms, no raw token survives', () => {- let result = { text: '', redactions: [] as ReturnType<typeof scanText> };- const ms = elapsedMs(() => { result = redactFindings(bearerLine); });+ test('(iii-b) redactFindings over the same line: no raw token survives; 10x the tokens costs < 30x the time', () => {+ const result = redactFindings(bearerLine);expect(result.redactions.length).toBe(5000);expect(result.text.includes(OPAQUE)).toBe(false);expect(result.text.startsWith('Bearer <REDACTED:bearer> Bearer <REDACTED:bearer>')).toBe(true);- expect(ms).toBeLessThan(1500);- });+ expect(scalingRatio(() => redactFindings(smallLine), () => redactFindings(bearerLine))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);- test('(iii-c) hit count scales linearly: 20000 tokens on one 760k line < 1500ms', () => {+ test('(iii-c) hit count scales linearly: 20000 tokens on one 760k line cost < 30x 2000 tokens', () => {// The first-wins overlap check and the preview window used to walk every// prior span per hit (O(hits²)): 5000 hits 305 ms, 10000 1.4 s, 20000// 5.4 s. The overlap check is O(value) per hit now (claimed-char bitmap)// and the preview window O(log hits) (binary search over sorted spans).- const line = Array.from({ length: 20_000 }, () => `Bearer ${OPAQUE}`).join(' ');- let findings: ReturnType<typeof scanText> = [];- const ms = elapsedMs(() => { findings = scanText(line); });- expect(findings.length).toBe(20_000);- expect(ms).toBeLessThan(1500);- });+ const line = bearers(20_000), small = bearers(20_000 / SCALE);+ expect(scanText(line).length).toBe(20_000);+ expect(scalingRatio(() => scanText(small), () => scanText(line))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);});describe('the bounded connection-string pattern still fires on real credentials', () => {@@ -192,77 +221,71 @@ describe('jwt + high_entropy_assignment are linear on adversarial `-`/`_` runs',// consumes to end-of-line and backtracks — quadratic. jwt now excludes `-`// from its boundary and bounds each segment; the entropy rule bounds the// keyword's trailing identifier segments (`{0,64}`) and the value.- test('200 KB of `-eyJ`: 0 findings, < 200ms (was ~25 s)', () => {- const line = '-eyJ'.repeat(50_000);- let findings: unknown[] = [];- const ms = elapsedMs(() => { findings = scanText(line); });- expect(findings).toEqual([]);- expect(ms).toBeLessThan(200);- });-- test('210 KB of `-apikey` with highEntropy: 0 findings, < 200ms (was ~42 s)', () => {- const line = '-apikey'.repeat(30_000);- let findings: unknown[] = [];- const ms = elapsedMs(() => { findings = scanText(line, { highEntropy: true }); });- expect(findings).toEqual([]);- expect(ms).toBeLessThan(200);- });-- test('180 KB of `_token` with highEntropy: 0 findings, < 200ms (was ~18 s)', () => {- const line = '_token'.repeat(30_000);- let findings: unknown[] = [];- const ms = elapsedMs(() => { findings = scanText(line, { highEntropy: true }); });- expect(findings).toEqual([]);- expect(ms).toBeLessThan(200);- });+ test('200 KB of `-eyJ`: 0 findings; 10x the run costs < 30x the time (was ~25 s)', () => {+ const line = '-eyJ'.repeat(50_000), small = '-eyJ'.repeat(50_000 / SCALE);+ expect(scanText(line)).toEqual([]);+ expect(scalingRatio(() => scanText(small), () => scanText(line))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);++ test('210 KB of `-apikey` with highEntropy: 0 findings; 10x the run costs < 30x the time (was ~42 s)', () => {+ const line = '-apikey'.repeat(30_000), small = '-apikey'.repeat(30_000 / SCALE);+ expect(scanText(line, { highEntropy: true })).toEqual([]);+ expect(scalingRatio(() => scanText(small, { highEntropy: true }), () => scanText(line, { highEntropy: true }))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);++ test('180 KB of `_token` with highEntropy: 0 findings; 10x the run costs < 30x the time (was ~18 s)', () => {+ const line = '_token'.repeat(30_000), small = '_token'.repeat(30_000 / SCALE);+ expect(scanText(line, { highEntropy: true })).toEqual([]);+ expect(scalingRatio(() => scanText(small, { highEntropy: true }), () => scanText(line, { highEntropy: true }))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);});describe('private-key claims are linear in headers and text', () => {- const MB_TAIL = 'x'.repeat(1024 * 1024);+ const MB = 1024 * 1024;const PEM_BODY_LINE = ['MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSj', 'AgEAAoIBAQC7VJTUt9Us8cKj'].join('');// Header/footer joined from fragments so the committed source never carries a whole PEM block (gitleaks private-key rule).const PEM_KEY = [['-----BEGIN', ' RSA PRIVATE KEY', '-----'].join(''), PEM_BODY_LINE, ['-----END', ' RSA PRIVATE KEY', '-----'].join('')].join('\n');- test('2000 header-only mentions ahead of a 1 MB tail: 2000 findings, < 300ms (was ~3.8 s)', () => {+ test('2000 header-only mentions ahead of a 1 MB tail: 2000 findings; 10x the headers and tail costs < 30x the time (was ~3.8 s)', () => {// The unbounded lazy body scanned from EVERY header to the end of the// text looking for an END that never comes. Bounded at// PEM_BODY_MAX_CHARS, each header does constant work.- const text = Array.from({ length: 2000 }, () => 'leaked -----BEGIN RSA PRIVATE KEY----- here').join('\n') + '\n' + MB_TAIL;- let findings: ReturnType<typeof scanText> = [];- const ms = elapsedMs(() => { findings = scanText(text); });+ const make = (headers: number, tail: number) => Array.from({ length: headers }, () => 'leaked -----BEGIN RSA PRIVATE KEY----- here').join('\n') + '\n' + 'x'.repeat(tail);+ const text = make(2000, MB), small = make(2000 / SCALE, MB / SCALE);+ const findings = scanText(text);expect(findings.length).toBe(2000);expect(findings.every((f) => f.pattern === 'private_key_pem')).toBe(true);- expect(ms).toBeLessThan(300);- });+ expect(scalingRatio(() => scanText(small), () => scanText(text))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);- test('2000 well-formed keys ahead of a 1 MB tail: 2000 findings with correct lines, < 300ms', () => {+ test('2000 well-formed keys ahead of a 1 MB tail: 2000 findings with correct lines; 10x the keys and tail costs < 30x the time', () => {// The 1-based header line used to be recomputed per hit as// `text.slice(0, index).split('\n').length` — O(hits × text). It is a// running cursor now; the line numbers must still be exact.- const text = Array.from({ length: 2000 }, () => PEM_KEY).join('\n') + '\n' + MB_TAIL;- let findings: ReturnType<typeof scanText> = [];- const ms = elapsedMs(() => { findings = scanText(text); });+ const make = (keys: number, tail: number) => Array.from({ length: keys }, () => PEM_KEY).join('\n') + '\n' + 'x'.repeat(tail);+ const text = make(2000, MB), small = make(2000 / SCALE, MB / SCALE);+ const findings = scanText(text);expect(findings.length).toBe(2000);expect(findings.map((f) => f.line)).toEqual(Array.from({ length: 2000 }, (_, k) => 3 * k + 1));expect(JSON.stringify(findings).includes(PEM_BODY_LINE)).toBe(false);- expect(ms).toBeLessThan(300);- });+ expect(scalingRatio(() => scanText(small), () => scanText(text))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);- test('2000 well-formed keys AFTER a 1 MB preamble: exact lines, < 300ms (was ~1.1 s)', () => {+ test('2000 well-formed keys AFTER a 1 MB preamble: exact lines; 10x the keys and preamble costs < 30x the time (was ~1.1 s)', () => {// The shape that isolates the per-hit line recount: every hit sits// behind >= 1 MB of text, so O(hits × prefix) slicing is >= 2 GB of// characters, while the running cursor walks the preamble once.- const preamble = Array.from({ length: 10_000 }, () => 'x'.repeat(104)).join('\n');- expect(preamble.length).toBeGreaterThan(1024 * 1024);- const text = preamble + '\n' + Array.from({ length: 2000 }, () => PEM_KEY).join('\n');- let findings: ReturnType<typeof scanText> = [];- const ms = elapsedMs(() => { findings = scanText(text); });+ const make = (preambleLines: number, keys: number) =>+ Array.from({ length: preambleLines }, () => 'x'.repeat(104)).join('\n') + '\n' + Array.from({ length: keys }, () => PEM_KEY).join('\n');+ const text = make(10_000, 2000), small = make(10_000 / SCALE, 2000 / SCALE);+ expect(text.length).toBeGreaterThan(MB);+ const findings = scanText(text);expect(findings.length).toBe(2000);expect(findings.map((f) => f.line)).toEqual(Array.from({ length: 2000 }, (_, k) => 10_001 + 3 * k));- expect(ms).toBeLessThan(300);- });+ expect(scalingRatio(() => scanText(small), () => scanText(text))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);- test('20000 header mentions on ONE line ahead of an 8 MB newline-free tail: 20000 findings on line 1, < 1500ms (was ~8 s)', () => {+ test('20000 header mentions on ONE line ahead of an 8 MB newline-free tail: 20000 findings on line 1; 10x the headers and tail costs < 30x the time (was ~8 s)', () => {// The running cursor used to call `text.indexOf('\n', cursor)` once per// hit; with no `\n` anywhere after the cursor each call rescanned to the// end of the text and returned -1 — O(hits × text) through a different@@ -272,13 +295,13 @@ describe('private-key claims are linear in headers and text', () => {// bounded PEM body probe (20000 headers × PEM_BODY_MAX_CHARS) plus the// per-line patterns over the 8 MB line — the accepted constants.const header = ['-----BEGIN', ' RSA PRIVATE KEY', '-----'].join('');- const text = Array.from({ length: 20_000 }, () => header + ' ').join('') + 'x'.repeat(8 << 20);- let findings: ReturnType<typeof scanText> = [];- const ms = elapsedMs(() => { findings = scanText(text); });+ const make = (headers: number, tail: number) => Array.from({ length: headers }, () => header + ' ').join('') + 'x'.repeat(tail);+ const text = make(20_000, 8 * MB), small = make(20_000 / SCALE, (8 * MB) / SCALE);+ const findings = scanText(text);expect(findings.length).toBe(20_000);expect(findings.every((f) => f.pattern === 'private_key_pem' && f.line === 1)).toBe(true);- expect(ms).toBeLessThan(1500);- });+ expect(scalingRatio(() => scanText(small), () => scanText(text))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);test('the carried newline position stays exact when hits and newlines interleave on and between lines', () => {const header = ['-----BEGIN', ' RSA PRIVATE KEY', '-----'].join('');@@ -365,44 +388,40 @@ describe(`the echo pass is at most ${ECHO_MAX_UNIQUE} substring sweeps over the});describe('redactFindings is linear in unique values (span-splice, not replaceAll per value)', () => {- test('1 MB transcript with 5000 UNIQUE high-entropy values: redact < 400ms (was ~3 s for a ~70 ms scan)', () => {+ const prose = 'the quick brown fox jumps over the lazy dog and keeps going for a while yet more prose to pad it out';+ const base = ['aB3xZ9qL7m', 'Np2Rt5Vw8Yk1D4'].join('');+ // Uppercase pad: base36 renders lowercase, so `Q0` can never collide with+ // a padded single digit the way a lowercase `q` pad did (k=936 → `q0`).+ const uniqueValues = (n: number) => Array.from({ length: n }, (_, k) => base + k.toString(36).padStart(6, 'Q'));++ test('1 MB transcript with 5000 UNIQUE high-entropy values: 10x the values and text costs < 30x the time (was ~3 s for a ~70 ms scan)', () => {// One full-text replaceAll per unique (pattern, value) pair made the// rebuild O(unique × text); the output is now spliced from the claimed// spans in one pass. Two prose lines between assignments keep the// transcript ~1 MB and mostly non-secret, as a real session is.- const prose = 'the quick brown fox jumps over the lazy dog and keeps going for a while yet more prose to pad it out';- const base = ['aB3xZ9qL7m', 'Np2Rt5Vw8Yk1D4'].join('');- const values = Array.from({ length: 5000 }, (_, k) => base + k.toString(36).padStart(6, 'Q'));- const lines: string[] = [];- for (const v of values) lines.push(`api_key = "${v}"`, prose, prose);- const text = lines.join('\n');+ const make = (values: string[]) => values.flatMap((v) => [`api_key = "${v}"`, prose, prose]).join('\n');+ const values = uniqueValues(5000);+ const text = make(values), small = make(uniqueValues(5000 / SCALE));expect(text.length).toBeGreaterThan(1024 * 1024);- let result = { text: '', redactions: [] as ReturnType<typeof scanText> };- const ms = elapsedMs(() => { result = redactFindings(text, { highEntropy: true }); });+ const result = redactFindings(text, { highEntropy: true });expect(result.redactions.length).toBe(5000);expect(result.text.split('<REDACTED:high_entropy_assignment>').length - 1).toBe(5000);for (const v of [values[0], values[2499], values[4999]]) expect(result.text.includes(v!)).toBe(false);expect(result.text.startsWith(`api_key = "<REDACTED:high_entropy_assignment>"\n${prose}\n${prose}\napi_key = "<REDACTED:high_entropy_assignment>"`)).toBe(true);- expect(ms).toBeLessThan(400);- });+ expect(scalingRatio(() => redactFindings(small, { highEntropy: true }), () => redactFindings(text, { highEntropy: true }))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);- test('1 MB transcript with 5000 UNIQUE high-entropy values, each echoed bare once: only the first 64 echoes are scrubbed, < 400ms', () => {+ test('1 MB transcript with 5000 UNIQUE high-entropy values, each echoed bare once: only the first 64 echoes are scrubbed; 10x the values and text costs < 30x the time', () => {// The echo pass now covers high_entropy_assignment. What keeps this// linear is the dictionary cap: 64 sweeps over the text, not 5000 —// echoes of values past the cap are the documented, accepted miss (their// CLAIMS are still redacted).- const prose = 'the quick brown fox jumps over the lazy dog and keeps going for a while yet more prose to pad it out';- const base = ['aB3xZ9qL7m', 'Np2Rt5Vw8Yk1D4'].join('');- // Uppercase pad: base36 renders lowercase, so `Q0` can never collide with- // a padded single digit the way a lowercase `q` pad did (k=936 → `q0`).- const values = Array.from({ length: 5000 }, (_, k) => base + k.toString(36).padStart(6, 'Q'));+ const make = (values: string[]) => values.flatMap((v) => [`api_key = "${v}"`, `then the agent pasted ${v} into the shell`, prose]).join('\n');+ const values = uniqueValues(5000);expect(new Set(values).size).toBe(5000);- const lines: string[] = [];- for (const v of values) lines.push(`api_key = "${v}"`, `then the agent pasted ${v} into the shell`, prose);- const text = lines.join('\n');+ const text = make(values), small = make(uniqueValues(5000 / SCALE));expect(text.length).toBeGreaterThan(1024 * 1024);- let result = { text: '', redactions: [] as ReturnType<typeof scanText> };- const ms = elapsedMs(() => { result = redactFindings(text, { highEntropy: true }); });+ const result = redactFindings(text, { highEntropy: true });expect(result.redactions.length).toBe(5000);expect(result.text.split('<REDACTED:high_entropy_assignment>').length - 1).toBe(5000 + ECHO_MAX_UNIQUE);expect(result.text.includes(values[0]!)).toBe(false);@@ -410,18 +429,18 @@ describe('redactFindings is linear in unique values (span-splice, not replaceAll// The 65th value: claim redacted, bare echo survives.expect(result.text).toContain(`then the agent pasted ${values[ECHO_MAX_UNIQUE]} into the shell`);expect(result.text).not.toContain(`api_key = "${values[ECHO_MAX_UNIQUE]}"`);- expect(ms).toBeLessThan(400);- });+ expect(scalingRatio(() => redactFindings(small, { highEntropy: true }), () => redactFindings(text, { highEntropy: true }))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);- test('5000 UNIQUE Bearer tokens on one line: redact < 200ms (was ~360 ms; the echo pass adds only its 64 sweeps)', () => {- const line = Array.from({ length: 5000 }, (_, k) => `Bearer ${OPAQUE}${k.toString(36).padStart(4, 'z')}`).join(' ');- let result = { text: '', redactions: [] as ReturnType<typeof scanText> };- const ms = elapsedMs(() => { result = redactFindings(line); });+ test('5000 UNIQUE Bearer tokens on one line: 10x the tokens costs < 30x the time (was ~360 ms; the echo pass adds only its 64 sweeps)', () => {+ const make = (n: number) => Array.from({ length: n }, (_, k) => `Bearer ${OPAQUE}${k.toString(36).padStart(4, 'z')}`).join(' ');+ const line = make(5000), small = make(5000 / SCALE);+ const result = redactFindings(line);expect(result.redactions.length).toBe(5000);expect(result.text.includes(OPAQUE)).toBe(false);expect(result.text).toBe(Array.from({ length: 5000 }, () => 'Bearer <REDACTED:bearer>').join(' '));- expect(ms).toBeLessThan(200);- });+ expect(scalingRatio(() => redactFindings(small), () => redactFindings(line))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);});describe('security fix wave shapes are linear (A1 walks, A2, A3, A5; ENG-15, ENG-17)', () => {@@ -431,64 +450,78 @@ describe('security fix wave shapes are linear (A1 walks, A2, A3, A5; ENG-15, ENGconst BEGIN = [DASHES, 'BEGIN RSA ', 'PRIVATE KEY', DASHES].join('');const END = [DASHES, 'END RSA ', 'PRIVATE KEY', DASHES].join('');const bodyLine = (i: number) => ['MIIEvQIBADANBgkqhkiG9w0BAQEF', 'AASCBKcwggSj', i.toString(36).padStart(24, 'Q')].join('');- const MB_OF_BODY_LINES = Array.from({ length: 16_000 }, (_, i) => bodyLine(i)).join('\n');+ const bodyLines = (n: number) => Array.from({ length: n }, (_, i) => bodyLine(i)).join('\n');const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#%<>';const entropic = (n: number, salt: number) =>Array.from({ length: n }, (_, k) => ALPHABET[(k * 7 + salt) % ALPHABET.length]).join('');- test('20000 unterminated BEGIN fences, each with a body line: 20000 claims, < 400ms', () => {- const text = Array.from({ length: 20_000 }, (_, i) => `${BEGIN}\n${bodyLine(i)}`).join('\n');- let findings: ReturnType<typeof scanText> = [];- const ms = elapsedMs(() => { findings = scanText(text); });+ test('20000 unterminated BEGIN fences, each with a body line: 20000 claims; 10x the fences costs < 30x the time', () => {+ const make = (n: number) => Array.from({ length: n }, (_, i) => `${BEGIN}\n${bodyLine(i)}`).join('\n');+ const text = make(20_000), small = make(20_000 / SCALE);+ const findings = scanText(text);expect(findings.length).toBe(20_000);expect(JSON.stringify(findings).includes(bodyLine(7))).toBe(false);- expect(ms).toBeLessThan(400);- });-- test('20000 END-only fences (each walk stops at the previous fence): 0 findings, < 300ms; on ONE line ahead of an 8 MB tail, < 1500ms', () => {- let ms = elapsedMs(() => { expect(scanText(`${END}\n`.repeat(20_000))).toEqual([]); });- expect(ms).toBeLessThan(300);- ms = elapsedMs(() => { expect(scanText(`${END} `.repeat(20_000) + 'x'.repeat(8 << 20))).toEqual([]); });- expect(ms).toBeLessThan(1500);- });-- test('20000 END fences each preceded by a body line: 20000 backward claims, < 400ms', () => {- const text = Array.from({ length: 20_000 }, (_, i) => `${bodyLine(i)}\n${END}`).join('\n');- const ms = elapsedMs(() => { expect(privateKeySpans(text).length).toBe(20_000); });- expect(ms).toBeLessThan(400);- });-- test('1 MB of base64 lines with no fence, after a BEGIN, before an END, and with a fence every 10 lines: each < 300ms', () => {- for (const text of [- MB_OF_BODY_LINES,- `${BEGIN}\n${MB_OF_BODY_LINES}`,- `${MB_OF_BODY_LINES}\n${END}`,- MB_OF_BODY_LINES.split('\n').map((l, i) => (i % 10 === 9 ? END : l)).join('\n'),- MB_OF_BODY_LINES.split('\n').map((l, i) => (i % 10 === 9 ? BEGIN : l)).join('\n'),- ]) {- const ms = elapsedMs(() => { scanText(text); });- expect(ms).toBeLessThan(300);- }- });+ expect(scalingRatio(() => scanText(small), () => scanText(text))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);++ test('20000 END-only fences (each walk stops at the previous fence): 0 findings, and on ONE line ahead of an 8 MB tail; 10x the fences (and tail) costs < 30x the time', () => {+ const lines = (n: number) => `${END}\n`.repeat(n);+ expect(scanText(lines(20_000))).toEqual([]);+ expect(scalingRatio(() => scanText(lines(20_000 / SCALE)), () => scanText(lines(20_000)))).toBeLessThan(MAX_RATIO);+ const oneLine = (n: number, tail: number) => `${END} `.repeat(n) + 'x'.repeat(tail);+ const text = oneLine(20_000, 8 << 20), small = oneLine(20_000 / SCALE, (8 << 20) / SCALE);+ expect(scanText(text)).toEqual([]);+ expect(scalingRatio(() => scanText(small), () => scanText(text))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);++ test('20000 END fences each preceded by a body line: 20000 backward claims; 10x the fences costs < 30x the time', () => {+ const make = (n: number) => Array.from({ length: n }, (_, i) => `${bodyLine(i)}\n${END}`).join('\n');+ const text = make(20_000), small = make(20_000 / SCALE);+ expect(privateKeySpans(text).length).toBe(20_000);+ expect(scalingRatio(() => privateKeySpans(small), () => privateKeySpans(text))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);++ test('1 MB of base64 lines with no fence, after a BEGIN, before an END, and with a fence every 10 lines: 10x the lines costs < 30x the time, each', () => {+ const shapes = (n: number) => {+ const lines = bodyLines(n);+ return [+ lines,+ `${BEGIN}\n${lines}`,+ `${lines}\n${END}`,+ lines.split('\n').map((l, i) => (i % 10 === 9 ? END : l)).join('\n'),+ lines.split('\n').map((l, i) => (i % 10 === 9 ? BEGIN : l)).join('\n'),+ ];+ };+ const large = shapes(16_000), small = shapes(16_000 / SCALE);+ expect(large[0]!.length).toBeGreaterThan(1_000_000);+ large.forEach((text, k) => {+ scanText(text);+ expect(scalingRatio(() => scanText(small[k]!), () => scanText(text))).toBeLessThan(MAX_RATIO);+ });+ }, RATIO_TIMEOUT_MS);- test('url_credentials: 160k of repeated scheme + user + colon and a lone @, and 8000 credential-less https URLs with an email: < 200ms', () => {+ test('url_credentials: 160k of repeated scheme + user + colon and a lone @, and 8000 credential-less https URLs with an email: 0 findings; 10x either costs < 30x the time', () => {const sep = ':' + '//';- let ms = elapsedMs(() => { expect(scanText(['https', sep, 'a:'].join('').repeat(16_000) + '@')).toEqual([]); });- expect(ms).toBeLessThan(200);- const json = '[' + Array.from({ length: 8000 }, (_, i) => `{"u":"${['https', sep, `host${i}.example:8443/x`].join('')}"}`).join(',') + ',{"e":"[email protected]"}]';- ms = elapsedMs(() => { expect(scanText(json)).toEqual([]); });- expect(ms).toBeLessThan(200);- });-- test('basic_auth: a 1 MB run of `Basic ` / `Authorization: Basic `, `Basic` + 1 MB of base64, and 500 valid 2048-char values: < 300ms', () => {- for (const text of ['Basic '.repeat(180_000), 'Authorization: Basic '.repeat(50_000), 'Basic ' + 'A'.repeat(1 << 20)]) {- const ms = elapsedMs(() => { expect(scanText(text)).toEqual([]); });- expect(ms).toBeLessThan(300);+ const run = (n: number) => ['https', sep, 'a:'].join('').repeat(n) + '@';+ expect(scanText(run(16_000))).toEqual([]);+ expect(scalingRatio(() => scanText(run(16_000 / SCALE)), () => scanText(run(16_000)))).toBeLessThan(MAX_RATIO);+ const json = (n: number) => '[' + Array.from({ length: n }, (_, i) => `{"u":"${['https', sep, `host${i}.example:8443/x`].join('')}"}`).join(',') + ',{"e":"[email protected]"}]';+ const text = json(8000), small = json(8000 / SCALE);+ expect(scanText(text)).toEqual([]);+ expect(scalingRatio(() => scanText(small), () => scanText(text))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);++ test('basic_auth: a 1 MB run of `Basic ` / `Authorization: Basic `, `Basic` + 1 MB of base64, and 500 valid 2048-char values: 10x each costs < 30x the time', () => {+ for (const make of [(n: number) => 'Basic '.repeat(180_000 * n), (n: number) => 'Authorization: Basic '.repeat(50_000 * n), (n: number) => 'Basic ' + 'A'.repeat((1 << 20) * n)]) {+ const text = make(1), small = make(1 / SCALE);+ expect(scanText(text)).toEqual([]);+ expect(scalingRatio(() => scanText(small), () => scanText(text))).toBeLessThan(MAX_RATIO);}const value = Buffer.from(['u', ':', 'a'.repeat(1534)].join('')).toString('base64');- const ms = elapsedMs(() => { expect(scanText(`Basic ${value} `.repeat(500)).length).toBe(500); });- expect(ms).toBeLessThan(300);- });+ const values = (n: number) => `Basic ${value} `.repeat(n);+ expect(scanText(values(500)).length).toBe(500);+ expect(scalingRatio(() => scanText(values(500 / SCALE)), () => scanText(values(500)))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);test('high_entropy_assignment: 250 quoted and 250 unquoted 4096-char values on one line, and 4100-char runs of trailing punctuation: < 300ms', () => {const quoted = Array.from({ length: 250 }, (_, i) => `password="${entropic(4096, i)}"`).join(' ');@@ -507,39 +540,31 @@ describe('security fix wave shapes are linear (A1 walks, A2, A3, A5; ENG-15, ENGdescribe('labeled_credential (transcript lane): every candidate start does constant work', () => {const LABELED = { highEntropy: true, labeledCredentials: true } as const;- const adversaries: Array<[string, string]> = [- ['240 KB of `login `', 'login '.repeat(40_000)],- ['220 KB of `login: a / `', 'login: a / '.repeat(20_000)],- ['200 KB of `password: `', 'password: '.repeat(20_000)],- ['a label, 200k spaces, then a value', 'password:' + ' '.repeat(200_000) + 'x'],- ['200 KB of `a/` after a login label', 'login: ' + 'a/'.repeat(100_000)],- ['20000 dangling pair lines', Array.from({ length: 20_000 }, () => 'login: alice-example /').join('\n')],- ['20000 dangling single labels', Array.from({ length: 20_000 }, () => 'password:').join('\n')],- ['a 200 KB row of escaped pipes', '| password | ' + '\\|'.repeat(100_000) + ' |'],- ['200 KB of `--password `', '--password '.repeat(20_000)],- ['a 64k-cell row of label cells under 64k password columns (W12 S3)', ['|' + 'password|'.repeat(64_000), '|' + '---|'.repeat(64_000), '|' + 'pwd|'.repeat(64_000)].join('\n')],+ // [name, input at `n` repetitions, n for the named size]; the timed pair is n and n / SCALE.+ const adversaries: Array<[string, (n: number) => string, number]> = [+ ['240 KB of `login `', (n) => 'login '.repeat(n), 40_000],+ ['220 KB of `login: a / `', (n) => 'login: a / '.repeat(n), 20_000],+ ['200 KB of `password: `', (n) => 'password: '.repeat(n), 20_000],+ ['a label, 200k spaces, then a value', (n) => 'password:' + ' '.repeat(n) + 'x', 200_000],+ ['200 KB of `a/` after a login label', (n) => 'login: ' + 'a/'.repeat(n), 100_000],+ ['20000 dangling pair lines', (n) => Array.from({ length: n }, () => 'login: alice-example /').join('\n'), 20_000],+ ['20000 dangling single labels', (n) => Array.from({ length: n }, () => 'password:').join('\n'), 20_000],+ ['a 200 KB row of escaped pipes', (n) => '| password | ' + '\\|'.repeat(n) + ' |', 100_000],+ ['200 KB of `--password `', (n) => '--password '.repeat(n), 20_000],+ ['a 64k-cell row of label cells under 64k password columns (W12 S3)', (n) => ['|' + 'password|'.repeat(n), '|' + '---|'.repeat(n), '|' + 'pwd|'.repeat(n)].join('\n'), 64_000],];- for (const [name, text] of adversaries) {- test(`${name}: redact < 400ms`, () => {- const ms = elapsedMs(() => { redactFindings(text, LABELED); });- expect(ms).toBeLessThan(400);- });+ for (const [name, make, n] of adversaries) {+ test(`${name}: 10x the input costs < 30x the time`, () => {+ const text = make(n), small = make(n / SCALE);+ redactFindings(text, LABELED);+ expect(scalingRatio(() => redactFindings(small, LABELED), () => redactFindings(text, LABELED))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);}- // A table row costs the same at row 10,000 as at row 1,000, so ten times the rows is about ten times the time- // (measured 9.9-12.4x idle; per-row work that grows with the rows already seen reads about 100x). Timing both- // sizes back to back cancels the load a shared CI VM puts on both: the former absolute 400 ms bound on the- // 10k table (~70 ms idle) read 409 ms at 32 busy slots. A pair passes below 30x; any of 3 pairs suffices.test('a 10k-row table with two credential columns: 10x the rows costs < 30x the time of 1k rows', () => {const table = (rows: number) => ['| user | password | pwd |', '|---|---|---|', ...Array.from({ length: rows }, (_, k) => `| u${k} | s3cret${k} | p${k}x\\|y |`)].join('\n');- const small = table(1_000), large = table(10_000);+ const small = table(10_000 / SCALE), large = table(10_000);expect(redactFindings(large, LABELED).redactions.length).toBe(20_000);- redactFindings(small, LABELED);- const ratios: number[] = [];- for (let pair = 0; pair < 3 && !(ratios.at(-1)! < 30); pair++) {- const t1 = elapsedMs(() => { redactFindings(small, LABELED); });- ratios.push(elapsedMs(() => { redactFindings(large, LABELED); }) / Math.max(t1, 0.5));- }- expect(Math.min(...ratios)).toBeLessThan(30);- }, 60_000);+ expect(scalingRatio(() => redactFindings(small, LABELED), () => redactFindings(large, LABELED))).toBeLessThan(MAX_RATIO);+ }, RATIO_TIMEOUT_MS);});