Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
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
42 changes: 42 additions & 0 deletions packages/cli/src/commands/review/base-tree.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { execFileSync } from 'node:child_process';
import {
appendFileSync,
chmodSync,
utimesSync,
mkdtempSync,
mkdirSync,
Expand Down Expand Up @@ -302,6 +304,46 @@ describe('runBaseTree', () => {
expect(r.note).toMatch(/base worktree could not be created/);
});

it('refuses while repo-local config defines a content filter — the add would execute it', () => {
// The base tree's `worktree add` checks every file out, and a checkout
// EXECUTES `filter.<name>.smudge` — the same surface `scratch-tree`
// refuses to reset through. The attributes line and a matching file make
// the execution real: without the screen, the add below fired the smudge.
const pwned = join(repo, 'PWNED-base');
git(worktree, 'config', 'filter.evil.smudge', `touch ${pwned}`);
const attrs = git(worktree, 'rev-parse', '--git-path', 'info/attributes');
appendFileSync(attrs, '*.txt filter=evil\n');

const r = run();

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

it('adds the base tree with a planted hook and fsmonitor inert', () => {
// The add's initial checkout fires `post-checkout` and refreshes the
// index — running `core.fsmonitor` — from the COMMON dir: one executable
// file and one config write a probe can make. The screen refuses content
// filters (above); these two surfaces are neutralised at the spawn
// instead, and this pins the prefix on THIS command's git — removing it
// creates both markers.
const hooksDir = join(repo, '.git', 'hooks');
git(repo, 'config', 'core.hooksPath', hooksDir);
mkdirSync(hooksDir, { recursive: true });
const hook = join(hooksDir, 'post-checkout');
writeFileSync(hook, `#!/bin/sh\ntouch ${repo}/PWNED-hook\n`);
chmodSync(hook, 0o755);
git(worktree, 'config', 'core.fsmonitor', `touch ${repo}/PWNED-fsm`);

const r = run();

expect(r.available).toBe(true);
expect(existsSync(join(repo, 'PWNED-hook'))).toBe(false);
expect(existsSync(join(repo, 'PWNED-fsm'))).toBe(false);
});

it('ignores an exported GIT_DIR redirect when adding the base tree', () => {
// An exported GIT_DIR overrides repository discovery for every git call
// that inherits it: the add would land in the redirected repository and
Expand Down
17 changes: 15 additions & 2 deletions packages/cli/src/commands/review/base-tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ import { writeStdoutLine, writeStderrLine } from '../../utils/stdioHelpers.js';
import { baseWorktreePath } from './lib/paths.js';
import {
discardWorktree,
INERT_GIT_ARGS,
localFilterRefusal,
sanitizedGitEnv,
worktreeCreateFailureDetail,
type SweepResult,
Expand Down Expand Up @@ -94,8 +96,11 @@ export interface BaseTreeArgs {
// discovery for every call at once — the base tree would be added into the
// redirected repository and its reuse check would read HEAD from it, an A/B
// against the wrong program while every check against the given tree passes.
// The INERT_GIT_ARGS prefix is for the `worktree add` below: its initial
// checkout fires hooks and `core.fsmonitor` from the common dir otherwise,
// and a probe's plant lands exactly there.
function gitOut(cwd: string, ...args: string[]): string {
const r = spawnSync('git', args, {
const r = spawnSync('git', [...INERT_GIT_ARGS, ...args], {
cwd,
encoding: 'utf8',
env: sanitizedGitEnv(),
Expand All @@ -108,7 +113,7 @@ function gitOut(cwd: string, ...args: string[]): string {
}

function git(cwd: string, ...args: string[]): void {
const r = spawnSync('git', args, {
const r = spawnSync('git', [...INERT_GIT_ARGS, ...args], {
Comment on lines 117 to +118

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 — round cap. This round implemented an 8-finding batch within the round cap; this finding is queued for the next round rather than dropped. The GIT_TIMEOUT_MS deadline for the timeout-less spawns is queued as one batch (mechanical but each site needs its own FIFO witness) so the fixes and their witnesses land together.

中文说明

推迟到下一轮 —— 每轮数量上限。本轮在每轮上限内实现了 8 个 finding;该 finding 已排入下一轮队列,不会被丢弃。 为无超时的 spawn 添加 GIT_TIMEOUT_MS 截止时间已作为一个批次排队(改动是机械性的,但每个位置都需要自己的 FIFO 见证),使修复与见证一起落地。

cwd,
encoding: 'utf8',
env: sanitizedGitEnv(),
Expand Down Expand Up @@ -260,6 +265,14 @@ export function runBaseTree(args: BaseTreeArgs): BaseTreeReport {

// The parameter re-narrows: TS narrowing does not cross function scopes.
function buildBaseTree(baseSha: string): BaseTreeReport {
// BEFORE any checkout runs: the `worktree add` below executes whatever
// the screen detects — the same surface `scratch-tree` refuses to reset
// through, one directory over.
const refusal = localFilterRefusal(
worktree,
'the worktree add this command runs',
);
if (refusal !== null) return unavailable(refusal);
let sweep: SweepResult | undefined;
try {
// Clear a stale base tree left by a crashed run — it would fail `add`. Its
Expand Down
39 changes: 38 additions & 1 deletion packages/cli/src/commands/review/fetch-pr.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import type { Argv, CommandModule } from 'yargs';
import { resolve } from 'node:path';
import { join, resolve } from 'node:path';
import {
fetchPrCommand,
countDiffChangedLines,
Expand Down Expand Up @@ -526,6 +529,40 @@ describe('fetch-pr report assembly', () => {
expect(report.host).toBe('ghe.example.com');
});

it('refuses BEFORE the fetch when repo-local config defines a content filter', async () => {
// Step 4's `worktree add` is the pipeline's FIRST checkout, and its
// initial checkout executes repo-local content filters: a plant an
// earlier review's probe left in the shared common dir fires there,
// ahead of every other screen, and persists for the user's own later
// checkouts. The fetch is refused before any ref or worktree exists.
// `spawnSync` stays real in this suite (the child_process mock replaces
// only execFileSync), so the screen reads a fixture repo the test
// chdirs into.
const dir = mkdtempSync(join(tmpdir(), 'qwen-fetch-screen-'));
const g = (...args: string[]) =>
spawnSync('git', args, { cwd: dir, encoding: 'utf8' });
g('init', '-q', '-b', 'main');
g('config', 'filter.evil.smudge', 'touch /tmp/qwen-never');
const prev = process.cwd();
process.chdir(dir);
try {
await expect(reportFor({})).rejects.toThrow('filter.evil.smudge');
// The worktree add — the firing checkout — never ran, and nothing was
// fetched into a ref.
expect(
producerMocks.git.mock.calls.some(
([a, b]: unknown[]) => a === 'worktree' && b === 'add',
),
).toBe(false);
expect(
producerMocks.git.mock.calls.some(([a]: unknown[]) => a === 'fetch'),
).toBe(false);
} finally {
process.chdir(prev);
rmSync(dir, { recursive: true, force: true });
}
});

it('refuses a dash-leading baseRefName from the platform metadata', async () => {
// The base ref is server-controlled and reaches git's argv through the
// base fetch — a dash-leading name (`--upload-pack=<payload>` is
Expand Down
14 changes: 13 additions & 1 deletion packages/cli/src/commands/review/fetch-pr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import {
reviewLeaseHeldByAnotherSession,
reviewLeasePath,
} from '../../services/review-worktree-lease.js';
import { sanitizedGitEnv } from './lib/worktree.js';
import { localFilterRefusal, sanitizedGitEnv } from './lib/worktree.js';
import { setGhHost } from './lib/gh.js';
import { getPlatformReader } from './lib/platform/registry.js';
import type { ReviewPlatformReader } from './lib/platform/types.js';
Expand Down Expand Up @@ -1000,6 +1000,18 @@ async function runFetchPr(args: FetchPrArgs): Promise<void> {
);
}

// Screen BEFORE the fetch, against the main checkout's common dir. The
// review worktree does not exist yet, so there is nothing to screen FROM
// — but step 4's `worktree add` initial checkout would execute any filter
// planted in the shared common dir by an EARLIER review's probe, ahead of
// every other screen this pipeline runs. Refuse before fetching so no ref
// or worktree is created on a dirty common dir. Same refusal as base-tree.
const filterRefusal = localFilterRefusal(
process.cwd(),
'the review worktree add this command runs',
);
if (filterRefusal !== null) throw new Error(filterRefusal);

// 1. Clean any stale worktree / branch from an earlier run.
cleanStale(prNumber);

Expand Down
44 changes: 43 additions & 1 deletion packages/cli/src/commands/review/lib/git.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,16 @@ import {
writeFileSync,
mkdirSync,
symlinkSync,
chmodSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { gitProbe, gitRawTolerateDiff, releaseWorktree } from './git.js';
import {
git as gitUnderTest,
gitProbe,
gitRawTolerateDiff,
releaseWorktree,
} from './git.js';
import { NULL_DEVICE } from './diff-flags.js';
import { isolateHostGitConfig } from './test-utils.js';

Expand Down Expand Up @@ -218,6 +224,42 @@ describe('releaseWorktree', () => {
});
});

describe('the INERT_GIT_ARGS prefix — checkouts through this module execute nothing the config names', () => {
// fetch-pr creates the review worktree through this module's `git` — the
// pipeline's FIRST checkout — and the common dir it reads is exactly where
// a probe's plant lands: ONE executable `post-checkout` file, ONE
// `core.fsmonitor` config write. The wrappers prepend the overrides, so a
// checkout they run fires neither (probe, git 2.39: the unprefixed shape
// fires both; the prefixed one does not).
it('runs a worktree add with a planted hook and fsmonitor inert', () => {
// The fixture points core.hooksPath here already: a plant into it is the
// one-file attack, no config write needed.
const hooksDir = join(repo, '.no-such-hooks');
mkdirSync(hooksDir, { recursive: true });
const hook = join(hooksDir, 'post-checkout');
writeFileSync(hook, `#!/bin/sh\ntouch "${repo}/PWNED-hook"\n`);
chmodSync(hook, 0o755);
git('config', 'core.fsmonitor', `touch ${repo}/PWNED-fsm`);

// Negative control: the SAME add without the prefix fires both plants —
// the fixture is armed, so an inert run below proves the prefix, not an
// unfirable plant.
execFileSync('git', ['worktree', 'add', '-q', 'control', '-b', 'ctrl'], {
cwd: repo,
encoding: 'utf8',
});
expect(existsSync(join(repo, 'PWNED-hook'))).toBe(true);
expect(existsSync(join(repo, 'PWNED-fsm'))).toBe(true);
rmSync(join(repo, 'PWNED-hook'));
rmSync(join(repo, 'PWNED-fsm'));

gitUnderTest('worktree', 'add', '-q', 'inert', '-b', 'inert-topic');
expect(existsSync(join(repo, 'inert'))).toBe(true);
expect(existsSync(join(repo, 'PWNED-hook'))).toBe(false);
expect(existsSync(join(repo, 'PWNED-fsm'))).toBe(false);
});
});

describe('gitRawTolerateDiff', () => {
it('returns the diff when git exits 1 because the inputs differ', () => {
writeFileSync(join(repo, 'new.ts'), 'export const a = 1;\n');
Expand Down
30 changes: 25 additions & 5 deletions packages/cli/src/commands/review/lib/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,29 @@
// across platforms.

import { execFileSync } from 'node:child_process';
import { redirectedAncestor, sanitizedGitEnv } from './worktree.js';
import {
INERT_GIT_ARGS,
redirectedAncestor,
sanitizedGitEnv,
} from './worktree.js';
import { existsSync, lstatSync, rmSync } from 'node:fs';
import { dirname, resolve } from 'node:path';

/** Deadline for a single `git` invocation. Generous; a hang must still end. */
export const GIT_TIMEOUT_MS = 120_000;

/**
* Args prepended to every invocation below: {@link INERT_GIT_ARGS}. A
* checkout launched through this module — fetch-pr's `worktree add` that
* creates the review worktree is one — executes hooks and `core.fsmonitor`
* from the common dir otherwise, and a probe's plant lands exactly there.
* Commands that run neither are unaffected by the overrides; uniformity is
* the same trade this file already makes with the sanitised env.
*/
function gitArgs(args: string[]): string[] {
return [...INERT_GIT_ARGS, ...args];
}

/**
* Options every wrapper shares, **read fresh on every call**.
*
Expand Down Expand Up @@ -47,7 +63,7 @@ function gitOpts() {

/** Run `git` with args. Returns stdout, trimmed and CRLF-normalised. */
export function git(...args: string[]): string {
return execFileSync('git', args, { ...gitOpts(), encoding: 'utf8' })
return execFileSync('git', gitArgs(args), { ...gitOpts(), encoding: 'utf8' })
.replace(/\r\n/g, '\n')
.trim();
}
Expand All @@ -60,7 +76,11 @@ export function git(...args: string[]): string {
* every other subcommand would try to open the name as an ordinary file.
*/
export function gitWithInput(input: Buffer, args: string[]): string {
return execFileSync('git', args, { ...gitOpts(), encoding: 'utf8', input })
return execFileSync('git', gitArgs(args), {
...gitOpts(),
encoding: 'utf8',
input,
})
.replace(/\r\n/g, '\n')
.trim();
}
Expand Down Expand Up @@ -99,7 +119,7 @@ export function gitProbe(...args: string[]): {
} {
try {
return {
out: execFileSync('git', args, {
out: execFileSync('git', gitArgs(args), {
...gitOpts(),
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
Expand Down Expand Up @@ -286,7 +306,7 @@ export function releaseWorktree(worktreePath: string): WorktreeRelease {
* ENOBUFS rather than returning a short read. Diff capture uses this instead.
*/
export function gitRaw(...args: string[]): Buffer {
return execFileSync('git', args, {
return execFileSync('git', gitArgs(args), {
...gitOpts(),
maxBuffer: 512 * 1024 * 1024,
stdio: ['ignore', 'pipe', 'pipe'],
Expand Down
Loading
Loading