redact: Insights › Masking and Try it mark a made-up key as a placeholder (#3599)

With "Keep a key's form" on (bea9f905d), a secret goes to the vendor as
a made-up key of its form, kept in the record as its placeholder. The
Masking page and Settings' Try it only matched {{…}}. So a request
masked that way showed no changed text: no marks, nothing side by side,
nothing lit. Try it showed the made-up key as plain text.

maskMatches (plugins/redact/page.js) matches the {{…}} placeholders and
the record's own non-{{ placeholders, longest first. A key of the same
form that the user wrote is not marked. All five page.js uses and
maskTryDraw in app.js use it. app.js grows 3 bytes.

Run at this head (origin/main 7536477c8):
- masking-records "a made-up key is marked as a placeholder is"
  (chromium/webkit, en/zh): red 4/4 on the old page.js/app.js (no
  .msk-msg drawn), green 4/4 with the fix.
- mask-actions "Try it marks a made-up key" (chromium, webkit): red 2/2
  on the old code (marks [] for [MADE, MADE]), green 2/2.
- GUI files masking-records, mask-actions, redact-*, privacy-*,
  provider-unmasked, vision-not-marked and i18n-keys, both engines,
  every language: 270 of 270 pass.
- go test ./internal/gui -run 'Budget|Assets|Script': ok.
- Rebased onto 642d430ec: six commits, and in the GUI only app.css and a
  heatmap test. Re-run at the pushed head: the budget tests ok, the six
  new GUI tests 6/6.
- Real run: a sandbox HOME with `magpie web` built from this tree,
  redact + redactShape on, a fake provider with an echo upstream, and
  "OPENAI_API_KEY=sk_w3ax…" sent through the gateway.
  - The upstream got sk_t1ns….
  - Insights › Masking marked sk_t1ns… on the vendor side and sk_w3ax…
    as written here; picking the value lit both.
  - Try it marked sk_t1ns….
  - No page errors.

Found on the way and filed: #3601. A value found by its KEY= context
is masked there only, and its other copies go as written, in either
mode.

Not tried: the old code in the real app (the GUI tests cover it), and
WebKitGTK/Windows.
This commit is contained in:
yetone
2026-10-25 19:57:25 +08:00
parent 642d430ecb
commit 642180a809
5 changed files with 90 additions and 16 deletions
+1 -1
View File
@@ -92,7 +92,7 @@ recorded as a prediction failure (`noPrediction`).
- With *Mask personal data* on, each kind in `redact.Categories` ([`internal/redact/more.go`](../../internal/redact/more.go)) is masked unless the user turned it off (`redactKinds` in settings, `Options.Kinds`). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so, MAC addresses, and serial numbers next to S/N or the like. Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. Context rules run only near their words (`rule.matches`). What reads as an address but ends in a file's extension that no domain has (`…@2x.jpg`, `strings@base.json`; `fileExt` in `realEmail`), or a scale before an extension that is a domain too (`icon@2x.zip`, `intro@1.5x.mov`; `scaleExt`), is a file's name, for the rule and the local model alike (#3029). `ops@files.zip` is still an address. The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults.
- With *Find with a local model* on (`settings.RedactModel`, this computer's own, kept by `KeepOwn`), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with it on a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name), and the model's are cut at punctuation and titles ([`zhname.go`](../../internal/redact/zhname.go)); a surname with nothing around it (王国的, 张开的) is left. The model is OpenAI's Privacy Filter as a q8 GGUF (1.6 GB), run by `pf-serve` ([`native/privacy-filter`](../../native/privacy-filter), built from privacy-filter.cpp on ggml and released under `pf-v*` tags): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, from hf-mirror first in China, `source.chinaFirst`) and saves the setting only once they are on disk (`/api/privacy-model`, [`privacymodel.go`](../../internal/gui/privacymodel.go)). `pii.Find` starts `pf-serve` on the first request (Metal, Vulkan, else the CPU; one that dies on the GPU is started on the CPU for the rest of the run), joins short texts into 12 KB chunks and maps the spans back, keeps the last 20000 answers by hash, and ends it after 10 minutes with no request ([`internal/pii`](../../internal/pii)). A model that is on and can't answer (not on disk, didn't start, hung) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`).
- With *Mask secrets* on, the user's own masking rules (`redactRules`, `redact.Rule`: a placeholder name and a prefix or an RE2 pattern, [`internal/redact/rules.go`](../../internal/redact/rules.go)) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (`POST /api/settings/redact-rule` with the rule's index and its current value, `editRedactRule` in [`internal/gui/api.go`](../../internal/gui/api.go)). Every rule is checked by `redact.CheckRules` when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The masker reads the rules from settings on each call (`options` in [`internal/masking`](../../internal/masking/masking.go)), so a change applies to the next request.
- With *Keep a key's form* on (`settings.RedactShape`, `Options.Shape`, under *Mask secrets*; Charles Cao on X), a secret of 16 characters or more, all letters, digits, `-`, `_` or `.`, goes as a made-up key of its form instead of a placeholder: its prefix kept (`sk-proj-`, `ghp_`, `AKIA`, up to four letters and their separator; `keyHead`), the same length and separators, and each other character a random one of its kind (a hex key's any hex digit of its case), drawn from an HMAC of the value under the placeholder key, so one key goes as the same made-up one every turn and a vendor's cache still matches (`shapeOf`, `shaped` in [`internal/redact/shape.go`](../../internal/redact/shape.go)). Personal data, the user's words and anything shorter or with other characters go as placeholders still. A made-up key is kept in the masker's memory with the placeholders, so it is recorded, re-masked in what a vendor sealed, and put back wherever the reply has it, before the placeholders (`restoreShapes`); a stream holds the end of an event that may be the start of one (`shapeTail`, after the last whole one), and a made-up key the vendor sends back unrestored isn't masked again (`outsideShapes`). `TestShapeKeepsForm`, `TestShapeJSON`, `TestShapeStream`.
- With *Keep a key's form* on (`settings.RedactShape`, `Options.Shape`, under *Mask secrets*; Charles Cao on X), a secret of 16 characters or more, all letters, digits, `-`, `_` or `.`, goes as a made-up key of its form instead of a placeholder: its prefix kept (`sk-proj-`, `ghp_`, `AKIA`, up to four letters and their separator; `keyHead`), the same length and separators, and each other character a random one of its kind (a hex key's any hex digit of its case), drawn from an HMAC of the value under the placeholder key, so one key goes as the same made-up one every turn and a vendor's cache still matches (`shapeOf`, `shaped` in [`internal/redact/shape.go`](../../internal/redact/shape.go)). Personal data, the user's words and anything shorter or with other characters go as placeholders still. A made-up key is kept in the masker's memory with the placeholders, so it is recorded, re-masked in what a vendor sealed, and put back wherever the reply has it, before the placeholders (`restoreShapes`); a stream holds the end of an event that may be the start of one (`shapeTail`, after the last whole one), and a made-up key the vendor sends back unrestored isn't masked again (`outsideShapes`). `TestShapeKeepsForm`, `TestShapeJSON`, `TestShapeStream`. Insights › Masking and Settings' *Try it* mark a made-up key where they mark a placeholder, matching the text against the request's own values only, so a key of the same form the user wrote isn't marked (`maskMatches` in `plugins/redact/page.js`; #3599, masking-records and mask-actions GUI tests).
- What is done with a value found is the user's per kind (#1977, `redactActions` in settings, `Options.Actions`, set by `POST /api/settings/redact-actions`; a kind left out is masked). `redact.Warn` sends it as written: the masker tells it, with a placeholder no one remembers, and it isn't counted as masked. `redact.Block` masks it as any other, and the gateway holds the request back with a 400 that names the kind and the value's hint, never the value (`blocked`, `maskBlocked` in [`redact.go`](../../internal/gateway/redact.go)); nothing is sent and the record is kept as `Blocked` (`noteBlocked`). A value on the *Never mask* list (`redactAllow`, `Options.Allow`, `POST /api/settings/redact-allow`) goes as written when it is the whole value found, in any case, and isn't told; a longer value it is part of is masked. Settings → Privacy's *Try it* posts a text to `POST /api/masking/preview` ([`masking.go`](../../internal/gui/masking.go)), which masks it as a request would be (`redact.Preview`) and remembers nothing: its placeholders stand for nothing afterwards, its values aren't masked later as seen before, and it returns only the masked text and each hit's kind, finder, action, placeholder and hint. The page keeps the text in no storage.
- Each request that had anything masked is recorded as it goes to the vendor (`noteMasked` in [`masked.go`](../../internal/gateway/masked.go), from chat, the Codex backend, search, images, video, System One, embeddings and audio; count_tokens is masked and not recorded). The masker says what it swapped through `gwmw.Teller` (`JSONHits`, `TextHits`: each placeholder's kind, its finder, `redact.ByRule`, `ByYours`, `ByWord`, `ByModel` or `ByKnown`, and a hint of its first characters and its length), and [`internal/maskrec`](../../internal/maskrec/maskrec.go) keeps one line per request in a file per day under `~/.config/magpie/masking`, 30 days and 100 MB in all: the agent, session, provider, model, and each placeholder with its kind, finder, action and hint, never the value. The text around each placeholder as the vendor saw it is kept in memory only, for the last 400 records, and what a placeholder stood for only in the masker's own memory (`Teller.Value`); after a restart neither is there. A recent call (`Call.Masked`) and the route trace (`Route.Masked`) carry the counts and the record's key, which the Gateway and Routing pages' badge opens in Settings → Privacy (`/api/masking/*`, [`internal/gui/masking.go`](../../internal/gui/masking.go)). A masker without `Teller`, a plugin's, masks as before and records nothing. Under a test binary testenv isolated nothing is written (`maskrec.inTest`).
- `DecidesModel` gives a 400.
+1 -1
View File
@@ -22557,7 +22557,7 @@ function maskTryDraw(out) {
}
const text = el("div", "mask-try-text");
let at = 0;
for (const m of res.text.matchAll(PLACEHOLDER)) {
for (const m of maskMatches(res.text, info)) {
text.append(document.createTextNode(res.text.slice(at, m.index)));
const h = info.get(m[0]);
const kind = h?.kind || m[0].slice(2, -2).replace(/_[^_]*$/, "");
+24 -8
View File
@@ -1,11 +1,27 @@
// Insights › Masking's code (client.js has its markup and hooks): run after
// app.js, whose masking helpers it shares (maskTip, maskColor,
// maskShape, maskValue: Settings' Try it and the masked calls' badges use
// them too). What a placeholder stood for is in this magpie's memory alone,
// never on disk, so after a restart it is gone; so is the text a request
// went out with (/api/masking/sent), kept for the newest requests only.
// them too; Try it uses this page's maskMatches in turn). What a
// placeholder stood for is in this magpie's memory alone, never on disk,
// so after a restart it is gone; so is the text a request went out with
// (/api/masking/sent), kept for the newest requests only.
const stillMotion = calm;
// maskMatches is text's stand-ins as matchAll gives them: its {{…}}
// placeholders, and the made-up keys "Keep a key's form" sent (redact's
// shape.go), the keys of info that are no placeholder, which only the
// record's own list tells from the text around them (#3599)
const maskLookRes = new WeakMap();
function maskMatches(text, info) {
let re = maskLookRes.get(info);
if (!re) {
const looks = [...info.keys()].filter((p) => p && !p.startsWith("{{")).sort((a, b) => b.length - a.length)
.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
re = looks.length ? new RegExp(PLACEHOLDER.source + "|" + looks.join("|"), "g") : PLACEHOLDER;
maskLookRes.set(info, re);
}
return text.matchAll(re);
}
// the providers' names, read once when the page opened before any page
// that loads them
let maskProv = null, maskProvAsked = false;
@@ -709,7 +725,7 @@ function maskBlocked(r) {
// got them or, here, as they were written
function maskInk(into, text, here, o, info) {
let at = 0;
for (const m of text.matchAll(PLACEHOLDER)) {
for (const m of maskMatches(text, info)) {
const x = info.get(m[0]);
if (!x) continue;
into.append(document.createTextNode(text.slice(at, m.index)));
@@ -731,7 +747,7 @@ function maskInk(into, text, here, o, info) {
// side, the rest left out
function maskWindows(text, info) {
const rs = [];
for (const m of text.matchAll(PLACEHOLDER)) if (info.has(m[0])) rs.push([Math.max(0, m.index - 120), Math.min(text.length, m.index + m[0].length + 120)]);
for (const m of maskMatches(text, info)) if (info.has(m[0])) rs.push([Math.max(0, m.index - 120), Math.min(text.length, m.index + m[0].length + 120)]);
const out = [];
for (const r of rs) {
const last = out.at(-1);
@@ -761,7 +777,7 @@ function maskContent(r, o, info) {
items = [];
let fold = null;
for (const l of o.leaves) {
const changed = [...l.text.matchAll(PLACEHOLDER)].some((m) => info.has(m[0]));
const changed = [...maskMatches(l.text, info)].some((m) => info.has(m[0]));
if (changed) { fold = null; items.push({ leaf: l }); continue; }
if (!fold) items.push(fold = { fold: [] });
fold.fold.push(l);
@@ -804,7 +820,7 @@ function maskContent(r, o, info) {
return list.append(f);
}
const l = it.leaf, m = el("div", "msk-msg");
const n = [...l.text.matchAll(PLACEHOLDER)].filter((x) => info.has(x[0])).length;
const n = [...maskMatches(l.text, info)].filter((x) => info.has(x[0])).length;
const mh = el("div", "msk-mhead");
if (l.role) mh.append(el("span", "msk-role", l.role));
if (l.path) mh.append(el("span", "msk-path", l.path));
@@ -845,7 +861,7 @@ function maskHow(r, o, info) {
head.append(el("h2", "", t("How it was masked")), el("span", "msk-hint", t(vs.length === 1 ? "1 value" : "{n} values", { n: fmtN(vs.length) }) + " · " + t(r.n === 1 ? "1 place" : "{n} places", { n: fmtN(r.n) })));
aside.append(head);
const where = new Map();
for (const l of o.leaves || []) for (const m of l.text.matchAll(PLACEHOLDER)) if (info.has(m[0]) && l.path) {
for (const l of o.leaves || []) for (const m of maskMatches(l.text, info)) if (info.has(m[0]) && l.path) {
const w = where.get(m[0]) || new Set();
w.add(l.path);
where.set(m[0], w);
+30 -2
View File
@@ -18,7 +18,7 @@ const assets = path.resolve(__dirname, "../assets");
const SECRET = "sk-proj-Tr1eDq8Wm3Rt6YxN2vLp";
const PH = "{{API_KEY_ab12cd34}}";
function serve(lang, posted) {
function serve(lang, posted, shown = { from: SECRET, to: PH }) {
let settings = { theme: "light", lang, tray: "panel", redact: true, redactPersonal: true };
return async (route) => {
const req = route.request(), url = new URL(req.url());
@@ -45,7 +45,7 @@ function serve(lang, posted) {
const { text } = req.postDataJSON();
posted.push(["preview", text]);
const block = settings.redactActions?.API_KEY === "block";
return json({ text: text.replace(SECRET, PH), hits: text.includes(SECRET) ? [{ kind: "API_KEY", by: "rule", action: block ? "block" : "", placeholder: PH, head: "sk-p", len: SECRET.length }] : [] });
return json({ text: text.replaceAll(shown.from, shown.to), hits: text.includes(shown.from) ? [{ kind: "API_KEY", by: "rule", action: block ? "block" : "", placeholder: shown.to, head: shown.from.slice(0, 4), len: shown.from.length }] : [] });
}
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
@@ -143,3 +143,31 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
}
}
}
// with "Keep a key's form" on the preview hands back a made-up key of the
// real one's form, not a {{…}} placeholder: Try it marks it all the same,
// and only it (#3599)
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: Try it marks a made-up key`, async (t) => {
const REAL = "sk_w3axCByTQgK1PxqPhfKTrJOLBqz6sbZv", MADE = "sk_hYQWRBFmdHNIo5XVT2VnIIGh4mmMiJNm";
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 1100, height: 900 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(8000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve("en", [], { from: REAL, to: MADE }));
await watchSettingsReads(page);
await page.goto("http://magpie.test/?view=settings&tab=privacy");
await settingsDrawn(page);
const box = page.locator("#maskTryList textarea.mask-try-in");
await reach(page, box);
await box.fill(`OPENAI_API_KEY=${REAL} sk_not_found_here, again ${REAL}`);
const out = page.locator("#maskTryList .mask-try-out");
await out.locator(".mask-try-hits").waitFor();
assert.equal(await out.locator(".mask-try-text").textContent(), `OPENAI_API_KEY=${MADE} sk_not_found_here, again ${MADE}`);
assert.deepEqual(await out.locator("mark.mo-ph").allTextContents(), [MADE, MADE]);
assert.equal(await out.locator("mark.mo-ph").first().getAttribute("title"), "API keys");
assert.deepEqual(errors, []);
});
}
+34 -4
View File
@@ -93,20 +93,21 @@ function serve(lang, sum, asked, opts = {}) {
if (url.pathname === "/api/masking/records") {
asked.push(url.search);
const q = url.searchParams, kinds = q.get("kind")?.split(",");
const rs = (opts.none ? [] : records).filter((r) => (!kinds || r.values.some((v) => kinds.includes(v.k))) && (!q.get("by") || r.values.some((v) => v.b === q.get("by")))
const rs = (opts.none ? [] : opts.records || records).filter((r) => (!kinds || r.values.some((v) => kinds.includes(v.k))) && (!q.get("by") || r.values.some((v) => v.b === q.get("by")))
&& (!q.get("agent") || r.agent === q.get("agent")) && (!q.get("provider") || r.provider === q.get("provider")) && (!q.get("blocked") || r.blocked));
return json({ records: rs, more: false });
}
if (url.pathname === "/api/masking/record") {
const r = records.find((r) => r.key === +url.searchParams.get("key"));
const r = (opts.records || records).find((r) => r.key === +url.searchParams.get("key"));
return r ? json(r) : route.fulfill({ status: 404, body: "404 page not found" });
}
if (url.pathname === "/api/masking/sent") {
asked.push("sent " + url.searchParams.get("key"));
return url.searchParams.get("key") === "1002" ? json({ body: SENT }) : route.fulfill({ status: 404, body: "404 page not found" });
const body = opts.sent ? opts.sent[url.searchParams.get("key")] : url.searchParams.get("key") === "1002" && SENT;
return body ? json({ body }) : route.fulfill({ status: 404, body: "404 page not found" });
}
if (url.pathname === "/api/masking/values") {
const known = { [KEY]: SECRET, [MAIL]: ADDR };
const known = { [KEY]: SECRET, [MAIL]: ADDR, ...opts.known };
const ps = JSON.parse(req.postData()).ps;
asked.push("values " + ps.join(","));
return json({ values: Object.fromEntries(ps.filter((p) => known[p]).map((p) => [p, known[p]])) });
@@ -381,3 +382,32 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(errors, []);
});
}
// "Keep a key's form" sends a made-up key of the real one's form in place of
// a {{…}} placeholder (redact's shape.go): the page marks it, and puts the
// real key against it, as it does a placeholder (#3599)
const MADE = "sk_hYQWRBFmdHNIo5XVT2VnIIGh4mmMiJNm", REAL = "sk_w3axCByTQgK1PxqPhfKTrJOLBqz6sbZv";
const made = {
records: [{ key: 1005, t: ago(60e3), route: "chat", what: "chat", agent: "codex", provider: "openai", model: "gpt-5", n: 2, back: { [MADE]: 1 },
values: [{ p: MADE, k: "API_KEY", b: "rule", h: "sk_w", l: 35, n: 2, known: true }],
snips: { [MADE]: `OPENAI_API_KEY=${MADE}` } }],
sent: { 1005: JSON.stringify({ model: "gpt-5", messages: [{ role: "user", content: `OPENAI_API_KEY=${MADE} sk_live_other\nonce more: ${MADE}` }] }) },
known: { [MADE]: REAL },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: a made-up key is marked as a placeholder is`, async (t) => {
const { browser, page, errors } = await open(engine, lang, 1100, summary, "", made);
t.after(() => browser.close());
await page.locator("#maskList .msk-row").first().click();
const one = page.locator("#maskOne");
await one.locator(".msk-msg").first().waitFor();
assert.deepEqual(await one.locator(".msk-msg .msk-text").last().locator("mark").allTextContents(), [MADE, MADE], "as the vendor got it");
assert.deepEqual(await one.locator(".msk-msg .msk-text").first().locator("mark").allTextContents(), [REAL, REAL], "as written here");
await stillClick(page, one.locator(".msk-val").first());
assert.equal(await one.locator("mark.lit").count(), 4);
await untranslated(page, lang);
assert.deepEqual(errors, []);
});
}
}