From c0b66e11b18d33e88d884eed10ddec55383a8156 Mon Sep 17 00:00:00 2001 From: ymac <707337118@qq.com> Date: Thu, 1 Oct 2026 22:00:36 +0800 Subject: [PATCH 1/2] fix(git): answer the dubious-ownership guard per command (#690) --- src/git.ts | 69 +++++++++++++++++++++++++-- tests/git-spawn.spec.ts | 101 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 165 insertions(+), 5 deletions(-) diff --git a/src/git.ts b/src/git.ts index 29e5aad4..794b962d 100644 --- a/src/git.ts +++ b/src/git.ts @@ -6,6 +6,10 @@ * `-C ` on the session's working directory and `--no-pager` / * `-c color.ui=false` so output stays machine-readable. * + * A repository whose owner differs from the running user is refused by git's + * own CVE-2022-24765 guard (git ≥ 2.35.2); {@link runGit} answers that + * refusal per command — see the `safe.directory` retry below (issue #690). + * * Commits use the user's git global identity untouched (never sets * user.name/user.email). */ @@ -156,14 +160,53 @@ export function parseLogLines(output: string): GitLogEntry[] { return rows } -/** Run one git command; resolves with stdout, rejects with GitCommandError. */ -function runGit(cwd: string, args: string[], timeoutMs = 30_000): Promise { - const full = ['-C', cwd, '--no-pager', '-c', 'color.ui=false', ...args] +/** + * git's CVE-2022-24765 guard (git ≥ 2.35.2) refuses to read a repository whose + * owner differs from the running user — the shape behind issue #690 is a + * root-run DSH over a site directory owned by `www`, where changing the owner + * is not an option. The refusal is per command and self-describing: git names + * the directory it refused, which is exactly what `safe.directory` takes. + * Answering it with `-c safe.directory=` therefore stays narrow — no + * config file is written, `*` is never used, and the next command faces the + * guard again. + */ +const DUBIOUS_OWNERSHIP = /dubious ownership/i +/** The directory named by the refusal (`fatal: detected dubious ownership in + * repository at '/srv/site'`). */ +const REFUSED_REPOSITORY = /detected dubious ownership in repository at '([^']*)'/ + +/** The repository path a dubious-ownership refusal names, or undefined when + * the message carries no path (an older or reworded git) — the caller then + * falls back to the cwd it already ran in. */ +export function refusedRepository(message: string): string | undefined { + const path = REFUSED_REPOSITORY.exec(message)?.[1] + return path === undefined || path === '' ? undefined : path +} + +/** Child environment for every git call. `GIT_OPTIONAL_LOCKS=0` keeps the + * read-only panel from taking write locks; `LC_ALL=C` keeps stdout AND stderr + * stable, which is what makes the refused path above parseable. */ +const GIT_ENV = { GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' } as const + +/** One spawn. `safe` directories ride in as per-invocation `safe.directory` + * overrides (empty on the first attempt, so a healthy repository sees the + * exact same argv it always did). */ +function spawnGit( + cwd: string, + args: string[], + timeoutMs: number, + safe: readonly string[], +): Promise { + const full = [ + '-C', cwd, '--no-pager', '-c', 'color.ui=false', + ...safe.flatMap(dir => ['-c', `safe.directory=${dir}`]), + ...args, + ] return new Promise((resolvePromise, reject) => { const child = spawn('git', full, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, - env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' }, + env: { ...process.env, ...GIT_ENV }, }) let stdout = '' let stderr = '' @@ -188,6 +231,24 @@ function runGit(cwd: string, args: string[], timeoutMs = 30_000): Promise { + return spawnGit(cwd, args, timeoutMs, []).catch((error: unknown) => { + if (!(error instanceof GitCommandError) || !DUBIOUS_OWNERSHIP.test(error.message)) throw error + const refused = refusedRepository(error.message) + const trust = refused === undefined || refused === cwd ? [cwd] : [refused, cwd] + return spawnGit(cwd, args, timeoutMs, trust) + }) +} + /** Cap on child directories probed by the workspace-container fallback scan. * A home-directory cwd can hold hundreds of visible folders (Library, iCloud * mounts…); probing them all serially is what froze the panel in #369. */ diff --git a/tests/git-spawn.spec.ts b/tests/git-spawn.spec.ts index 569df70c..6ddfd3d0 100644 --- a/tests/git-spawn.spec.ts +++ b/tests/git-spawn.spec.ts @@ -6,12 +6,111 @@ const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() })) vi.mock('node:child_process', () => ({ spawn: spawnMock })) -import { isGitRepo, worktrees } from '../src/git.ts' +import { currentBranch, isGitRepo, refusedRepository, worktrees } from '../src/git.ts' afterEach(() => { spawnMock.mockReset() }) +/** A fake spawned git that ends its streams and closes with `code`. */ +function fakeGit(stdoutText = '', stderrText = '', code = 0): EventEmitter { + const child = new EventEmitter() + const stdout = new PassThrough() + const stderr = new PassThrough() + Object.assign(child, { stdout, stderr, kill: vi.fn() }) + queueMicrotask(() => { + stdout.end(stdoutText) + stderr.end(stderrText) + child.emit('close', code) + }) + return child +} + +/** git ≥ 2.35.2's refusal, verbatim (the hint text included). */ +const DUBIOUS = "fatal: detected dubious ownership in repository at '/srv/site'\n" + + 'To add an exception for this directory, call:\n\n' + + '\tgit config --global --add safe.directory /srv/site\n' + +describe('dubious-ownership retry (issue #690)', () => { + it('retries once, trusting only the repository git refused for this invocation', async () => { + const calls: string[][] = [] + spawnMock.mockImplementation((_file: string, args: string[]) => { + calls.push(args) + return calls.length === 1 ? fakeGit('', DUBIOUS, 128) : fakeGit('true\n') + }) + + await expect(isGitRepo('/srv/site/wp-content')).resolves.toBe(true) + + expect(calls).toHaveLength(2) + // The first attempt is the argv a healthy repository always got... + expect(calls[0]).toEqual([ + '-C', '/srv/site/wp-content', '--no-pager', '-c', 'color.ui=false', + 'rev-parse', '--is-inside-work-tree', + ]) + // ...and the retry trusts exactly what git named (the repository ROOT, not + // the cwd — the refusal names the root) plus the cwd, and never '*'. + expect(calls[1]).toEqual([ + '-C', '/srv/site/wp-content', '--no-pager', '-c', 'color.ui=false', + '-c', 'safe.directory=/srv/site', + '-c', 'safe.directory=/srv/site/wp-content', + 'rev-parse', '--is-inside-work-tree', + ]) + }) + + it('runs git under a C locale so the refused path stays parseable', async () => { + spawnMock.mockImplementation(() => fakeGit('true\n')) + + await isGitRepo('/srv/site') + + expect(spawnMock).toHaveBeenCalledWith( + 'git', + expect.anything(), + expect.objectContaining({ + env: expect.objectContaining({ GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' }), + }), + ) + }) + + it('does not retry a failure that is not the ownership guard', async () => { + spawnMock.mockImplementation(() => fakeGit('', 'fatal: not a git repository (or any of the parent directories): .git\n', 128)) + + await expect(isGitRepo('/tmp/plain')).resolves.toBe(false) + + expect(spawnMock).toHaveBeenCalledTimes(1) + }) + + it('falls back to the cwd when the refusal names no directory', async () => { + const calls: string[][] = [] + spawnMock.mockImplementation((_file: string, args: string[]) => { + calls.push(args) + return calls.length === 1 ? fakeGit('', 'fatal: detected dubious ownership\n', 128) : fakeGit('true\n') + }) + + await expect(isGitRepo('/srv/site')).resolves.toBe(true) + + expect(calls[1]?.slice(5, 7)).toEqual(['-c', 'safe.directory=/srv/site']) + expect(calls[1]?.some(arg => arg.includes('safe.directory=*'))).toBe(false) + }) + + it('reports a second refusal instead of retrying forever', async () => { + const calls: string[][] = [] + spawnMock.mockImplementation((_file: string, args: string[]) => { + calls.push(args) + return fakeGit('', DUBIOUS, 128) + }) + + await expect(currentBranch('/srv/site')).rejects.toThrow(/dubious ownership/) + expect(calls).toHaveLength(2) + }) + + it('reads the refused path out of the git message', () => { + expect(refusedRepository(DUBIOUS)).toBe('/srv/site') + // Percent-escaped or otherwise unusual messages must simply yield nothing. + expect(refusedRepository('fatal: detected dubious ownership\n')).toBeUndefined() + expect(refusedRepository('')).toBeUndefined() + }) +}) + describe('git subprocess spawning', () => { it('hides spawned git windows', async () => { spawnMock.mockImplementation(() => { From cf9e1c29995050bef5abcc967c1e62d8cb800926 Mon Sep 17 00:00:00 2001 From: ymac <707337118@qq.com> Date: Mon, 5 Oct 2026 10:06:43 +0800 Subject: [PATCH 2/2] test(git): follow dev's core.quotePath=false into the argv assertions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dev added `-c core.quotePath=false` to every git invocation, which shifts both pinned argv shapes and makes the positional `slice(5, 7)` in the cwd-fallback case read the wrong pair. Name the flag set instead of counting positions — the file's own subcommandOf() comment already says counting breaks on every added `-c`. --- tests/git-spawn.spec.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/tests/git-spawn.spec.ts b/tests/git-spawn.spec.ts index 4e812ec3..d075c552 100644 --- a/tests/git-spawn.spec.ts +++ b/tests/git-spawn.spec.ts @@ -26,6 +26,18 @@ function fakeGit(stdoutText = '', stderrText = '', code = 0): EventEmitter { return child } +/** The `-c key=value` overrides runGit put in front of the subcommand. + * Collected by name rather than by index: the flag set grows whenever a new + * global `-c` lands (color.ui, core.quotePath, the per-invocation + * safe.directory…), so a positional slice pins a shape nothing depends on. */ +function configFlagsOf(args: string[] | undefined): string[] { + const flags: string[] = [] + for (let at = 0; at < (args?.length ?? 0); at += 1) { + if (args?.[at] === '-c') flags.push(args[at + 1] ?? '') + } + return flags +} + /** git ≥ 2.35.2's refusal, verbatim (the hint text included). */ const DUBIOUS = "fatal: detected dubious ownership in repository at '/srv/site'\n" + 'To add an exception for this directory, call:\n\n' @@ -45,12 +57,14 @@ describe('dubious-ownership retry (issue #690)', () => { // The first attempt is the argv a healthy repository always got... expect(calls[0]).toEqual([ '-C', '/srv/site/wp-content', '--no-pager', '-c', 'color.ui=false', + '-c', 'core.quotePath=false', 'rev-parse', '--is-inside-work-tree', ]) // ...and the retry trusts exactly what git named (the repository ROOT, not // the cwd — the refusal names the root) plus the cwd, and never '*'. expect(calls[1]).toEqual([ '-C', '/srv/site/wp-content', '--no-pager', '-c', 'color.ui=false', + '-c', 'core.quotePath=false', '-c', 'safe.directory=/srv/site', '-c', 'safe.directory=/srv/site/wp-content', 'rev-parse', '--is-inside-work-tree', @@ -88,7 +102,7 @@ describe('dubious-ownership retry (issue #690)', () => { await expect(isGitRepo('/srv/site')).resolves.toBe(true) - expect(calls[1]?.slice(5, 7)).toEqual(['-c', 'safe.directory=/srv/site']) + expect(configFlagsOf(calls[1])).toContain('safe.directory=/srv/site') expect(calls[1]?.some(arg => arg.includes('safe.directory=*'))).toBe(false) })