Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
971494d
fix(review): screen content filters before the probe tree's restore t…
wenshao Aug 20, 2026
a25e8e6
fix(review): screen every pipeline checkout and fail closed on unread…
qwen-code-ci-bot Aug 22, 2026
1fe2fae
fix(review): screen every creation checkout and inert the probe check…
qwen-code-ci-bot Aug 23, 2026
49ba19a
fix(review): inert creation checkouts and close the include, FIFO, an…
qwen-code-ci-bot Aug 23, 2026
c06aab3
fix(review): close the newline fail-open, bound refusals, and pin the…
qwen-code-ci-bot Aug 23, 2026
4c5bff7
fix(review): close the recursion, transport-key, EACCES, and teardown…
qwen-code-ci-bot Aug 23, 2026
c959a08
fix(review): screen the head fetch, complete the transport set, gate …
qwen-code-ci-bot Aug 23, 2026
c137f03
fix(review): pin the gate's shape and HEAD, bound the screen spawns, …
qwen-code-ci-bot Aug 24, 2026
deba877
Merge remote-tracking branch 'origin/main' into fix/review-filter-scr…
qwen-code-ci-bot Aug 24, 2026
8cfb0ab
fix(review): NUL-read the screen's values, widen the destination judg…
qwen-code-ci-bot Aug 24, 2026
5258b5e
fix(review): judge refspec grammar fail-closed, screen the main confi…
qwen-code-ci-bot Aug 24, 2026
c9cec1e
fix(review): remove the probe verdict channel on every exit path (#9741)
qwen-code-ci-bot Aug 24, 2026
eb6a46b
Merge branch 'main' into fix/review-filter-screen-v2
qwen-code-dev-bot Aug 24, 2026
1567ea0
fix(review): close the round-10/11 config-screen holes named by revie…
Aug 24, 2026
7e65377
test(cli): stabilize gate-rejected update and serve-wiring tests (#9741)
Aug 25, 2026
ad017a8
Merge branch 'main' into fix/review-filter-screen-v2
Aug 25, 2026
526575b
Merge branch 'main' into fix/review-filter-screen-v2
qwen-code-dev-bot Aug 25, 2026
832ad51
Merge branch 'main' into fix/review-filter-screen-v2
wenshao Aug 26, 2026
776e147
Merge branch 'main' into fix/review-filter-screen-v2
qwen-code-dev-bot Aug 26, 2026
377ec3a
Merge branch 'main' into fix/review-filter-screen-v2
qwen-code-dev-bot Aug 27, 2026
4c4eca3
Merge branch 'main' into fix/review-filter-screen-v2
qwen-code-dev-bot Aug 27, 2026
90e1494
fix(review): inert the remaining branch deletes and resume probe, gat…
Aug 27, 2026
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
161 changes: 161 additions & 0 deletions packages/cli/src/commands/review/lib/worktree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

import { spawnSync } from 'node:child_process';
import {
accessSync,
constants,
existsSync,
lstatSync,
mkdtempSync,
Expand All @@ -34,6 +36,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path';
import { inertPath } from './paths.js';
import { readWorkspacePackages } from './workspaces.js';

export type SweepResult = ReturnType<typeof spawnSync>;
Expand Down Expand Up @@ -557,6 +560,164 @@ function trackedIgnoreSources(cwd: string, sources: Set<string>): Set<string> {
return new Set(r.stdout.split('\0').filter((p) => p.length > 0));
}

/**
* The refusal for a checkout about to run through a repo-local content filter —
* or through a repo-local config file the screen could not read — and null
* when the screen came back clean. `checkout` is the noun phrase naming the
* checkout being authorised ("this tree's restore", "the revert checkout"); it
* lands in the message verbatim.
*
* Every checkout in this pipeline EXECUTES these filters — the scratch tree's
* reset and rebuild, the probe tree's creation, per-run restore and revert
* checkouts — 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 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. `--file` likewise does not expand
Comment on lines +757 to +759

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.

Not implemented this round — explicitly deferred to the next. The fix (snapshotting the reviewer's global config before the first suite run and redirecting GIT_CONFIG_GLOBAL to the snapshot on every pipeline git spawn, with GIT_CONFIG_NOSYSTEM=1) touches every pipeline spawn's env plumbing and needs its own careful batch with witnesses for both the snapshot and the redirect; the round batch was bounded at ~8 findings. The erroneous premise in the docstring ('a probe's planting surface is the repo-local files') will be corrected together with that fix. The thread stays open.

中文说明

本轮未实现——显式延后到下一轮。修复方案(在第一个套件运行前快照评审者的全局配置,并让每个管线 git spawn 把 GIT_CONFIG_GLOBAL 重定向到该快照、附带 GIT_CONFIG_NOSYSTEM=1)触及每个管线 spawn 的环境管道,需要自己独立的一批,并为快照与重定向各自配见证;本轮批次以约 8 条发现为上限。docstring 里的错误前提('探针的植入面是仓库本地文件')将随该修复一并更正。线程保持开放。

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 next round with the plan fixed: snapshot the reviewer's global config before the first suite run, redirect GIT_CONFIG_GLOBAL to the snapshot on every pipeline git spawn, and set GIT_CONFIG_NOSYSTEM=1. This round's batch was bounded (~8 findings, Critical-first); this fix touches the environment of every pipeline git spawn and warrants its own round rather than a squeezed implementation. Not declined — the gap is real and remains tracked.

中文说明

延后到下一轮,方案已确定:在第一次套件运行前快照审阅者的全局配置,在每个管线 git spawn 上把 GIT_CONFIG_GLOBAL 重定向到该快照,并设置 GIT_CONFIG_NOSYSTEM=1。本轮批次受限(约 8 项、Critical 优先);该修复触及每个管线 git spawn 的环境,值得单独一轮而非仓促实现。不是拒绝——缺口真实存在并继续被跟踪。

Comment on lines +757 to +759

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 next round with the plan fixed: snapshot the reviewer's global config before the first suite run, redirect GIT_CONFIG_GLOBAL to the snapshot on every pipeline git spawn, and set GIT_CONFIG_NOSYSTEM=1. This round's batch was bounded (~8 findings, Critical-first); this fix touches the environment of every pipeline git spawn and warrants its own round rather than a squeezed implementation. Not declined — the gap is real and remains tracked.

中文说明

延后到下一轮,方案已确定:在第一次套件运行前快照审阅者的全局配置,在每个管线 git spawn 上把 GIT_CONFIG_GLOBAL 重定向到该快照,并设置 GIT_CONFIG_NOSYSTEM=1。本轮批次受限(约 8 项、Critical 优先);该修复触及每个管线 git spawn 的环境,值得单独一轮而非仓促实现。不是拒绝——缺口真实存在并继续被跟踪。

* `include.path`/`includeIf.*.path`, so a filter planted behind an include is
* invisible here; the origin-scoped follow-up tracked on this PR closes that —

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.

Still deferred, as this PR documents — the mechanism is unchanged at this round's commit and the fix (an origin-scoped merged read via --show-origin, refusing only repo-local hits) remains the tracked follow-up. The interim options were weighed again this round and still conflict with the PR's recorded direction: --includes re-imports global filters like git-lfs into permanent refusal, and failing closed on any include.path/includeIf.*.path key in the candidate files would do the same for repositories that legitimately use includes. The gap stays disclosed in the localFilterRefusal docstring and is recorded in this round's deferred-findings; the thread stays open to keep the blocker visible.

中文说明

仍然推迟,与本 PR 的记载一致——该机制在本轮提交上未变,修复(按来源限定的 --show-origin 合并读取,仅对仓库本地命中拒绝)仍是已跟踪的后续改动。本轮重新权衡了过渡选项,它们仍与本 PR 记录的方向冲突:--includes 会把 git-lfs 等全局过滤器拖回造成永久拒绝;对候选文件中任何 include.path/includeIf.*.path 键失败关闭,对合法使用 include 的仓库同样如此。该缺口继续在 localFilterRefusal 的 docstring 中披露,并已记入本轮的 deferred-findings;主题保持打开以让阻断项持续可见。

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.

Still open and tracked, unchanged this round — the interim fail-closed treatment stands: any include.path/includeIf.*.path directive in the screen's candidate files refuses the checkout, so a filter planted behind an include cannot EXECUTE unseen (it is refused, not certified). The remaining gap is the permanent refusal for legitimate user includes; closing it is the origin-scoped merged-read follow-up (--show-origin refusing only repo-local hits), still deferred and tracked on this PR. Round 7's batch addressed the nine new Critical findings; this re-post keeps the follow-up visible.

中文说明

本线程仍然开放且处于跟踪状态,本轮未变——过渡期的失败关闭处理保持不变:屏蔽候选文件中的任何 include.path/includeIf.*.path 指令都会拒绝该 checkout,因此藏在 include 后面的过滤器不可能在不可见的情况下执行(会被拒绝而非放行)。剩余缺口是对用户合法 include 的永久拒绝;收口方案是按来源限定的合并读取后续改动(用 --show-origin 只拒绝仓库本地命中),该后续仍被推迟并挂在本 PR 上跟踪。第 7 轮批量处理了九个新的 Critical 发现;此次重发保持该后续事项可见。

* `--includes` or merged config would follow the include into the user's
* global config and re-import `filter.lfs.clean`, the permanent-refusal
* failure. 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 localFilterRefusal(
worktree: string,
checkout: string,
): string | null {
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 null;
}
const [commonDir, gitDir] = files.stdout.trim().split('\n');
const common = resolve(worktree, commonDir);

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 next round — this round's batch was capped at the seven Critical findings (plus the two Suggestions entangled with them). The lines.length !== 2 fail-closed guard with its newline-path witness is queued for the next round.

中文说明

推迟到下一轮——本轮批次以七个 Critical 发现(加上与其纠缠的两个 Suggestion)为上限。带换行路径见证的 lines.length !== 2 失败关闭守卫,已排入下一轮。

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 can run in ANOTHER
// tree — the SCRATCH tree, the probe 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 filters: Array<{ key: string; file: string }> = [];
// Neither a config key nor a path can carry NUL, so the pair separator is
// unambiguous — and an O(1) dedup, because a padded config can hand this
// loop tens of thousands of keys.
const seen = new Set<string>();
const unreadable: Array<{ file: string; detail: string }> = [];
for (const file of candidates) {
if (!existsSync(file)) continue;
// An unreadable file fails the screen CLOSED, asked directly: git answers
// an unreadable `--file` with the SAME exit 1 as "no keys matched" (and a
// warning on stderr), so the exit code cannot tell the two apart — and a
// screen that could not read a file cannot certify the checkout that will.
try {
accessSync(file, constants.R_OK);
} catch (e) {
Comment on lines +928 to +940

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 next round — this round's batch was capped at the seven Critical findings (plus the two Suggestions entangled with them). The lstatSync(file).isFile() candidate gate (and/or a spawn timeout) is queued for the next round; agreed it fails closed, which is why it could wait.

中文说明

推迟到下一轮——本轮批次以七个 Critical 发现(加上与其纠缠的两个 Suggestion)为上限。lstatSync(file).isFile() 候选过滤(和/或 spawn 超时)已排入下一轮;认同它是失败关闭的,因此可以等待。

unreadable.push({
file,
detail: e instanceof Error ? e.message : String(e),
});
continue;
}
const r = spawnSync(
'git',
[
'config',
'--file',

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, in line with this finding's own framing. The gap is real and was reproduced here too: git config --file does not expand include.path/includeIf.*.path, so a filter planted behind an include is invisible to the screen and executed by the very restore it certifies. Closing it needs origin-scoped filtering (a merged read with --show-origin, keeping only repo-local origins); the naive --includes fix is exactly what reproduces the permanent-refusal failure on global filters like git-lfs, which is why this PR scoped it out. This round: the gap is now documented in the screen's docstring (so it lives in the code, not only in the PR description) and the finding is recorded for the deferred-findings follow-up issue. The origin-scoped fix itself lands there.

中文说明

按该发现本身的定位,推迟到后续队列处理。缺口真实存在,本轮也已复现:git config --file 不展开 include.path/includeIf.*.path,因此经由 include 植入的过滤器对屏蔽不可见,却会被屏蔽背书的 restore 执行。关闭它需要按来源限定范围的过滤(用 --show-origin 做合并读取、仅保留仓库本地来源);朴素的 --includes 修法恰好会因 git-lfs 这类全局过滤器复刻永久拒绝的失败,这正是本 PR 将其排除在外的原因。本轮的处理:该缺口现已写入屏蔽的 docstring(让它记录在代码里,而不只存在于 PR 描述中),且该发现已登记进延迟发现后续 issue。按来源限定范围的修复本身将在后续改动中落地。

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.

Still open and tracked, unchanged this round — the interim fail-closed treatment stands: any include.path/includeIf.*.path directive in the screen's candidate files refuses the checkout, so a filter planted behind an include cannot EXECUTE unseen (it is refused, not certified). The remaining gap is the permanent refusal for legitimate user includes; closing it is the origin-scoped merged-read follow-up (--show-origin refusing only repo-local hits), still deferred and tracked on this PR. Round 7's batch addressed the nine new Critical findings; this re-post keeps the follow-up visible.

中文说明

本线程仍然开放且处于跟踪状态,本轮未变——过渡期的失败关闭处理保持不变:屏蔽候选文件中的任何 include.path/includeIf.*.path 指令都会拒绝该 checkout,因此藏在 include 后面的过滤器不可能在不可见的情况下执行(会被拒绝而非放行)。剩余缺口是对用户合法 include 的永久拒绝;收口方案是按来源限定的合并读取后续改动(用 --show-origin 只拒绝仓库本地命中),该后续仍被推迟并挂在本 PR 上跟踪。第 7 轮批量处理了九个新的 Critical 发现;此次重发保持该后续事项可见。

file,
'--get-regexp',
Comment on lines +950 to +959

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.

Still open and tracked, unchanged this round — the interim fail-closed treatment stands: any include.path/includeIf.*.path directive in the screen's candidate files refuses the checkout, so a filter planted behind an include cannot EXECUTE unseen (it is refused, not certified). The remaining gap is the permanent refusal for legitimate user includes; closing it is the origin-scoped merged-read follow-up (--show-origin refusing only repo-local hits), still deferred and tracked on this PR. Round 7's batch addressed the nine new Critical findings; this re-post keeps the follow-up visible.

中文说明

本线程仍然开放且处于跟踪状态,本轮未变——过渡期的失败关闭处理保持不变:屏蔽候选文件中的任何 include.path/includeIf.*.path 指令都会拒绝该 checkout,因此藏在 include 后面的过滤器不可能在不可见的情况下执行(会被拒绝而非放行)。剩余缺口是对用户合法 include 的永久拒绝;收口方案是按来源限定的合并读取后续改动(用 --show-origin 只拒绝仓库本地命中),该后续仍被推迟并挂在本 PR 上跟踪。第 7 轮批量处理了九个新的 Critical 发现;此次重发保持该后续事项可见。

// `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)$',
],
{
cwd: worktree,
encoding: 'utf8',
// Padding beside a planted key pushes the output past spawnSync's
// 1 MiB default: ENOBUFS, and the `continue` that used to follow
// certified — and ran — a checkout the screen had never read. The
// 64 MiB ceiling the other readers in these files already use.
maxBuffer: 64 * 1024 * 1024,
env: sanitizedGitEnv(),
},
);
// Exit 1 is the legitimate "no keys matched"; every other failure on a
// file that EXISTS and was readable — a spawn error, a malformed config
// git exits 128 on — is a read the screen cannot vouch for.
if (r.status === 1) continue;
if (r.error || r.status !== 0 || typeof r.stdout !== 'string') {
unreadable.push({
file,
detail: r.error
? r.error.message
: (r.stderr ?? '').toString().trim() ||
`git config exited ${r.status}`,
});
continue;
}
for (const line of r.stdout.split('\n')) {
const key = line.split(/\s+/)[0];
const pair = `${file}\u0000${key}`;
if (key && !seen.has(pair)) {
// The defining file rides along: with `extensions.worktreeConfig` a
// filter can live only in a SIBLING worktree's config.worktree, and a
// refusal that lists keys alone points at nothing the oncall's first
// move — `git config --local --get-regexp '^filter\.'` in the review
// worktree — can see.
seen.add(pair);
filters.push({ key, file });
}
}
}
if (filters.length === 0 && unreadable.length === 0) return null;
// Keys and paths arrive from config files a probe can write, so both go
// through `inertPath` the way `scratch-tree`'s note always has: a caught
// attacker still controls the bytes naming the catch, and they reach the
// terminal and the report the next agent treats as authoritative.
const parts: string[] = [];
if (filters.length > 0) {
parts.push(
`the repository's local config defines content filter(s) ${filters
.map((f) => `${inertPath(f.key)} (in ${inertPath(f.file)})`)

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 next round — this round's batch was capped at the seven Critical findings (plus the two Suggestions entangled with them). The control-character witness for the inertPath sanitization is queued for the next round.

中文说明

推迟到下一轮——本轮批次以七个 Critical 发现(加上与其纠缠的两个 Suggestion)为上限。inertPath 净化的控制字符见证测试已排入下一轮。

.join(', ')} — ${checkout} would EXECUTE them`,

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 next round — this round's batch was capped at the seven Critical findings (plus the two Suggestions entangled with them), and implementing the bounded enumeration with its own witness did not make the cut. It is first in the queue for the next round.

中文说明

推迟到下一轮——本轮批次以七个 Critical 发现(加上与其纠缠的两个 Suggestion)为上限,实现带上限的枚举及其自身见证未能排入。它是下一轮队列中的第一项。

);
}
if (unreadable.length > 0) {
parts.push(
`the repository's local config could not be read (${unreadable

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.

Partially addressed this round. The unreadable-list join is now capped at MAX_NAMED_SCREEN_KEYS with an overflow count, witnessed by the new ten-planted-entry test in worktree.test.ts (see the round-13 and round-15 threads of this finding, resolved this round). The second half recorded here — spawn amplification from many READABLE planted config.worktree entries (bounding the <common>/worktrees enumeration itself) — remains for the next round.

中文说明

本轮已部分处理。unreadable 列表的 join 现在以 MAX_NAMED_SCREEN_KEYS 为上限并带溢出计数,由 worktree.test.ts 新增的植入十条目测试见证(见本发现的第 13/15 轮线程,本轮已解决)。此处记录的第二半——大量可读的植入 config.worktree 条目造成的 spawn 放大(需要对 <common>/worktrees 枚举本身设界)——留待下一轮。

.map((u) => `${inertPath(u.file)}: ${inertPath(u.detail)}`)
.join(
'; ',
)}), so the screen cannot certify that ${checkout} would not EXECUTE a content filter`,
);
}
return parts.join('; ');
}

/**
* The paths a tree carries that its HEAD commit does not — probe residue, seen
* from the reading side (#9207).
Expand Down
94 changes: 92 additions & 2 deletions packages/cli/src/commands/review/scratch-tree.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ vi.mock('../../utils/stdioHelpers.js', () => ({
import { writeStdoutLine } from '../../utils/stdioHelpers.js';
import { execFileSync } from 'node:child_process';
import {
appendFileSync,
chmodSync,
existsSync,
mkdirSync,
Expand Down Expand Up @@ -107,9 +108,30 @@ describe('runScratchTree', () => {
existsSync(scratchWorktreePath(worktree, 'verify--round-1--abc123')),
).toBe(false);

// `process` is the third executable key — a long-running filter git speaks
// a protocol to — and enumerating `smudge`/`clean` and stopping is how the
// first cut of this screen read as complete.
git(worktree, 'config', '--unset', 'filter.evil.smudge');
git(worktree, 'config', 'filter.evil.process', `touch ${pwned}`);
const viaProcess = run();
expect(viaProcess.available).toBe(false);
expect(viaProcess.note).toContain('filter.evil.process');
expect(existsSync(pwned)).toBe(false);

// `clean` completes the executable trio: with it unnamed in the regex a
// repo-local `filter.evil.clean` passed the screen at BOTH call sites
// while the whole suite stayed green — the "enumerate two of three" shape
// the comment above warns about, one token over.
git(worktree, 'config', '--unset', 'filter.evil.process');
git(worktree, 'config', 'filter.evil.clean', `touch ${pwned}`);
const viaClean = run();
expect(viaClean.available).toBe(false);
expect(viaClean.note).toContain('filter.evil.clean');
expect(existsSync(pwned)).toBe(false);

// A repo WITHOUT the filter still gets a tree (the global-config filters
// a user's own git-lfs install carries are not this surface).
git(worktree, 'config', '--unset', 'filter.evil.smudge');
git(worktree, 'config', '--unset', 'filter.evil.clean');
expect(run().available).toBe(true);
});

Expand Down Expand Up @@ -140,7 +162,7 @@ describe('runScratchTree', () => {
});
writeFileSync(
scratchAdmin,
'[filter "planted"]\n\tsmudge = touch /tmp/qwen-should-never-run\n',
`[filter "planted"]\n\tsmudge = touch ${join(repo, 'planted-never-ran')}\n`,
);

const r = run();
Expand All @@ -149,6 +171,74 @@ describe('runScratchTree', () => {
expect(r.note).toContain('filter.planted.smudge');
});

it('refuses when filter keys pad the config past the old 1 MiB buffer — never fails open', () => {
// Padding beside a planted key pushed `--get-regexp`'s output past
// spawnSync's 1 MiB default: ENOBUFS, and the `continue` that followed
// certified — and ran — a checkout the screen had never read. Padding is
// one larger write to the same common-dir file the docstring documents,
// and the common dir is never wiped, so the defeat persisted at both call
// sites.
const pwned = join(repo, 'PWNED-padded');
const padding = Array.from(
{ length: 50000 },
(_, i) => `[filter "pad${i}"]\n\tsmudge = x`,
).join('\n');
appendFileSync(
join(repo, '.git', 'config'),
`${padding}\n[filter "evil"]\n\tsmudge = touch ${pwned}\n`,
);
mkdirSync(join(repo, '.git', 'info'), { recursive: true });
writeFileSync(join(repo, '.git', 'info', 'attributes'), '* filter=evil\n');

const r = run();

expect(r.available).toBe(false);
expect(r.note).toContain('filter.evil.smudge');
expect(existsSync(pwned)).toBe(false);
});

it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(
'refuses when a candidate config cannot be read or parsed — never certifies it',
() => {
// git answers an unreadable `--file` with the SAME exit 1 as "no keys
// matched" (a warning on stderr), so the exit code cannot tell the two
// apart — and a screen that could not read a file cannot certify the
// checkout that will parse it. Both shapes fail the screen closed.
const first = run();
expect(first.available).toBe(true);
const common = execFileSync(
'git',
['rev-parse', '--path-format=absolute', '--git-common-dir'],
{ cwd: worktree, encoding: 'utf8' },
).trim();
const scratchConfig = join(
common,
'worktrees',
basename(first.path!),
'config.worktree',
);

writeFileSync(scratchConfig, '');
chmodSync(scratchConfig, 0o000);
try {
const unreadable = run();
expect(unreadable.available).toBe(false);
expect(unreadable.note).toContain('could not be read');
expect(unreadable.note).toContain(scratchConfig);
} finally {
chmodSync(scratchConfig, 0o644);
}

// A file git can open but not parse exits 128 — not the "no keys
// matched" 1 — and is the same uncertifiable read.
writeFileSync(scratchConfig, '[filter "evil"\n\tsmudge = x\n');
const malformed = run();
expect(malformed.available).toBe(false);
expect(malformed.note).toContain('could not be read');
expect(malformed.note).toContain(scratchConfig);
},
);

it('places it BESIDE the review worktree, never inside it', () => {
// Nested, every probe file would land in the tree this command exists to
// keep clean — and in the PR's own diff with it.
Expand Down
Loading
Loading