// Review round 1 of lane/privacy: the regex rule (M1), the window cut (M3), // fail-closed settings (S3), a linear maskEmail (S5), the engine's coverage // (S6) and hideUser. Every slow-shape case is under a HARD time assertion. // // Run with: node_modules/.bin/tsx --test common/lib/privacy/safety.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { DEFAULT_PRIVACY_SETTINGS, STRICT_PRIVACY_SETTINGS, privacyProblems, sanitizePrivacy, type PrivacySettings } from "../privacySettings"; import { certainFragments, compilePrivacy } from "./compile"; import { applyPrivacy, isDisabled, onBudget, onSlowRule, PRIVACY_REGEX_MAX_INPUT, resetBudgetNotes, type PrivacyRules } from "./display"; import { analyzeRegex, MATCH_MAX } from "./regexSafety"; const base = (privacy: Partial, extra: Record = {}) => compilePrivacy({ privacy: { ...DEFAULT_PRIVACY_SETTINGS, ...privacy }, homeDir: "/home/zqu", hostnames: ["zqbox.lan"], username: "zqu", locations: [{ id: "d", label: "Drive", root: "/run/media/zqu/BIG", volume: { uuid: "ABCD-1234", mountpoint: "/run/media/zqu/BIG" } }], ...extra, }); const rulesOf = (aliases: string[], extra: Partial = {}) => base({ ...extra, aliases }); const applied = (r: ReturnType, n = 1) => r.rules?.steps.some((s) => s.why === `aliases line ${n}` && s.bounded && !s.refused) ?? false; const timed = (fn: () => void) => { const t0 = performance.now(); fn(); return performance.now() - t0; }; const INPUTS = ["a".repeat(4095), " ".repeat(4095), "a".repeat(5000), "a".repeat(100_000)]; // The reviewer's list (probes one.mts / scale.mts): each ran > 10 s on 4 KB. const REFUSED = [ ".*.*x", "a*a*b", "\\s*\\s*x", "[a-z]*[a-z]*x", "(.*)(.*)x", "a+?a+?b", "(a*)\\1*b", "a{0,4096}a{0,4096}a{0,4096}x", "a{1,9999}a{1,9999}b", "(a+)+b", "(a|aa)*b", "((ab)*c)+", "a{0,64}a{0,64}a{0,64}x", "(?a)\\k", // Review round 2 (M-B): alternation chains multiply; no lookaround at all. "(a|a)".repeat(20) + "x", "(a|b|c)(a|b|c)(a|b|c)(a|b|c)(a|b|c)(a|b|c)(a|b|c)", "KEY(?=a{0,200}!)", "(? { for (const p of REFUSED) { const r = rulesOf([`regex:${p}==>R`]); assert.equal(applied(r), false, `${p} must not be applied`); assert.equal(r.problems.length, 1, `${p} is reported`); assert.match(r.problems[0].what, /refused as possibly slow|does not compile/); const ms = timed(() => INPUTS.forEach((s) => applyPrivacy(r.rules, s))); assert.ok(ms < 1000, `${p}: ${ms.toFixed(0)} ms`); } // A glob of two stars is two unbounded quantifiers: refused too. assert.equal(applied(rulesOf(["glob:*zz*==>G"])), false); }); test("M1: the safe shapes are applied, rewritten to a bounded repeat, and fast on 100 KB", () => { for (const p of ["proj-(\\d+)", "sec[a-z]+", "a.*b", "(?:ab)?c+", "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}", "(a|b)?x"]) { const r = rulesOf([`regex:${p}==>R`]); assert.equal(applied(r), true, p); const ms = timed(() => INPUTS.forEach((s) => applyPrivacy(r.rules, s))); assert.ok(ms < 1500, `${p}: ${ms.toFixed(0)} ms`); } const v = analyzeRegex(".*x"); assert.ok(v.ok && v.source === ".{0,256}x" && v.maxLen === 257); const lazy = analyzeRegex("a+?b"); assert.ok(lazy.ok && lazy.source === "a{1,256}?b"); assert.equal(analyzeRegex("[a-z]{64}".repeat(40)).ok, false, `a match longer than ${MATCH_MAX}`); assert.equal(applied(rulesOf(["glob:priv*te==>p"])), true); }); test("M1: the runtime backstop disables a rule slower than 50 ms on one call, by its number", () => { const said: string[] = []; onSlowRule((why) => said.push(why)); try { const r = rulesOf(["regex:zq.*qz==>R"]); const step = r.rules!.steps.find((s) => s.why === "aliases line 1")!; const big = "zq".repeat(400_000); applyPrivacy(r.rules, big); if (isDisabled(step)) { assert.deepEqual(said, ["aliases line 1"]); // Disabled: its fragments only, at once. assert.ok(timed(() => applyPrivacy(r.rules, big)) < 200); assert.equal(applyPrivacy(r.rules, "x zq.qz y"), "x zq.qz y", "no fragment of three characters to hide"); } else { // A machine fast enough that no call took 50 ms: nothing said. assert.deepEqual(said, []); } // A hand-made step that is slow on any machine. const slow: PrivacyRules = { v: 1, steps: [{ re: "(x+x+)+y", flags: "g", to: "R", why: "aliases line 9", bounded: true, maxLen: 64, fallback: [{ re: "SECRETWORD", lead: true }] }], }; applyPrivacy(slow, "x".repeat(28)); assert.equal(isDisabled(slow.steps[0]), true); assert.ok(said.includes("aliases line 9")); assert.equal(applyPrivacy(slow, "a SECRETWORD b"), "a [hidden]", "fails closed: from its leading fragment to the line's end"); } finally { onSlowRule(null); } }); test("M3: nothing straddling a 4,096-character cut is shown raw", () => { const N = PRIVACY_REGEX_MAX_INPUT; const pad = (k: number) => "x".repeat(k); const cases: Array<[string, ReturnType, string, string]> = [ ["regex", rulesOf(["regex:SECRET[A-Z]+==>[r]"]), "SECRETWORD", "[r]"], ["glob", rulesOf(["glob:SECRET*WORD==>[g]"]), "SECRETxWORD", "[g]"], [ "secret rule", base({ useSourceRules: true }, { scrubText: "regex:SECRET[A-Z]+==>[s]\n", denyText: "" }), "SECRETWORD", "[s]", ], ["e-mail", base({ maskEmail: true }), "person@example.org", "[email]"], ["hostname", base({ hideHost: true }), "zqbox", "host"], ["home path", base({ displayPaths: "masked" }), "/home/zqu/a", "/home/user/a"], ]; for (const [name, r, secret, shown] of cases) { for (let off = 1; off < secret.length; off++) { const s = `${pad(N - off)} ${secret} ${pad(N)} ${secret} ${pad(20)}`; const out = applyPrivacy(r.rules, s); assert.ok(!out.includes(secret), `${name} straddling at ${off} is shown raw`); if (name === "glob") { // `SECRET*WORD` is `.*` inside: from its first match it could run to // the line's last WORD, so the rest of the line is hidden (M-D). assert.ok(out.endsWith(`${shown}[hidden]`), `${name} at ${off}: the rest of the line hidden`); continue; } assert.equal(out.split(shown).length - 1, 2, `${name} at ${off}: both shown as ${shown}`); assert.equal(out.length, s.length - 2 * (secret.length - shown.length), `${name} at ${off}: nothing else changed`); } } }); test("S5: maskEmail is linear — 5 MB on one line in under a second", () => { const r = base({ maskEmail: true }); for (const big of ["a".repeat(5_000_000), "a@".repeat(2_500_000), `${"a.".repeat(2_000_000)}@b`, "@".repeat(5_000_000)]) { const ms = timed(() => applyPrivacy(r.rules, big)); assert.ok(ms < 1000, `${ms.toFixed(0)} ms`); } const m = (s: string) => applyPrivacy(r.rules, s); assert.equal(m("a.b+tag@ex.com, ME@EX.ORG; mailto:me@ex.org."), "[email], [email]; mailto:[email]."); assert.equal(m("me@localhost x@[127.0.0.1] @x.com a@b"), "me@localhost x@[127.0.0.1] @x.com a@b"); assert.equal(m("a@b.co@c.org"), "[email]@c.org"); }); test("S6: case, punctuation, JSON-escaped, percent-encoded and file:// forms; media mounts in home mode", () => { const home = base({ displayPaths: "home", hideHost: true }); const masked = base({ displayPaths: "masked", hideHost: true }); const h = (s: string) => applyPrivacy(home.rules, s); const m = (s: string) => applyPrivacy(masked.rules, s); for (const [s, hs, ms] of [ ["/home/zqu.", "~.", "/home/user."], ["/home/zqu, /home/zqu) (/home/zqu)", "~, ~) (~)", "/home/user, /home/user) (/home/user)"], ["/home/zqu.bak /home/zqu2/x", "/home/zqu.bak /home/zqu2/x", "/home/zqu.bak /home/zqu2/x"], ['{"p":"\\/home\\/zqu\\/a"}', '{"p":"~\\/a"}', '{"p":"\\/home\\/user\\/a"}'], ["%2Fhome%2Fzqu%2Fa %2fhome%2fzqu", "~%2Fa ~", "%2Fhome%2Fuser%2Fa %2Fhome%2Fuser"], ["file:///home/zqu/a", "file:///home/user/a", "file:///home/user/a"], ["/run/media/zqu/OTHER/x", "/run/media/user/OTHER/x", "/media/drive/x"], ["ZQBOX Zqbox.local zqbox-2 zqbox_x", "host host.local zqbox-2 zqbox_x", "host host.local zqbox-2 zqbox_x"], ["uuid abcd-1234 / ABCD-1234", "uuid abcd-1234 / ABCD-1234", "uuid [volume] / [volume]"], ] as const) { assert.equal(h(s), hs, `home: ${s}`); assert.equal(m(s), ms, `masked: ${s}`); } }); test("hideUser: the bare user name as `user`, whole word, any case", () => { const r = base({ hideUser: true }, { username: "zqu" }); const u = (s: string) => applyPrivacy(r.rules, s); assert.equal(u("by: umtool queue add (zqu); ZQU; zqu-2"), "by: umtool queue add (user); user; zqu-2"); assert.equal(u("zquser zqus mzqu"), "zquser zqus mzqu", "a name inside another word is left alone"); assert.equal(base({ hideUser: true }, { username: "al" }).rules, null, "shorter than three: no rule"); assert.equal(base({ hideUser: false }, { username: "zqu" }).rules, null); }); test("S3: a present but wrong privacy block fails CLOSED, named by key", () => { assert.deepEqual(sanitizePrivacy(undefined), DEFAULT_PRIVACY_SETTINGS); for (const bad of ["on", null, 1, ["masked"]]) { assert.deepEqual(sanitizePrivacy(bad), STRICT_PRIVACY_SETTINGS, JSON.stringify(bad)); assert.match(privacyProblems(bad)[0], /not an object/); } const s = sanitizePrivacy({ displayPaths: "Masked", hideHost: "yes", maskEmail: 0, aliases: "x==>y", junk: 1 }); assert.equal(s.displayPaths, "masked"); assert.equal(s.hideHost, true); assert.equal(s.maskEmail, true); assert.deepEqual(s.aliases, []); assert.equal(s.hideUser, false, "an absent key keeps its default"); assert.deepEqual(privacyProblems({ displayPaths: "Masked", hideHost: "yes", maskEmail: 0, aliases: "x==>y", junk: 1 }), [ 'displayPaths is not "full", "home" or "masked": read as "masked"', "hideHost is not true or false: read as true", "maskEmail is not true or false: read as true", "aliases is not a list: read as []", "1 key is not a privacy key: ignored", ]); assert.deepEqual(privacyProblems(undefined), []); assert.deepEqual(privacyProblems({ displayPaths: "home", hideHost: false }), []); }); test("M-B: a scrub-file line over 1,000 characters runs in fallback only", () => { const long = `regex:LONGRULE${"[a-z]".repeat(250)}==>x`; const r = base({ useSourceRules: true }, { scrubText: `${long}\n`, denyText: "" }); assert.equal(r.rules!.steps.some((s) => s.why === "scrub line 1" && !s.refused), false); assert.match(r.problems[0].what, /longer than 1,000 characters; it runs in fallback/); assert.equal(applyPrivacy(r.rules, "a LONGRULE b"), "a [hidden]", "from its leading fragment to the line's end"); }); test("M-C: a rule in fallback with no literal fragment hides every line it would run on — never a no-op", () => { const r = rulesOf(["regex:(a|b)+==>R"]); assert.equal(applied(r), false); assert.match(r.problems[0].what, /no certain literal fragment, so every line it would run on is shown as \[hidden\]/); assert.equal(applyPrivacy(r.rules, "one\n\ntwo"), "[hidden]\n\n[hidden]"); // Disabled at run time, the same: a hand-made slow step with no fragment. const said: string[] = []; onSlowRule((why) => said.push(why)); try { const slow: PrivacyRules = { v: 1, steps: [{ re: "(x+x+)+y", flags: "g", to: "R", why: "aliases line 7", bounded: true, maxLen: 64, fallback: [] }] }; assert.equal(applyPrivacy(slow, "x".repeat(28)), "[hidden]"); assert.deepEqual(said, ["aliases line 7"]); assert.equal(applyPrivacy(slow, "a TOKEN b\nc"), "[hidden]\n[hidden]"); } finally { onSlowRule(null); } }); test("M-C: the backstop times one WINDOW, not one call — a cheap rule over megabytes stays on", () => { const said: string[] = []; onSlowRule((why) => said.push(why)); try { const r = rulesOf(["regex:[A-Z0-9]{20}==>[tok]"]); const big = ("ABCDEFGHIJ0123456789 " + "x".repeat(200)).repeat(20_000); const out = applyPrivacy(r.rules, big); assert.ok(!out.includes("ABCDEFGHIJ0123456789")); assert.deepEqual(said, []); assert.equal(applyPrivacy(r.rules, "id ABCDEFGHIJ0123456789 end"), "id [tok] end"); } finally { onSlowRule(null); } }); test("M-D: a match that used the capped quantifier to its cap hides the rest of the line", () => { const tail = "q".repeat(600) + "TAILSECRET"; for (const a of ["regex:tok-.*==>[t]", "glob:tok-*==>[t]"]) { const r = rulesOf([a]); assert.equal(applyPrivacy(r.rules, `x tok-${tail}`), "x [t]", `${a}: cap hit at the end of the pattern`); assert.equal(applyPrivacy(r.rules, `x tok-${tail}\nnext line`), "x [t]\nnext line", `${a}: only to the end of the line`); assert.equal(applyPrivacy(r.rules, "x tok-short y"), "x [t]", `${a}: a short match, as before`); } // The cap hit in the MIDDLE of a pattern: the rest of the line goes too. const mid = rulesOf(["regex:BEGIN.*END==>[m]"]); // `BEGIN.*END` could match past its cap wherever `BEGIN` has 256 more // characters after it: from there the line is hidden, whatever matched. assert.equal(applyPrivacy(mid.rules, `a BEGIN${"z".repeat(300)}END tail SECRET`), "a [hidden]", "the pattern runs past the cap: hidden from BEGIN"); assert.equal(applyPrivacy(mid.rules, `a BEGIN${"z".repeat(254)}END tail SECRET`), "a [m][hidden]", "a match within the cap, more after it: hidden from there"); assert.equal(applyPrivacy(mid.rules, `a BEGIN${"z".repeat(10)}END tail`), "a [m] tail", "a short line: as before"); // Inside a group, the same. const grp = rulesOf(["regex:id-(\\d+)==>ID"]); assert.equal(applyPrivacy(grp.rules, `x id-${"7".repeat(400)} SECRET`), "x ID", "a capped group match hides the rest of the line"); assert.equal(applyPrivacy(grp.rules, "x id-42 y"), "x ID y"); }); test("windows keep the whole-line match grid", () => { const hex = "FAKE-TEST-VALUE".repeat(1024); for (const n of [7, 13, 30]) { const r = rulesOf([`regex:[0-9a-f]{${n}}==>H`]); assert.equal(applyPrivacy(r.rules, hex), hex.replace(new RegExp(`[0-9a-f]{${n}}`, "g"), "H"), `{${n}}`); } }); test("round 3, M1: one call has a total budget — six cheap-per-window rules on a 5 MB line return in under a second, nothing raw", () => { const said: string[] = []; onBudget((why) => said.push(why)); resetBudgetNotes(); try { const line = ("a".repeat(999) + "x").repeat(5000); let disabledN = 0; for (const a of ["glob:*x==>R", "regex:.*x==>R", "regex:a*x==>R", "regex:[a-z]{0,31}[a-z]{0,31}x==>R", "regex:(?i)A{0,31}a{0,31}x==>R", "regex:[a-z]+x==>R"]) { const r = rulesOf([a]); assert.equal(applied(r), true, `${a} is accepted`); // Every rule here is "aliases line 1": the once-per-rule note is reset. resetBudgetNotes(); const t0 = performance.now(); const out = applyPrivacy(r.rules, line); const ms = performance.now() - t0; assert.ok(ms < 1000, `${a}: ${ms.toFixed(0)} ms`); assert.ok(!out.includes("x"), `${a}: no raw match of the rule is left`); // The budget is the input's problem: it never disables the rule. (A // machine so loaded that one 4 KB window took over 50 ms disables it by // the OTHER backstop, which is fine — and then it is in fallback.) const step = r.rules!.steps.find((x) => x.why === "aliases line 1")!; const small = applyPrivacy(r.rules, "b ax c"); if (isDisabled(step)) disabledN++; if (!isDisabled(step)) assert.ok(small.includes("R") && !small.includes("x") && !small.includes("[hidden]"), `${a}: still on (${small})`); else assert.ok(!small.includes("x"), `${a}: in fallback, nothing raw`); } // The rules that do not end early on their cap probe run out of the // call's budget and say so by number — or, on a machine loaded enough // that one window took over 50 ms, are disabled by the window backstop. assert.ok(said.length + disabledN >= 1, `budget notes ${said.length}, disabled ${disabledN}`); for (const w of said) assert.match(w, /^aliases line 1$/); } finally { onBudget(null); resetBudgetNotes(); } }); test("round 3, M1: page-sized strings never touch the budget", () => { const said: string[] = []; onBudget((why) => said.push(why)); resetBudgetNotes(); try { const r = rulesOf(["regex:proj-(\\d+)==>P", "regex:sec[a-z]+==>S", "glob:tok-*==>T", "regex:[A-Z0-9]{20}==>K", "regex:a.*b==>A"]); for (let i = 0; i < 200; i++) { const s = `row ${i}: proj-${i} secret ${"word ".repeat(20)} ABCDEFGHIJ0123456789 /home/zqu/x a then b ${"z".repeat(i % 50)}`; applyPrivacy(r.rules, s); } assert.deepEqual(said, []); } finally { onBudget(null); resetBudgetNotes(); } }); test("round 3, M2: a refused rule's fallback shows no part of the token", () => { for (const [p, sample, token] of [ ["([A-Z0-9]{2}|[a-z])+", "id QW12 x", "QW12"], ["([A-F0-9]{8}-)+[A-F0-9]{4}", "vol ABCD1234-ABCD1234-EF01 x", "ABCD1234"], ["(\\d{3}-)+\\d{4}", "tel 555-123-4567 x", "4567"], ["(tok_[a-z0-9]+)+", "key tok_abc123 x", "abc123"], ] as const) { const r = rulesOf([`regex:${p}==>T`]); assert.equal(applied(r), false, `${p} is refused`); const out = applyPrivacy(r.rules, sample); assert.ok(!out.includes(token), `${p}: ${out}`); assert.ok(!out.includes("tok_") && !/\d{3}/.test(out), `${p}: no part of it`); } // Fragments come only from literal runs every match holds. assert.deepEqual(certainFragments("([A-F0-9]{8}-)+[A-F0-9]{4}", "regex"), []); assert.deepEqual(certainFragments("(tok_[a-z0-9]+)+", "regex"), [{ text: "tok_", lead: true }]); assert.deepEqual(certainFragments("x[0-9]+-tok", "regex"), [{ text: "-tok", lead: false }]); assert.deepEqual(certainFragments("(?:ab)?cde|zzz", "regex"), []); assert.deepEqual(certainFragments("SECRET*WORD", "glob"), [ { text: "SECRET", lead: true }, { text: "WORD", lead: false }, ]); }); test("round 3: more than four optional groups in a row are refused", () => { assert.equal(analyzeRegex("(a)?(b)?(c)?(d)?x").ok, true); assert.equal(analyzeRegex("(a)?(b)?(c)?(d)?(e)?x").ok, false); assert.equal(analyzeRegex("(a)?(b)?(c)?(d)?y(e)?x").ok, true, "a required atom between ends the run"); });