Skip to content

Commit 845f31a

Browse files
fix(review): refuse credential files by the path actually read
- Verifier `readFile`/`compiledSql` check a renamed file's old path on the old side, so `git mv profiles.yml profiles.yml.example` no longer exposes the base content (engine old SQL included) - `safeReadInside` refuses a symlink whose resolved target is a credential file, closing working-tree reads like `docs/link.md -> ../profiles.yml` - Credential name list moves to `credentials.ts` and covers `.envrc`, `.env-*`, `*.env`, `.npmrc`, `.pypirc`, `.git-credentials`, `keyfile*.json`, `*service*account*.json`, `credentials*.json`, `*.p8`, `*.tfvars.json` - `holdsCredentials` screens read content for private keys and service-account JSON; the verifier and the AI lane's supporting files refuse it - `grepFixedAt` uses `git grep -z`, so non-ASCII paths come back unquoted and the credential filter matches them - Remove the blank line before `exclusionReason`; direct tests for `packageDocNames` Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 8f019b5 commit 845f31a

7 files changed

Lines changed: 286 additions & 19 deletions

File tree

‎packages/opencode/src/altimate/review/ai-verify.ts‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,13 @@ import type { Finding } from "./finding"
1919
import { type AiReviewFile, type AiTokens, type BatchUsage, addUsage, aiTimeoutMs, streamUsage } from "./ai-review"
2020
import { type ReviewRunner, scanDiffLines, walkDiffLines } from "./orchestrate"
2121
import { readStreamStep, type StepToolCall } from "../llm/stream-text"
22+
import { isCredentialPath } from "./credentials"
2223

2324
const log = Log.create({ service: "ai-verify" })
2425

25-
// Connection profiles, env files, key material and Terraform variables hold credentials: never sent to a model.
26-
const CREDENTIAL_FILE =
27-
/(^|\/)(profiles\.ya?ml|\.env(\.[^/]*)?|\.netrc|\.pgpass|id_(rsa|dsa|ecdsa|ed25519)|[^/]+\.(pem|key|p12|pfx|tfvars))$/i
28-
29-
/** A path whose content may hold credentials; the AI lane and the verifier never read or show it. */
30-
export function isCredentialPath(path: string): boolean {
31-
return CREDENTIAL_FILE.test(path)
32-
}
26+
// Credential files are refused by name (the requested path, a renamed file's old path, a
27+
// working-tree symlink's target) and by content (private keys, service-account keys).
28+
export { holdsCredentials, isCredentialPath } from "./credentials"
3329

3430
/** What the verifier may read: the PR's files, the engine, and the dbt project. */
3531
export interface AiVerifyEvidence {
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Connection profiles, env files, package-registry and git credential stores, cloud
2+
// service-account keys, key material and Terraform variables. Matched on the file name.
3+
const CREDENTIAL_FILE = new RegExp(
4+
"(^|/)(" +
5+
[
6+
"profiles\\.ya?ml",
7+
"\\.env[^/]*", // .env, .env.local, .env-prod, .envrc
8+
"[^/]+\\.env", // prod.env
9+
"\\.netrc",
10+
"\\.pgpass",
11+
"\\.npmrc",
12+
"\\.pypirc",
13+
"\\.git-credentials",
14+
"id_(rsa|dsa|ecdsa|ed25519)",
15+
"keyfile[^/]*\\.json",
16+
"[^/]*service[^/]*account[^/]*\\.json",
17+
"credentials[^/]*\\.json",
18+
"[^/]+\\.(pem|key|p12|pfx|p8|tfvars|tfvars\\.json)",
19+
].join("|") +
20+
")$",
21+
"i",
22+
)
23+
24+
/** A path whose name says it may hold credentials; the AI lane and the verifier never read or show it. */
25+
export function isCredentialPath(path: string): boolean {
26+
return CREDENTIAL_FILE.test(path)
27+
}
28+
29+
const CREDENTIAL_CONTENT = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----|"type"\s*:\s*"service_account"/
30+
31+
/** Text that carries a private key or a cloud service-account key, whatever the file is called. */
32+
export function holdsCredentials(text: string): boolean {
33+
return CREDENTIAL_CONTENT.test(text)
34+
}

‎packages/opencode/src/altimate/review/git.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { promisify } from "node:util"
33
import { promises as fs } from "node:fs"
44
import path from "node:path"
55
import type { ChangedFile } from "./diff-filter"
6+
import { isCredentialPath } from "./credentials"
67

78
/**
89
* Git helpers for the review pipeline. Produces the ChangedFile[] for a PR
@@ -95,7 +96,8 @@ export async function collectChangedFiles(opts: CollectOptions): Promise<Changed
9596
* Blocks the "tracked symlink escapes the root" class of attack — e.g. a
9697
* `models/evil.sql → /etc/passwd` symlink that would otherwise leak external
9798
* files into the review pipeline (coderabbit + cubic security review).
98-
* Returns undefined when the target escapes, is missing, or realpath fails.
99+
* Returns undefined when the target escapes, is a credential file (by its
100+
* resolved name), is missing, or realpath fails.
99101
*
100102
* Exported for the compiled-SQL resolver in compiled.ts so both content
101103
* paths go through the same containment check — cubic + kilo suggested
@@ -114,6 +116,9 @@ export async function safeReadInside(root: string, rel: string): Promise<string
114116
// startsWith check so `/repo-backup` doesn't count as inside `/repo`.
115117
const sep = path.sep
116118
if (targetReal !== rootReal && !targetReal.startsWith(rootReal + sep)) return undefined
119+
// Judge the file actually read: an in-repo symlink (`docs/link.md -> ../profiles.yml`)
120+
// must not reach a credential file the requested name doesn't show.
121+
if (isCredentialPath(path.relative(rootReal, targetReal).split(sep).join("/"))) return undefined
117122
return await fs.readFile(targetReal, "utf8")
118123
} catch {
119124
return undefined
@@ -220,7 +225,9 @@ export async function grepFixedAt(
220225
// No pathspec would search the whole repository.
221226
if (!pathspecs.length) return undefined
222227
const maxHits = opts.maxHits ?? 50
223-
const args = ["grep", "-n", "-I", "-F", "--full-name", "-m", String(maxHits), "-e", pattern, ...(ref ? [ref] : []), "--"]
228+
// -z: NUL after the path and line number, and paths unquoted (git otherwise
229+
// C-quotes non-ASCII names, `"models/caf\303\251/x.yml"`), so callers see canonical paths.
230+
const args = ["grep", "-z", "-n", "-I", "-F", "--full-name", "-m", String(maxHits), "-e", pattern, ...(ref ? [ref] : []), "--"]
224231
args.push(...pathspecs.map((p) => `:(top)${p}`))
225232
let out: string
226233
let failed = false
@@ -235,7 +242,7 @@ export async function grepFixedAt(
235242
const hits: Array<{ path: string; line: number; text: string }> = []
236243
for (const row of out.split("\n")) {
237244
const rest = ref && row.startsWith(ref + ":") ? row.slice(ref.length + 1) : row
238-
const m = /^(.+?):(\d+):(.*)$/.exec(rest)
245+
const m = /^([^\0]+)\0(\d+)\0(.*)$/.exec(rest)
239246
if (!m) continue
240247
hits.push({ path: m[1], line: Number(m[2]), text: m[3].slice(0, 300) })
241248
if (hits.length >= maxHits) break

‎packages/opencode/src/altimate/review/orchestrate.ts‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,8 @@ import {
6262
import { type AiContextFile, type AiLaneStatus, type AiReviewFile, type AiReviewInput, type AiReviewResult, aiInputBudget, safeReason, selectAiFiles, selectAiFilesByQuota } from "./ai-review"
6363
import { type MacroCard, type ModelCard, attachContextCards } from "./ai-context-card"
6464
import { ruleTier } from "./rule-tiers"
65-
import { type AiVerifyEvidence, isCredentialPath, numberedSlice } from "./ai-verify"
65+
import { type AiVerifyEvidence, numberedSlice } from "./ai-verify"
66+
import { holdsCredentials, isCredentialPath } from "./credentials"
6667
import type { ColumnReach } from "../native/dbt/column-reach"
6768

6869
const AI_SUPPORTING_KINDS = new Set(["macro", "test", "snapshot", "schema_yml", "source_yml", "seed", "project_config"])
@@ -2608,10 +2609,20 @@ export async function runReview(input: OrchestrateInput): Promise<VerdictEnvelop
26082609
// Macros, data tests, snapshots, yml and seeds carry defects no model diff shows.
26092610
// Seeds go as a diff only: the full CSV is data, not logic.
26102611
const supporting = reviewable.filter(
2611-
(f) => AI_SUPPORTING_KINDS.has(f.kind) && f.status !== "deleted" && !isCredentialPath(f.path),
2612+
(f) =>
2613+
AI_SUPPORTING_KINDS.has(f.kind) &&
2614+
f.status !== "deleted" &&
2615+
!isCredentialPath(f.path) &&
2616+
!(f.oldPath && isCredentialPath(f.oldPath)),
26122617
)
26132618
const contents = await Promise.all(
2614-
supporting.map((f) => (f.kind === "seed" ? undefined : getContent?.(f.path, "new")?.catch(() => undefined))),
2619+
supporting.map((f) =>
2620+
f.kind === "seed"
2621+
? undefined
2622+
: getContent?.(f.path, "new")
2623+
?.then((t) => (t && holdsCredentials(t) ? undefined : t))
2624+
.catch(() => undefined),
2625+
),
26152626
)
26162627
supporting.forEach((f, i) =>
26172628
aiFiles.push({ path: f.path, status: f.status, model: modelNameFromPath(f.path), kind: f.kind, diff: f.diff, sql: contents[i] }),
@@ -2626,6 +2637,11 @@ export async function runReview(input: OrchestrateInput): Promise<VerdictEnvelop
26262637
const prFiles = (input.prFiles ?? input.changedFiles.map((f) => f.path)).filter(
26272638
(p) => !isExcludedPath(p, input.rubric.exclusions.excludeGlobs) && !isCredentialPath(p),
26282639
)
2640+
// The verifier refuses a credential file by the path actually read: a renamed file's
2641+
// old side is read from its old path. Symlink targets are refused by safeReadInside.
2642+
const oldPathOf = new Map(input.changedFiles.flatMap((f) => (f.oldPath ? [[f.path, f.oldPath] as const] : [])))
2643+
const readPath = (p: string, side: "old" | "new") => (side === "old" ? (oldPathOf.get(p) ?? p) : p)
2644+
const REFUSED = "not available: may hold credentials"
26292645
// The verifier reads engine SQL first (the same SQL the engine lanes saw), then compiled output.
26302646
const evidence: AiVerifyEvidence | undefined = input.aiVerify
26312647
? {
@@ -2638,11 +2654,18 @@ export async function runReview(input: OrchestrateInput): Promise<VerdictEnvelop
26382654
prBody: input.prBody,
26392655
grepProject: input.grepProject,
26402656
prFiles,
2641-
readFile: async (p, side, start, end) => numberedSlice(await getContent?.(p, side), start, end),
2657+
readFile: async (p, side, start, end) => {
2658+
if (isCredentialPath(readPath(p, side))) return REFUSED
2659+
const text = await getContent?.(p, side)
2660+
return text && holdsCredentials(text) ? REFUSED : numberedSlice(text, start, end)
2661+
},
26422662
compiledSql: async (p, side) => {
26432663
const ctx = ctxByPath.get(p)
2664+
const from = side === "old" ? (ctx?.file.oldPath ?? readPath(p, side)) : p
2665+
if (isCredentialPath(from)) return undefined
26442666
const engine = side === "new" ? ctx?.engineNewSql : ctx?.engineOldSql
2645-
return engine ?? (await getCompiled?.(ctx?.file.oldPath && side === "old" ? ctx.file.oldPath : p, side))
2667+
const sql = engine ?? (await getCompiled?.(from, side))
2668+
return sql && holdsCredentials(sql) ? undefined : sql
26462669
},
26472670
}
26482671
: undefined

‎packages/opencode/src/altimate/review/rubric.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,6 @@ const PROJECT_BREAKING_RULES = new Set(["dbt-project-rules:yaml-parse-error", "d
7878
* be dropped, or null to keep it. Centralizing this here (vs prompt text) is
7979
* what keeps the false-positive rate down deterministically.
8080
*/
81-
8281
export function exclusionReason(finding: Finding, rubric: Rubric): string | null {
8382
const ex = rubric.exclusions
8483
const isStaging = /(^|\/)stg_|(^|\/)staging\//.test(finding.file) || finding.model?.startsWith("stg_")

‎packages/opencode/test/altimate/review-ai-verify.test.ts‎

Lines changed: 175 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
toolsChars,
1515
verifierTools,
1616
isCredentialPath,
17+
holdsCredentials,
1718
type AiVerifyEvidence,
1819
type VerifierLlm,
1920
type VerifierStep,
@@ -39,9 +40,9 @@ import type { AiReviewFile } from "../../src/altimate/review/ai-review"
3940
import { runAiReview } from "../../src/altimate/review/ai-review"
4041
import { createDispatcherRunner } from "../../src/altimate/review/runner"
4142
import { LLM } from "../../src/session/llm"
42-
import { mkdirSync, writeFileSync } from "fs"
43+
import { mkdirSync, symlinkSync, writeFileSync } from "fs"
4344
import { execFileSync } from "child_process"
44-
import { grepFixedAt, projectGrepSpecs } from "../../src/altimate/review/git"
45+
import { grepFixedAt, makeContentResolver, projectGrepSpecs } from "../../src/altimate/review/git"
4546
import path from "path"
4647
import { tmpdir } from "../fixture/fixture"
4748
import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate"
@@ -1138,6 +1139,178 @@ describe("runAiVerify: the bounded tool loop", () => {
11381139
})
11391140
})
11401141

1142+
describe("credential files: refused by name, by the path actually read, and by content", () => {
1143+
test.each([
1144+
"profiles.yml",
1145+
"config/Profiles.YAML",
1146+
".env",
1147+
"dbt/.env.local",
1148+
".envrc",
1149+
".env-prod",
1150+
"deploy/prod.env",
1151+
".netrc",
1152+
".pgpass",
1153+
".npmrc",
1154+
".pypirc",
1155+
".git-credentials",
1156+
"home/.ssh/id_ed25519",
1157+
"keyfile.json",
1158+
"secrets/keyfile-bq.json",
1159+
"gcp/my-service-account.json",
1160+
"gcp/service_account_key.json",
1161+
"credentials.json",
1162+
"aws/credentials-prod.json",
1163+
"certs/client.pem",
1164+
"tls/server.key",
1165+
"apple/AuthKey.p8",
1166+
"store.p12",
1167+
"infra/prod.tfvars",
1168+
"infra/terraform.tfvars.json",
1169+
])("%s is a credential path", (p) => expect(isCredentialPath(p)).toBe(true))
1170+
1171+
test.each([
1172+
"models/profiles_summary.sql",
1173+
"models/env.yml",
1174+
"models/environment.sql",
1175+
"models/accounts.json",
1176+
"macros/keys.sql",
1177+
"docs/credentials.md",
1178+
"seeds/service_accounts.csv",
1179+
])("%s is not a credential path", (p) => expect(isCredentialPath(p)).toBe(false))
1180+
1181+
test("content holding a private key or a service-account key is credentials, whatever the name", () => {
1182+
expect(holdsCredentials("x\n-----BEGIN RSA PRIVATE KEY-----\nMII...")).toBe(true)
1183+
expect(holdsCredentials("-----BEGIN PRIVATE KEY-----")).toBe(true)
1184+
expect(holdsCredentials('{ "type": "service_account", "project_id": "p" }')).toBe(true)
1185+
expect(holdsCredentials("select private_key_id from keys -- BEGIN")).toBe(false)
1186+
expect(holdsCredentials("-----BEGIN PUBLIC KEY-----")).toBe(false)
1187+
})
1188+
1189+
const git = (cwd: string, ...args: string[]) =>
1190+
execFileSync("git", ["-c", "user.email=t@t", "-c", "user.name=t", ...args], { cwd, stdio: "ignore" })
1191+
const runner = {
1192+
async impact() {
1193+
return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 }
1194+
},
1195+
async grade() {
1196+
return { grade: "B" }
1197+
},
1198+
async check() {
1199+
return { issues: [], ran: true }
1200+
},
1201+
async equivalence() {
1202+
return { decided: true, equivalent: true }
1203+
},
1204+
async detectPii() {
1205+
return { columns: [] }
1206+
},
1207+
} as ReviewRunner
1208+
/** The verifier evidence runReview builds over the real git content resolver. */
1209+
const evidenceFor = async (root: string, changedFiles: Parameters<typeof runReview>[0]["changedFiles"], head?: string) => {
1210+
const renames = new Map(changedFiles.flatMap((f) => (f.oldPath ? [[f.path, f.oldPath] as [string, string]] : [])))
1211+
let ev: AiVerifyEvidence | undefined
1212+
await runReview({
1213+
changedFiles,
1214+
config: { ...DEFAULT_REVIEW_CONFIG },
1215+
rubric: DEFAULT_RUBRIC,
1216+
mode: "comment",
1217+
runner,
1218+
forceTier: "full",
1219+
aiVerify: true,
1220+
getContent: makeContentResolver({ base: "HEAD~1", head, cwd: root, renames, gitRoot: root }),
1221+
prFiles: changedFiles.map((f) => f.path),
1222+
generatedAt: "2026-11-23T00:00:00Z",
1223+
aiReview: async (input) => ((ev = input.evidence), { findings: [], status: { state: "ok" } }),
1224+
})
1225+
return ev!
1226+
}
1227+
1228+
test("the old side of a renamed credential file is refused (read_file, compiled_sql, equivalence)", async () => {
1229+
await using tmp = await tmpdir()
1230+
const root = tmp.path
1231+
git(root, "init", "-q")
1232+
writeFileSync(path.join(root, "profiles.yml"), "prod:\n password: SECRET123\n")
1233+
writeFileSync(path.join(root, ".env"), "select 'SECRET456' as id\n")
1234+
mkdirSync(path.join(root, "models"))
1235+
writeFileSync(path.join(root, "models", "a.sql"), "select 1 as id\n")
1236+
git(root, "add", ".")
1237+
git(root, "commit", "-qm", "base")
1238+
git(root, "mv", "profiles.yml", "profiles.yml.example")
1239+
writeFileSync(path.join(root, "profiles.yml.example"), "prod:\n password: \"{{ env_var('PW') }}\"\n")
1240+
git(root, "mv", ".env", "models/env_model.sql")
1241+
git(root, "commit", "-qam", "head")
1242+
const ev = await evidenceFor(
1243+
root,
1244+
[
1245+
{ path: "profiles.yml.example", oldPath: "profiles.yml", status: "renamed", diff: "@@ -2 +2 @@\n- password: SECRET123\n+ password: x\n" },
1246+
{ path: "models/env_model.sql", oldPath: ".env", status: "renamed", diff: "" },
1247+
],
1248+
"HEAD",
1249+
)
1250+
const tools = verifierTools(ev)
1251+
const old = await tools.read_file.run({ path: "profiles.yml.example", side: "old" })
1252+
expect(old).toBe("not available: may hold credentials")
1253+
expect(await tools.read_file.run({ path: "profiles.yml.example", side: "new" })).toContain("env_var('PW')")
1254+
// A model renamed from a credential file: neither the engine's old SQL nor compiled output is shown.
1255+
expect(await ev.compiledSql("models/env_model.sql", "old")).toBeUndefined()
1256+
expect(await tools.compiled_sql.run({ path: "models/env_model.sql", side: "old" })).not.toContain("SECRET456")
1257+
expect(await tools.equivalence.run({ path: "models/env_model.sql" })).toStartWith("not available")
1258+
expect(await tools.read_file.run({ path: "models/env_model.sql", side: "old" })).toBe("not available: may hold credentials")
1259+
})
1260+
1261+
test("working-tree mode never follows a symlink to a credential file; other symlinks still read", async () => {
1262+
await using tmp = await tmpdir()
1263+
const root = tmp.path
1264+
git(root, "init", "-q")
1265+
writeFileSync(path.join(root, "profiles.yml"), "prod:\n password: SECRET123\n")
1266+
mkdirSync(path.join(root, "docs"))
1267+
writeFileSync(path.join(root, "docs", "readme.md"), "hello\n")
1268+
git(root, "add", ".")
1269+
git(root, "commit", "-qm", "base")
1270+
symlinkSync("../profiles.yml", path.join(root, "docs", "link.md"))
1271+
symlinkSync("readme.md", path.join(root, "docs", "alias.md"))
1272+
const resolver = makeContentResolver({ base: "HEAD", cwd: root, gitRoot: root })
1273+
expect(await resolver("docs/link.md", "new")).toBeUndefined()
1274+
expect(await resolver("docs/alias.md", "new")).toBe("hello\n")
1275+
const ev = await evidenceFor(root, [
1276+
{ path: "docs/link.md", status: "added", diff: "@@ -0,0 +1 @@\n+../profiles.yml\n" },
1277+
{ path: "docs/alias.md", status: "added", diff: "@@ -0,0 +1 @@\n+readme.md\n" },
1278+
])
1279+
const tools = verifierTools(ev)
1280+
expect(await tools.read_file.run({ path: "docs/link.md" })).not.toContain("SECRET123")
1281+
expect(await tools.read_file.run({ path: "docs/alias.md" })).toStartWith("1: hello")
1282+
})
1283+
1284+
test("read_file refuses a file whose content is a private key, whatever it is called", async () => {
1285+
await using tmp = await tmpdir()
1286+
const root = tmp.path
1287+
git(root, "init", "-q")
1288+
writeFileSync(path.join(root, "notes.md"), "x\n")
1289+
git(root, "add", ".")
1290+
git(root, "commit", "-qm", "base")
1291+
writeFileSync(path.join(root, "notes.md"), "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjE\n")
1292+
const ev = await evidenceFor(root, [{ path: "notes.md", status: "modified", diff: "@@ -1 +1,2 @@\n-x\n+k\n" }])
1293+
expect(await verifierTools(ev).read_file.run({ path: "notes.md" })).toBe("not available: may hold credentials")
1294+
})
1295+
1296+
test("grepFixedAt returns canonical non-ASCII paths, so the credential filter still matches", async () => {
1297+
await using tmp = await tmpdir()
1298+
const root = tmp.path
1299+
git(root, "init", "-q")
1300+
mkdirSync(path.join(root, "models", "café"), { recursive: true })
1301+
writeFileSync(path.join(root, "models", "café", "profiles.yml"), "password: SECRET123\n")
1302+
writeFileSync(path.join(root, "models", "café", "a.sql"), "select password_hash\n")
1303+
git(root, "add", ".")
1304+
git(root, "commit", "-qm", "init")
1305+
for (const ref of ["HEAD", undefined]) {
1306+
const hits = await grepFixedAt(root, ref, "password", ["models"])
1307+
expect(hits?.map((h) => h.path).sort()).toEqual(["models/café/a.sql", "models/café/profiles.yml"])
1308+
const tools = verifierTools({ ...evidence(), grepProject: async () => hits })
1309+
expect(await tools.grep_project.run({ pattern: "password" })).toBe("models/café/a.sql:1: select password_hash")
1310+
}
1311+
})
1312+
})
1313+
11411314
describe("runAiReview with the verifier on (harness path, scripted LLM.stream)", () => {
11421315
afterEach(() => mock.restore())
11431316

0 commit comments

Comments
 (0)