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 a38e733a5..b3eb4a50e 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) | an occurrence of a registered value reads as its session fake, every other byte of a match as `*`, so sizes and offsets hold; a fake or marker written back to its own file is restored | built (#2205, rulings 100 and 101) | | A file's NAME under `/files` that holds a registered value | the listing shows it with its registered values masked, as the file block of the turn does, and a shown name opens its file | built (#2166) | -| A GitHub token, registered or not | `[a GitHub token]`, by its shape, in what crosses `scrubSecrets` (a tool result and an error bound for the model or a page, the stored render the sidebar and both exports draw) and in a file's name under `/files` (`maskName`); a file's bytes read from `/files` show it as `*`, and a live output's view (`forLive`) shows it until the step settles. Not in what the person or a page sends (the turn, its files' text, the page context, a page's own model request) until ruling 39's detector: "Known limits" below | built for those paths, the one pattern there is | +| A GitHub token, registered or not | `[a GitHub token]`, by its shape, in what crosses `scrubSecrets` (a tool result and an error bound for the model or a page, the stored render the sidebar and both exports draw), an `ml.sh.read` range that cuts it included, and in a file's name under `/files` (`maskName`); a file's bytes read from `/files` show it as `*`, and a live output's view (`forLive`) shows it until the step settles. Not in what the person or a page sends (the turn, its files' text, the page context, a page's own model request) until ruling 39's detector: "Known limits" below | built for those paths, the one pattern there is | | 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) | @@ -272,11 +272,13 @@ 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 - are the start of a registered form is cut before them, and its `complete` is false. + 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 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 @@ -300,7 +302,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..352dff9f3 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,24 @@ 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 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. * @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 +329,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 2bca2b907..55806db93 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..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 }; @@ -719,9 +720,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 +731,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 +748,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/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); + } +}); diff --git a/tests/secret-registry.test.mjs b/tests/secret-registry.test.mjs index 94b3aff05..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,9 +169,26 @@ 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("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); + 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 37662e4aa..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 () => { @@ -149,6 +174,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", () => {