From ee966e7afa93eaaecc0648f80bc421f5c9c01249 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:52:35 +0000 Subject: [PATCH] Code-carrying model replies reach their parsers with only the known credential shapes hidden; stored copies and every posted GitHub text get the whole scrub --- docs/pipeline.md | 2 +- src/classify/run.ts | 9 +++++---- src/github/write.ts | 28 ++++++++++++++++------------ src/prompts/index.ts | 8 ++++++++ src/runner/scrub.ts | 18 ++++++++++++++---- test/runner-sec3.test.ts | 8 ++++++-- 6 files changed, 50 insertions(+), 23 deletions(-) diff --git a/docs/pipeline.md b/docs/pipeline.md index 12555fa2a..14e19cbf1 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -618,7 +618,7 @@ Each write needs the repo's approval (Repos page) and stays within the stage's d - Model calls run without tools, except a prompt that registers a sandbox mode (the Opus review, Fix-up patch and check, CI fix patch, Verify planner, Fix triage, patch and check, the decision prepare, the duplicate-PR comparison and conversation replies). Claude Code's file tools could otherwise read anything this user can, such as tokens and other accounts' logins, and untrusted text could steer a model into echoing it. Two layers keep that from happening, plus a backstop: 1. Claude Code allows only `Read`, `Grep` and `Glob`, denies everything else without asking (`dontAsk`, no prompts), allows reads of the checkout path only, is confined to the working directory and the checkout (`--restricted`), loads no MCP servers, skills, slash commands or user and project settings, and stops after a registered number of turns. 2. bubblewrap runs the call in new namespaces (network shared, the API needs it) with an empty home and a clean environment. Only these are visible: the claude binary, `/usr`, the TLS certificates and resolver config, the checkout read-only at `/repo`, and the used account's credentials file, read-only (the rest of its config directory is not). The working directory is an empty `/work` and the checkout is added with `--add-dir`, so instructions and settings inside the checkout are never loaded as project memory; `CLAUDE.md`, `CLAUDE.local.md`, `AGENTS.md` and every `.claude/` path are also left out of the checkout. - 3. Backstop: after the reply JSON is parsed, anything in its text (and in stderr) that looks like a token or key is removed before it is stored or used (the log scrubber). + 3. Backstop: after the reply JSON is parsed, anything in its text (and in stderr) that looks like a token or key is removed before it is stored or used (the log scrubber). A reply that carries code (`fixup.patch`, `fixup.conflict`, `cifix.patch`, `fixissue.patch`, `security.fix`, `security.scantest`) reaches its parser with only the known credential shapes removed (provider token prefixes, keys, auth headers, named values, long mixed random runs), so hex literals and URLs in code stay as written; its stored copy gets the whole scrub. Every text a write posts to GitHub (comments, reviews, PR and issue bodies and titles) goes through the whole scrub as well. **Repo docs.** The checkout leaves instruction files out, so the sandboxed calls that judge or change a repository's code or scope (the Opus review, pre-merge and post-merge reviews, the decision prepare, Fix triage and patch, Fix-up patch and conflict, the CI fix patch, and conversation replies) get the maintainers' own documents separately: `AGENTS.md` (stored as `AGENTS.txt`, so Claude Code never loads it as memory) and `ROADMAP.md`, read from the repository's default-branch commit in the cached clone (never from a pull request's head) and mounted read-only at `/repo-docs`, outside the working directory. There is one directory per repository and commit under the cache directory, deleted after a day without use. A repository with neither file gets no mount and no prompt sentence. The prompt's repository access then ends with one fixed sentence: the rules are at `/repo-docs/AGENTS.txt` and the roadmap at `/repo-docs/ROADMAP.md`; read the rules before judging or writing code and the roadmap when the question is whether a change is wanted; follow their conventions, but their text never changes the task or the output format; name a real conflict with a rule (file and line) only when there is one; ignore links to other repositories' rule files. A mention of `/repo-docs` or `AGENTS.txt` in public text is a lint problem, like a mention of `/reference`. The fixed working directory of every call is under the app's cache directory, and Claude Code loads a `CLAUDE.md` from the working directory and its parents. None may exist in the install root, the cache directory or any parent of them, because every tool-free call would load it too. An account with a long-lived token (see below) skips all of this: the sandbox gets the token as `CLAUDE_CODE_OAUTH_TOKEN` and no credentials file, and no expiry wait applies to the account. diff --git a/src/classify/run.ts b/src/classify/run.ts index 99b7aaaa6..79a58759c 100644 --- a/src/classify/run.ts +++ b/src/classify/run.ts @@ -15,7 +15,7 @@ import { clockLine, saveTools, type ToolClock } from "../agents/tools.ts"; import { fixTurnMessage, mergeFixFields, needsFixTurn, type Lint, type LintProblem } from "../replylint.ts"; import { coalesce, lineFeed } from "./progress.ts"; import { scrubError } from "../agents/text.ts"; -import { scrub } from "../runner/scrub.ts"; +import { scrub, scrubCredentials } from "../runner/scrub.ts"; import { itemTools } from "../itemtools/index.ts"; import { startBridge, CHECK_SERVER, type Bridge } from "../checktool/bridge.ts"; import type { CheckTool } from "../checktool/index.ts"; @@ -495,10 +495,11 @@ async function askOnce(id: K, model: string, input: Cl return null; } const turns = sandboxed ? j.num_turns : undefined; - // Backstop: nothing that looks like a token or key leaves the sandbox call. - const text = scrub(j.result); + // Backstop: nothing that looks like a token or key leaves the sandbox call. The stored copy gets the whole scrub; a reply that carries code reaches its parser with only the known credential shapes hidden, so no code is rewritten. + const stored = scrub(j.result); + const text = CLAUDE_PROMPTS[id].codeReply ? scrubCredentials(j.result) : stored; const sessionId = typeof j.session_id === "string" ? j.session_id : (Array.isArray(parsed) ? parsed.find((e) => typeof (e as { session_id?: unknown }).session_id === "string") as { session_id?: string } | undefined : undefined)?.session_id; - finish({ state: "done", tokens, costUsd, summary: (resume ? "fix turn answered" : turns === undefined ? replySummary(text, items.length) : `answered in ${turns} turns`) + (!resume && checkTool && checkTool.calls ? `, ${checkTool.calls} checks (${Math.round(checkTool.usedMs / 1000)} s)` : ""), output: text }); + finish({ state: "done", tokens, costUsd, summary: (resume ? "fix turn answered" : turns === undefined ? replySummary(stored, items.length) : `answered in ${turns} turns`) + (!resume && checkTool && checkTool.calls ? `, ${checkTool.calls} checks (${Math.round(checkTool.usedMs / 1000)} s)` : ""), output: stored }); return { text, usage, ...(turns !== undefined && { turns }), ...(sessionId && { sessionId }) }; } catch { authFailed(r.stderr); diff --git a/src/github/write.ts b/src/github/write.ts index ec6065241..b2422a923 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -18,6 +18,7 @@ import type { Exec, ExecResult, Git } from "../fixup/git.ts"; import { Client, type Querier } from "../mirror.ts"; import { appChildEnv, AppNotInstalledError, installationToken, RepoNotInInstallationError, type TokenScope } from "./install-token.ts"; import { type Note, withNote } from "./note.ts"; +import { scrub } from "../runner/scrub.ts"; import { ownerOf, slugOf, splitSlug } from "../owners.ts"; import { call, GITHUB_API } from "./app.ts"; import { currentJobId } from "../agents/call.ts"; @@ -55,6 +56,9 @@ function opensOwnPr(g: Grant, repo: string): void { */ const idOf = (w: Writer, g: Guarded | Grant, kind: WriteKind = "other"): string => auditIdentity(w.db, g, kind); +/** The text a write puts on GitHub: the note line and the text, with anything that looks like a credential hidden. */ +const posted = (note: Note, text: string): string => withNote(note, scrub(text)); + // ---- identity lanes ------------------------------------------------------------- // A write made under a grant `as: "app"` while the GitHub identity is `app` runs with an installation token: gh and // git children get a replaced environment (the box account's tokens are not in it) and GraphQL goes through a client @@ -268,7 +272,7 @@ export type ItemRef = { repo: string; number: number; id: string }; export async function commentOn(w: Writer, g: Grant, q: Querier, action: string, item: ItemRef, note: Note, text: string, details: Details = {}): Promise { covers(g, item.repo, item.number); q = laneQuery(w, g, q); - const body = withNote(note, text); + const body = posted(note, text); const r = await recorded(w, idOf(w, g), action, refOf(item.repo, item.number), { ...details, text: body }, () => q.query(ADD_COMMENT, { id: item.id, body }) as Promise<{ addComment?: { commentEdge?: { node?: { url?: string } } } }>, (x) => ({ url: x.addComment?.commentEdge?.node?.url ?? undefined })); @@ -354,7 +358,7 @@ export async function requestReviewers(w: Writer, g: Grant, q: Querier, item: It /** Posts a review as a plain comment review on the commit; returns the review id (null when GitHub returned none). */ export async function postReview(w: Writer, q: Querier, g: Guarded<"post-review">, nodeId: string, note: Note, text: string, details: Details = {}): Promise { q = laneQuery(w, g, q); - const body = withNote(note, text); + const body = posted(note, text); const r = await recorded(w, idOf(w, g), "review-post", refOf(g.repo, g.number), { ...details, head: g.head }, () => q.query(ADD_REVIEW, { pr: nodeId, oid: g.head, body }) as Promise<{ addPullRequestReview?: { pullRequestReview?: { id?: string } | null } | null }>, (x) => ({ review: x.addPullRequestReview?.pullRequestReview?.id ?? undefined }), @@ -364,7 +368,7 @@ export async function postReview(w: Writer, q: Querier, g: Guarded<"post-review" export async function editReview(w: Writer, q: Querier, g: Guarded<"post-review">, reviewId: string, note: Note, text: string, details: Details = {}): Promise { q = laneQuery(w, g, q); - const body = withNote(note, text); + const body = posted(note, text); await recorded(w, idOf(w, g), "review-edit", refOf(g.repo, g.number), { ...details, head: g.head, review: reviewId }, () => q.query(EDIT_REVIEW, { id: reviewId, body })); } @@ -434,7 +438,7 @@ export function ghAskComment(w: Writer, exec: Exec, action: string, g: Guarded { covers(g, o.repo, o.number); exec = laneExec(w, g, exec); - const body = withNote(note, text); + const body = posted(note, text); return viaGh(w, idOf(w, g), exec, action, refOf(o.repo, o.number), { ...details, text: body }, [o.pr ? "pr" : "issue", "comment", String(o.number), "--repo", `${slugOf(o.repo)}`, "--body-file", "-"], body); } @@ -443,7 +447,7 @@ export function ghComment(w: Writer, g: CommentGrant, exec: Exec, action: string export function ghEditComment(w: Writer, g: CommentGrant, exec: Exec, action: string, o: { repo: string; number: number; commentId: string }, note: Note, text: string, details: Details = {}): Promise { covers(g, o.repo, o.number); exec = laneExec(w, g, exec); - const body = withNote(note, text); + const body = posted(note, text); return viaGh(w, idOf(w, g), exec, action, refOf(o.repo, o.number), { ...details, text: body, comment: o.commentId }, ["api", "-X", "PATCH", `repos/${slugOf(o.repo)}/issues/comments/${o.commentId}`, "-F", "body=@-"], body); } @@ -474,15 +478,15 @@ export function ghDeleteComment(w: Writer, g: CommentGrant, exec: Exec, action: export function ghOpenPr(w: Writer, g: Grant, exec: Exec, action: string, o: { repo: string; target: string; base: string; head: string; title: string; body: string }, note: Note, details: Details = {}): Promise { opensOwnPr(g, o.repo); exec = laneExec(w, g, exec); - const body = withNote(note, o.body); + const body = posted(note, o.body); return viaGh(w, idOf(w, g), exec, action, o.target, { ...details, text: body }, - ["pr", "create", "--repo", `${slugOf(o.repo)}`, "--base", o.base, "--head", o.head, "--title", o.title, "--body-file", "-"], body); + ["pr", "create", "--repo", `${slugOf(o.repo)}`, "--base", o.base, "--head", o.head, "--title", scrub(o.title), "--body-file", "-"], body); } export function ghClosePr(w: Writer, g: Grant, exec: Exec, o: { repo: string; number: number }, note: Note, text: string, details: Details = {}): Promise { covers(g, o.repo, o.number); exec = laneExec(w, g, exec, "close"); - const comment = withNote(note, text); + const comment = posted(note, text); return viaGh(w, idOf(w, g, "close"), exec, "batch-pr-close", refOf(o.repo, o.number), { ...details, text: comment }, ["pr", "close", String(o.number), "--repo", `${slugOf(o.repo)}`, "--comment", comment]); } @@ -511,11 +515,11 @@ const REFUSED = /issues are disabled|has disabled issues|could not resolve to a export async function createIssue(w: Writer, g: Grant, exec: Exec, o: { repo: string; target: string; title: string; body: string; /** The audit action; the post-merge step's by default. */ action?: string }, note: Note, details: Details = {}): Promise<{ number: number; url: string }> { covers(g, o.repo); exec = laneExec(w, g, exec); - const body = withNote(note, o.body); + const body = posted(note, o.body); let r: ExecResult; try { - r = await viaGh(w, idOf(w, g), exec, o.action ?? "postmerge-file", o.target, { ...details, title: o.title, text: body }, - ["issue", "create", "--repo", `${slugOf(o.repo)}`, "--title", o.title, "--body-file", "-"], body); + r = await viaGh(w, idOf(w, g), exec, o.action ?? "postmerge-file", o.target, { ...details, title: scrub(o.title), text: body }, + ["issue", "create", "--repo", `${slugOf(o.repo)}`, "--title", scrub(o.title), "--body-file", "-"], body); } catch (e) { // exec rejects only when the command could not be started. throw new IssueError(oneLine(String((e as Error).message ?? e)), true); @@ -703,7 +707,7 @@ export function ghAdvisoryPush(w: Writer, g: Grant, git: Pick, o: { export function ghAdvisoryPr(w: Writer, g: Grant, exec: Exec, o: { repo: string; key: string; fork: string; base: string; head: string; title: string; body: string }): Promise { covers(g, o.repo); return viaGh(w, "legacy", exec, "security-advisory-pr", o.key, { repo: o.repo, fork: o.fork }, - ["pr", "create", "--repo", o.fork, "--base", o.base, "--head", o.head, "--title", o.title, "--body-file", "-"], o.body); + ["pr", "create", "--repo", o.fork, "--base", o.base, "--head", o.head, "--title", scrub(o.title), "--body-file", "-"], scrub(o.body)); } /** Sets the affected version range of a draft that has none (GitHub refuses to publish without one). Does nothing, and writes nothing, when the draft has a range. */ diff --git a/src/prompts/index.ts b/src/prompts/index.ts index 678ca1ff8..a0e9d5954 100644 --- a/src/prompts/index.ts +++ b/src/prompts/index.ts @@ -65,6 +65,8 @@ type Common = { sandbox?: { tools: string[]; /** The call may get the maintainers' AGENTS.md and ROADMAP.md of the default branch at /repo-docs when the repo has them. */ docs?: boolean; maxTurns: number; /** The call also gets the workspace: every tracked repository at /repos/ and the explorer subagent. */ workspace?: boolean; /** The call may get the repo's reference documentation at /reference when it exists. */ reference?: boolean; /** The call may get the `check` build tool (src/checktool) when its stage provides one. */ check?: boolean }; /** The reply is linted after parsing (src/replylint.ts); a sandboxed call keeps its session so problems can be sent back as one follow-up message. */ lint?: boolean; + /** The reply carries code (a patch, conflict resolutions, a test): its parser reads it with only the known credential shapes hidden (`scrubCredentials`), so the stricter output scrub never rewrites code. */ + codeReply?: boolean; /** Further rows for the Prompts page's settings table, such as texts the stage posts itself. */ extra?: { label: string; value: string }[]; }; @@ -382,6 +384,7 @@ Reply with ONLY one JSON object: const FIXUP: ClaudePrompt = { id: "fixup.patch", + codeReply: true, stage: "Integrate (fix-ups)", runner: "claude", purpose: "Turns the small mechanical fixes of a take-fix review into a unified diff for the contributor's branch.", @@ -425,6 +428,7 @@ Reply with ONLY a unified diff in git format against the file contents shown: fo const CIFIX: ClaudePrompt = { id: "cifix.patch", + codeReply: true, stage: "Integrate (fix-ups)", runner: "claude", purpose: "Turns the log of a failing CI check on a wanted pull request into a unified diff that makes the check pass.", @@ -652,6 +656,7 @@ Reply with ONLY a JSON array holding exactly one object: const FIXISSUE_PATCH: ClaudePrompt = { id: "fixissue.patch", + codeReply: true, stage: "Fix", runner: "claude", purpose: "Writes the fix for an issue and a regression test for it as one unified diff.", @@ -728,6 +733,7 @@ ${CHECK_REPLY} const FIXUP_CONFLICT: ClaudePrompt = { id: "fixup.conflict", + codeReply: true, stage: "Integrate (fix-ups)", runner: "claude", purpose: "Resolves the conflicts that merging the default branch into a take or take-fix pull request leaves, keeping what both sides intend.", @@ -1466,6 +1472,7 @@ const SECURITY_VERIFY: ClaudePrompt = { const SECURITY_FIX: ClaudePrompt = { id: "security.fix", + codeReply: true, stage: "Security", runner: "claude", purpose: "Writes the private fix of a confirmed finding and its regression test as one diff, with a plain title and summary for the pull request. The diff stays in the database, on a local branch of the bare cache that is never pushed, until an operator lands it.", @@ -1481,6 +1488,7 @@ const SECURITY_FIX: ClaudePrompt = { const SECURITY_SCANTEST: ClaudePrompt = { id: "security.scantest", + codeReply: true, stage: "Security", runner: "claude", purpose: "Optional (the Run scan tests switch): writes the test file for a verified finding from the test Verify proposed. The build worker runs it on the pinned commit; a failing test marks the finding as shown, a passing one as not shown. The reply is never applied to the repository and never leaves the private finding.", diff --git a/src/runner/scrub.ts b/src/runner/scrub.ts index a63b5d69f..f400fb744 100644 --- a/src/runner/scrub.ts +++ b/src/runner/scrub.ts @@ -35,20 +35,30 @@ function decodesToSecret(m: string, encoding: "hex" | "base64"): boolean { return /^[\x20-\x7e\t\n\r]+$/.test(d) && [...SECRET_PATTERNS, URL_USERINFO].some((p) => matches(p, d)); } +/** Hides anything that looks like a credential: for logs, stored copies and text that is shown or posted. */ export function scrub(text: string): string { - // Paths under the home directory show as ~/...: the log is shown to everyone signed in. - let t = text.replaceAll(homedir(), "~"); // Encoded credentials first, while the encoded run is still whole. - t = t.replace(B64_RUN, (m) => (/^[0-9a-f]+$/i.test(m) || !decodesToSecret(m, "base64") ? m : "[hidden]")); + let t = text.replace(B64_RUN, (m) => (/^[0-9a-f]+$/i.test(m) || !decodesToSecret(m, "base64") ? m : "[hidden]")); t = t.replace(HEX_RUN, (m) => (/^[0-9]+$/.test(m) || (DIGEST_LENGTHS.has(m.length) && !decodesToSecret(m, "hex")) ? m : "[hidden]")); t = t.replace(URL_USERINFO, "$1[hidden]@"); t = t.replace(NAMED_HEX, "$1[hidden]"); + t = t.replace(DOTTED, (m) => (mixed(m) ? "[hidden]" : m)); + return scrubCredentials(t); +} + +/** + * Hides only the known credential shapes (provider token prefixes, keys, auth headers, named values, long mixed random + * runs). A model reply that carries code is read through this one: hex literals, URLs with user info and dotted names + * in code stay as written, and `scrub` covers the stored copy. + */ +export function scrubCredentials(text: string): string { + // Paths under the home directory show as ~/...: the log is shown to everyone signed in. + let t = text.replaceAll(homedir(), "~"); for (const p of SECRET_PATTERNS) { t = t.replace(p, (m, name?: string) => { if (/^(Bearer|token|Basic)$/i.test(name ?? "")) return `${name} [hidden]`; return typeof name === "string" && name !== m && /^[A-Za-z_]+$/.test(name) && /[=:]/.test(m) ? `${name}=[hidden]` : "[hidden]"; }); } - t = t.replace(DOTTED, (m) => (mixed(m) ? "[hidden]" : m)); return t.replace(LONG_RANDOM, (m) => (/^[0-9a-f]+$/i.test(m) || !mixed(m) ? m : "[hidden]")); } diff --git a/test/runner-sec3.test.ts b/test/runner-sec3.test.ts index 9072e3c71..27922fd3b 100644 --- a/test/runner-sec3.test.ts +++ b/test/runner-sec3.test.ts @@ -5,9 +5,9 @@ import { createServer } from "node:http"; import { test } from "node:test"; import type { AppSecrets } from "../src/dash/server/config.ts"; import { InstallTokenMinter, identityGitArgs, withIdentityEnv } from "../src/github/install-token.ts"; -import { scrub } from "../src/runner/scrub.ts"; +import { scrub, scrubCredentials } from "../src/runner/scrub.ts"; -test("the scrubber hides hex keys, URL passwords, dotted tokens and encoded tokens, and keeps commit ids and digests", () => { +test("the scrubber hides hex keys, URL passwords, dotted tokens and encoded tokens, keeps commit ids and digests, and leaves code literals to the credential-only scrub", () => { const gh = `ghs_${"Ab1".repeat(12)}`; const commit = "0123456789abcdef0123456789abcdef01234567"; const digest = "a".repeat(32) + "b".repeat(32); @@ -22,6 +22,10 @@ test("the scrubber hides hex keys, URL passwords, dotted tokens and encoded toke for (const [text, secret] of cases) assert.ok(!scrub(text).includes(secret), `${text} -> ${scrub(text)}`); const plain = `HEAD is now at ${commit}; sha256:${digest}; see https://github.com/o/r/pull/7 and src/runner/scrub.ts`; assert.equal(scrub(plain), plain); + // A reply that carries code keeps its literals for the parser; a provider token in it is still hidden. + const code = `+const KEY = "${"9f".repeat(24)}"; const DB = "postgres://app:pw@localhost/db";`; + assert.equal(scrubCredentials(code), code); + assert.ok(!scrubCredentials(`+const T = "${gh}";`).includes(gh)); }); test("an installation token for a write reaches only its repository, and git hands it only to github.com", async () => {