fix(windows): slow launch + keystroke stalls — main process synchronously spawns powershell to re-harden env-store ACLs (#4840)

* fix(windows): stop synchronous powershell ACL spawns blocking the main thread

markEnvironmentUsed re-hardened the env-store on every runtime round-trip,
spawning powershell.exe ~5x synchronously (~1-1.5s each) and freezing the
Windows UI on launch and every keystroke. Throttle the non-security lastUsedAt
write (60s window; runtimeId changes bypass) and make path hardening idempotent
per process. ACL hardening is preserved; post-rename credential hardening still
always runs. ~14.0s -> ~6.8s launch; main thread 95.7% blocked -> 99.0% idle.

* Fix secure-file hardening cache retries

---------

Co-authored-by: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com>
This commit is contained in:
Lesley Murfin
2026-06-07 21:47:54 -04:00
committed by GitHub
co-authored by Jinwoo Hong
parent 102cbdbda2
commit 3d013e48e8
4 changed files with 316 additions and 43 deletions
+53 -2
View File
@@ -1,12 +1,13 @@
import { mkdtempSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { afterEach, describe, expect, it } from 'vitest'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { encodePairingOffer } from './pairing'
import {
RuntimeEnvironmentStoreError,
addEnvironmentFromPairingCode,
listEnvironments
listEnvironments,
markEnvironmentUsed
} from './runtime-environment-store'
function pairingCode(endpoint = 'ws://127.0.0.1:6768'): string {
@@ -20,8 +21,17 @@ function pairingCode(endpoint = 'ws://127.0.0.1:6768'): string {
describe('runtime environment store', () => {
const tempDirs: string[] = []
const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
beforeEach(() => {
// Why: this suite tests store timestamps, while secure-file tests cover Windows ACLs.
Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' })
})
afterEach(() => {
if (originalPlatform) {
Object.defineProperty(process, 'platform', originalPlatform)
}
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
@@ -44,4 +54,45 @@ describe('runtime environment store', () => {
).toThrow(RuntimeEnvironmentStoreError)
expect(listEnvironments(userDataPath)).toEqual([first])
})
it('throttles lastUsedAt writes so it does not rewrite the store on every runtime call', () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-env-store-'))
tempDirs.push(userDataPath)
const env = addEnvironmentFromPairingCode(userDataPath, {
name: 'dev box',
pairingCode: pairingCode()
})
// First use persists (lastUsedAt started null).
markEnvironmentUsed(userDataPath, env.id, { runtimeId: 'runtime-1', now: 1_000 })
expect(listEnvironments(userDataPath)[0]).toMatchObject({
lastUsedAt: 1_000,
runtimeId: 'runtime-1'
})
// A second use shortly after, same runtime, is skipped — lastUsedAt stays put.
markEnvironmentUsed(userDataPath, env.id, { runtimeId: 'runtime-1', now: 5_000 })
expect(listEnvironments(userDataPath)[0]!.lastUsedAt).toBe(1_000)
// Once the throttle window elapses, it persists again.
markEnvironmentUsed(userDataPath, env.id, { runtimeId: 'runtime-1', now: 61_000 })
expect(listEnvironments(userDataPath)[0]!.lastUsedAt).toBe(61_000)
})
it('persists immediately when the runtimeId changes within the throttle window', () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-env-store-'))
tempDirs.push(userDataPath)
const env = addEnvironmentFromPairingCode(userDataPath, {
name: 'dev box',
pairingCode: pairingCode()
})
markEnvironmentUsed(userDataPath, env.id, { runtimeId: 'runtime-1', now: 1_000 })
// A different runtimeId inside the window must not be dropped.
markEnvironmentUsed(userDataPath, env.id, { runtimeId: 'runtime-2', now: 2_000 })
expect(listEnvironments(userDataPath)[0]).toMatchObject({
lastUsedAt: 2_000,
runtimeId: 'runtime-2'
})
})
})
+13
View File
@@ -96,6 +96,11 @@ export function resolveEnvironmentPairingOffer(
return getPreferredPairingOffer(resolveEnvironment(userDataPath, selector))
}
// Why: markEnvironmentUsed runs on every runtime round-trip; persisting lastUsedAt each
// time forces a secure-file rewrite (ACL hardening), which blocks the main thread on
// Windows. lastUsedAt only needs coarse freshness, so skip writes within this window.
const LAST_USED_PERSIST_INTERVAL_MS = 60_000
export function markEnvironmentUsed(
userDataPath: string,
selector: string,
@@ -104,6 +109,14 @@ export function markEnvironmentUsed(
const store = readEnvironmentStore(userDataPath)
const environment = resolveEnvironmentFromStore(store, selector)
const now = args.now ?? Date.now()
const runtimeIdChanged = args.runtimeId != null && args.runtimeId !== environment.runtimeId
const lastUsedIsFresh =
environment.lastUsedAt != null &&
now >= environment.lastUsedAt &&
now - environment.lastUsedAt < LAST_USED_PERSIST_INTERVAL_MS
if (!runtimeIdChanged && lastUsedIsFresh) {
return
}
const next = store.environments.map((entry) =>
entry.id === environment.id
? {
+112 -1
View File
@@ -1,6 +1,15 @@
import { execFileSync } from 'child_process'
import { mkdtempSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { __resetSecureFileWindowsUserSidForTests, hardenSecurePath } from './secure-file'
import {
__resetSecureFileHardenedPathsForTests,
__resetSecureFileWindowsUserSidForTests,
hardenExistingSecureFile,
hardenSecurePath,
writeSecureFile
} from './secure-file'
vi.mock('child_process', () => ({
execFileSync: vi.fn()
@@ -9,11 +18,14 @@ vi.mock('child_process', () => ({
describe('hardenSecurePath', () => {
const originalSystemRoot = process.env.SystemRoot
const originalWindir = process.env.WINDIR
const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
const tempDirs: string[] = []
beforeEach(() => {
process.env.SystemRoot = 'C:\\Windows'
delete process.env.WINDIR
__resetSecureFileWindowsUserSidForTests()
__resetSecureFileHardenedPathsForTests()
vi.mocked(execFileSync).mockReset()
vi.mocked(execFileSync).mockImplementation((file) => {
if (file === 'C:\\Windows\\System32\\whoami.exe') {
@@ -35,6 +47,13 @@ describe('hardenSecurePath', () => {
process.env.WINDIR = originalWindir
}
__resetSecureFileWindowsUserSidForTests()
__resetSecureFileHardenedPathsForTests()
if (originalPlatform) {
Object.defineProperty(process, 'platform', originalPlatform)
}
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
it('rewrites Windows ACLs through the system PowerShell path', () => {
@@ -95,4 +114,96 @@ describe('hardenSecurePath', () => {
})
).not.toThrow()
})
it('caches successful existing-file hardening within a process', () => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-secure-file-'))
tempDirs.push(userDataPath)
const targetPath = join(userDataPath, 'secret.json')
writeFileSync(targetPath, '{}')
hardenExistingSecureFile(targetPath)
hardenExistingSecureFile(targetPath)
expect(getPowerShellCalls()).toHaveLength(2)
expect(getPowerShellCalls().map(getPowerShellTarget)).toEqual([userDataPath, targetPath])
})
it('re-hardens an existing file when its metadata changes after caching', async () => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-secure-file-'))
tempDirs.push(userDataPath)
const targetPath = join(userDataPath, 'secret.json')
writeFileSync(targetPath, '{}')
hardenExistingSecureFile(targetPath)
await waitForFileTimestampTick()
writeFileSync(targetPath, '{"changed":true}')
hardenExistingSecureFile(targetPath)
expect(getPowerShellCalls()).toHaveLength(3)
expect(getPowerShellCalls().map(getPowerShellTarget)).toEqual([
userDataPath,
targetPath,
targetPath
])
})
it('retries existing-file hardening after a failed ACL rewrite', () => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-secure-file-'))
tempDirs.push(userDataPath)
const targetPath = join(userDataPath, 'secret.json')
writeFileSync(targetPath, '{}')
let powershellCalls = 0
vi.mocked(execFileSync).mockImplementation((file) => {
if (file === 'C:\\Windows\\System32\\whoami.exe') {
return '"USER","S-1-5-21-1000"'
}
powershellCalls += 1
if (powershellCalls === 2) {
throw new Error('access denied')
}
return ''
})
hardenExistingSecureFile(targetPath)
hardenExistingSecureFile(targetPath)
expect(getPowerShellCalls()).toHaveLength(3)
expect(getPowerShellCalls().map(getPowerShellTarget)).toEqual([
userDataPath,
targetPath,
targetPath
])
})
it('keeps post-rename target hardening on every write while caching the directory', () => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-secure-file-'))
tempDirs.push(userDataPath)
const targetPath = join(userDataPath, 'secret.json')
writeSecureFile(targetPath, 'first')
writeSecureFile(targetPath, 'second')
const powershellTargets = getPowerShellCalls().map(getPowerShellTarget)
expect(powershellTargets).toHaveLength(5)
expect(powershellTargets.filter((entry) => entry === userDataPath)).toHaveLength(1)
expect(powershellTargets.filter((entry) => entry === targetPath)).toHaveLength(2)
})
})
function getPowerShellCalls(): unknown[][] {
return vi
.mocked(execFileSync)
.mock.calls.filter(([file]) => String(file).endsWith('WindowsPowerShell\\v1.0\\powershell.exe'))
}
function getPowerShellTarget(call: unknown[]): string {
return (call[1] as string[])[6]!
}
async function waitForFileTimestampTick(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 20))
}
+138 -40
View File
@@ -1,10 +1,42 @@
import { execFileSync } from 'child_process'
import { randomBytes } from 'crypto'
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'fs'
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, statSync, writeFileSync } from 'fs'
import { dirname, win32 as pathWin32 } from 'path'
let cachedWindowsUserSid: string | null | undefined
type HardenedPathCacheEntry = {
isDirectory: boolean
dev: number
ino: number
size: number
ctimeMs: number
mtimeMs: number
birthtimeMs: number
}
// Why: hardening shells out to PowerShell on Windows (~1-1.5s each). Re-hardening a path
// whose ACLs we already applied in this process is wasted work that stalls the main thread,
// so cache idempotent calls. The post-rename target write is NOT routed through this — it
// always re-hardens (new inode) and then refreshes the cache entry.
const hardenedPathsThisProcess = new Map<string, HardenedPathCacheEntry>()
function hardenSecurePathOnce(targetPath: string, isDirectory: boolean): boolean {
const currentEntry = getHardenedPathCacheEntry(targetPath, isDirectory)
if (!currentEntry) {
hardenedPathsThisProcess.delete(targetPath)
}
const cachedEntry = hardenedPathsThisProcess.get(targetPath)
if (currentEntry && cachedEntry && hardenedPathCacheEntriesMatch(currentEntry, cachedEntry)) {
return true
}
if (applySecurePathRestriction(targetPath, isDirectory, process.platform)) {
rememberHardenedPath(targetPath, isDirectory)
return true
}
return false
}
export function writeSecureJsonFile(targetPath: string, value: unknown): void {
writeSecureFile(targetPath, JSON.stringify(value, null, 2))
}
@@ -14,7 +46,7 @@ export function writeSecureFile(targetPath: string, contents: string): void {
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 })
}
hardenSecurePath(dir, { isDirectory: true, platform: process.platform })
const directoryWasHardened = hardenSecurePathOnce(dir, true)
const tmpFile = `${targetPath}.${process.pid}.${Date.now()}.${randomBytes(4).toString('hex')}.tmp`
try {
@@ -26,7 +58,12 @@ export function writeSecureFile(targetPath: string, contents: string): void {
renameSync(tmpFile, targetPath)
// Why: these files carry runtime auth/device credentials; the published
// path must remain current-user only after the atomic rename.
hardenSecurePath(targetPath, { isDirectory: false, platform: process.platform })
if (applySecurePathRestriction(targetPath, false, process.platform)) {
rememberHardenedPath(targetPath, false)
}
if (directoryWasHardened) {
rememberHardenedPath(dir, true)
}
} catch (error) {
rmSync(tmpFile, { force: true })
throw error
@@ -36,10 +73,10 @@ export function writeSecureFile(targetPath: string, contents: string): void {
export function hardenExistingSecureFile(targetPath: string): void {
const dir = dirname(targetPath)
if (existsSync(dir)) {
hardenSecurePath(dir, { isDirectory: true, platform: process.platform })
hardenSecurePathOnce(dir, true)
}
if (existsSync(targetPath)) {
hardenSecurePath(targetPath, { isDirectory: false, platform: process.platform })
hardenSecurePathOnce(targetPath, false)
}
}
@@ -50,11 +87,99 @@ export function hardenSecurePath(
platform: NodeJS.Platform
}
): void {
if (options.platform === 'win32') {
bestEffortRestrictWindowsPath(targetPath, options.isDirectory)
return
applySecurePathRestriction(targetPath, options.isDirectory, options.platform)
}
function applySecurePathRestriction(
targetPath: string,
isDirectory: boolean,
platform: NodeJS.Platform
): boolean {
if (platform === 'win32') {
return bestEffortRestrictWindowsPath(targetPath, isDirectory)
}
chmodSync(targetPath, isDirectory ? 0o700 : 0o600)
return true
}
function rememberHardenedPath(targetPath: string, isDirectory: boolean): void {
const entry = getHardenedPathCacheEntry(targetPath, isDirectory)
if (entry) {
hardenedPathsThisProcess.set(targetPath, entry)
} else {
hardenedPathsThisProcess.delete(targetPath)
}
}
function getHardenedPathCacheEntry(
targetPath: string,
isDirectory: boolean
): HardenedPathCacheEntry | null {
try {
const stats = statSync(targetPath)
if (stats.isDirectory() !== isDirectory) {
return null
}
return {
isDirectory,
dev: stats.dev,
ino: stats.ino,
size: stats.size,
ctimeMs: stats.ctimeMs,
mtimeMs: stats.mtimeMs,
birthtimeMs: stats.birthtimeMs
}
} catch {
return null
}
}
function hardenedPathCacheEntriesMatch(
a: HardenedPathCacheEntry,
b: HardenedPathCacheEntry
): boolean {
return (
a.isDirectory === b.isDirectory &&
a.dev === b.dev &&
a.ino === b.ino &&
a.size === b.size &&
a.ctimeMs === b.ctimeMs &&
a.mtimeMs === b.mtimeMs &&
a.birthtimeMs === b.birthtimeMs
)
}
function bestEffortRestrictWindowsPath(targetPath: string, isDirectory: boolean): boolean {
const currentUserSid = getCurrentWindowsUserSid()
if (!currentUserSid) {
return false
}
try {
execFileSync(
getWindowsSystemToolPath('WindowsPowerShell\\v1.0\\powershell.exe'),
[
'-NoProfile',
'-NonInteractive',
'-ExecutionPolicy',
'Bypass',
'-Command',
WINDOWS_RESTRICT_ACL_SCRIPT,
targetPath,
currentUserSid,
isDirectory ? '1' : '0'
],
{
stdio: 'ignore',
windowsHide: true,
timeout: 5000
}
)
return true
} catch {
// Why: credential-file hardening should not prevent Orca from starting on
// Windows machines where PowerShell ACL APIs are unavailable or locked down.
return false
}
chmodSync(targetPath, options.isDirectory ? 0o700 : 0o600)
}
const WINDOWS_RESTRICT_ACL_SCRIPT = `
@@ -107,37 +232,6 @@ foreach ($rule in @($verifiedAcl.Access)) {
}
`.trim()
function bestEffortRestrictWindowsPath(targetPath: string, isDirectory: boolean): void {
const currentUserSid = getCurrentWindowsUserSid()
if (!currentUserSid) {
return
}
try {
execFileSync(
getWindowsSystemToolPath('WindowsPowerShell\\v1.0\\powershell.exe'),
[
'-NoProfile',
'-NonInteractive',
'-ExecutionPolicy',
'Bypass',
'-Command',
WINDOWS_RESTRICT_ACL_SCRIPT,
targetPath,
currentUserSid,
isDirectory ? '1' : '0'
],
{
stdio: 'ignore',
windowsHide: true,
timeout: 5000
}
)
} catch {
// Why: credential-file hardening should not prevent Orca from starting on
// Windows machines where PowerShell ACL APIs are unavailable or locked down.
}
}
function getCurrentWindowsUserSid(): string | null {
if (cachedWindowsUserSid !== undefined) {
return cachedWindowsUserSid
@@ -173,3 +267,7 @@ function parseCsvLine(line: string): string[] {
export function __resetSecureFileWindowsUserSidForTests(): void {
cachedWindowsUserSid = undefined
}
export function __resetSecureFileHardenedPathsForTests(): void {
hardenedPathsThisProcess.clear()
}