From d173c02d79d0b39d972ca91d0de498f156ea625f Mon Sep 17 00:00:00 2001 From: Shane B Date: Tue, 1 Dec 2026 19:02:46 +0100 Subject: [PATCH 1/4] test(redteam): a range cut inside a GitHub token must not hand back its body Seven rows on `ml.sh.read`. Six fail on this branch: 1. a text range that starts inside an unregistered `ghp_` token returns its body (`forModel` needs the prefix and 36 body characters in the same text); 2. a text range that ends inside returns the token's front, prefix included; 3. and 4. the same two cuts on the bytewise path, which never reaches `forModel`; 5. the same start-cut on a `github_pat_` token; 6. two ranges that split a token leave neither half scrubbed. The seventh pins what holds: a range holding the whole (line-delimited) token still reads `[a GitHub token]`. A refusal counts as an answer that keeps the token, so the rows assert the property over both shapes of answer. Fixtures put the token on its own line, because the shape rule anchors on `\b`. Co-Authored-By: Claude Code --- tests/redteam-sh-read-token-range.test.mjs | 185 +++++++++++++++++++++ 1 file changed, 185 insertions(+) create mode 100644 tests/redteam-sh-read-token-range.test.mjs diff --git a/tests/redteam-sh-read-token-range.test.mjs b/tests/redteam-sh-read-token-range.test.mjs new file mode 100644 index 000000000..cc35e23c7 --- /dev/null +++ b/tests/redteam-sh-read-token-range.test.mjs @@ -0,0 +1,185 @@ +// redteam-sh-read-token-range.test.mjs — RED TEAM (e4): a GitHub token is a secret the registry does not hold, and +// `ml.sh.read`'s range widens by the longest REGISTERED form only (`margin(subs)`), then hands back just the range for +// `forModel` to scrub. A range that starts or ends inside an unregistered `ghp_`/`github_pat_` token therefore cuts it +// before the shape rule in `scrubSecrets` ever sees it: the rule needs the prefix and 36 body characters in the SAME +// text, and a part of a token is not matched by any rule. What comes back is a run of the token's body — the secret — +// with the scrub silent. +// +// The property each row pins (SECRET_HANDLES.md, "A cut never lets a prefix through", applied to the shapes as well as +// to registered values): outside a `[a GitHub token]` replacement, nothing the worker answers with — a text range, a +// byte range, or the sentence of a refusal — holds a run of the token long enough to matter (the same six-character +// standard the registered rows use), and a range that holds the whole token still reads as the marker. A refusal is an +// answer that keeps the token, so the rows assert the property against both shapes of answer. Every fixture puts the +// token on its own line: the shape rule anchors on `\b`, so a token FUSED to letters on both sides is outside it by +// design, and that is a limit of the shape (src/secret-scrub.ts), not the cut this file is about. +// +// Rows 1-2 are the text path, 3 the binary path, 4 the regression pin, 5 the fine-grained token's shape, 6 two ranges +// that split a token between them. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { fakeNativeHost } from "./fake-native-host.mjs"; + +const T = { timeout: 20000 }; + +const VALUE = "REALSECRET-4b1d-77"; +const NAME = "PLUG_PASSWORD"; +const MARK = "[a GitHub token]"; +/** GitHub's documented shapes (src/secret-scrub.ts, GITHUB_TOKEN): `ghp_` and 36 body characters, `github_pat_` and 22+ . */ +const GH = `ghp_${Array.from({ length: 36 }, (_, i) => "Ab3dEf6hIj9lMn2pQr5tUv8xYz1Bc4De7Fg0H"[i % 36]).join("")}`; +const PAT = `github_pat_${Array.from({ length: 30 }, (_, i) => "Zq7Wx1Kp9Vr3Tn5Bm8Lc2Hd6Jf4G"[i % 29]).join("")}`; + +// The worker's chrome, as much of it as sw-shell.ts, sw-shell-call.ts, sw-scrub.ts and sw-secret-registry.ts use. +const sync = { shellEnabled: true, shellRoots: ["/w/s0"], shellSandbox: true, shellPath: [], chatUrl: "http://host/api/chat/completions", apiKey: "sk-test-config-key" }; +let native = null; +globalThis.chrome = { + runtime: { + id: "ext-id", lastError: undefined, onMessage: { addListener() {} }, getURL: (p) => p, + connectNative: (name) => { + const onMsg = [], onDisc = []; + let closed = false; + const end = { send: (m) => { if (!closed) setTimeout(() => { for (const f of onMsg) f(JSON.parse(JSON.stringify(m))); }, 0); }, close: () => { closed = true; } }; + const receive = native ? native(name, end) : null; + return { name, postMessage: (m) => receive?.(JSON.parse(JSON.stringify(m))), disconnect: () => { closed = true; }, + onMessage: { addListener: (f) => onMsg.push(f) }, onDisconnect: { addListener: (f) => onDisc.push(f) } }; + }, + }, + storage: { + local: { get: async (d) => ({ ...(d ?? {}) }), set: async () => {}, remove: async () => {} }, + sync: { get: async (d) => ({ ...(d ?? {}), ...sync }), set: async () => {} }, + session: { get: async () => ({}), set: async () => {}, remove: async () => {} }, + onChanged: { listeners: [], addListener(f) { this.listeners.push(f); } }, + }, +}; +const { _setRegistryForTest } = await import("../src/sw/sw-secret-registry.ts"); +const { shRun, shRead } = await import("../src/sw/sw-shell-call.ts"); +const { SH_HEAD_BYTES } = await import("../src/shell/sh-call.ts"); +const { TokenStore } = await import("../src/pointers/token-pipe.ts"); + +// One registered value, so the margin is real (its length) and still cannot cover an unregistered token's shape. +_setRegistryForTest([{ name: NAME, value: VALUE }]); + +let rootN = 0; +/** A fresh fake host whose calls print `out`. */ +function hostPrinting(out) { + const host = fakeNativeHost({ done: () => ({ out, err: "", code: 0 }) }); + native = host.onNative; + sync.shellRoots = [`/w/s${++rootN}`]; + return host; +} +const ctxFor = (runId) => ({ runId, seq: 3, local: { step: 1, seq: 3 }, signal: new AbortController().signal, tokens: new TokenStore() }); + +/** The longest run of `token`'s characters, any 6 of them in a row, found in `text` outside a replacement. */ +function leaked(text, token) { + const bare = String(text).split(MARK).join(""); + for (let i = 0; i + 6 <= token.length; i++) { + const w = token.slice(i, i + 6); + if (bare.includes(w)) return w; + } + return null; +} +const assertNoLeak = (text, token, label) => { + const w = leaked(text, token); + assert.equal(w, null, `${label}: no six characters of the token cross outside the marker; got ${JSON.stringify(w)} in ${JSON.stringify(String(text).slice(0, 200))}`); + // Nor does the token's prefix survive with any body behind it. + const prefix = token.startsWith("github_pat_") ? "github_pat_" : token.slice(0, 4); + assert.ok(!String(text).includes(prefix), `${label}: the token's prefix is not left behind: ${JSON.stringify(String(text).slice(0, 200))}`); +}; + +/** + * What the read answered with: its `text`, its `bytes` read as latin1, or, when the read was refused rather than + * answered, the refusal's sentence. A refusal is an acceptable way to keep the token out of a page's hands, so the + * rows assert the property against every answer instead of requiring an `ok`. + */ +function answered(x, label) { + if ("ok" in x) { + const o = x.ok; + if (typeof o?.text === "string") return o.text; + if (o?.bytes?.$bytes) return Buffer.from(o.bytes.$bytes, "base64").toString("latin1"); + assert.fail(`${label}: the read's answer is neither text nor bytes: ${JSON.stringify(x).slice(0, 300)}`); + } + if ("error" in x) return String(x.error); + assert.fail(`${label}: the read answered neither ok nor an error: ${JSON.stringify(x).slice(0, 300)}`); +} + +/** Run one program printing `out`, and answer the ctx and the output's pointer. */ +async function started(runId, out) { + hostPrinting(out); + const ctx = ctxFor(runId); + const r = await shRun(ctx, [["ls"], { expectMs: 5000 }]); + assert.ok("ok" in r, JSON.stringify(r).slice(0, 300)); + return { ctx, token: r.ok.stdout.token }; +} + +// --- the text path: a range that starts, or ends, inside an unregistered token --- + +const pad = (n) => "b".repeat(n); +const NL = "\n"; +/** A text with the token on its own line, and the offset the token starts at: the shape rule anchors on `\b`, so a token the fixture fuses to letters on either side is outside it by design (src/secret-scrub.ts). */ +const onALine = (tok) => { const before = pad(SH_HEAD_BYTES + 100); return { text: `${before}${NL}${tok}${NL}${"c".repeat(200)}`, at: before.length + NL.length }; }; + +test("a read range that STARTS inside an unregistered ghp_ token does not hand back the token's body", T, async () => { + const { text, at } = onALine(GH); + const { ctx, token } = await started("run-gh-start", text); + // Three bytes into the body: the prefix and the first three body characters are outside the range. + const x = await shRead(ctx, [token, { offset: at + 7, length: 30 }]); + assertNoLeak(answered(x, "starts inside"), GH, "starts inside"); +}); + +test("a read range that ENDS inside an unregistered ghp_ token does not hand back its front", T, async () => { + const { text, at } = onALine(GH); + const { ctx, token } = await started("run-gh-end", text); + // Ten bytes before the token, twenty long: the range ends ten bytes into the token. + const x = await shRead(ctx, [token, { offset: at - 10, length: 20 }]); + assertNoLeak(answered(x, "ends inside"), GH, "ends inside"); +}); + +// --- the binary path: the same two cuts, over bytes the model reads as `$bytes` --- + +const nulPad = "\u0000\u0001\u0002".repeat(SH_HEAD_BYTES / 3 + 50); +const nulBytes = Buffer.byteLength(nulPad); + +test("on the bytewise path, a read range that STARTS inside the token does not hand back its body", T, async () => { + const { ctx, token } = await started("run-bin-start", `${nulPad}${GH}\u0000\u0000`); + // Inside the token, then past it into the NULs, so the range is binary and takes the bytewise branch. + const x = await shRead(ctx, [token, { offset: nulBytes + 7, length: 100 }]); + assertNoLeak(answered(x, "binary starts inside"), GH, "binary starts inside"); +}); + +test("on the bytewise path, a read range that ENDS inside the token does not hand back its front", T, async () => { + const { ctx, token } = await started("run-bin-end", `${nulPad}${GH}\u0000\u0000`); + const x = await shRead(ctx, [token, { offset: nulBytes - 10, length: 20 }]); + assertNoLeak(answered(x, "binary ends inside"), GH, "binary ends inside"); +}); + +// --- the regression pin: a range that holds the whole token still reads as the marker --- + +test("a range that holds the whole token reads as [a GitHub token], and says it scrubbed", T, async () => { + const { text, at } = onALine(GH); + const { ctx, token } = await started("run-gh-whole", text); + const x = await shRead(ctx, [token, { offset: at - NL.length, length: GH.length + 2 * NL.length }]); + assert.ok("ok" in x, `the whole token is answered, not refused: ${JSON.stringify(x).slice(0, 300)}`); + assert.ok(x.ok.text.includes(MARK), `the whole token is replaced: ${JSON.stringify(x.ok.text)}`); + assertNoLeak(x.ok.text, GH, "whole"); +}); + +// --- the fine-grained shape --- + +test("a range that starts inside an unregistered github_pat_ token does not hand back its body", T, async () => { + const { text, at } = onALine(PAT); + const { ctx, token } = await started("run-pat-start", text); + const x = await shRead(ctx, [token, { offset: at + 15, length: 30 }]); + assertNoLeak(answered(x, "pat starts inside"), PAT, "pat starts inside"); +}); + +// --- two ranges that split the token between them --- + +test("two ranges that split a token in half leak neither half", T, async () => { + const { text, at } = onALine(GH); + const { ctx, token } = await started("run-gh-split", text); + const left = await shRead(ctx, [token, { offset: at + 4, length: 18 }]); + const right = await shRead(ctx, [token, { offset: at + 22, length: 18 }]); + for (const [x, side] of [[left, "left"], [right, "right"]]) { + assertNoLeak(answered(x, side), GH, side); + } +}); From 4f033e8f8e33e144fc698067ddf8f0157e7f709b Mon Sep 17 00:00:00 2001 From: Shane B Date: Tue, 1 Dec 2026 19:13:33 +0100 Subject: [PATCH 2/4] fix(security): an ml.sh.read range that cuts a GitHub token is scrubbed by its shape, text and bytes alike The range scrub matched registered forms only and widened by the longest of them, so a range cut inside an unregistered ghp_/github_pat_ token handed back its part, and a binary range never met the shape rule. margin() now floors at the longest token (266), scrubRange matches the token's shape over the window, and a token counts in `scrubbed`. Co-Authored-By: Claude Opus 5.5 --- docs/dev/site-access.md | 5 +++-- docs/spec/SECRET_HANDLES.md | 17 +++++++++++------ src/secret-registry.ts | 25 ++++++++++++++++--------- src/secret-scrub.ts | 3 +++ src/sw/sw-shell-call.ts | 11 +++++------ tests/secret-registry.test.mjs | 9 ++++++--- tests/secret-scrub-crossings.test.mjs | 18 ++++++++++++++++++ 7 files changed, 62 insertions(+), 26 deletions(-) diff --git a/docs/dev/site-access.md b/docs/dev/site-access.md index 1b56e5b23..f40b8b1be 100644 --- a/docs/dev/site-access.md +++ b/docs/dev/site-access.md @@ -40,8 +40,9 @@ handler's answer and is left alone), and `forModel` on every step result a worke once in the shared loop after the step settles (`forModel` in `agent-loop.ts`: a tool's answer, a read-only try, a precheck, a dispatch that threw, a denial), which records the raw text in the execution log's `key` (`tool`/`scrubbed`). Extension pages (the popup, the DevTools panel, Settings) are answered unscrubbed: they are where a person diagnoses a wrong URL. `SET_MODEL`'s unknown-model error lists only the models the filter allows. -The forms (`secretsOf`): the URL, its origin, host and host name (as typed and as parsed, any letter case; not a dotless -or loopback name such as `ollama` or `localhost`, which are ordinary words), each also JSON-escaped and percent-encoded; +The forms (`secretsOf`): the URL, its origin, host and host name (as typed and as parsed, any letter case; a host with a +port always, while a name without one is skipped when it is dotless or loopback, such as `ollama` or `localhost`, which +are ordinary words), each also JSON-escaped and percent-encoded; the key only from 12 characters (a shorter one is a placeholder like `ollama`); the filter in its error form `(/re/)`, and bare only when it holds a regex character other than `.` (else it is a model's name). A quoted backend body is cut clear of a secret (`clipClear`), never through it. Every key ending in `error` is scrubbed (`transportError` too). The diff --git a/docs/spec/SECRET_HANDLES.md b/docs/spec/SECRET_HANDLES.md index dd310566e..40e2a0660 100644 --- a/docs/spec/SECRET_HANDLES.md +++ b/docs/spec/SECRET_HANDLES.md @@ -24,7 +24,7 @@ characters, matched as written and in its JSON, percent, base64 and shell forms) | A session row leaving the worker (lists, search, the hub, the HUD) | `[REDACTED:]` | built (ruling 61) | | Bytes read from `/files` (`ml.fs`, Python's mount) | each byte of a match is `*`, so sizes and offsets hold | built; the per-secret fake value and the write-back (rulings 100, 101) are not | | A file's NAME under `/files` that holds a registered value | the listing shows the raw name; the file block of the turn shows it redacted | a defect (the session-store lane's account, 2026-11-24), repaired in the reader | -| A GitHub token, registered or not | `[a GitHub token]`, by its shape | built, the one pattern there is | +| A GitHub token, registered or not | `[a GitHub token]`, by its shape, an `ml.sh.read` range that cuts it included | built, the one pattern there is; a live output's stream shows an unregistered one until the step settles ("Known limits") | | Any other unregistered key shape (`sk-`, `AKIA`, a JWT, a PEM block, URL userinfo) | the value | not built (scrub PR 2; ruling 39's detector for the person's input) | | A value in a password field of a page | the value | ruled (30), not built | | A value of a hidden file that a program the person allowed prints | the value, unless it is registered | open design ("Open questions", below) | @@ -267,10 +267,12 @@ on real captured output in its PR. - **The host does not scrub.** A process's held output stays its raw bytes, so a registered value can pass between the stages of a pipe on the host (an OS pipe, which never crosses into the worker); it is scrubbed before any script or model reads it. `done`'s `sha256` and `size` are over the raw bytes. A scrubbed read says so: a text range comes - back with its matches replaced, a binary range as scrubbed bytes with `scrubbed: `, and either may be shorter or - longer than `length`. -- **A cut never lets a prefix through.** A read range is fetched with a margin of the longest registered form on each - side and scrubbed whole, and a match that overlaps the range is replaced where it overlaps. A head whose last bytes + back with its matches replaced, a binary range as scrubbed bytes with `scrubbed: ` (registered matches and GitHub + tokens alike), and either may be shorter or longer than `length`. +- **A cut never lets a prefix through.** A read range is fetched with a margin of the longest registered form, and + never less than the longest GitHub token (266 characters), on each side and scrubbed whole, and a match that overlaps + the range is replaced where it overlaps: a registered form, or a GitHub token matched by its shape. A head whose + last bytes are the start of a registered form is cut before them, and its `complete` is false. - **The registry**, by name and value, is `ml_secret_registry` in `chrome.storage.local` (never sync), declared in the state registry beside its store. It is class secret under [`MODEL_SETTINGS.md`](MODEL_SETTINGS.md) ("Not settings, @@ -295,7 +297,10 @@ on real captured output in its PR. `1 secret redacted (PLUG_PASSWORD)`, names and a count, never a value. What the run stores and exports is what the model saw, so the sidebar (its live output included), the run log and both exports never hold a registered value that arrived after it was registered. -- **Known limits**: images; what the person or a page sends is scrubbed by registered value only (ruling 39, PR 1: the +- **Known limits**: `forLive` applies the registered forms only, so a GitHub token that is not registered shows in a + live output's stream until the step settles (the settled step, what is stored and what the model reads carry + `[a GitHub token]`); ruling 39's shape detector is where that is repaired; images; what the person or a page sends + is scrubbed by registered value only (ruling 39, PR 1: the turn's words, a right-clicked element, its files' text and the page context a run starts with, behind `scrubPersonInput`), so a token in it that is neither registered nor the extension's own key reaches the model until the shape detector (ruling 39, PR 3); a value that was transformed or only partly echoed (threat 2); a value diff --git a/src/secret-registry.ts b/src/secret-registry.ts index af8ea593d..27f1e19e2 100644 --- a/src/secret-registry.ts +++ b/src/secret-registry.ts @@ -1,6 +1,6 @@ // secret-registry.ts — the values the person registered as secret (a name and a value each) and the pure matching over them: the forms a value is written in, the scrub of a text, of bytes and of a read range, and how much of a cut text's end to hold back. -import type { SecretSub } from "./secret-scrub"; +import { GITHUB_TOKEN, GITHUB_TOKEN_MAX, GITHUB_TOKEN_PUT, type SecretSub } from "./secret-scrub"; /** One registered secret: the NAME written into model-facing text in its place, and the value that is never shown. */ export interface RegistryEntry { name: string; value: string } @@ -259,12 +259,13 @@ export function heldTail(text: string, subs: readonly RegistrySub[]): number { } /** - * How far a read range must be widened on each side to see every match that overlaps it. + * How far a read range must be widened on each side to see every match that overlaps it: a registered form or a + * GitHub token, which `scrubRange` matches by shape. * @param subs from `registrySubs` - * @returns the longest form's length, 0 when there are none + * @returns the longest form's length, and never less than the longest GitHub token */ export function margin(subs: readonly RegistrySub[]): number { - return subs.reduce((n, s) => Math.max(n, s.find.length), 0); + return subs.reduce((n, s) => Math.max(n, s.find.length), GITHUB_TOKEN_MAX); } /** @@ -317,28 +318,34 @@ export function scrubBytes(bytes: Uint8Array, subs: readonly RegistrySub[]): { b /** * The slice [from, to) of a text fetched with a margin on both sides, scrubbed: matches are found in the whole window, * and one that overlaps the slice becomes its marker (once, its outside part dropped), so a cut never shows a prefix. + * A GitHub token is matched by its shape the same way (first, as `scrubSecrets` does) and counted apart, in `tokens`: + * it has no registered name. The window must be widened by `margin`, so a token the slice cuts is still whole in it. * @param window the fetched text * @param from the start of the wanted slice, in the window * @param to the end of the wanted slice, exclusive * @param subs from `registrySubs` - * @returns the slice and the counts of the matches that overlap it + * @returns the slice, the counts of the registered matches that overlap it, and how many GitHub tokens overlap it */ -export function scrubRange(window: string, from: number, to: number, subs: readonly RegistrySub[]): { text: string; counts: Record } { +export function scrubRange(window: string, from: number, to: number, subs: readonly RegistrySub[]): { text: string; counts: Record; tokens: number } { const lo = Math.max(0, from); const hi = Math.min(window.length, to); const counts: Record = {}; let out = ""; let pos = lo; - for (const h of findHits(window, subs)) { + let tokenCount = 0; + const tokens: Hit[] = [...window.matchAll(new RegExp(GITHUB_TOKEN))].map((m) => ({ start: m.index, end: m.index + m[0].length, put: GITHUB_TOKEN_PUT, name: "" })); + const free = (h: Hit): boolean => !tokens.some((t) => h.start < t.end && t.start < h.end); + const hits = [...tokens, ...findHits(window, subs).filter(free)].sort((a, b) => a.start - b.start); + for (const h of hits) { if (h.end <= lo) continue; if (h.start >= hi) break; if (h.start > pos) out += window.slice(pos, h.start); out += h.put; pos = Math.max(pos, h.end); - counts[h.name] = (counts[h.name] ?? 0) + 1; + if (h.name) counts[h.name] = (counts[h.name] ?? 0) + 1; else tokenCount++; } if (pos < hi) out += window.slice(pos, hi); - return { text: out, counts }; + return { text: out, counts, tokens: tokenCount }; } /** diff --git a/src/secret-scrub.ts b/src/secret-scrub.ts index e8f259425..ada94f01f 100644 --- a/src/secret-scrub.ts +++ b/src/secret-scrub.ts @@ -25,6 +25,9 @@ export const GITHUB_TOKEN = /\b(?:gh[pousr]_[A-Za-z0-9]{36,255}|github_pat_[A-Za /** What stands in for one. */ export const GITHUB_TOKEN_PUT = "[a GitHub token]"; +/** The longest text `GITHUB_TOKEN` matches: `github_pat_` and 255 characters. */ +export const GITHUB_TOKEN_MAX = 266; + /** Shorter than this, an API key is a placeholder (`ollama`, `EMPTY`, `sk-1234`) and also an ordinary word. */ const MIN_KEY = 12; diff --git a/src/sw/sw-shell-call.ts b/src/sw/sw-shell-call.ts index de8968019..f4b53ea79 100644 --- a/src/sw/sw-shell-call.ts +++ b/src/sw/sw-shell-call.ts @@ -719,9 +719,9 @@ export async function shRead(ctx: ShCallContext, args: readonly unknown[]): Prom if (h.client !== x.client) { forgetClient(x.client); return refuse("Refused", `${ref}: the process host restarted, and the output went with it`); } await registryReady(); const subs = registrySubsNow(); - // Widened by the longest registered form on each side, so a value the range cuts is still seen whole and - // replaced where it overlaps (SECRET_HANDLES.md, "A cut never lets a prefix through"); the range shrinks to keep - // the widened read inside the host's cap. + // Widened by the longest registered form or GitHub token on each side, so a value the range cuts is still seen + // whole and replaced where it overlaps (SECRET_HANDLES.md, "A cut never lets a prefix through"); the range + // shrinks to keep the widened read inside the host's cap. const m = margin(subs), want = Math.min(length, SH_READ_MAX - 2 * m); const lo = Math.max(0, offset - m); const r = await h.client.read(x.ptr, lo, want + (offset - lo) + m); @@ -730,10 +730,9 @@ export async function shRead(ctx: ShCallContext, args: readonly unknown[]): Prom const eof = r.eof && offset - lo + want >= win.length; const base = { offset, length: bytes.length, size: r.size, eof }; if (binaryKind(bytes)) { - if (!m) return { ok: { ...base, bytes: r.data } }; const sc = scrubRange(latin1(win), offset - lo, offset - lo + bytes.length, bytewise(subs)); noteInnerCuts(ctx, sc.counts); - const n = Object.values(sc.counts).reduce((a, b) => a + b, 0); + const n = Object.values(sc.counts).reduce((a, b) => a + b, 0) + sc.tokens; const out = Uint8Array.from(sc.text, (c) => c.charCodeAt(0)); return { ok: { ...base, bytes: { $bytes: base64Of(out) }, ...(n ? { scrubbed: n } : {}) } }; } @@ -748,7 +747,7 @@ export async function shRead(ctx: ShCallContext, args: readonly unknown[]): Prom while (cont(b)) b++; const from = dec(win.subarray(0, a)).length, to = dec(win.subarray(0, b)).length; const sc = scrubRange(dec(win), from, to, subs); - const n = Object.values(sc.counts).reduce((a, b) => a + b, 0); + const n = Object.values(sc.counts).reduce((a, b) => a + b, 0) + sc.tokens; const m2 = await forModel(sc.text); noteInnerCuts(ctx, addCounts(sc.counts, m2.counts)); return { ok: { ...base, text: m2.text, ...(n ? { scrubbed: n } : {}) } }; diff --git a/tests/secret-registry.test.mjs b/tests/secret-registry.test.mjs index 94b3aff05..e6e1d1f90 100644 --- a/tests/secret-registry.test.mjs +++ b/tests/secret-registry.test.mjs @@ -169,9 +169,12 @@ test("heldTail: a full value at the end is a match, not a prefix; none holds not assert.equal(heldTail("abc", []), 0); }); -test("margin: the longest form, 0 for none", () => { - assert.equal(margin([]), 0); - assert.equal(margin(SUBS), Math.max(...SUBS.map((s) => s.find.length))); +test("margin: the longest form, and never less than the longest GitHub token (266), which scrubRange matches by shape", () => { + assert.equal(margin([]), 266, "nothing registered still widens enough to see a cut token whole"); + assert.ok(Math.max(...SUBS.map((s) => s.find.length)) < 266); + assert.equal(margin(SUBS), 266); + const long = subsOf(e("LONG", "x".repeat(400))); + assert.equal(margin(long), Math.max(...long.map((s) => s.find.length)), "a registered form longer than a token sets it"); }); // --- raw bytes --- diff --git a/tests/secret-scrub-crossings.test.mjs b/tests/secret-scrub-crossings.test.mjs index c30f717e2..499bbcfd0 100644 --- a/tests/secret-scrub-crossings.test.mjs +++ b/tests/secret-scrub-crossings.test.mjs @@ -149,6 +149,24 @@ test("a binary read range comes back as scrubbed bytes with scrubbed: n", T, asy assert.equal(x.ok.scrubbed, 1); }); +test("a binary read range holding an unregistered GitHub token reads [a GitHub token] in its bytes, and counts it in scrubbed", T, async () => { + const pad = "\u0000\u0001\u0002".repeat(SH_HEAD_BYTES / 3 + 50); + const gh = `ghp_${"Ab3dEf6hIj".repeat(4).slice(0, 36)}`; + hostPrinting(`${pad}${gh}\u0000\u0000${"\u0003".repeat(64)}`); + const ctx = ctxFor("run-bin-token"); + const r = await shRun(ctx, [["ls"], { expectMs: 5000 }]); + const x = await shRead(ctx, [r.ok.stdout.token, { offset: Buffer.byteLength(pad) - 4, length: gh.length + 8 }]); + assert.ok("ok" in x && x.ok.bytes, JSON.stringify(x).slice(0, 200)); + const got = Buffer.from(x.ok.bytes.$bytes, "base64").toString("latin1"); + assert.equal(got, `${pad.slice(-4)}[a GitHub token]\u0000\u0000\u0003\u0003`, "the token's bytes become the marker's, the rest as read"); + assert.equal(x.ok.scrubbed, 1, "the bytes were changed, so the answer says so"); + assert.equal(x.ok.length, gh.length + 8, "length stays the raw range's byte count"); + // A binary range with no match is the bytes as read, and says nothing. + const clean = await shRead(ctx, [r.ok.stdout.token, { offset: 0, length: 12 }]); + assert.equal(Buffer.from(clean.ok.bytes.$bytes, "base64").toString("latin1"), pad.slice(0, 12)); + assert.equal(clean.ok.scrubbed, undefined); +}); + // --- a live output's view (streamOutput), per delta --- test("forLive scrubs the text so far and holds back a tail that begins a value, at every delta", () => { From 308a1dee31a8675f9efb14c8a2942a9df1bf6b3b Mon Sep 17 00:00:00 2001 From: Shane B Date: Tue, 1 Dec 2026 19:50:13 +0100 Subject: [PATCH 3/4] test(security): a cut ml.sh head must not end in the front of an unregistered GitHub token's body Fails on 4a1bbffd: scrubbedHead holds back the start of a registered form only. Co-Authored-By: Claude Opus 5.5 --- tests/secret-scrub-crossings.test.mjs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/secret-scrub-crossings.test.mjs b/tests/secret-scrub-crossings.test.mjs index b6092ccf1..80761ff29 100644 --- a/tests/secret-scrub-crossings.test.mjs +++ b/tests/secret-scrub-crossings.test.mjs @@ -101,6 +101,31 @@ test("a cut head whose last bytes begin a registered value holds them back, so n assert.match(r.ok.stdout.text, /… \[first \d+ of \d+ bytes\]$/); }); +test("a cut head whose last bytes begin an unregistered GitHub token holds them back, so no front of its body shows", T, async () => { + const body = "Ab3dEf6hIj".repeat(6); + for (const [prefix, n] of [["ghp_", 36], ["github_pat_", 40]]) { + // The head ends 30 characters into the token's body: short of the shape's minimum, so the shape alone never matches it. + const pad = `${"a".repeat(SH_HEAD_BYTES - prefix.length - 31)} `; + hostPrinting(`${pad}${prefix}${body.slice(0, n)} and more after it\n`); + const r = await shRun(ctxFor(`run-cut-${prefix}`), [["ls"], { expectMs: 5000 }]); + assert.ok("ok" in r); + assert.equal(r.ok.stdout.complete, false); + assert.ok(!r.ok.stdout.text.includes(prefix) && !r.ok.stdout.text.includes(body.slice(0, 8)), r.ok.stdout.text.slice(-80)); + assert.ok(r.ok.stdout.text.startsWith(pad), "only the token's front is held back"); + assert.match(r.ok.stdout.text, /… \[first \d+ of \d+ bytes\]$/); + } +}); + +test("a whole output that ends in a short ghp_ run reads as printed and is complete: nothing follows it, so it is no token's front", T, async () => { + // The model reads `token ghp_abc` as the program printed it: three characters cannot be a token (the shape needs 36), + // and with the whole output in the head no later read can join them to more. `complete` is true because it is. + hostPrinting("token ghp_abc"); + const r = await shRun(ctxFor("run-whole-short"), [["ls"], { expectMs: 5000 }]); + assert.ok("ok" in r); + assert.equal(r.ok.stdout.complete, true); + assert.equal(r.ok.stdout.text, "token ghp_abc"); +}); + // --- ml.sh.read: a range, widened by the margin --- test("a read range that cuts a registered value shows its marker, never a front or back of it, and says it scrubbed", T, async () => { From 326a0dffacf21af25ea615429a8a5376f91f10a1 Mon Sep 17 00:00:00 2001 From: Shane B Date: Tue, 1 Dec 2026 19:50:48 +0100 Subject: [PATCH 4/4] fix(security): a cut ml.sh head holds back the front of an unregistered GitHub token's body tokenTail, beside heldTail: a tail of gh?_ (or github_pat_) and a body short of the shape's minimum, 39 characters at most. scrubbedHead holds back the larger of the two; heldTail and forLive are unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/spec/SECRET_HANDLES.md | 3 ++- src/secret-registry.ts | 11 +++++++++++ src/sw/sw-shell-call.ts | 9 +++++---- tests/secret-registry.test.mjs | 16 +++++++++++++++- 4 files changed, 33 insertions(+), 6 deletions(-) diff --git a/docs/spec/SECRET_HANDLES.md b/docs/spec/SECRET_HANDLES.md index 9b1d9eca6..f6851319d 100644 --- a/docs/spec/SECRET_HANDLES.md +++ b/docs/spec/SECRET_HANDLES.md @@ -277,7 +277,8 @@ on real captured output in its PR. - **A cut never lets a prefix through.** A read range is fetched with a margin of the longest registered form, and never less than the longest GitHub token (266 characters), on each side and scrubbed whole, and a match that overlaps the range is replaced where it overlaps: a registered form, or a GitHub token matched by its shape. A head whose - last bytes are the start of a registered form is cut before them, and its `complete` is false. + last bytes are the start of a registered form or of a GitHub token's body is cut before them (for a token, at most + `ghp_` and 35 characters, 39 bytes), and its `complete` is false. - **The registry**, by name and value, is `ml_secret_registry` in `chrome.storage.local` (never sync), declared in the state registry beside its store. It is class secret under [`MODEL_SETTINGS.md`](MODEL_SETTINGS.md) ("Not settings, never writable"): never in `GET_CONFIG`, `ml.settings()` or an answer to any page-reachable message, never written by diff --git a/src/secret-registry.ts b/src/secret-registry.ts index 27f1e19e2..352dff9f3 100644 --- a/src/secret-registry.ts +++ b/src/secret-registry.ts @@ -258,6 +258,17 @@ export function heldTail(text: string, subs: readonly RegistrySub[]): number { return 0; } +/** + * How many characters at the end of a text to hold back because they begin a GitHub token's body: `GITHUB_TOKEN` + * needs 36 characters after `gh?_` (22 after `github_pat_`), so a cut inside a token's body leaves a front the shape + * never matches. A body already that long is a match, not a front; the most held is `ghp_` and 35 characters (39). + * @param text the text so far, already scrubbed + * @returns the length of the token front at the end, 0 when none + */ +export function tokenTail(text: string): number { + return /\b(?:gh[pousr]_[A-Za-z0-9]{0,35}|github_pat_[A-Za-z0-9_]{0,21})$/.exec(text)?.[0].length ?? 0; +} + /** * How far a read range must be widened on each side to see every match that overlaps it: a registered form or a * GitHub token, which `scrubRange` matches by shape. diff --git a/src/sw/sw-shell-call.ts b/src/sw/sw-shell-call.ts index f4b53ea79..b0f74c33f 100644 --- a/src/sw/sw-shell-call.ts +++ b/src/sw/sw-shell-call.ts @@ -30,7 +30,7 @@ import { MAX_DETAIL_STRING } from "../log/housekeeping"; import { ASKED_TAIL_CHARS, PEEK_DEFAULT_BYTES, peekBytesFor, peekDetail } from "../shell/sh-tail"; import { forModel } from "./sw-scrub"; import { registryReady, registrySubsNow } from "./sw-secret-registry"; -import { cutsInJson, heldTail, margin, scrubRange, shiftCuts, type RedactionCut, type RegistrySub } from "../secret-registry"; +import { cutsInJson, heldTail, margin, scrubRange, shiftCuts, tokenTail, type RedactionCut, type RegistrySub } from "../secret-registry"; import { holdOutput, shellHost, ShellUnavailable, withShell, type ShellHost } from "./sw-shell"; import { hideRuleWords, spawnBound } from "./sw-spawn"; import { manifestsReady, storedManifests } from "./sw-manifests"; @@ -625,8 +625,9 @@ async function keep(ctx: ShCallContext, h: ShellHost, s: HostStream, f: ShFacts) /** * A stream's head as it crosses into the script: the config's and the registered secrets taken out (`forModel`), and, - * when the head is cut, any tail that begins a registered value held back, so the script never holds a secret or the - * front of one. The run's token store keeps this text, never the raw head. A binary head is a note, with nothing to take. + * when the head is cut, any tail that begins a registered value or a GitHub token's body held back, so the script never + * holds a secret or the front of one. The run's token store keeps this text, never the raw head. A binary head is a + * note, with nothing to take. * @param out the stream as `shOut` shaped it * @param head the head's bytes * @param size the stream's whole size @@ -641,7 +642,7 @@ async function scrubbedHead(out: ShOut, head: Uint8Array, size: number, counted: let text = s.text; let kept = text.length; if (!whole) { - kept = text.length - heldTail(text, registrySubsNow()); + kept = text.length - Math.max(heldTail(text, registrySubsNow()), tokenTail(text)); text = `${text.slice(0, kept)}… [first ${head.length} of ${size} bytes]`; } const scrubbed = { ...out, text }; diff --git a/tests/secret-registry.test.mjs b/tests/secret-registry.test.mjs index e6e1d1f90..8d7b60b5f 100644 --- a/tests/secret-registry.test.mjs +++ b/tests/secret-registry.test.mjs @@ -4,7 +4,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; const R = await import("../src/secret-registry.ts"); -const { entryRefusal, valueForms, registrySubs, scrubRegistry, redactedLine, heldTail, margin, scrubBytes, scrubRange } = R; +const { entryRefusal, valueForms, registrySubs, scrubRegistry, redactedLine, heldTail, tokenTail, margin, scrubBytes, scrubRange } = R; const e = (name, value) => ({ name, value }); const subsOf = (...entries) => registrySubs(entries); @@ -169,6 +169,20 @@ test("heldTail: a full value at the end is a match, not a prefix; none holds not assert.equal(heldTail("abc", []), 0); }); +test("tokenTail: a text ending in a GitHub token's prefix and a body short of the shape holds them; 39 at most", () => { + const body = "Ab3dEf6hIj".repeat(4); + assert.equal(tokenTail("x ghp_"), 4); + assert.equal(tokenTail(`x ghp_${body.slice(0, 35)}`), 39, "the worst case: one character short of a match"); + assert.equal(tokenTail(`x github_pat_${body.slice(0, 21)}`), 32); + assert.equal(tokenTail("x gho_ab"), 6); + // A body the shape already matches was replaced before this runs; one the shape cannot match is no token's front. + assert.equal(tokenTail(`x ghp_${body.slice(0, 36)}`), 0); + assert.equal(tokenTail("xghp_abc"), 0, "glued to a word, as GITHUB_TOKEN's \\b also refuses"); + assert.equal(tokenTail("x gh"), 0, "the prefix's own front shows nothing of a body"); + assert.equal(tokenTail("plain text"), 0); + assert.equal(tokenTail(""), 0); +}); + test("margin: the longest form, and never less than the longest GitHub token (266), which scrubRange matches by shape", () => { assert.equal(margin([]), 266, "nothing registered still widens enough to see a cut token whole"); assert.ok(Math.max(...SUBS.map((s) => s.find.length)) < 266);