Files
orca/src/main/win32-utils.test.ts
T
cfc444242c fix(win32): resolve EPERM on userData writes, batch-file spawn failures, and native dep rebuild (#1152)
* chore: update .gitignore to include stackdump and .serena, enhance pre-commit script

* fix(win32): resolve EPERM on userData writes and batch-file spawn failures

Three Windows-specific issues prevented Orca from running correctly on
machines where Chromium resets the userData DACL during startup:

1. **EPERM on userData writes** — Chromium's BrowserWindow constructor calls
   SetNamedSecurityInfo on the userData folder with a Protected DACL.  When
   propagated to child directories the ACEs carry the Inherit-Only flag,
   meaning they apply to children-of-children but NOT to the directories
   themselves.  Any file write inside codex-runtime-home, agent-hooks, or
   similar subdirectories fails with EPERM.

   Fix: grant an explicit Full Control ACE (OI)(CI)(F) on userData and all
   existing children before BrowserWindow is created (icacls /T /C).
   Explicit ACEs survive future DACL propagation from the parent.  Per-write
   EPERM retries in fs-utils and installer-utils serve as the backstop for
   directories created after startup.

2. **Batch-file spawn failures** — resolveCodexCommand() can return a .cmd
   or .bat path (e.g. codex.cmd installed via npm).  Node's spawn() cannot
   execute batch scripts directly without shell:true, but shell:true with an
   args array triggers DEP0190 because args are concatenated rather than
   escaped.  Both service.ts and codex-fetcher.ts were affected.

   Fix: detect .cmd/.bat paths and route through cmd.exe /c explicitly,
   which is equivalent to what shell:true does internally but avoids the
   deprecation warning and arg-escaping hazard.

3. **Native dep rebuild failure** — electron-builder install-app-deps does
   not expose the ignoreModules option.  On Windows dev machines without the
   full VC++ / Python toolchain, cpu-features (an optional dep of ssh2) fails
   to build with node-gyp, aborting the entire postinstall step.

   Fix: replace electron-builder install-app-deps with a thin wrapper script
   (scripts/rebuild-native-deps.mjs) that calls @electron/rebuild's JS API
   directly with ignoreModules: ['cpu-features'] on Windows.  ssh2 detects
   the missing native module and falls back to pure-JS automatically.

Refactoring: extract shared win32-utils.ts with getIcaclsExePath(),
getCmdExePath(), isWindowsBatchScript(), isPermissionError(), grantDirAcl(),
and getSpawnArgsForWindows() to eliminate five instances of duplicated
SystemRoot path construction and two near-identical EPERM retry blocks.
Reduce startup icacls calls from three sequential blocking /T invocations
to one, removing up to 20 s of potential startup delay.

* fix(win32): address review feedback on ACL and spawn helpers

- Fall back to SID via `whoami /user` when `USERNAME` is unset so
  `grantDirAcl` works under services, CI, and hardened envs instead of
  silently no-op'ing.
- Use a 60s timeout for recursive `icacls /T` walks; the 10s cap could
  starve on large userData trees and silently fail the startup grant.
- Pass `windowsHide: true` to `icacls` and the cmd.exe-routed Codex
  spawns so no console window flashes in the packaged GUI app.
- Add `/d` to `cmd.exe /c` invocations to disable AutoRun registry
  commands — safer default for background spawns.
- Drop unused `createRequire`/`require` from rebuild-native-deps.mjs.
- Add `@electron/rebuild` as an explicit devDependency; relying on the
  electron-builder transitive was brittle under pnpm.
- Fix two misleading "Re-enable inheritance" comments that describe
  behavior opposite to what the code actually does (explicit ACL grant).
- Add unit tests for `isWindowsBatchScript`, `getSpawnArgsForWindows`,
  and `isPermissionError` to lock in Windows batch detection + cmd.exe
  routing.

Co-authored-by: Orca <help@stably.ai>

* fix(win32): unify PTY spawn through /d and document cmd.exe safety

- fetchViaPty now uses getCmdExePath() and /d /c, matching the rest of
  the codebase instead of hand-rolling 'cmd.exe' + ['/c', ...].
- getSpawnArgsForWindows gains a SAFETY note: when the .cmd/.bat branch
  is taken, cmd.exe re-parses the combined command line, so callers
  must only pass trusted/literal args.

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>
Co-authored-by: Orca <help@stably.ai>
2026-04-26 22:29:58 -07:00

92 lines
3.3 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { getSpawnArgsForWindows, isPermissionError, isWindowsBatchScript } from './win32-utils'
function withPlatform<T>(platform: NodeJS.Platform, fn: () => T): T {
const original = process.platform
Object.defineProperty(process, 'platform', { configurable: true, value: platform })
try {
return fn()
} finally {
Object.defineProperty(process, 'platform', { configurable: true, value: original })
}
}
describe('isWindowsBatchScript', () => {
it('detects .cmd and .bat on win32', () => {
withPlatform('win32', () => {
expect(isWindowsBatchScript('C:\\tools\\codex.cmd')).toBe(true)
expect(isWindowsBatchScript('C:\\tools\\codex.BAT')).toBe(true)
})
})
it('returns false for non-batch extensions', () => {
withPlatform('win32', () => {
expect(isWindowsBatchScript('C:\\tools\\codex.exe')).toBe(false)
expect(isWindowsBatchScript('C:\\tools\\codex')).toBe(false)
})
})
it('returns false on non-win32 regardless of extension', () => {
withPlatform('linux', () => {
expect(isWindowsBatchScript('/usr/bin/foo.cmd')).toBe(false)
})
})
})
describe('getSpawnArgsForWindows', () => {
it('routes .cmd through cmd.exe with /d /c on win32', () => {
const originalComSpec = process.env.ComSpec
process.env.ComSpec = 'C:\\Windows\\System32\\cmd.exe'
try {
withPlatform('win32', () => {
const { spawnCmd, spawnArgs } = getSpawnArgsForWindows('C:\\tools\\codex.cmd', [
'login',
'--foo'
])
expect(spawnCmd).toBe('C:\\Windows\\System32\\cmd.exe')
// Why: /d disables AutoRun; /c runs the given command and exits. Args
// follow the batch path literally without re-escaping.
expect(spawnArgs).toEqual(['/d', '/c', 'C:\\tools\\codex.cmd', 'login', '--foo'])
})
} finally {
if (originalComSpec === undefined) {
delete process.env.ComSpec
} else {
process.env.ComSpec = originalComSpec
}
}
})
it('passes .exe through unchanged on win32', () => {
withPlatform('win32', () => {
const { spawnCmd, spawnArgs } = getSpawnArgsForWindows('C:\\tools\\codex.exe', ['login'])
expect(spawnCmd).toBe('C:\\tools\\codex.exe')
expect(spawnArgs).toEqual(['login'])
})
})
it('passes posix paths through unchanged on non-win32', () => {
withPlatform('darwin', () => {
const { spawnCmd, spawnArgs } = getSpawnArgsForWindows('/usr/local/bin/codex', ['login'])
expect(spawnCmd).toBe('/usr/local/bin/codex')
expect(spawnArgs).toEqual(['login'])
})
})
})
describe('isPermissionError', () => {
it('returns true for EPERM and EACCES Node errors', () => {
const eperm = Object.assign(new Error('denied'), { code: 'EPERM' })
const eacces = Object.assign(new Error('denied'), { code: 'EACCES' })
expect(isPermissionError(eperm)).toBe(true)
expect(isPermissionError(eacces)).toBe(true)
})
it('returns false for unrelated errors and non-error values', () => {
expect(isPermissionError(Object.assign(new Error('nope'), { code: 'ENOENT' }))).toBe(false)
expect(isPermissionError(new Error('plain'))).toBe(false)
expect(isPermissionError(null)).toBe(false)
expect(isPermissionError('EPERM')).toBe(false)
})
})