Skip to content

Commit 474683a

Browse files
naimish-browseclaude
authored andcommitted
test-companion: check the pushed tree against the base as listed before the run
The agent can write .git. Git checks the hash of every object it reads, so a forged loose or packed object is refused by git itself. But some files are trusted without that check, and the base the Action builds on is read after the agent ran: - Before the agent runs, the Action now lists the base's whole tree and reads .git/objects/info/alternates and http-alternates, keeping both in its own memory, which the agent can't reach. - Before pushing a saved commit or a hand-back pull request, it refuses if the alternates files changed, and compares the new commit's whole tree with that listing: every path that differs must be one the Action chose (for a saved commit) and one it would ever commit. - Its git calls no longer use the commit-graph or multi-pack-index files, which git reads without checking the objects (core.commitGraph=false, core.multiPackIndex=false). Variables that point git at other objects were already never passed on. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b0f78f9 commit 474683a

3 files changed

Lines changed: 177 additions & 1 deletion

File tree

‎test-companion/src/main.mjs‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,8 @@ import {
105105
isRequestedByPerson,
106106
leaveOut,
107107
commitPaths,
108+
parseLsTree,
109+
checkTreeAgainstBase,
108110
leaveOutMessage,
109111
listFiles,
110112
renderPushNote,
@@ -245,6 +247,32 @@ let approvedPlan
245247

246248
/** Which failed run a build-reading job looked at, and what it left out. */
247249
let buildNote = ""
250+
/** The base's whole tree, listed before the agent ran. */
251+
let baseListing = new Map()
252+
/** Where git would look for borrowed objects, and what those files said before the agent ran. */
253+
const ALTERNATES_FILES = ["objects/info/alternates", "objects/info/http-alternates"]
254+
let alternatesPaths = []
255+
let alternatesBefore = ""
256+
257+
function readAlternates(paths) {
258+
return paths
259+
.map((p) => {
260+
try {
261+
return readFileSync(p, "utf8")
262+
} catch {
263+
return ""
264+
}
265+
})
266+
.join("\0")
267+
}
268+
269+
/** Why git's object store can't be trusted any more, or undefined. */
270+
function alternatesChanged() {
271+
return readAlternates(alternatesPaths) === alternatesBefore
272+
? undefined
273+
: "the run changed where git borrows objects from (.git/objects/info/alternates), so what git reads can't be trusted"
274+
}
275+
248276
/** A generate plan's room: the run's report above the cases is kept to this. */
249277
const PLAN_SUMMARY_LIMIT = 12_000
250278
/** The proposal's own text and marker, around the plan. */
@@ -940,6 +968,11 @@ async function main() {
940968

941969
// Where HEAD was before the agent touched anything.
942970
headBeforeRun = git(["rev-parse", "HEAD"]).out
971+
// What the base holds, and where git may borrow objects from, before the agent can write .git.
972+
// Kept in this process, which the agent can't reach.
973+
baseListing = headBeforeRun ? parseLsTree(git(["ls-tree", "-r", "-z", "--full-tree", headBeforeRun]).raw) : new Map()
974+
alternatesPaths = ALTERNATES_FILES.map((f) => git(["rev-parse", "--git-path", f]).out).filter(Boolean)
975+
alternatesBefore = readAlternates(alternatesPaths)
943976
notice(`tc ${args.join(" ")}`)
944977
// Remove stale files so a run that produces nothing can't report an earlier run's work.
945978
for (const f of [SUMMARY_FILE, RESULT_FILE, `${RESULT_FILE}.json`, CASES_DIR]) {
@@ -1163,6 +1196,8 @@ function saveWork(saving, plan) {
11631196
"changes are in the job's workspace only.",
11641197
].join(" ")
11651198
}
1199+
const borrowed = alternatesChanged()
1200+
if (borrowed) return `**Could not save this work to \`${branch}\`:** ${borrowed}. Nothing was committed or pushed.`
11661201
// quotePath=false keeps non-ASCII paths as-is; -uall lists new directories file by file.
11671202
const status = git(["-c", "core.quotePath=false", "status", "--porcelain", "--untracked-files=all"])
11681203
if (!status.ok) return undefined
@@ -1197,6 +1232,12 @@ function saveWork(saving, plan) {
11971232
if (!made.sha) {
11981233
return renderPushNote({ branch, files: push, skipped: skip, error: made.error || "nothing to commit" })
11991234
}
1235+
// The agent can write .git/objects, so git's view of the base can be forged. The new commit
1236+
// must differ from the base as listed before the run only in the files chosen above.
1237+
const forged = checkTreeAgainstBase(baseListing, parseLsTree(git(["ls-tree", "-r", "-z", "--full-tree", made.sha]).raw), {
1238+
allowed: push,
1239+
})
1240+
if (forged) return `**Could not save this work to \`${branch}\`:** ${forged}. Nothing was pushed.`
12001241

12011242
// Push to a URL built from GITHUB_REPOSITORY, not `origin`: an insteadOf rewrite in
12021243
// .git/config could send the token elsewhere.
@@ -1380,6 +1421,8 @@ function openHandedOffPr(path, plan) {
13801421
if (unexpected.length) {
13811422
return `**Did not open a pull request:** the repository's git config carries ${listFiles(unexpected)}, which \`actions/checkout\` does not write.`
13821423
}
1424+
const borrowed = alternatesChanged()
1425+
if (borrowed) return `**Did not open a pull request:** ${borrowed}.`
13831426
const tip = git(["rev-parse", "--verify", "--quiet", `refs/heads/${req.branch}^{commit}`])
13841427
if (!tip.ok || !tip.out) return `**Did not open a pull request:** the run did not leave a \`${req.branch}\` branch.`
13851428
// The squash goes onto the commit the run started on, and only if the agent's branch builds
@@ -1432,6 +1475,11 @@ function openHandedOffPr(path, plan) {
14321475
rmSync(indexFile, { force: true })
14331476
}
14341477
if (left.error) return `**Could not open the pull request:** ${left.error}.`
1478+
// Checked against the base as listed before the run, not as git reads it now.
1479+
if (left.sha) {
1480+
const forged = checkTreeAgainstBase(baseListing, parseLsTree(git(["ls-tree", "-r", "-z", "--full-tree", left.sha]).raw))
1481+
if (forged) return `**Did not open a pull request:** ${forged}.`
1482+
}
14351483
if (left.empty) {
14361484
return dropped.length
14371485
? `**Did not open a pull request:** the run's only changes were files Test Companion never commits: ${listFiles(dropped)}.`

‎test-companion/src/push-work.mjs‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,12 @@ export const GIT_SAFE_ARGS = Object.freeze([
409409
// which callers read as an error.
410410
"-c",
411411
"advice.graftFileDeprecated=false",
412+
// The agent can write .git/objects/info/commit-graph and the multi-pack-index. Git reads a
413+
// commit's parents and tree from them without checking the objects, so don't use them.
414+
"-c",
415+
"core.commitGraph=false",
416+
"-c",
417+
"core.multiPackIndex=false",
412418
])
413419

414420
/**
@@ -514,6 +520,44 @@ export function commitPaths({ git, base, paths, identity, message, indexFile })
514520
return commit.ok && commit.out ? { sha: commit.out } : { error: commit.err || "could not commit" }
515521
}
516522

523+
/**
524+
* `git ls-tree -r -z` output as path → "mode type id". Used to compare a commit's whole tree
525+
* with the base's, as listed before the agent ran.
526+
*/
527+
export function parseLsTree(raw) {
528+
const out = new Map()
529+
for (const entry of String(raw ?? "").split("\0")) {
530+
const tab = entry.indexOf("\t")
531+
if (tab > 0) out.set(entry.slice(tab + 1), entry.slice(0, tab))
532+
}
533+
return out
534+
}
535+
536+
/** Paths whose entry differs between two listings (added, removed or changed), sorted. */
537+
export function treeChanges(before, after) {
538+
const paths = new Set([...before.keys(), ...after.keys()])
539+
return [...paths].filter((p) => before.get(p) !== after.get(p)).sort()
540+
}
541+
542+
/**
543+
* Why a commit about to be pushed can't be trusted, or undefined. `before` is the base's
544+
* listing taken before the agent ran; `after` is the new commit's. The agent can write
545+
* .git/objects, so git's own view of the base can be forged: comparing against the listing
546+
* taken earlier catches a changed base tree or objects fed in from elsewhere. Every path that
547+
* differs must be one the Action chose (`allowed`, when given) and one it would ever commit.
548+
*/
549+
export function checkTreeAgainstBase(before, after, { allowed } = {}) {
550+
if (!before || before.size === 0) return "the commit the run started on couldn't be listed before the run"
551+
const changed = treeChanges(before, after)
552+
const chosen = allowed ? new Set(allowed) : undefined
553+
const unchosen = chosen ? changed.filter((p) => !chosen.has(p)) : []
554+
if (unchosen.length) return `it would also change files nobody chose: ${listFiles(unchosen)}`
555+
const isLink = (p) => String(after.get(p) ?? "").startsWith("120000 ")
556+
const { skip } = splitPushable(changed, { isSymlink: isLink })
557+
if (skip.length) return `it would change files Test Companion never commits: ${listFiles(skip)}`
558+
return undefined
559+
}
560+
517561
// Agent-chosen text on one line, so it can't add a trailer such as Co-authored-by.
518562
const oneLine = (s) => String(s ?? "").replace(/[\x00-\x1f\x7f]+/g, " ").trim()
519563

‎test-companion/test/push-work.test.mjs‎

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { test, describe } from "node:test"
22
import assert from "node:assert/strict"
33
import { execFileSync, spawnSync } from "node:child_process"
4-
import { mkdtempSync, mkdirSync, rmSync, readdirSync, readFileSync, writeFileSync, symlinkSync, unlinkSync, existsSync } from "node:fs"
4+
import { mkdtempSync, mkdirSync, rmSync, readdirSync, readFileSync, writeFileSync, symlinkSync, unlinkSync, existsSync, copyFileSync, chmodSync } from "node:fs"
55
import { tmpdir } from "node:os"
66
import { dirname, join } from "node:path"
77
import {
@@ -29,6 +29,9 @@ import {
2929
savingFor,
3030
leaveOut,
3131
commitPaths,
32+
parseLsTree,
33+
treeChanges,
34+
checkTreeAgainstBase,
3235
startedOnMergeCommit,
3336
checkHandoffDescends,
3437
REWROTE_HISTORY,
@@ -1282,3 +1285,84 @@ describe("a staged rename is a move, not a copy", () => {
12821285
rmSync(dir, { recursive: true, force: true })
12831286
})
12841287
})
1288+
1289+
describe("the base is checked against a listing taken before the agent ran", () => {
1290+
const identity = { name: "Test Companion", email: BOT_EMAIL }
1291+
const ls = (git, rev) => parseLsTree(spawnSync("git", ["ls-tree", "-r", "-z", "--full-tree", rev], { cwd: git.dir, encoding: "utf8" }).stdout)
1292+
1293+
test("listings compare path by path", () => {
1294+
const before = parseLsTree("100644 blob aaa\ta.ts\x00100644 blob bbb\tb.ts\0")
1295+
const after = parseLsTree("100644 blob aaa\ta.ts\x00100644 blob ccc\tb.ts\x00120000 blob ddd\tlink\0")
1296+
assert.deepEqual(treeChanges(before, after), ["b.ts", "link"])
1297+
assert.match(checkTreeAgainstBase(before, after, { allowed: ["b.ts"] }), /nobody chose: `link`/)
1298+
assert.match(checkTreeAgainstBase(before, after, { allowed: ["b.ts", "link"] }), /never commits: `link`/)
1299+
assert.equal(checkTreeAgainstBase(before, parseLsTree("100644 blob aaa\ta.ts\x00100644 blob ccc\tb.ts\0"), { allowed: ["b.ts"] }), undefined)
1300+
assert.match(checkTreeAgainstBase(new Map(), after), /couldn't be listed/)
1301+
})
1302+
1303+
test("git itself refuses a forged object, loose or packed", () => {
1304+
const { dir, git, tip } = repoWithBranch({ "a.ts": "new\n" })
1305+
const tree = git(["rev-parse", `${tip}^{tree}`]).out
1306+
const file = join(dir, ".git/objects", tree.slice(0, 2), tree.slice(2))
1307+
// Swap the base tree's object file for another tree's.
1308+
const other = git(["mktree"], {}, "").out
1309+
chmodSync(file, 0o644)
1310+
copyFileSync(join(dir, ".git/objects", other.slice(0, 2), other.slice(2)), file)
1311+
const r = git(["ls-tree", "-r", tip])
1312+
assert.equal(r.ok, false)
1313+
assert.match(r.err, /hash mismatch/)
1314+
rmSync(dir, { recursive: true, force: true })
1315+
})
1316+
1317+
test("a commit built on a base other than the one listed is refused", () => {
1318+
// What a forged read of the base would produce: a commit whose tree differs from the
1319+
// listed base in more than the chosen files.
1320+
const { dir, git, base, tip } = repoWithBranch({ "a.ts": "new\n", ".github/actions/x/action.yml": "runs: evil\n" })
1321+
git.dir = dir
1322+
const listedBase = ls(git, base)
1323+
writeFileSync(join(dir, "a.ts"), "newer\n")
1324+
const out = commitPaths({ git, base: tip, paths: ["a.ts"], identity, message: "m", indexFile: join(dir, "scratch") })
1325+
assert.ok(out.sha, JSON.stringify(out))
1326+
assert.match(checkTreeAgainstBase(listedBase, ls(git, out.sha), { allowed: ["a.ts"] }), /nobody chose: `\.github\/actions\/x\/action\.yml`/)
1327+
rmSync(dir, { recursive: true, force: true })
1328+
})
1329+
1330+
test("commit-graph and multi-pack-index files are not used", () => {
1331+
const settings = GIT_SAFE_ARGS.filter((a) => a !== "-c")
1332+
assert.ok(settings.includes("core.commitGraph=false"))
1333+
assert.ok(settings.includes("core.multiPackIndex=false"))
1334+
})
1335+
1336+
test("git never inherits a variable that points it at other objects", () => {
1337+
const got = gitEnvFrom({ GIT_ALTERNATE_OBJECT_DIRECTORIES: "/tmp/evil", GIT_OBJECT_DIRECTORY: "/tmp/evil", GIT_DIR: "/tmp/evil", GIT_INDEX_FILE: "/tmp/evil" })
1338+
for (const k of ["GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_OBJECT_DIRECTORY", "GIT_DIR", "GIT_INDEX_FILE"]) assert.equal(got[k], undefined, k)
1339+
})
1340+
1341+
test("an alternates file feeds git objects from another folder, which is why it's checked", () => {
1342+
const { dir, git } = repoWithBranch({ "a.ts": "new\n" })
1343+
const other = mkdtempSync(join(tmpdir(), "tc-alt-"))
1344+
spawnSync("git", ["init", "-q"], { cwd: other })
1345+
const foreign = spawnSync("git", ["hash-object", "-w", "--stdin"], { cwd: other, encoding: "utf8", input: "foreign\n" }).stdout.trim()
1346+
assert.equal(git(["cat-file", "-e", foreign]).ok, false)
1347+
mkdirSync(join(dir, ".git/objects/info"), { recursive: true })
1348+
writeFileSync(join(dir, ".git/objects/info/alternates"), `${join(other, ".git/objects")}\n`)
1349+
assert.equal(git(["cat-file", "-e", foreign]).ok, true)
1350+
rmSync(dir, { recursive: true, force: true })
1351+
rmSync(other, { recursive: true, force: true })
1352+
})
1353+
1354+
test("the wiring: listed before the agent, alternates and listings checked before anything is pushed", () => {
1355+
const main = readFileSync(new URL("../src/main.mjs", import.meta.url), "utf8")
1356+
const start = main.indexOf('headBeforeRun = git(["rev-parse", "HEAD"]).out')
1357+
assert.ok(main.indexOf("baseListing = headBeforeRun ? parseLsTree(", start) > start)
1358+
assert.ok(main.indexOf("alternatesBefore = readAlternates(", start) > start)
1359+
assert.ok(main.indexOf("baseListing = headBeforeRun", start) < main.indexOf("runLockedDown(", start), "listed before the agent runs")
1360+
assert.match(main, /const ALTERNATES_FILES = \["objects\/info\/alternates", "objects\/info\/http-alternates"\]/)
1361+
const save = main.slice(main.indexOf("function saveWork("), main.indexOf("function isolateAgent("))
1362+
assert.ok(save.indexOf("alternatesChanged()") < save.indexOf('"status", "--porcelain"'))
1363+
assert.ok(save.indexOf("checkTreeAgainstBase(baseListing") < save.indexOf('git(["push"'))
1364+
const hand = main.slice(main.indexOf("function openHandedOffPr("), main.indexOf("function openHandedOffPr(") + 7000)
1365+
assert.ok(hand.indexOf("alternatesChanged()") < hand.indexOf("refs/heads/${req.branch}^{commit}"))
1366+
assert.ok(hand.indexOf("checkTreeAgainstBase(baseListing") < hand.indexOf('git(["push"'))
1367+
})
1368+
})

0 commit comments

Comments
 (0)