merge pr-827 (#827 fix(git): 自动应答 dubious ownership 守卫,单命令注入 safe.directory) into dev(@yanzhaohui1999)
冲突解决:保留 dev 的 runGit 三道护栏(8 MiB 输出上限 / maxNulFields 行数上限 / core.quotePath=false),
把 #827 的 spawnGit + safe.directory 重试叠在其上;GIT_ENV 取并集(GIT_OPTIONAL_LOCKS=0 + LC_ALL=C)。
不复活已被 ebc5d0b6 删除的 runGitRaw(无调用者)。
This commit is contained in:
commit
f132c69cb0
2 files changed
+182
-10
No files matched your search
+68
-9
@@ -243,6 +243,34 @@ export function parseLogLines(output: string): GitLogEntry[] {
|
||||
return rows
|
||||
}
|
||||
|
||||
/**
|
||||
* 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=<dir>` 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
|
||||
|
||||
/**
|
||||
* Hard ceiling on one git command's stdout. A runaway command — a whole-repo
|
||||
* `diff` with no pathspec (the shape a repository with an unignored nested
|
||||
@@ -276,21 +304,34 @@ function countNulFields(chunk: Buffer): number {
|
||||
return count
|
||||
}
|
||||
|
||||
/** Run one git command; resolves with stdout, rejects with GitCommandError. */
|
||||
export function runGit(cwd: string, args: string[], timeoutMs = 30_000, options: RunGitOptions = {}): Promise<string> {
|
||||
// `core.quotePath=false`: emit paths verbatim instead of C-quoting them
|
||||
// (git's default turns a CJK/space path into an octal-escaped, quoted
|
||||
// string, and every diff surface renders that string as the file name).
|
||||
// The `-z`-framed porcelain callers are unaffected: git never quotes
|
||||
// NUL-framed output.
|
||||
const full = ['-C', cwd, '--no-pager', '-c', 'color.ui=false', '-c', 'core.quotePath=false', ...args]
|
||||
/** 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[],
|
||||
options: RunGitOptions = {},
|
||||
): Promise<string> {
|
||||
const full = [
|
||||
'-C', cwd, '--no-pager', '-c', 'color.ui=false',
|
||||
// `core.quotePath=false`: emit paths verbatim instead of C-quoting them
|
||||
// (git's default turns a CJK/space path into an octal-escaped, quoted
|
||||
// string, and every diff surface renders that string as the file name).
|
||||
// The `-z`-framed porcelain callers are unaffected: git never quotes
|
||||
// NUL-framed output.
|
||||
'-c', 'core.quotePath=false',
|
||||
...safe.flatMap(dir => ['-c', `safe.directory=${dir}`]),
|
||||
...args,
|
||||
]
|
||||
const maxBytes = options.maxBytes ?? GIT_OUTPUT_MAX_BYTES
|
||||
const maxNulFields = options.maxNulFields
|
||||
return new Promise<string>((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 outBytes = 0
|
||||
@@ -347,6 +388,24 @@ export function runGit(cwd: string, args: string[], timeoutMs = 30_000, options:
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Run one git command; resolves with stdout, rejects with GitCommandError.
|
||||
*
|
||||
* A dubious-ownership refusal is retried ONCE with the refused repository
|
||||
* (plus the cwd, which is the answer when the message named no path) trusted
|
||||
* for that invocation only. Anything else — including a second refusal — is
|
||||
* reported as-is, so a repository git cannot be talked into reading still
|
||||
* surfaces its real error instead of a misleading "not a git repository".
|
||||
*/
|
||||
export function runGit(cwd: string, args: string[], timeoutMs = 30_000, options: RunGitOptions = {}): Promise<string> {
|
||||
return spawnGit(cwd, args, timeoutMs, [], options).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, options)
|
||||
})
|
||||
}
|
||||
|
||||
/** One parsed `git blame --porcelain` row (the editor's hover blame). */
|
||||
export interface GitBlameLine {
|
||||
/** 1-based line number in the file as it exists in the worktree. */
|
||||
|
||||
+114
-1
@@ -6,12 +6,125 @@ const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }))
|
||||
|
||||
vi.mock('node:child_process', () => ({ spawn: spawnMock }))
|
||||
|
||||
import { isGitRepo, runGit, worktrees } from '../src/git.ts'
|
||||
import { currentBranch, isGitRepo, refusedRepository, runGit, 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
|
||||
}
|
||||
|
||||
/** 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'
|
||||
+ '\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',
|
||||
'-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',
|
||||
])
|
||||
})
|
||||
|
||||
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(configFlagsOf(calls[1])).toContain('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(() => {
|
||||
|
||||
Reference in new issue
Block a user