Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions packages/cli/src/commands/review/lib/worktree.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,56 @@ describe('worktreeResidue', () => {
expect(worktreeResidue(tree).unmeasured).toBeUndefined();
});

it('says UNMEASURED for a gitfile swapped at a repo that answers for this path', () => {
// The identity gate reads `--show-toplevel`, which prints the directory the
// `.git` FILE sits in — whatever that file points at. A repository whose
// `core.worktree` names this tree answers with this path, so the gate saw
// itself while every command after it measured the plant's index, which
// already holds the contamination as committed content. Measured: through
// discovery the swap reports a clean tree with the mutant on disk.
writeFileSync(join(tree, 'a.ts'), 'export const x = 2; // MUTANT\n');
writeFileSync(join(tree, '__probe__.test.ts'), 'probe');
// Genuine first, so the fixture is known to be measurable at all.
expect(worktreeResidue(tree).paths.sort()).toEqual([
'__probe__.test.ts',
'a.ts',
]);

const forge = join(repo, 'forge');
mkdirSync(forge);
const fgit = (...args: string[]) =>
execFileSync(
'git',
[
'-c',
'user.email=t@t.t',
'-c',
'user.name=t',
'-c',
'commit.gpgsign=false',
...args,
],
{ cwd: forge, encoding: 'utf8' },
);
fgit('init', '-q', '-b', 'main', '--template=', '.');
writeFileSync(join(forge, 'a.ts'), 'export const x = 2; // MUTANT\n');
writeFileSync(join(forge, '__probe__.test.ts'), 'probe');
fgit('add', '-A');
fgit(
'commit',
'-qm',
'the mutant, as if it were the commit',
'--no-verify',
);
fgit('config', 'core.worktree', tree);
writeFileSync(join(tree, '.git'), `gitdir: ${join(forge, '.git')}\n`);

const got = worktreeResidue(tree);

expect(got.paths).toEqual([]);
expect(got.unmeasured).toContain('does not point back');
});

it('says UNMEASURED, not clean, when a repository is planted at the path', () => {
// The concealment: `rm .git && git init && git add -A && git commit` over
// the contamination answers a clean `git status` for a dirty tree, and no
Expand Down
167 changes: 154 additions & 13 deletions packages/cli/src/commands/review/lib/worktree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -474,10 +474,18 @@ interface IgnoreRule {
function ignoreSourcesOf(
cwd: string,
paths: string[],
anchor: readonly string[] = [],
): Map<string, IgnoreRule> | null {
const r = spawnSync(
'git',
[...pipelineExcludeArgs(), 'check-ignore', '-z', '-v', '--stdin'],
[
...anchor,
...pipelineExcludeArgs(),
'check-ignore',
'-z',
'-v',
'--stdin',
],
{
cwd,
input: `${paths.join('\0')}\0`,
Expand Down Expand Up @@ -539,13 +547,17 @@ function hidesEverything(pattern: string): boolean {
* out of the worktree is not asked about at all — `ls-files` would reject the
* pathspec, and unknown provenance is untrusted provenance.
*/
function trackedIgnoreSources(cwd: string, sources: Set<string>): Set<string> {
function trackedIgnoreSources(
cwd: string,
sources: Set<string>,
anchor: readonly string[] = [],
): Set<string> {
const inside = [...sources].filter(
(s) =>
s.length > 0 && !isAbsolute(s) && !s.split('/').some((p) => p === '..'),
);
if (inside.length === 0) return new Set();
const r = spawnSync('git', ['ls-files', '-z', '--', ...inside], {
const r = spawnSync('git', [...anchor, 'ls-files', '-z', '--', ...inside], {
cwd,
encoding: 'utf8',
maxBuffer: 64 * 1024 * 1024,
Expand All @@ -557,6 +569,80 @@ function trackedIgnoreSources(cwd: string, sources: Set<string>): Set<string> {
return new Set(r.stdout.split('\0').filter((p) => p.length > 0));
}

/**
* The repo-local `filter.<name>` COMMANDS, when any are defined.
*
* Every checkout in this pipeline EXECUTES these — the scratch tree's reset and
* rebuild, and the probe tree's per-run restore — hooks being disabled covers
* hooks and not filters. The planting surface is two plain writes a probe can
* make into the COMMON dir this command's report calls shared:
* `git config filter.evil.smudge CMD` and one line appended to
* `$(git rev-parse --git-path info/attributes)`. discard and cleanup never
* wipe the common dir, so a filter planted while reviewing one PR fires on
* every later matching checkout of the user's OWN repository — persistence
* planted by reviewing a malicious PR, measured live. The two local config
* files are checked with `--file` rather than merged config because filters
* in the user's global config (git-lfs is the common one) are the user's own
* contract, exactly like any git command they run — while a probe's planting
* surface is the repo-local files. The state cannot be told apart from a
* filter the user set deliberately, and cannot be safely wiped, so a hit is a
* refusal upstream, not a cleanup here.
*/
export function localFilterCommands(worktree: string): string[] {
const files = spawnSync(
'git',
['rev-parse', '--git-common-dir', '--git-dir'],
{ cwd: worktree, encoding: 'utf8', env: sanitizedGitEnv() },
);
if (files.error || files.status !== 0 || typeof files.stdout !== 'string') {
return [];
}
const [commonDir, gitDir] = files.stdout.trim().split('\n');
const common = resolve(worktree, commonDir);
const candidates = [
join(common, 'config'),
join(resolve(worktree, gitDir), 'config.worktree'),
];
// Every OTHER worktree's per-worktree config too. This screen runs against
// the review worktree, but the checkout it authorises runs in the SCRATCH
// tree, whose own `<common>/worktrees/<label>/config.worktree` is honored
// once `extensions.worktreeConfig` is on and was never read here — a filter
// planted there executed during the reset while this function reported the
// repository clean. The admin directory is one `readdir`, and a filter in
// any of these is a plant whichever tree carries it.
try {
for (const entry of readdirSync(join(common, 'worktrees'))) {
candidates.push(join(common, 'worktrees', entry, 'config.worktree'));
}
} catch {
// No linked worktrees registered: the two candidates above are all of it.
}
const found: string[] = [];
for (const file of candidates) {
if (!existsSync(file)) continue;
const r = spawnSync(
'git',
[
'config',
'--file',
file,
'--get-regexp',

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deferred to the follow-up queue (verified, not declined). The claim reproduces with real git: git config --file <f> --get-regexp exits 1 on an [include]-planted filter.evil.smudge that --includes surfaces, so the screen is blind to exactly the plant the checkout executes. This round dropped the dead localFilterCommands export from this PR per the review's request, so the PR no longer carries any filter-screen code — the hole lives in scratch-tree.ts's pre-existing live private copy, which is outside this PR's footprint. The --includes fix is recorded in the follow-up queue together with the process key and the tests this copy still owes, so they land as one coherent change.

中文说明

延迟到后续队列(已验证,非拒绝)。该论断用真实 git 复现成立:git config --file <f> --get-regexp 对经 [include] 植入的 filter.evil.smudge 返回 exit 1,而加上 --includes 即可见——筛查对 checkout 恰恰会执行的那种植入是盲的。本轮按评审要求把死导出 localFilterCommands 从本 PR 移除,因此本 PR 不再携带任何过滤器筛查代码——漏洞在 scratch-tree.ts 既有的活私有副本里,超出本 PR 足迹。--includes 修复已与process 键以及该副本仍欠的测试一并记入后续队列,作为一次完整的改动落地。

// `process` beside the pair: it is the third executable key (a
// long-running filter git speaks a protocol to), and enumerating two
// of three is how the first cut of this screen read as complete.
'^filter\\..*\\.(smudge|clean|process)$',

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deferred to the follow-up queue with R1-4. Verified: after this round dropped the dead export, this PR owns no filter-screen code at all — the only live copy is scratch-tree.ts's private two-key function, which predates this commit and is exercised by no test (scratch-tree.test.ts reaches it only through smudge keys). The prescribed tests — filter.pwn.smudge/clean/process planted one per candidate location (common config, the tree's config.worktree, a sibling's config.worktree) plus the global-config negative — belong with that copy's --includes + process fix, recorded as one follow-up so the screen and its regression net land together.

中文说明

与 R1-4 一并延迟到后续队列。已验证:本轮移除死导出后,本 PR 完全不再拥有过滤器筛查代码——唯一的活副本是 scratch-tree.ts 的私有两键函数,它早于本提交且没有任何测试覆盖(scratch-tree.test.ts 只经由 smudge 键触及它)。规定的测试——在三个候选位置(common config、本树的 config.worktree、兄弟 worktree 的 config.worktree)各植入一个 filter.pwn.smudge/clean/process,外加大局配置负例——应与该副本的 --includes + process 修复一起,作为同一个后续工作落地,让筛查与它的回归保护网同时交付。

],
{ cwd: worktree, encoding: 'utf8', env: sanitizedGitEnv() },
);
if (r.error || r.status !== 0 || typeof r.stdout !== 'string') continue;
for (const line of r.stdout.split('\n')) {
const key = line.split(/\s+/)[0];
if (key && !found.includes(key)) found.push(key);
}
}
return found;
}

/**
* The paths a tree carries that its HEAD commit does not — probe residue, seen
* from the reading side (#9207).
Expand Down Expand Up @@ -652,20 +738,73 @@ export function worktreeResidue(cwd: string, cap = 12): WorktreeResidue {
// add`, a cleanup whose `rmSync` failed — `status` exits 0 against the
// enclosing user checkout: the wrong tree's dirty state answered as this
// one's. Fail closed the way a loud git failure below does.
const top = spawnSync('git', ['rev-parse', '--show-toplevel'], {
cwd,
encoding: 'utf8',
env: sanitizedGitEnv(),
});
const top = spawnSync(
'git',
['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir'],
{ cwd, encoding: 'utf8', env: sanitizedGitEnv() },
);
let isWorktree = false;
let anchor: string[] = [];
try {
const [toplevel, gitDir] = (top.stdout ?? '').trim().split('\n');
isWorktree =
!top.error &&
top.status === 0 &&
typeof top.stdout === 'string' &&
realpathSync(top.stdout.trim()) === realpathSync(cwd);
realpathSync(toplevel) === realpathSync(cwd);
if (isWorktree) {
// And the gitfile must name an admin entry that names this tree BACK.
// The pin below closes the window between this gate and the commands
// after it; it cannot help when the swap is already in place when the
// probe starts, because then the gate resolves the plant too — a
// repository whose `core.worktree` points here answers `--show-toplevel`
// with this path. `scratch-tree` gates its own reset on the round-trip
// for the same reason, and a planted standalone repo has no admin entry
// to round-trip at all.
// Its own try: a plant has no `gitdir` file to read, and letting that
// ENOENT fall into the outer catch reported it as "not a git worktree",
// which is a different and much vaguer thing than what was found.
let pointsBack = false;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deferred to the follow-up queue. The three divergent spellings are verified, and the cross-file dedup is the right end state — but it requires editing scratch-tree.ts, which this PR has never touched, so it is recorded for the follow-up that already owns that file (the filter-copy cluster above). One divergence is deliberate and worth pinning now so that dedup does not flatten it: adminDirOf's samePath spelling normalises the PARENT and keeps the leaf literal because the tree is often already deleted when cleanup asks, while the residue gate compares live trees with full realpathSync. Measured: rewriting adminDirOf onto the gate's full-realpath comparison makes a symlinked tree path resolve to the VICTIM's admin dir and hand it to discardWorktree for deletion — a cleanup regression, not a neutral refactor.

中文说明

延迟到后续队列。三处分歧写法已验证,跨文件去重是正确的最终形态——但它需要修改本 PR 从未触碰过的 scratch-tree.ts,因此记入已经负责该文件的后续工作(上方的过滤器副本簇)。其中一处分歧是刻意的,现在钉住以免去重时把它抹平:adminDirOf 的 samePath 写法对父目录归一化、末级保持字面,因为清理来询问时树往往已被删除;而残留探针对活着的树用完整 realpathSync 比较。实测:把 adminDirOf 改写成门里的完整 realpath 比较,会让符号链接树路径解析到受害者的 admin 目录,并把它交给 discardWorktree 删除——是清理回归,不是中性重构。

try {
const backpointer = readFileSync(join(gitDir, 'gitdir'), 'utf8').trim();
pointsBack =
realpathSync(dirname(resolve(gitDir, backpointer))) ===
realpathSync(cwd);
} catch {
// No admin entry at all — a standalone repository answering for this
// path, which is exactly the shape being refused.
}
if (!pointsBack) {
return {
paths: [],
total: 0,
unmeasured:
'the .git gitfile names an admin entry that does not point back ' +
'at this tree — the commands below would measure whichever ' +
'repository it does name',
};
}
// PIN the identity this gate just verified, for every spawn below.
// Without it the gate is one-shot: each later command re-discovers the
// repository through the same `.git` file the check read, and that file
// is writable by anything running as this user — so a gitfile swapped in
// afterwards, pointing at a repo whose index already holds the
// contamination, answers a clean `status` for a dirty tree. Measured:
// through discovery the swap certifies a mutant clean deterministically,
// with no race; pinned, the same tree still reports ` M a.ts` and the
// untracked probe file. Measured too, because a WRONG pin would be worse
// than none: across a standalone checkout, a linked worktree, a
// superproject with an initialised submodule and a worktree reached
// through a symlinked ancestor, all five commands below return
// byte-identical output pinned and unpinned.
anchor = [

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified and deferred — with one open question for a maintainer. Confirmed at this commit: scratch-tree.ts and base-tree.ts have 0 changed lines, so issue 9557 would close at one third of its named scope. Extending the pin to both helpers is a multi-file change (gates, pins, tests, and for scratch-tree a non-circular sha source, which its caller can only get through new CLI plumbing) beyond this PR's declared single-commit scope — it is recorded in the follow-up queue so it is not lost at merge. The remaining half is not the bot's to do: should the PR body's Closes #9557 be changed to Part of #9557 before merge so the tracker stays open for scratch-tree.ts and base-tree.ts? A maintainer (or the workflow on instruction) needs to edit the body; please advise here.

中文说明

已验证并延迟——另有一个留给维护者的开放问题。本提交确认:scratch-tree.ts 与 base-tree.ts 改动行数均为 0,issue 9557 会在其点名范围的三分之一处被关闭。把固定扩展到这两个辅助模块是多文件改动(门、固定、测试,以及 scratch-tree 需要一个非循环的 sha 来源——其调用方只能通过新的 CLI 参数获得),超出本 PR 声明的单一提交范围——已记入后续队列,合并时不会丢失。剩下一半不是机器人能做的:合并前是否应把 PR 正文的 Closes #9557 改为 Part of #9557,以便跟踪 issue 对 scratch-tree.ts 与 base-tree.ts 保持开启?需要维护者(或工作流按指示)编辑正文,请在此线程给出意见。

`--git-dir=${realpathSync(gitDir)}`,
`--work-tree=${realpathSync(toplevel)}`,
];
Comment on lines +856 to +859

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The overclaim is fixed in code: the round-trip and sha-pin comment blocks no longer say the pin "closes the window" — they now say it freezes NAMES, that a writer active between the pin and the measurement can still rewrite the pinned admin entry's HEAD/index/commondir or swap the tree path itself, and that this raises the attack's cost rather than closing it, with the structural close (a gate-time snapshot or a sandbox boundary) named as #9556. The trailing re-verification is NOT implemented this round: worktreeResidue is fully synchronous (spawnSync end to end), so no deterministic vitest witness can exercise the pin→measurement window, and this repository's own rule is that a guard ships with a witness or not at all — an unwitnessed race guard would read as protection the code does not provide. The in-window active-writer class is the sandbox-tracked class of issue 9556; if a maintainer wants the cost-raising re-check despite the missing witness, say so on this thread and it comes back as a follow-up.

中文说明

过度声明已在代码中修正:round-trip 与 sha 固定的注释块不再声称 pin"关闭了窗口"——现在明确写明它冻结的是名字(NAMES),活跃在"固定→测量"窗口内的写入者仍可改写被固定 admin 条目的 HEAD/index/commondir,或掉包树路径本身;这只是提高攻击成本,并非关闭该类攻击,结构性关闭(门时快照或沙箱边界)指向 #9556。尾部再验证本轮未实现:worktreeResidue 全程同步(全部 spawnSync),vitest 中不存在能演练"固定→测量"窗口的确定性见证,而本仓库自身的规则是守卫要么带见证、要么不上——一个没有见证的竞态守卫会被误读为代码并不提供的保护。窗口内活跃写入者这一类别正是 issue 9556 所跟踪的沙箱类别;若维护者在缺少见证的情况下仍希望加上这个提高成本的复查,请在本帖说明,它将作为后续跟进项处理。

Comment on lines +856 to +859

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same disposition as the round-2 thread: the overclaim is fixed in code (the comments now state the pin freezes names, raises the attack's cost, and does not close the in-window class — the structural close is the sandbox boundary, #9556). The trailing re-verification is not implemented this round: the probe is fully synchronous, so no deterministic vitest witness can exercise the window, and an unwitnessed guard violates this repository's mutation-witness rule. If a maintainer wants the cost-raising re-check anyway, say so here and it comes back as a follow-up.

中文说明

与第 2 轮线程的处置相同:过度声明已在代码中修正(注释现在写明 pin 冻结的是名字、只提高攻击成本、并不关闭窗口内类别——结构性关闭是沙箱边界,见 #9556)。尾部再验证本轮未实现:探针全程同步,vitest 中无法确定性演练该窗口,无见证的守卫违反本仓库的突变见证规则。若维护者仍希望加上这个提高成本的复查,请在此说明,将作为后续跟进项处理。

}
} catch {
// A cwd that no longer resolves is not a tree this probe can measure.
isWorktree = false;
}
if (!isWorktree) {
return {
Expand All @@ -679,6 +818,7 @@ export function worktreeResidue(cwd: string, cap = 12): WorktreeResidue {
const r = spawnSync(
'git',
[
...anchor,
...pipelineExcludeArgs(),
// The measurement must not itself become the execution: `core.fsmonitor`
// runs a command on `status`, and this tree's config is writable by
Expand Down Expand Up @@ -749,7 +889,7 @@ export function worktreeResidue(cwd: string, cap = 12): WorktreeResidue {
// from the name.
const others = spawnSync(
'git',
['-c', 'core.fsmonitor=', 'ls-files', '--others', '-z'],
[...anchor, '-c', 'core.fsmonitor=', 'ls-files', '--others', '-z'],
{
cwd,
encoding: 'utf8',
Expand Down Expand Up @@ -780,7 +920,7 @@ export function worktreeResidue(cwd: string, cap = 12): WorktreeResidue {
extras.push(rec);
}
if (extras.length > 0) {
const hiddenBy = ignoreSourcesOf(cwd, extras);
const hiddenBy = ignoreSourcesOf(cwd, extras, anchor);
if (hiddenBy === null) {
return {
paths: paths.slice(0, cap),
Expand All @@ -793,6 +933,7 @@ export function worktreeResidue(cwd: string, cap = 12): WorktreeResidue {
const fromTheCommit = trackedIgnoreSources(
cwd,
new Set([...hiddenBy.values()].map((rule) => rule.source)),
anchor,
);
for (const rec of extras) {
const rule = hiddenBy.get(rec);
Expand Down Expand Up @@ -826,7 +967,7 @@ export function worktreeResidue(cwd: string, cap = 12): WorktreeResidue {
// gitlink is certified clean.
const stage = spawnSync(
'git',
['-c', 'core.fsmonitor=', 'ls-files', '-s', '-z'],
[...anchor, '-c', 'core.fsmonitor=', 'ls-files', '-s', '-z'],
{
cwd,
encoding: 'utf8',
Expand Down Expand Up @@ -884,7 +1025,7 @@ export function worktreeResidue(cwd: string, cap = 12): WorktreeResidue {
// read as "no bits found" and fell through to a clean verdict.
const bits = spawnSync(
'git',
['-c', 'core.fsmonitor=', 'ls-files', '-v', '-z'],
[...anchor, '-c', 'core.fsmonitor=', 'ls-files', '-v', '-z'],
{
cwd,
encoding: 'utf8',
Expand Down
Loading