commit 24eff72a1b0c5baa78aefd2aa0a3def3c4c596e8
parent d1eadbce3a86151799c5ce23ef1cf06c9444c775
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 13 Nov 2026 03:55:02 -0500
privacy D4: a call budget for operator rules, and a fallback that hides the variable part
M1. One displayText / displayPath call spends at most PRIVACY_CALL_BUDGET_MS
(150 ms, beside the other limits) on all operator regex and glob rules
together. Past it, the text a rule has not read -- the rest of its line, and
every line after -- is shown as [hidden], one per non-empty line, and so is
all the text for an operator rule that had not run yet. The built-in and
literal steps (paths, host, user, aliases' literals, the denylist, e-mail)
always run on all of it, in compile order. A budget run-out is the input's
problem: logged once per rule by number, the rule stays on (only the
per-window backstop disables one). Six cheap-per-window rules on one 5 MB line
return in under a second with no raw match; 200 page-sized strings x 5 rules
never touch it.
M2. A rule's fallback fragments are its CERTAIN literal runs -- outside
character classes, quantifier bodies, group syntax and escapes, not optional,
not in an alternation branch -- each marked whether it starts every match. In
fallback, a line holding a leading fragment is hidden from it to the line's
end, a line holding a non-leading one is hidden whole, and a rule with no
certain fragment hides every non-empty line. The warnings say exactly that.
Also: more than four optional groups in a row are refused statically.
SETTINGS.md regenerated.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
8 files changed, 391 insertions(+), 60 deletions(-)
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -1466,7 +1466,7 @@ What the editor's and umtool's pages SHOW of this machine (demo epic D4): local
| `hideHost` | `false` | Show this machine's hostname (os.hostname(), its short form and ARCHILYZER_HOST_ID; three characters or more) as the word `host` wherever a page draws it as text. Matched whole-word, in any case, so a hostname inside another word is left alone (a hostname that is itself an ordinary word is replaced where it stands alone); links and other attributes a page needs to work are never rewritten. Default false. |
| `hideUser` | `false` | Show this account's user name (three characters or more) as the word `user` wherever a page draws it as a whole word, in any case — a log line's `by: … (name)`, a path segment under `/run/media/`. A name inside another word is left alone. Default false. |
| `hidePrivateSites` | `false` | Leave the sites marked private (site.json `audience: "private"`) out of the lists and pickers a page DRAWS: the editor's site-scope picker, /channels' Focus bar and a channel's site memberships (a hidden membership is still saved as it was), umtool's home, /projects, /work and its research source pickers (a project is hidden when it belongs to a private site's article). A private site that is the current choice is shown as "A private site". Only what is drawn: every lookup, default and allow-list keeps the private sites, so a case on a private site's source keeps reading it. Not access control: a private site's own pages still open by URL. An article's own `audience` is a different notion and hides nothing. If the sites cannot be read, umtool hides every site's pieces (fail closed). Default false. |
-| `aliases` | `[]` | Display rules in the SOURCE MIRROR's scrub format (common/lib/scrubRuleLine.ts): one rule per entry — `lhs==>rhs` (literal), `literal:lhs==>rhs`, `regex:pattern==>rhs` (`\1` in rhs is group 1) or `glob:pattern==>rhs`; with no `==>` the match shows as `***REMOVED***`. Applied to displayed text after the path and host rules. A `regex:` or `glob:` rule must be cheap to run on every render: at most ONE unbounded or large quantifier (`*`, `+`, `{n,}`, `{n,m}` with m > 64, lazy forms too; it then repeats at most 256 times), no backreference, no repeated group holding a quantifier or an alternation, quantifier ranges multiplying to at most 1,024 and a match of at most 2,048 characters — so a glob has at most one `*`. A rule that breaks this, or does not compile, is not applied: its literal fragments (three characters or more) are shown as `[hidden]` instead (fail closed) and it is reported by its number in the server log and in `archilyzer privacy audit`. A rule that still takes over 50 ms on one call is disabled the same way for the rest of the process. Rules run per line; a line over 4,096 characters is read in overlapping windows. Set with `pnpm ops settings --json '{"patch":{"privacy":{"aliases":["old==>new"]}}}'`. Default []. |
+| `aliases` | `[]` | Display rules in the SOURCE MIRROR's scrub format (common/lib/scrubRuleLine.ts): one rule per entry — `lhs==>rhs` (literal), `literal:lhs==>rhs`, `regex:pattern==>rhs` (`\1` in rhs is group 1) or `glob:pattern==>rhs`; with no `==>` the match shows as `***REMOVED***`. Applied to displayed text after the path and host rules. A `regex:` or `glob:` rule must be cheap to run on every render: at most ONE unbounded or large quantifier (`*`, `+`, `{n,}`, `{n,m}` with m > 64, lazy forms too; it then repeats at most 256 times, and where the pattern could match past that the rest of the line is hidden), no backreference, no lookahead or lookbehind, no repeated group holding a quantifier or an alternation, at most four optional groups in a row, quantifier ranges and alternation branches multiplying to at most 1,024 and a match of at most 2,048 characters — so a glob has at most one `*`. A rule that breaks this, or does not compile, is not applied: it runs in FALLBACK — on each line holding one of its certain literal fragments (three characters or more that every match contains), the text from that fragment to the line's end (the whole line, where the fragment does not start the match) is shown as `[hidden]`; with no such fragment, every non-empty line is — and it is reported by its number in the server log and in `archilyzer privacy audit`. A rule that takes over 50 ms on one 4,096-character window is disabled into the same fallback for the rest of the process. One display call spends at most 150 ms on all operator rules together: past that, the text a rule has not read is shown as `[hidden]`, one per line (the rule stays on; the built-in path, host, user and e-mail rules always run on all of it). Rules run per line; a line over 4,096 characters is read in overlapping windows. Set with `pnpm ops settings --json '{"patch":{"privacy":{"aliases":["old==>new"]}}}'`. Default []. |
| `maskEmail` | `false` | Show every e-mail address a page draws as text as `[email]` (mailto links keep working). Default false. |
| `useSourceRules` | `false` | Also apply the source mirror's private rule files (SOURCE_SCRUB_FILE, default `~/.config/archilyzer/source-scrub.txt`, as aliases; SOURCE_DENYLIST_FILE's literals shown as `[hidden]`). Read by the SERVER only: their rules are applied where a page is rendered on the server and are never sent to a browser, a response, a log or an error (a client-rendered panel does not get them). A missing file is a server-log warning naming its path and error code, and nothing else — `archilyzer privacy audit` is the check that the rules took. Default false. AFTER TURNING PRIVACY ON, RELOAD THE OPEN PAGES: a client-rendered panel on a page already open stays unmasked until it is loaded again (a change while on, or turning it off, reaches them on the next navigation). NOTE, for every rule but these: the browser applies the rules itself, so the page it receives CARRIES the values they hide (the home dir, the hostname, the user name, the volume UUIDs and roots, each alias's left side) in its script payload — view-source shows them; the audit reads only what a page draws, not its scripts. |
diff --git a/common/lib/privacy/compile.ts b/common/lib/privacy/compile.ts
@@ -154,39 +154,167 @@ export function riskyRegex(re: string): boolean {
return !analyzeRegex(re).ok;
}
-/** The runs of three or more plain characters a broken regex or glob still names. */
-export function literalFragments(pattern: string, kind: "regex" | "glob"): string[] {
- const out: string[] = [];
+export type Fragment = { text: string; lead: boolean };
+
+/**
+ * The CERTAIN literal fragments of a regex or glob (review round 3, M2): runs
+ * of three or more plain characters that EVERY match contains — outside
+ * character classes, quantifier bodies, group syntax and escapes, not made
+ * optional by a quantifier, not in a branch of an alternation. `lead`: the
+ * fragment is where every match starts (nothing variable before it), so a
+ * match containing it starts there. A rule in fallback (display.ts) hides,
+ * on each line where a fragment occurs, from a leading one to the end of the
+ * line — or the WHOLE line for a fragment that is not leading; a rule with no
+ * certain fragment hides every non-empty line it runs on.
+ */
+export function certainFragments(pattern: string, kind: "regex" | "glob"): Fragment[] {
+ if (kind === "glob") {
+ const out: Fragment[] = [];
+ let run = "";
+ let runAt = 0;
+ const flush = () => {
+ if (run.length >= 3) out.push({ text: run, lead: runAt === 0 });
+ run = "";
+ };
+ for (let i = 0; i < pattern.length; i++) {
+ const c = pattern[i];
+ if (c === "*" || c === "?" || c === "[") {
+ flush();
+ if (c === "[") {
+ const j = pattern.indexOf("]", i + 2);
+ if (j === -1) break;
+ i = j;
+ }
+ continue;
+ }
+ if (run === "") runAt = i;
+ run += c;
+ }
+ flush();
+ return dedupeFragments(out);
+ }
+ type Frame = { runs: Array<Fragment & { pos: number }>; alt: boolean };
+ const stack: Frame[] = [{ runs: [], alt: false }];
let run = "";
+ let runAt = -1;
+ // Where the first matched character of the pattern is (after any leading
+ // `^` and group openings): a fragment there leads every match.
+ let leadAt = -1;
+ let variableSeen = false;
+ const top = () => stack[stack.length - 1];
const flush = () => {
- if (run.length >= 3) out.push(run);
+ if (run.length >= 3) top().runs.push({ text: run, lead: runAt === leadAt && !variableSeen, pos: runAt });
run = "";
};
- const meta = kind === "glob" ? "*?[]" : ".*+?()[]{}|^$";
+ const quantAfter = (i: number): { min: number; len: number } | null => {
+ const c = pattern[i];
+ let q: { min: number; len: number } | null = null;
+ if (c === "*") q = { min: 0, len: 1 };
+ else if (c === "+") q = { min: 1, len: 1 };
+ else if (c === "?") q = { min: 0, len: 1 };
+ else if (c === "{") {
+ const m = /^\{(\d+)(,\d*)?\}/.exec(pattern.slice(i));
+ if (m) q = { min: Number(m[1]), len: m[0].length };
+ }
+ if (q && pattern[i + q.len] === "?") q.len++;
+ return q;
+ };
for (let i = 0; i < pattern.length; i++) {
const c = pattern[i];
- if (kind === "regex" && c === "\\") {
+ if (c === "\\") {
+ flush();
+ variableSeen = true;
+ if (leadAt === -1) leadAt = -2;
const n = pattern[i + 1];
- i++;
- if (n !== undefined && /[^A-Za-z0-9]/.test(n)) run += n;
- else flush();
+ i += n === "x" ? 3 : n === "u" ? (pattern[i + 2] === "{" ? Math.max(1, pattern.indexOf("}", i) - i) : 5) : 1;
+ const q = quantAfter(i + 1);
+ if (q) i += q.len;
+ continue;
+ }
+ if (c === "[") {
+ flush();
+ if (leadAt === -1) leadAt = -2;
+ variableSeen = true;
+ let j = i + 1;
+ if (pattern[j] === "^") j++;
+ if (pattern[j] === "]") j++;
+ while (j < pattern.length && pattern[j] !== "]") j += pattern[j] === "\\" ? 2 : 1;
+ i = j;
+ const q = quantAfter(i + 1);
+ if (q) i += q.len;
continue;
}
- if (kind === "regex" && (c === "?" || c === "*" || c === "{")) {
- // The character before an optional or repeated quantifier is not a
- // certain part of a match.
- run = run.slice(0, -1);
+ if (c === "(") {
flush();
+ const m = /^\(\?(?::|=|!|<=|<!|<[A-Za-z_][A-Za-z0-9_]*>)/.exec(pattern.slice(i));
+ i += m ? m[0].length - 1 : 0;
+ stack.push({ runs: [], alt: false });
continue;
}
- if (meta.includes(c)) {
+ if (c === ")") {
flush();
+ const f = stack.length > 1 ? stack.pop()! : { runs: [], alt: false };
+ const q = quantAfter(i + 1);
+ if (q) i += q.len;
+ // Kept only when every match goes through the group's text.
+ if (!f.alt && !(q && q.min === 0)) top().runs.push(...f.runs);
+ else variableSeen = true;
continue;
}
+ if (c === "|") {
+ flush();
+ top().alt = true;
+ continue;
+ }
+ if (c === "." || c === "^" || c === "$") {
+ flush();
+ if (c === ".") {
+ variableSeen = true;
+ if (leadAt === -1) leadAt = -2;
+ const q = quantAfter(i + 1);
+ if (q) i += q.len;
+ }
+ continue;
+ }
+ const q = quantAfter(i + 1);
+ if (q) {
+ // The character before a quantifier: optional (min 0) is not certain;
+ // a repeat ends the run (`ab+c` holds "ab", then "c").
+ if (run === "" && leadAt === -1) leadAt = i;
+ if (run === "") runAt = i;
+ if (q.min > 0) run += c;
+ flush();
+ variableSeen = true;
+ i += q.len;
+ continue;
+ }
+ if (leadAt === -1) leadAt = i;
+ if (run === "") runAt = i;
run += c;
}
flush();
- return [...new Set(out)];
+ // An unclosed group (a rule that does not compile): its text counts.
+ while (stack.length > 1) {
+ const f = stack.pop()!;
+ if (!f.alt) top().runs.push(...f.runs);
+ }
+ if (stack[0].alt) return [];
+ return dedupeFragments(stack[0].runs.map(({ text, lead }) => ({ text, lead })));
+}
+
+function dedupeFragments(list: Fragment[]): Fragment[] {
+ const seen = new Map<string, Fragment>();
+ for (const f of list) {
+ const prev = seen.get(f.text);
+ if (!prev) seen.set(f.text, { ...f });
+ else prev.lead = prev.lead || f.lead;
+ }
+ return [...seen.values()];
+}
+
+/** The certain fragments' texts (the probes' and the tests' view). */
+export function literalFragments(pattern: string, kind: "regex" | "glob"): string[] {
+ return certainFragments(pattern, kind).map((f) => f.text);
}
type LineSource = "aliases" | "scrub";
@@ -201,24 +329,33 @@ function compileScrubLine(
const mark = secret ? ({ secret: true } as const) : {};
const why = `${where.source} line ${where.n}`;
const hideFragments = (what: string) => {
- const frags =
+ const frags: Fragment[] =
line.kind === "regex" || line.kind === "glob"
- ? literalFragments(line.pattern, line.kind)
+ ? certainFragments(line.pattern, line.kind)
: line.pattern.length >= 3
- ? [line.pattern]
+ ? [{ text: line.pattern, lead: true }]
: [];
problems.push({
source: where.source,
line: where.n,
what: `${what}; ${
frags.length
- ? `it runs in fallback: its ${frags.length} literal fragment${frags.length === 1 ? " is" : "s are"} hidden instead`
- : "it runs in fallback: it has no literal fragment, so every line it would run on is shown as [hidden]"
+ ? `it runs in fallback: on every line holding one of its ${frags.length} certain literal fragment${frags.length === 1 ? "" : "s"}, the text from that fragment (or the whole line, where the fragment does not start the match) is shown as [hidden]`
+ : "it runs in fallback: it has no certain literal fragment, so every line it would run on is shown as [hidden]"
}`,
});
// A REFUSED step: display.ts never runs its pattern, only its fallback —
// the fragments, or the whole line when there are none (never a no-op).
- steps.push({ re: "(?!)", flags: "g", to: HIDDEN_WORD, why: `${why} (fallback)`, bounded: true, refused: true, fallback: frags.map(escapeRegExp), ...mark });
+ steps.push({
+ re: "(?!)",
+ flags: "g",
+ to: HIDDEN_WORD,
+ why: `${why} (fallback)`,
+ bounded: true,
+ refused: true,
+ fallback: frags.map((f) => ({ re: escapeRegExp(f.text), lead: f.lead })),
+ ...mark,
+ });
};
if (where.tooLong) return hideFragments(`is longer than ${PRIVACY_ALIAS_MAX_CHARS.toLocaleString("en-US")} characters`);
if (line.kind === "plain" || line.kind === "literal") {
@@ -247,7 +384,7 @@ function compileScrubLine(
}
const to = line.replacement === null ? SCRUB_REMOVED : line.kind === "regex" ? pythonReplacement(line.replacement) : escapeReplacement(line.replacement);
// What the rule falls back to if display.ts finds it slow at run time.
- const fallback = literalFragments(line.pattern, line.kind).map(escapeRegExp);
+ const fallback = certainFragments(line.pattern, line.kind).map((f) => ({ re: escapeRegExp(f.text), lead: f.lead }));
steps.push({
re: verdict.source,
flags: js.flags,
diff --git a/common/lib/privacy/display.test.ts b/common/lib/privacy/display.test.ts
@@ -117,8 +117,11 @@ test("a broken or unbounded regex fails CLOSED: reported by number, its fragment
// Rule 2's fragments are hidden; rule 3 has none, so every line it would run
// on is hidden whole (review round 2, M-C: a fallback is never a no-op).
assert.equal(applyPrivacy(rules, "ok jeralyzer-private"), "[hidden]");
+ // Rule 2's certain fragments: "jeral" leads, "yzer-private" does not — a
+ // line holding a non-leading one is hidden whole (review round 3, M2).
const two = compilePrivacy(base({ aliases: ["ok==>fine", "regex:jeral(yzer-private==>x"] }));
- assert.equal(applyPrivacy(two.rules, "ok jeralyzer-private"), "fine [hidden][hidden]");
+ assert.equal(applyPrivacy(two.rules, "ok jeralyzer-private"), "[hidden]");
+ assert.equal(applyPrivacy(two.rules, "ok jeral then"), "fine [hidden]", "from a leading fragment to the line's end");
assert.ok(riskyRegex("(a+)+"));
assert.ok(riskyRegex("(a|aa)*"));
assert.ok(riskyRegex("((ab)*c)+"));
@@ -149,7 +152,8 @@ test("useSourceRules: the files' rules are secret steps the client never gets",
{ scrubText: "\uFEFFMARKER-SCRUB==>alias\r\n# c\nregex:QQQ(ZZZ==>z\n", denyText: "MARKER-DENY\ni:marker-ci\n" },
);
const { rules, problems } = compilePrivacy(input);
- assert.equal(applyPrivacy(rules, "MARKER-SCRUB MARKER-DENY Marker-CI QQQZZZ"), "alias [hidden] [hidden] [hidden][hidden]");
+ assert.equal(applyPrivacy(rules, "MARKER-SCRUB MARKER-DENY Marker-CI"), "alias [hidden] [hidden]");
+ assert.equal(applyPrivacy(rules, "x QQQZZZ"), "[hidden]", "the broken scrub rule's fallback: a line with a non-leading fragment, whole");
assert.deepEqual(problems.map((p) => `${p.source}:${p.line}`), ["scrub:3"]);
assert.ok(!JSON.stringify(problems).includes("QQQ"));
assert.ok(!JSON.stringify(publicRules(rules)).includes("QQQ"));
diff --git a/common/lib/privacy/display.ts b/common/lib/privacy/display.ts
@@ -44,9 +44,12 @@ export type PrivacyStep = {
bounded?: true;
// Its longest possible match (regexSafety.ts).
maxLen?: number;
- // Its literal fragments (regex sources), shown as [hidden] when it runs in
- // fallback; with none, every line it would run on is shown as [hidden].
- fallback?: string[];
+ // Its CERTAIN literal fragments (regex sources; compile.ts certainFragments)
+ // for when it runs in fallback: on a line holding one, the text from a
+ // leading fragment to the line's end — or the whole line, for a fragment
+ // that does not start every match — is shown as [hidden]; with none, every
+ // non-empty line it would run on is.
+ fallback?: Array<{ re: string; lead: boolean }>;
// Refused at compile time: its pattern never runs, only its fallback.
refused?: true;
// A match this long may have used its rewritten (capped) quantifier to the
@@ -76,7 +79,7 @@ type Compiled = {
bounded: boolean;
email: boolean;
overlap: number;
- fallback: RegExp[];
+ fallback: Array<{ rx: RegExp; lead: boolean }>;
capAt: number | null;
probe: RegExp | null;
};
@@ -109,7 +112,7 @@ function stepsOf(rules: PrivacyRules): Compiled[] {
probe: s.capProbe ? new RegExp(s.capProbe, flags) : null,
fallback: (s.fallback ?? []).flatMap((f) => {
try {
- return [new RegExp(f, "g")];
+ return [{ rx: new RegExp(f.re, "g"), lead: f.lead === true }];
} catch {
return [];
}
@@ -200,6 +203,18 @@ function applyTemplate(m: RegExpExecArray, to: string): string {
});
}
+/** What one displayText / displayPath call may spend on operator rules, in all. */
+export const PRIVACY_CALL_BUDGET_MS = 150;
+
+// One call's budget across every operator rule and window.
+type Call = { deadline: number; spent: boolean };
+
+class OutOfBudget extends Error {
+ constructor(readonly emitted: string) {
+ super("budget");
+ }
+}
+
class Slow extends Error {
constructor(readonly ms: number) {
super("slow");
@@ -228,10 +243,16 @@ function windows(line: string, overlap: number): Array<{ start: number; from: nu
}
/** Where the cap probe first matches in the line (the rule may match past its cap there), or null. */
-function probeAt(line: string, c: Compiled): number | null {
+function probeAt(line: string, c: Compiled, call: Call): number | null {
if (!c.probe) return null;
const W = PRIVACY_REGEX_MAX_INPUT;
for (const w of windows(line, c.overlap)) {
+ // Out of the call's budget before the probe has looked everywhere: the
+ // line is hidden from the window it had not read (fail closed).
+ if (now() > call.deadline) {
+ call.spent = true;
+ return w.start;
+ }
const t0 = now();
c.probe.lastIndex = w.own0;
const m = c.probe.exec(w.win);
@@ -242,14 +263,20 @@ function probeAt(line: string, c: Compiled): number | null {
return null;
}
-function scanLine(line: string, c: Compiled): string {
+function scanLine(line: string, c: Compiled, call: Call): string {
const W = PRIVACY_REGEX_MAX_INPUT;
const rx = c.rx;
- const stopAt = probeAt(line, c);
+ const stopAt = probeAt(line, c, call);
let out = "";
let pos = 0;
let rest = false;
for (const { from, win, own0 } of windows(line, c.overlap)) {
+ if (now() > call.deadline) {
+ // Out of the call's budget: what was read stays as it was drawn, the
+ // rest of this line is hidden.
+ call.spent = true;
+ throw new OutOfBudget(out + (line.slice(pos).trim() ? HIDDEN : line.slice(pos)));
+ }
rx.lastIndex = Math.max(0, pos - from);
const t0 = now();
let m: RegExpExecArray | null;
@@ -291,27 +318,84 @@ function scanLine(line: string, c: Compiled): string {
return out + line.slice(pos);
}
-function boundedReplace(s: string, c: Compiled): string {
- return s.includes("\n") ? s.split("\n").map((line) => scanLine(line, c)).join("\n") : scanLine(s, c);
+const hideLines = (lines: string[]) => lines.map((line) => (line.trim() ? HIDDEN : line));
+
+/** Line by line; out of the call's budget, every line not yet read is hidden. */
+function boundedReplace(s: string, c: Compiled, call: Call): string {
+ const lines = s.split("\n");
+ const out: string[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ try {
+ out.push(scanLine(lines[i], c, call));
+ } catch (err) {
+ if (!(err instanceof OutOfBudget)) throw err;
+ out.push(err.emitted, ...hideLines(lines.slice(i + 1)));
+ return out.join("\n");
+ }
+ }
+ return out.join("\n");
}
-/** A rule in fallback: its literal fragments hidden — or, with none, every non-empty line it would run on. */
+/**
+ * A rule in FALLBACK (refused, or disabled for a slow window): on a line that
+ * holds one of its certain fragments, from a leading fragment's first
+ * occurrence to the line's end — or the whole line, for a fragment that does
+ * not start every match — is shown as [hidden]; a rule with no certain
+ * fragment hides every non-empty line. Never a no-op, never only the literal.
+ */
function fallbackReplace(s: string, c: Compiled): string {
- if (c.fallback.length) {
- let out = s;
- for (const f of c.fallback) out = out.replace(f, HIDDEN);
- return out;
- }
+ if (!c.fallback.length) return hideLines(s.split("\n")).join("\n");
return s
.split("\n")
- .map((line) => (line.trim() ? HIDDEN : line))
+ .map((line) => {
+ let from = -1;
+ for (const f of c.fallback) {
+ f.rx.lastIndex = 0;
+ const m = f.rx.exec(line);
+ if (!m) continue;
+ if (!f.lead) return HIDDEN;
+ if (from === -1 || m.index < from) from = m.index;
+ }
+ return from === -1 ? line : line.slice(0, from) + HIDDEN;
+ })
.join("\n");
}
-function runBounded(s: string, c: Compiled): string {
+const budgetSaid = new Set<string>();
+let budgetReporter: ((why: string) => void) | null = null;
+
+/** Who hears that a rule ran out of a call's budget (once per rule per process). */
+export function onBudget(fn: ((why: string) => void) | null): void {
+ budgetReporter = fn;
+}
+
+/** Forget which rules were told about the budget (tests). */
+export function resetBudgetNotes(): void {
+ budgetSaid.clear();
+}
+
+function runBounded(s: string, c: Compiled, call: Call): string {
if (c.step.refused || disabled.has(c.step)) return fallbackReplace(s, c);
+ const sayBudget = () => {
+ if (budgetSaid.has(c.step.why)) return;
+ budgetSaid.add(c.step.why);
+ const say =
+ budgetReporter ??
+ ((why: string) =>
+ console.warn(
+ `[privacy] ${why} ran out of one call's budget (${PRIVACY_CALL_BUDGET_MS} ms for every operator rule): the text it had not read is shown as [hidden], one per line; the rule stays on`,
+ ));
+ say(c.step.why);
+ };
+ if (call.spent) {
+ // An operator rule that has not run on this call's text at all.
+ sayBudget();
+ return hideLines(s.split("\n")).join("\n");
+ }
try {
- return boundedReplace(s, c);
+ const out = boundedReplace(s, c, call);
+ if (call.spent) sayBudget();
+ return out;
} catch (err) {
if (!(err instanceof Slow)) throw err;
disabled.add(c.step);
@@ -319,7 +403,7 @@ function runBounded(s: string, c: Compiled): string {
slowReporter ??
((why: string, t: number) =>
console.warn(
- `[privacy] ${why} took ${Math.round(t)} ms on one window; it now runs in fallback (its literal fragments, or every line it runs on where it has none, shown as [hidden])`,
+ `[privacy] ${why} took ${Math.round(t)} ms on one window; disabled, it now runs in fallback (on a line holding one of its certain fragments, from that fragment or the whole line; with none, every non-empty line, shown as [hidden])`,
));
say(c.step.why, err.ms);
return fallbackReplace(s, c);
@@ -335,9 +419,16 @@ export function isDisabled(step: PrivacyStep): boolean {
export function applyPrivacy(rules: PrivacyRules | null | undefined, s: string): string {
if (!rules || typeof s !== "string" || s === "") return s;
let out = s;
+ // ORDER: the steps run in compile.ts's order (roots, home, mounts, volumes,
+ // host, user, aliases, the private files' rules, e-mail). The built-in and
+ // literal ones always run on all the text; only an operator regex or glob
+ // spends the call's budget, and one that finds it spent shows the text it
+ // could not read as [hidden] (one per non-empty line). The budget is the
+ // input's problem, not the rule's: it is not disabled for it.
+ const call: Call = { deadline: now() + PRIVACY_CALL_BUDGET_MS, spent: false };
for (const c of stepsOf(rules)) {
if (c.email) out = maskEmails(out, c.to);
- else if (c.bounded) out = runBounded(out, c);
+ else if (c.bounded) out = runBounded(out, c, call);
else out = out.replace(c.rx, c.to);
}
return out;
diff --git a/common/lib/privacy/privacy-server.test.ts b/common/lib/privacy/privacy-server.test.ts
@@ -64,7 +64,7 @@ test("useSourceRules: the files are applied on the server, never handed to the c
const client = JSON.stringify(clientPrivacyRules());
assert.ok(!client.includes("MARKER"), "the client rules carry no private text");
assert.ok(!JSON.stringify(c.problems).includes("MARKER"));
- assert.deepEqual(warnings, ["[privacy] scrub line 2: does not compile (regex); it runs in fallback: its 1 literal fragment is hidden instead"]);
+ assert.deepEqual(warnings, ["[privacy] scrub line 2: does not compile (regex); it runs in fallback: on every line holding one of its 1 certain literal fragment, the text from that fragment (or the whole line, where the fragment does not start the match) is shown as [hidden]"]);
for (const w of warnings) assert.ok(!w.includes("MARKER"));
});
diff --git a/common/lib/privacy/regexSafety.ts b/common/lib/privacy/regexSafety.ts
@@ -13,6 +13,7 @@
// - the product of every quantifier's range (max − min + 1) AND of every
// alternation's number of branches at most QUANTIFIER_PRODUCT_MAX, so
// three `{0,64}` side by side, or twenty `(a|a)`, are refused too;
+// - at most OPTIONAL_GROUPS_MAX optional groups in a row (`(a)?(b)?…`);
// - a match at most MATCH_MAX characters long: the one unbounded quantifier
// is REWRITTEN to at most UNBOUNDED_CAP repeats (`.*` → `.{0,256}`), and
// the longest possible match is computed and refused above MATCH_MAX —
@@ -29,6 +30,7 @@ export const UNBOUNDED_CAP = 256;
export const LARGE_QUANTIFIER = 64;
export const QUANTIFIER_PRODUCT_MAX = 1024;
export const MATCH_MAX = 2048;
+export const OPTIONAL_GROUPS_MAX = 4;
export type RegexVerdict =
// capTrigger: a match at least this long MAY have used the rewritten
@@ -128,6 +130,7 @@ export function analyzeRegex(re: string): RegexVerdict {
const parseSequence = (): Node => {
const node: Node = { maxLen: 0, minLen: 0, hasQuant: false, hasAlt: false, out: "" };
+ let optionalRun = 0;
while (i < re.length && re[i] !== "|" && re[i] !== ")") {
const start = i;
let atom: Node;
@@ -189,6 +192,11 @@ export function analyzeRegex(re: string): RegexVerdict {
i += q.len;
atom = quantify(atom, q, isGroup);
}
+ // More than OPTIONAL_GROUPS_MAX optional groups in a row: refused (each
+ // doubles the paths a failing match tries).
+ if (isGroup && q && q.min === 0) {
+ if (++optionalRun > OPTIONAL_GROUPS_MAX) throw new Refused(`more than ${OPTIONAL_GROUPS_MAX} optional groups in a row`);
+ } else optionalRun = 0;
if (i === start) throw new Refused("an unparsable pattern");
node.maxLen += atom.maxLen;
node.minLen += atom.minLen;
diff --git a/common/lib/privacy/safety.test.ts b/common/lib/privacy/safety.test.ts
@@ -7,8 +7,8 @@
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 { compilePrivacy } from "./compile";
-import { applyPrivacy, isDisabled, onSlowRule, PRIVACY_REGEX_MAX_INPUT, type PrivacyRules } from "./display";
+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<PrivacySettings>, extra: Record<string, unknown> = {}) =>
@@ -101,12 +101,12 @@ test("M1: the runtime backstop disables a rule slower than 50 ms on one call, by
// 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: ["SECRETWORD"] }],
+ 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] b", "fails closed to its fragments");
+ assert.equal(applyPrivacy(slow, "a SECRETWORD b"), "a [hidden]", "fails closed: from its leading fragment to the line's end");
} finally {
onSlowRule(null);
}
@@ -215,13 +215,13 @@ test("M-B: a scrub-file line over 1,000 characters runs in fallback only", () =>
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] b");
+ 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 literal fragment, so every line it would run on is shown as \[hidden\]/);
+ 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[] = [];
@@ -279,3 +279,87 @@ test("windows keep the whole-line match grid", () => {
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");
+});
diff --git a/common/lib/privacySettings.ts b/common/lib/privacySettings.ts
@@ -73,13 +73,20 @@ export const PRIVACY_SETTINGS_FIELD_DOCS: FieldDocs<PrivacySettings> = {
"`lhs==>rhs` (literal), `literal:lhs==>rhs`, `regex:pattern==>rhs` (`\\1` in rhs is group 1) or " +
"`glob:pattern==>rhs`; with no `==>` the match shows as `***REMOVED***`. Applied to displayed text after the " +
"path and host rules. A `regex:` or `glob:` rule must be cheap to run on every render: at most ONE unbounded " +
- "or large quantifier (`*`, `+`, `{n,}`, `{n,m}` with m > 64, lazy forms too; it then repeats at most 256 times), " +
- "no backreference, no repeated group holding a quantifier or an alternation, quantifier ranges multiplying to " +
- "at most 1,024 and a match of at most 2,048 characters — so a glob has at most one `*`. A rule that breaks " +
- "this, or does not compile, is not applied: its literal fragments (three characters or more) are shown as " +
- "`[hidden]` instead (fail closed) and it is reported by its number in the server log and in `archilyzer " +
- "privacy audit`. A rule that still takes over 50 ms on one call is disabled the same way for the rest of the " +
- "process. Rules run per line; a line over 4,096 characters is read in overlapping windows. Set with " +
+ "or large quantifier (`*`, `+`, `{n,}`, `{n,m}` with m > 64, lazy forms too; it then repeats at most 256 times, " +
+ "and where the pattern could match past that the rest of the line is hidden), no backreference, no lookahead " +
+ "or lookbehind, no repeated group holding a quantifier or an alternation, at most four optional groups in a " +
+ "row, quantifier ranges and alternation branches multiplying to at most 1,024 and a match of at most 2,048 " +
+ "characters — so a glob has at most one `*`. A rule that breaks this, or does not compile, is not applied: it " +
+ "runs in FALLBACK — on each line holding one of its certain literal fragments (three characters or more that " +
+ "every match contains), the text from that fragment to the line's end (the whole line, where the fragment " +
+ "does not start the match) is shown as `[hidden]`; with no such fragment, every non-empty line is — and it is " +
+ "reported by its number in the server log and in `archilyzer privacy audit`. A rule that takes over 50 ms on " +
+ "one 4,096-character window is disabled into the same fallback for the rest of the process. One display call " +
+ "spends at most 150 ms on all operator rules together: past that, the text a rule has not read is shown as " +
+ "`[hidden]`, one per line (the rule stays on; the built-in path, host, user and e-mail rules always run on all " +
+ "of it). Rules run per line; a line over 4,096 characters is read in overlapping windows. Set with " +
+
"`pnpm ops settings --json '{\"patch\":{\"privacy\":{\"aliases\":[\"old==>new\"]}}}'`. Default [].",
maskEmail: "Show every e-mail address a page draws as text as `[email]` (mailto links keep working). Default false.",
useSourceRules: