From 4100e16c731738d6da760f9ed745bb7ad9ab81c8 Mon Sep 17 00:00:00 2001 From: 6699ll <6699ll@users.noreply.github.com> Date: Tue, 22 Sep 2026 03:12:00 +0800 Subject: [PATCH] fix(security): stop git operands parsing as options, and harden the API dispatch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three small hardening fixes on the host half, all in the same request path. 1) git revisions were spliced into argv as bare operands, so a value beginning with `-` was consumed by git's OPTION parser instead of being treated as a revision. `git.show` with rev `--stat` (or `--output=…`) returned empty instead of failing, which silently blanked the Changes tab's diff/blame panes; `git.commit-diff`/`revert`/`cherry-pick` took the same shape. Adding `--end-of-options` before the operand ends option parsing. Chosen over a regex allowlist on purpose: the UI legitimately sends `:0` (git's index selector, used for the worktree side of a diff) and `^`, and users have branch names this code cannot enumerate. A whitelist would have to keep growing and would still reject valid refs; the sentinel is exact and needs no enumeration. 2) `GitCommandError` had no branch in `writeError`, so every ordinary git failure — unknown ref, path outside the repository, not a repository — surfaced as 500 `internal`. That reads as a plugin crash and meant the `not-repo` code (already defined in git.ts) and its localized copy were unreachable from every route. Non-repository now answers 409 `not-repo`; other git failures answer 400 `git-error`. 3) the `/sidebar/api` dispatch table is an object literal, so a bare lookup resolved `Object.prototype` members as handlers: POST /sidebar/api/constructor -> 200 {} POST /sidebar/api/toString -> 200 "[object Undefined]" POST /sidebar/api/valueOf -> 500 internal POST /sidebar/api/hasOwnProperty -> 500 internal Switched to `Object.hasOwn` plus a `typeof === 'function'` guard, so every one of those is the documented 404. Verified: - `tests/smoke.spec.ts` gains four cases. Three are red on the pre-change source (operand guard: `show(dir,'--stat',…)` returned content instead of null; dispatch: `constructor` answered 200; git status: 500 instead of 409) and green after. - the fourth pins the `:0` index selector as a NON-regression, so a future tightening of the operand handling cannot silently break the diff UI. - the repo's own `harden` regression is covered: `git.revert(dir, '--abort')` and `cherryPick(dir, '--abort')` now reject rather than being honoured. - empirically re-verified against git 2.53.0 that every legitimate revision form still resolves (`HEAD`, `:0`, ``, `^`, `HEAD~1`) while `--stat` / `--output=nul` / `-n` are refused. - the wire.ts -> git.ts import introduces no cycle (git.ts imports only node builtins) and both bundles build clean; typecheck / lint / build / check:consumer-types clean. - `pnpm test:windows` 1351 passed, 4 failed — byte-identical to the clean-main baseline for those two files (pre-existing Windows environment failures). --- src/git.ts | 25 ++++++++++++----- src/index.ts | 9 ++++-- src/wire.ts | 17 ++++++++++++ tests/smoke.spec.ts | 67 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 109 insertions(+), 9 deletions(-) diff --git a/src/git.ts b/src/git.ts index 29e5aad4..c506b2da 100644 --- a/src/git.ts +++ b/src/git.ts @@ -430,10 +430,18 @@ export async function log(cwd: string, count = 30, skip = 0, selected?: string): /** * Content of a file at a revision (`git show :`), or null when the * revision has no such path (a new/untracked file has no HEAD side). + * + * `--end-of-options` precedes the operand: without it a caller-supplied `rev` + * beginning with `-` is parsed as an OPTION rather than a revision, so + * `rev: "--output=NUL"` silently wrote to a file and returned empty instead of + * failing (the Changes tab's diff/blame panes then rendered blank). The + * sentinel ends option parsing, so the operand can never be a flag while every + * legitimate revision form still works (`HEAD`, `:0`, `^`, `HEAD~2`, + * `origin/main`, any branch name). */ export async function show(cwd: string, rev: string, path: string, selected?: string): Promise { try { - return await runGit(await repoRoot(cwd, selected), ['show', `${rev}:${path}`]) + return await runGit(await repoRoot(cwd, selected), ['show', '--end-of-options', `${rev}:${path}`]) } catch { return null } @@ -441,9 +449,10 @@ export async function show(cwd: string, rev: string, path: string, selected?: st /** Full patch text of one commit (`git show` with the commit header suppressed). * Merge commits show their diff against the first parent (`-m --first-parent` - * is a no-op for regular commits), so a history click always has content. */ + * is a no-op for regular commits), so a history click always has content. + * `--end-of-options` keeps a caller-supplied hash from parsing as an option. */ export async function commitDiff(cwd: string, hash: string, selected?: string): Promise { - return runGit(await repoRoot(cwd, selected), ['show', '--no-ext-diff', '--no-color', '--format=', '-m', '--first-parent', hash]) + return runGit(await repoRoot(cwd, selected), ['show', '--no-ext-diff', '--no-color', '--format=', '-m', '--first-parent', '--end-of-options', hash]) } /** Discard the worktree changes of one path (`git checkout -- `; the index is untouched). */ @@ -451,12 +460,14 @@ export async function discard(cwd: string, path: string, selected?: string): Pro await runGit(await repoRoot(cwd, selected), ['checkout', '--', path]) } -/** Revert one commit onto the current branch with an auto-generated message. */ +/** Revert one commit onto the current branch with an auto-generated message. + * `--end-of-options` keeps a caller-supplied hash from parsing as an option. */ export async function revert(cwd: string, hash: string, selected?: string): Promise { - await runGit(await repoRoot(cwd, selected), ['revert', '--no-edit', hash]) + await runGit(await repoRoot(cwd, selected), ['revert', '--no-edit', '--end-of-options', hash]) } -/** Cherry-pick one commit onto the current branch. */ +/** Cherry-pick one commit onto the current branch. + * `--end-of-options` keeps a caller-supplied hash from parsing as an option. */ export async function cherryPick(cwd: string, hash: string, selected?: string): Promise { - await runGit(await repoRoot(cwd, selected), ['cherry-pick', hash]) + await runGit(await repoRoot(cwd, selected), ['cherry-pick', '--end-of-options', hash]) } diff --git a/src/index.ts b/src/index.ts index 9598be87..a3f95316 100644 --- a/src/index.ts +++ b/src/index.ts @@ -901,8 +901,13 @@ export function apply(ctx: Context, config?: SidebarConfig): void { } try { const payload = await readJsonBody(req) - const handler = api[method] - if (handler === undefined) { + // Own properties only. The dispatch table is an object literal, so a + // bare lookup resolved Object.prototype members as "methods": + // POST /sidebar/api/constructor answered 200 {}, toString answered + // 200 "[object Undefined]", valueOf/hasOwnProperty answered 500. + // The typeof guard also rejects a non-function own value. + const handler = Object.hasOwn(api, method) ? api[method] : undefined + if (typeof handler !== 'function') { throw new SidebarError('not-found', `unknown sidebar API method "${method}"`, 404) } writeOk(res, await handler(payload)) diff --git a/src/wire.ts b/src/wire.ts index 30025432..bef8dec5 100644 --- a/src/wire.ts +++ b/src/wire.ts @@ -5,6 +5,10 @@ * (HTTP 4xx/5xx matching the code) on failure. */ import type { SidebarHttpRequest, SidebarHttpResponse } from './context-types.ts' +// Value import for the error-class branch in writeError. git.ts imports only +// node builtins, so this introduces no cycle; wire.ts is host-half only and is +// never reachable from the browser bundle. +import { GitCommandError } from './git.ts' /** Machine-readable error codes of the sidebar API. */ export type SidebarErrorCode = @@ -88,6 +92,19 @@ export function writeError(res: SidebarHttpResponse, error: unknown): void { writeJson(res, error.status, { ok: false, error: { code: error.code, message: error.message } }) return } + // A git failure is a state/input problem the user caused (unknown ref, path + // outside the repository, not a repository), not a plugin fault. Reporting it + // as 500 "internal" reads as a crash and hides the localized not-a-repository + // copy the client already knows how to render; `not-repo` carries its own + // code (409) so that path is reachable at all. + if (error instanceof GitCommandError) { + const notRepo = error.code === 'not-repo' + writeJson(res, notRepo ? 409 : 400, { + ok: false, + error: { code: notRepo ? 'not-repo' : 'git-error', message: error.message }, + }) + return + } const message = error instanceof Error ? error.message : String(error) writeJson(res, 500, { ok: false, error: { code: 'internal', message } }) } diff --git a/tests/smoke.spec.ts b/tests/smoke.spec.ts index 16caa480..938f61f9 100644 --- a/tests/smoke.spec.ts +++ b/tests/smoke.spec.ts @@ -491,6 +491,42 @@ describe('git destructive operations (scratch repository)', () => { rmSync(dir, { recursive: true, force: true }) } }) + + it('never parses a revision-shaped operand as a git option', async () => { + const dir = makeScratchRepo() + try { + const hash = (await git.log(dir))[0]!.hashFull + // Every revision form the UI actually sends must keep working. + await expect(git.show(dir, 'HEAD', 'a.txt')).resolves.toContain('one') + await expect(git.show(dir, hash, 'a.txt')).resolves.toContain('one') + await expect(git.commitDiff(dir, hash)).resolves.toContain('a.txt') + // Operand-shaped option strings must NOT be honoured as flags. Before + // --end-of-options, `show(dir, '--stat', ...)` was consumed as a flag and + // returned empty, blanking the Changes tab's diff/blame panes. + for (const hostile of ['--stat', '--output=nul', '-n', '--no-color']) { + const content = await git.show(dir, hostile, 'a.txt') + expect(content, hostile).toBeNull() + } + await expect(git.commitDiff(dir, '--stat')).rejects.toThrow() + await expect(git.revert(dir, '--abort')).rejects.toThrow() + await expect(git.cherryPick(dir, '--abort')).rejects.toThrow() + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('keeps the index revision selector (:0) working', async () => { + // `:0` is git's own index syntax and the UI uses it for the worktree side + // of a diff, so the operand guard must not reject it. + const dir = makeScratchRepo() + try { + writeFileSync(join(dir, 'a.txt'), 'staged-change\n') + gitRun(dir, ['add', 'a.txt']) + await expect(git.show(dir, ':0', 'a.txt')).resolves.toContain('staged-change') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) }) describe('session cwd resolution over the API route', () => { @@ -572,6 +608,37 @@ describe('session cwd resolution over the API route', () => { expect(result.value?.cwd).toBe(process.cwd()) }) + it('answers 404 for Object.prototype member names instead of resolving them as methods', async () => { + // The dispatch table is an object literal, so a bare lookup used to find + // Object.prototype members and treat them as handlers: `constructor` + // answered 200 {}, `toString` answered 200 "[object Undefined]", and + // `valueOf` / `hasOwnProperty` answered 500. All must be the documented 404. + const route = mount() + for (const method of ['constructor', 'toString', 'valueOf', 'hasOwnProperty', '__proto__']) { + const result = await invoke(route, method, {}) + expect(result, method).toMatchObject({ ok: false, status: 404, error: { code: 'not-found' } }) + } + // A genuinely unknown method keeps its existing 404 contract. + const unknown = await invoke(route, 'no-such-method', {}) + expect(unknown).toMatchObject({ ok: false, status: 404, error: { code: 'not-found' } }) + }) + + it('reports a git failure as a 4xx git error, not an internal 500', async () => { + // `GitCommandError` used to fall through to the generic branch and surface + // as 500 "internal", which reads as a plugin crash and hid the localized + // not-a-repository copy the client already renders. A non-repository cwd + // must answer 409 not-repo. + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-git-notrepo-')) + try { + const route = mount({ sessions: { get: () => ({ header: { cwd: dir } }) } }) + const notRepo = await invoke(route, 'git.branch', { sessionId: 's', cwd: dir }) + expect(notRepo).toMatchObject({ ok: false, status: 409, error: { code: 'not-repo' } }) + expect(notRepo.error?.message).not.toContain('internal') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + it('resolves a cold (detached) session cwd through the persistence index', async () => { // Regression: a detached first request (session not yet attached, no // client cwd) must resolve the cwd from the session-persistence index