From bb71a3a991b6359a5c1eb70f1fe38f85edb403e1 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sat, 18 Jul 2026 10:16:21 -0700 Subject: [PATCH] fix(terminal): bypass rejected macOS login sessions (#9301) * fix(terminal): bypass rejected macOS login sessions * fix(terminal): bound macOS login preflight * test(terminal): isolate macOS login preflight * fix(terminal): avoid blocking macOS login preflight * fix(terminal): cancel pending PTY preparation * fix(terminal): cancel preparation on daemon shutdown --- src/main/daemon/daemon-entry.ts | 2 + src/main/daemon/daemon-main.ts | 2 + src/main/daemon/daemon-server.test.ts | 128 +++++++++++++++++ src/main/daemon/daemon-server.ts | 65 ++++++++- src/main/daemon/pty-subprocess.test.ts | 20 +-- src/main/daemon/types.ts | 4 +- src/main/ipc/pty.test.ts | 24 ++++ src/main/providers/local-pty-provider.test.ts | 41 ++++++ src/main/providers/local-pty-provider.ts | 46 +++++++ .../providers/macos-tcc-login-shell.test.ts | 130 ++++++++++++++++-- src/main/providers/macos-tcc-login-shell.ts | 102 +++++++++++++- 11 files changed, 534 insertions(+), 30 deletions(-) diff --git a/src/main/daemon/daemon-entry.ts b/src/main/daemon/daemon-entry.ts index 34c040439..4d5207276 100644 --- a/src/main/daemon/daemon-entry.ts +++ b/src/main/daemon/daemon-entry.ts @@ -12,6 +12,7 @@ import { warmWindowsConptyOnce } from './windows-conpty-warmup' import { warmPwshAvailabilityCache } from '../pwsh' import { createDaemonFileLog, createNoopDaemonFileLog } from './daemon-file-log' import { PROTOCOL_VERSION } from './types' +import { prepareMacosTccLoginShell } from '../providers/macos-tcc-login-shell' export type ParsedDaemonArgs = { socketPath: string @@ -126,6 +127,7 @@ async function main(): Promise { socketPath, tokenPath, log: daemonLog, + preparePtySpawn: prepareMacosTccLoginShell, spawnSubprocess: (opts) => createPtySubprocess(opts) }) diff --git a/src/main/daemon/daemon-main.ts b/src/main/daemon/daemon-main.ts index 82f4dad7b..8d2d0a36c 100644 --- a/src/main/daemon/daemon-main.ts +++ b/src/main/daemon/daemon-main.ts @@ -5,6 +5,7 @@ export type DaemonStartOptions = { socketPath: string tokenPath: string spawnSubprocess: DaemonServerOptions['spawnSubprocess'] + preparePtySpawn?: DaemonServerOptions['preparePtySpawn'] log?: DaemonFileLog } @@ -17,6 +18,7 @@ export async function startDaemon(opts: DaemonStartOptions): Promise { }) }) + it('keeps RPC responsive and creates one subprocess while spawn preparation is pending', async () => { + let finishPreparation!: () => void + const preparation = new Promise((resolve) => { + finishPreparation = resolve + }) + const preparePtySpawn = vi.fn(() => preparation) + const spawnSubprocess = vi.fn(() => createMockSubprocess()) + server = new DaemonServer({ + socketPath, + tokenPath, + preparePtySpawn, + spawnSubprocess + }) + await server.start() + const c = await connectClient() + + const firstCreate = c.request<{ isNew: boolean }>('createOrAttach', { + sessionId: 'prepared-session', + cols: 80, + rows: 24 + }) + const concurrentCreate = c.request<{ isNew: boolean }>('createOrAttach', { + sessionId: 'prepared-session', + cols: 80, + rows: 24 + }) + await vi.waitFor(() => expect(preparePtySpawn).toHaveBeenCalledTimes(2)) + + // The old spawnSync probe blocked this ping and all live PTY traffic. + await expect(c.request('ping', undefined)).resolves.toEqual({ pong: true }) + expect(spawnSubprocess).not.toHaveBeenCalled() + + finishPreparation() + const results = await Promise.all([firstCreate, concurrentCreate]) + expect(results.map((result) => result.isNew).sort()).toEqual([false, true]) + expect(spawnSubprocess).toHaveBeenCalledOnce() + }) + + it.each(['cancelCreateOrAttach', 'kill'] as const)( + 'prevents a pending subprocess after %s and permits later session reuse', + async (requestType) => { + let finishPreparation!: () => void + const preparation = new Promise((resolve) => { + finishPreparation = resolve + }) + const preparePtySpawn = vi.fn(() => preparation) + const spawnSubprocess = vi.fn(() => createMockSubprocess()) + server = new DaemonServer({ + socketPath, + tokenPath, + preparePtySpawn, + spawnSubprocess + }) + await server.start() + const c = await connectClient() + + const creates = [ + c.request('createOrAttach', { + sessionId: 'canceled-preparation', + cols: 80, + rows: 24 + }), + c.request('createOrAttach', { + sessionId: 'canceled-preparation', + cols: 80, + rows: 24 + }) + ] + const canceledCreates = Promise.all( + creates.map((create) => + expect(create).rejects.toThrow('Attach canceled for session canceled-preparation') + ) + ) + await vi.waitFor(() => expect(preparePtySpawn).toHaveBeenCalledTimes(2)) + + const cancelRequest = + requestType === 'kill' + ? c.request('kill', { sessionId: 'canceled-preparation', immediate: true }) + : c.request('cancelCreateOrAttach', { sessionId: 'canceled-preparation' }) + await expect(cancelRequest).resolves.toEqual({}) + finishPreparation() + await canceledCreates + expect(spawnSubprocess).not.toHaveBeenCalled() + + await expect( + c.request('createOrAttach', { + sessionId: 'canceled-preparation', + cols: 80, + rows: 24 + }) + ).resolves.toMatchObject({ isNew: true }) + expect(spawnSubprocess).toHaveBeenCalledOnce() + } + ) + + it('cancels pending subprocess preparation during daemon shutdown', async () => { + let finishPreparation!: () => void + const preparation = new Promise((resolve) => { + finishPreparation = resolve + }) + const preparePtySpawn = vi.fn(() => preparation) + const spawnSubprocess = vi.fn(() => createMockSubprocess()) + server = new DaemonServer({ + socketPath, + tokenPath, + preparePtySpawn, + spawnSubprocess + }) + await server.start() + const daemon = server as unknown as DaemonServerPrivate + + const create = daemon.routeRequest('shutdown-client', { + id: 'shutdown-create', + type: 'createOrAttach', + payload: { sessionId: 'shutdown-pending', cols: 80, rows: 24 } + }) + const canceledCreate = expect(create).rejects.toThrow( + 'Attach canceled for session shutdown-pending' + ) + await vi.waitFor(() => expect(preparePtySpawn).toHaveBeenCalledOnce()) + + const shutdown = server.shutdown() + finishPreparation() + await canceledCreate + await shutdown + expect(spawnSubprocess).not.toHaveBeenCalled() + }) + it('persists only an allowlisted launch identity across reattach', async () => { await startServer() const c = await connectClient() diff --git a/src/main/daemon/daemon-server.ts b/src/main/daemon/daemon-server.ts index 3396493e0..c33e618bf 100644 --- a/src/main/daemon/daemon-server.ts +++ b/src/main/daemon/daemon-server.ts @@ -27,6 +27,7 @@ import { PROTOCOL_VERSION, NOTIFY_PREFIX, SessionNotFoundError, + TerminalAttachCanceledError, type HelloMessage, type DaemonRequest } from './types' @@ -35,6 +36,7 @@ export type DaemonServerOptions = { socketPath: string tokenPath: string ptySpawnHealthCheck?: () => Promise + preparePtySpawn?: () => Promise log?: DaemonFileLog spawnSubprocess: (opts: { sessionId: string @@ -53,6 +55,10 @@ type ConnectedClient = { streamSocket: Socket | null } +type PendingPtySpawnPreparation = { + canceled: boolean +} + export class DaemonServer { private server: Server | null = null private token: string @@ -60,6 +66,7 @@ export class DaemonServer { private socketPath: string private tokenPath: string private ptySpawnHealthCheck: () => Promise + private preparePtySpawn: () => Promise private log: DaemonFileLog private clients = new Map() @@ -96,6 +103,7 @@ export class DaemonServer { }) private streamClientIdBySessionId = new Map() private lastInputAtBySessionId = new Map() + private pendingPtySpawnPreparations = new Map>() private stopStreamBacklogProbe: () => void = () => {} // Why: main-process PTY IPC has the same recent-input bypass, but daemon @@ -111,6 +119,7 @@ export class DaemonServer { this.token = randomUUID() this.host = new TerminalHost({ spawnSubprocess: opts.spawnSubprocess }) this.ptySpawnHealthCheck = opts.ptySpawnHealthCheck ?? checkPtySpawnHealth + this.preparePtySpawn = opts.preparePtySpawn ?? (() => Promise.resolve()) this.stopStreamBacklogProbe = startDaemonStreamBacklogProbe(() => ({ clients: Array.from(this.clients.values(), (client) => ({ clientId: client.clientId, @@ -149,6 +158,7 @@ export class DaemonServer { async shutdown(): Promise { this.stopStreamBacklogProbe() this.transientFactRelay.dispose() + this.cancelAllPendingPtySpawnPreparations() try { await this.host.dispose() } catch (err) { @@ -335,12 +345,50 @@ export class DaemonServer { } } + private async preparePtySpawnUnlessCanceled(sessionId: string): Promise { + const preparation: PendingPtySpawnPreparation = { canceled: false } + const pending = this.pendingPtySpawnPreparations.get(sessionId) ?? new Set() + pending.add(preparation) + this.pendingPtySpawnPreparations.set(sessionId, pending) + try { + // Why: registration precedes the async capability probe so a concurrent + // close can cancel this exact creation before a subprocess exists. + await this.preparePtySpawn() + if (preparation.canceled) { + throw new TerminalAttachCanceledError(sessionId) + } + } finally { + pending.delete(preparation) + if (pending.size === 0) { + this.pendingPtySpawnPreparations.delete(sessionId) + } + } + } + + private cancelPendingPtySpawnPreparations(sessionId: string): boolean { + const pending = this.pendingPtySpawnPreparations.get(sessionId) + if (!pending) { + return false + } + for (const preparation of pending) { + preparation.canceled = true + } + return true + } + + private cancelAllPendingPtySpawnPreparations(): void { + for (const sessionId of this.pendingPtySpawnPreparations.keys()) { + this.cancelPendingPtySpawnPreparations(sessionId) + } + } + private async routeRequest(clientId: string, request: DaemonRequest): Promise { const client = this.clients.get(clientId) switch (request.type) { case 'createOrAttach': { const p = request.payload + await this.preparePtySpawnUnlessCanceled(p.sessionId) const result = await this.host.createOrAttach({ sessionId: p.sessionId, cols: p.cols, @@ -424,6 +472,7 @@ export class DaemonServer { } case 'cancelCreateOrAttach': + this.cancelPendingPtySpawnPreparations(request.payload.sessionId) return {} case 'write': @@ -500,14 +549,26 @@ export class DaemonServer { return {} } - case 'kill': + case 'kill': { + const canceledPendingSpawn = this.cancelPendingPtySpawnPreparations( + request.payload.sessionId + ) this.lastInputAtBySessionId.delete(request.payload.sessionId) this.log.log('session-killed', { sessionId: request.payload.sessionId, immediate: request.payload.immediate === true }) - await this.host.kill(request.payload.sessionId, { immediate: request.payload.immediate }) + try { + await this.host.kill(request.payload.sessionId, { immediate: request.payload.immediate }) + } catch (error) { + // Why: a kill that wins before session registration has already + // canceled the pending spawn and therefore completed its intent. + if (!(canceledPendingSpawn && error instanceof SessionNotFoundError)) { + throw error + } + } return {} + } case 'signal': this.host.signal(request.payload.sessionId, request.payload.signal) diff --git a/src/main/daemon/pty-subprocess.test.ts b/src/main/daemon/pty-subprocess.test.ts index ae8c834d8..62011ccd1 100644 --- a/src/main/daemon/pty-subprocess.test.ts +++ b/src/main/daemon/pty-subprocess.test.ts @@ -324,9 +324,9 @@ describe('createPtySubprocess', () => { expect(Object.values(spawnEnv)).toContain('credential.guiPrompt') }) - it('uses a new daemon protocol for post-merge Git guard behavior', () => { - expect(PROTOCOL_VERSION).toBeGreaterThan(21) - expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(21) + it('uses a new daemon protocol for the macOS login preflight host behavior', () => { + expect(PROTOCOL_VERSION).toBeGreaterThan(22) + expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(22) }) it('resolves a missing Unix default before spawning node-pty', () => { @@ -518,17 +518,11 @@ describe('createPtySubprocess', () => { } } - // On macOS the shell is spawned through /usr/bin/login so terminal children - // carry their own TCC identity (#6996); the real shell rides behind it, and - // env(1) re-asserts the SHELL that login(1) would overwrite. + // The sync subprocess layer consumes the capability prepared by its async + // daemon boundary; this cwd-repair test deliberately exercises it unprepared. expect(spawnMock).toHaveBeenCalledWith( - '/usr/bin/login', - expect.arrayContaining([ - '-flpq', - '/usr/bin/env', - expect.stringMatching(/^SHELL=/), - '/bin/bash' - ]), + '/bin/bash', + expect.any(Array), expect.objectContaining({ cwd: originalCwd }) ) }) diff --git a/src/main/daemon/types.ts b/src/main/daemon/types.ts index e9e7fb3c7..6f48e1ccd 100644 --- a/src/main/daemon/types.ts +++ b/src/main/daemon/types.ts @@ -16,10 +16,10 @@ import type { TuiAgent } from '../../shared/types' // when daemon-baked behavior cannot be delivered by on-disk wrapper refresh. // Why: bump when adding daemon wire behavior so same-version old daemons do // not silently accept the handshake and then reject new RPCs. -export const PROTOCOL_VERSION = 22 +export const PROTOCOL_VERSION = 23 export const GIT_CREDENTIAL_GUARD_HOST_PROTOCOL_VERSION = 22 export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [ - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ] as const // ─── Session State Machine ────────────────────────────────────────── diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index bd226f81a..b3a41ef10 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -41,6 +41,7 @@ const { writeFileSyncMock, chmodSyncMock, getPathMock, + loginPreflightExecFileMock, spawnMock, openCodeBuildPtyEnvMock, openCodeClearPtyMock, @@ -72,6 +73,7 @@ const { writeFileSyncMock: vi.fn(), chmodSyncMock: vi.fn(), getPathMock: vi.fn(), + loginPreflightExecFileMock: vi.fn(), spawnMock: vi.fn(), openCodeBuildPtyEnvMock: vi.fn(), mimoCodeBuildPtyEnvMock: vi.fn(), @@ -129,6 +131,13 @@ vi.mock('node-pty', () => ({ spawn: spawnMock })) +// Why: this suite forces darwin on non-macOS hosts; isolate the PAM probe +// while preserving every other child_process API used by the IPC graph. +vi.mock('node:child_process', async (importOriginal) => ({ + ...(await importOriginal>()), + execFile: loginPreflightExecFileMock +})) + vi.mock('../opencode/hook-service', () => ({ openCodeHookService: { buildPtyEnv: openCodeBuildPtyEnvMock, @@ -206,6 +215,7 @@ import { getLocalPtyProvider } from './pty' import { _resetLocalPtyProviderStateForTest } from '../providers/local-pty-provider' +import { resetMacosLoginShellPreflightForTests } from '../providers/macos-tcc-login-shell' import { _resetHiddenRendererPtyDeliveryGateForTest, isHiddenRendererPty @@ -326,6 +336,7 @@ describe('registerPtyHandlers', () => { writeFileSyncMock.mockReset() chmodSyncMock.mockReset() getPathMock.mockReset() + loginPreflightExecFileMock.mockReset() spawnMock.mockReset() openCodeBuildPtyEnvMock.mockReset() mimoCodeBuildPtyEnvMock.mockReset() @@ -7203,6 +7214,18 @@ describe('registerPtyHandlers', () => { // Re-enable the TCC login wrapper the suite-level beforeEach disables. delete process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL process.env.SHELL = '/bin/zsh' + loginPreflightExecFileMock.mockImplementation( + ( + _file: string, + _args: string[], + _options: unknown, + callback: (error: Error | null, stdout: string, stderr: string) => void + ) => { + callback(null, 'ORCA_LOGIN_PREFLIGHT_OK', '') + return { stdin: { end: vi.fn() } } + } + ) + resetMacosLoginShellPreflightForTests() try { const [file, args, options] = await spawnAndGetCall({ cwd: '/tmp' }) @@ -7218,6 +7241,7 @@ describe('registerPtyHandlers', () => { // The spawn env keeps the real shell so identity/name logic is intact. expect(options.env.SHELL).toBe('/bin/zsh') } finally { + resetMacosLoginShellPreflightForTests() process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL = '1' if (originalShell === undefined) { delete process.env.SHELL diff --git a/src/main/providers/local-pty-provider.test.ts b/src/main/providers/local-pty-provider.test.ts index 40f43cd6f..0e4a82881 100644 --- a/src/main/providers/local-pty-provider.test.ts +++ b/src/main/providers/local-pty-provider.test.ts @@ -1,6 +1,7 @@ /* oxlint-disable max-lines */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { delimiter } from 'node:path' +import type * as MacosTccLoginShell from './macos-tcc-login-shell' const { existsSyncMock, @@ -9,6 +10,7 @@ const { mkdirSyncMock, writeFileSyncMock, spawnMock, + prepareMacosTccLoginShellMock, resolveAgentForegroundProcessMock, captureDescendantSnapshotMock, terminateDescendantSnapshotMock @@ -19,6 +21,7 @@ const { mkdirSyncMock: vi.fn(), writeFileSyncMock: vi.fn(), spawnMock: vi.fn(), + prepareMacosTccLoginShellMock: vi.fn(), resolveAgentForegroundProcessMock: vi.fn(), captureDescendantSnapshotMock: vi.fn(), terminateDescendantSnapshotMock: vi.fn() @@ -44,6 +47,11 @@ vi.mock('node-pty', () => ({ spawn: spawnMock })) +vi.mock('./macos-tcc-login-shell', async (importOriginal) => ({ + ...(await importOriginal()), + prepareMacosTccLoginShell: prepareMacosTccLoginShellMock +})) + vi.mock('../pty-descendant-termination', () => ({ captureDescendantSnapshot: captureDescendantSnapshotMock, terminateDescendantSnapshot: terminateDescendantSnapshotMock @@ -139,6 +147,8 @@ describe('LocalPtyProvider', () => { captureDescendantSnapshotMock.mockReset() captureDescendantSnapshotMock.mockResolvedValue(null) terminateDescendantSnapshotMock.mockReset() + prepareMacosTccLoginShellMock.mockReset() + prepareMacosTccLoginShellMock.mockResolvedValue(undefined) resolveAgentForegroundProcessMock.mockReset() resolveAgentForegroundProcessMock.mockImplementation( async (_pid: number, fallbackProcess: string | null) => ({ @@ -226,6 +236,37 @@ describe('LocalPtyProvider', () => { expect(spawnMock).toHaveBeenCalledOnce() }) + it('does not spawn after shutdown cancels a pending stable session id', async () => { + let finishPreparation!: () => void + spawnMock.mockClear() + prepareMacosTccLoginShellMock.mockImplementationOnce( + () => + new Promise((resolve) => { + finishPreparation = resolve + }) + ) + + const spawn = provider.spawn({ + cols: 80, + rows: 24, + sessionId: 'pending-local-session' + }) + const canceledSpawn = expect(spawn).rejects.toThrow( + 'PTY spawn canceled: pending-local-session' + ) + await vi.waitFor(() => expect(prepareMacosTccLoginShellMock).toHaveBeenCalledOnce()) + + await provider.shutdown('pending-local-session', { immediate: true }) + finishPreparation() + await canceledSpawn + expect(spawnMock).not.toHaveBeenCalled() + + await expect( + provider.spawn({ cols: 80, rows: 24, sessionId: 'pending-local-session' }) + ).resolves.toMatchObject({ id: 'pending-local-session' }) + expect(spawnMock).toHaveBeenCalledOnce() + }) + it('calls node-pty spawn with correct args', async () => { await provider.spawn({ cols: 120, rows: 40, cwd: '/tmp' }) expect(spawnMock).toHaveBeenCalledWith( diff --git a/src/main/providers/local-pty-provider.ts b/src/main/providers/local-pty-provider.ts index 0faea3109..292999c02 100644 --- a/src/main/providers/local-pty-provider.ts +++ b/src/main/providers/local-pty-provider.ts @@ -27,6 +27,7 @@ import { validateWorkingDirectory, spawnShellWithFallback } from './local-pty-utils' +import { prepareMacosTccLoginShell } from './macos-tcc-login-shell' import { getAttributionShellLaunchConfig, getShellReadyLaunchConfig, @@ -90,6 +91,10 @@ type PtyShutdownOperation = { proc: pty.IPty } const ptyShutdownOperations = new Map() +type PendingLocalPtySpawn = { + canceled: boolean +} +const pendingLocalPtySpawns = new Map>() const ptyShellName = new Map() const ptyAgentForegroundContextPaths = new Map() // Why: remembers the last positively-recognized agent foreground per PTY so a @@ -313,6 +318,42 @@ function allocatePtyId(sessionId: string | undefined): string { return id } +async function prepareLocalPtySpawn(id: string): Promise { + const pendingSpawn: PendingLocalPtySpawn = { canceled: false } + const pending = pendingLocalPtySpawns.get(id) ?? new Set() + pending.add(pendingSpawn) + pendingLocalPtySpawns.set(id, pending) + try { + // Why: shutdown must be able to cancel a stable session id while the + // asynchronous macOS capability probe runs and before node-pty exists. + await prepareMacosTccLoginShell() + if (pendingSpawn.canceled) { + throw new Error(`PTY spawn canceled: ${id}`) + } + } finally { + pending.delete(pendingSpawn) + if (pending.size === 0) { + pendingLocalPtySpawns.delete(id) + } + } +} + +function cancelPendingLocalPtySpawns(id: string): void { + const pending = pendingLocalPtySpawns.get(id) + if (!pending) { + return + } + for (const pendingSpawn of pending) { + pendingSpawn.canceled = true + } +} + +function cancelAllPendingLocalPtySpawns(): void { + for (const id of pendingLocalPtySpawns.keys()) { + cancelPendingLocalPtySpawns(id) + } +} + /** * Normalizes renderer session ids that should be reused for local PTY reattach. */ @@ -795,6 +836,7 @@ export class LocalPtyProvider implements IPtyProvider { logHistoryInjection(worktreeId, historyResult) } + await prepareLocalPtySpawn(id) const spawnResult = spawnShellWithFallback({ shellPath, shellArgs, @@ -1037,6 +1079,7 @@ export class LocalPtyProvider implements IPtyProvider { } async shutdown(id: string, opts: { immediate?: boolean; keepHistory?: boolean }): Promise { + cancelPendingLocalPtySpawns(id) const pending = ptyShutdownOperations.get(id) if (pending) { if (opts.immediate === true) { @@ -1342,6 +1385,7 @@ export class LocalPtyProvider implements IPtyProvider { /** Kill all in-process local PTYs. Call on app quit. */ killAll(): void { + cancelAllPendingLocalPtySpawns() for (const [id, proc] of ptyProcesses) { runPtyCleanup(id) disposePtyListeners(id) @@ -1365,6 +1409,8 @@ export class LocalPtyProvider implements IPtyProvider { } export function _resetLocalPtyProviderStateForTest(): void { + cancelAllPendingLocalPtySpawns() + pendingLocalPtySpawns.clear() for (const id of ptyProcesses.keys()) { clearPtyState(id) } diff --git a/src/main/providers/macos-tcc-login-shell.test.ts b/src/main/providers/macos-tcc-login-shell.test.ts index b3adf6ea1..ee43bf922 100644 --- a/src/main/providers/macos-tcc-login-shell.test.ts +++ b/src/main/providers/macos-tcc-login-shell.test.ts @@ -1,14 +1,23 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -const { existsSyncMock, userInfoMock } = vi.hoisted(() => ({ +const { existsSyncMock, userInfoMock, execFileMock, stdinEndMock } = vi.hoisted(() => ({ existsSyncMock: vi.fn(), - userInfoMock: vi.fn() + userInfoMock: vi.fn(), + execFileMock: vi.fn(), + stdinEndMock: vi.fn() })) vi.mock('node:fs', () => ({ existsSync: existsSyncMock })) vi.mock('node:os', () => ({ userInfo: userInfoMock })) +vi.mock('node:child_process', () => ({ execFile: execFileMock })) -import { wrapShellSpawnForMacosTccAttribution } from './macos-tcc-login-shell' +import { + prepareMacosTccLoginShell, + resetMacosLoginShellPreflightForTests, + wrapShellSpawnForMacosTccAttribution +} from './macos-tcc-login-shell' + +type ExecFileCallback = (error: Error | null, stdout: string, stderr: string) => void describe('wrapShellSpawnForMacosTccAttribution', () => { let origPlatform: PropertyDescriptor | undefined @@ -23,7 +32,14 @@ describe('wrapShellSpawnForMacosTccAttribution', () => { origDisable = process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL delete process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL existsSyncMock.mockReturnValue(true) - userInfoMock.mockReturnValue({ username: 'ada' }) + userInfoMock.mockReturnValue({ username: 'ada', homedir: '/Users/ada' }) + execFileMock.mockImplementation( + (_file: string, _args: string[], _options: unknown, callback: ExecFileCallback) => { + callback(null, 'ORCA_LOGIN_PREFLIGHT_OK', '') + return { stdin: { end: stdinEndMock } } + } + ) + resetMacosLoginShellPreflightForTests() }) afterEach(() => { @@ -38,16 +54,99 @@ describe('wrapShellSpawnForMacosTccAttribution', () => { vi.clearAllMocks() }) - it('wraps the shell in /usr/bin/login on macOS, preserving the shell args behind it', () => { + it('wraps the shell in /usr/bin/login on macOS, preserving the shell args behind it', async () => { setPlatform('darwin') + await prepareMacosTccLoginShell() expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'])).toEqual({ file: '/usr/bin/login', args: ['-flpq', 'ada', '/usr/bin/env', 'SHELL=/bin/zsh', '/bin/zsh', '-l'] }) + expect(execFileMock).toHaveBeenCalledWith( + '/usr/bin/login', + ['-flpq', 'ada', '/usr/bin/printf', 'ORCA_LOGIN_PREFLIGHT_OK'], + { + cwd: '/Users/ada', + encoding: 'utf8', + killSignal: 'SIGKILL', + maxBuffer: 1024, + timeout: 500 + }, + expect.any(Function) + ) + expect(stdinEndMock).toHaveBeenCalledOnce() }) - it('keeps bash rcfile args intact after the shell path', () => { + it('spawns the shell directly when login PAM policy rejects the current user', async () => { setPlatform('darwin') + execFileMock.mockImplementation( + (_file: string, _args: string[], _options: unknown, callback: ExecFileCallback) => { + callback(null, 'Login incorrect\nlogin: ', '') + return { stdin: { end: stdinEndMock } } + } + ) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + await prepareMacosTccLoginShell() + expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'])).toEqual({ + file: '/bin/zsh', + args: ['-l'] + }) + expect(console.warn).toHaveBeenCalledWith( + '[pty] macOS login(1) preflight failed; spawning shells directly' + ) + }) + + it('caches a failed login preflight for later terminal spawns', async () => { + setPlatform('darwin') + execFileMock.mockImplementation( + (_file: string, _args: string[], _options: unknown, callback: ExecFileCallback) => { + callback(new Error('timed out'), '', '') + return { stdin: { end: stdinEndMock } } + } + ) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + await prepareMacosTccLoginShell() + await prepareMacosTccLoginShell() + expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l']).file).toBe('/bin/zsh') + expect(wrapShellSpawnForMacosTccAttribution('/bin/bash', ['-l']).file).toBe('/bin/bash') + expect(execFileMock).toHaveBeenCalledTimes(1) + expect(console.warn).toHaveBeenCalledTimes(1) + }) + + it('rejects a marker emitted by a preflight that does not exit cleanly', async () => { + setPlatform('darwin') + execFileMock.mockImplementation( + (_file: string, _args: string[], _options: unknown, callback: ExecFileCallback) => { + callback( + Object.assign(new Error('timed out'), { code: 'ETIMEDOUT' }), + 'ORCA_LOGIN_PREFLIGHT_OK', + '' + ) + return { stdin: { end: stdinEndMock } } + } + ) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + await prepareMacosTccLoginShell() + expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'])).toEqual({ + file: '/bin/zsh', + args: ['-l'] + }) + }) + + it('dedupes concurrent successful preflights and caches later terminal spawns', async () => { + setPlatform('darwin') + + await Promise.all([prepareMacosTccLoginShell(), prepareMacosTccLoginShell()]) + expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l']).file).toBe('/usr/bin/login') + expect(wrapShellSpawnForMacosTccAttribution('/bin/bash', ['-l']).file).toBe('/usr/bin/login') + expect(execFileMock).toHaveBeenCalledTimes(1) + }) + + it('keeps bash rcfile args intact after the shell path', async () => { + setPlatform('darwin') + await prepareMacosTccLoginShell() expect( wrapShellSpawnForMacosTccAttribution('/bin/bash', ['--rcfile', '/orca/bash/rcfile']) ).toEqual({ @@ -64,8 +163,9 @@ describe('wrapShellSpawnForMacosTccAttribution', () => { }) }) - it('re-asserts the spawn env SHELL that login(1) would overwrite', () => { + it('re-asserts the spawn env SHELL that login(1) would overwrite', async () => { setPlatform('darwin') + await prepareMacosTccLoginShell() expect( wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'], { SHELL: '/opt/homebrew/bin/fish' }) ).toEqual({ @@ -74,25 +174,30 @@ describe('wrapShellSpawnForMacosTccAttribution', () => { }) }) - it('falls back to the spawned shell for SHELL when the env value is empty', () => { + it('falls back to the spawned shell for SHELL when the env value is empty', async () => { setPlatform('darwin') + await prepareMacosTccLoginShell() expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'], { SHELL: '' })).toEqual({ file: '/usr/bin/login', args: ['-flpq', 'ada', '/usr/bin/env', 'SHELL=/bin/zsh', '/bin/zsh', '-l'] }) }) - it('skips the env(1) interposition when the shell path would parse as an assignment', () => { + it('skips the env(1) interposition when the shell path would parse as an assignment', async () => { setPlatform('darwin') + await prepareMacosTccLoginShell() expect(wrapShellSpawnForMacosTccAttribution('/odd=dir/zsh', ['-l'])).toEqual({ file: '/usr/bin/login', args: ['-flpq', 'ada', '/odd=dir/zsh', '-l'] }) }) - it('still wraps with login when /usr/bin/env is missing, without interposition', () => { + it('still wraps with login when /usr/bin/env is missing, without interposition', async () => { setPlatform('darwin') - existsSyncMock.mockImplementation((path: string) => path === '/usr/bin/login') + existsSyncMock.mockImplementation( + (path: string) => path === '/usr/bin/login' || path === '/usr/bin/printf' + ) + await prepareMacosTccLoginShell() expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'])).toEqual({ file: '/usr/bin/login', args: ['-flpq', 'ada', '/bin/zsh', '-l'] @@ -138,7 +243,7 @@ describe('wrapShellSpawnForMacosTccAttribution', () => { it('falls back to the plain spawn when the username is empty', () => { setPlatform('darwin') - userInfoMock.mockReturnValue({ username: '' }) + userInfoMock.mockReturnValue({ username: '', homedir: '/Users/ada' }) expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'])).toEqual({ file: '/bin/zsh', args: ['-l'] @@ -152,5 +257,6 @@ describe('wrapShellSpawnForMacosTccAttribution', () => { file: '/bin/zsh', args: ['-l'] }) + expect(execFileMock).not.toHaveBeenCalled() }) }) diff --git a/src/main/providers/macos-tcc-login-shell.ts b/src/main/providers/macos-tcc-login-shell.ts index 806b6669f..ad8bbfa96 100644 --- a/src/main/providers/macos-tcc-login-shell.ts +++ b/src/main/providers/macos-tcc-login-shell.ts @@ -1,8 +1,13 @@ +import { execFile } from 'node:child_process' import { existsSync } from 'node:fs' import { userInfo } from 'node:os' const MACOS_LOGIN_PATH = '/usr/bin/login' const MACOS_ENV_PATH = '/usr/bin/env' +const MACOS_PRINTF_PATH = '/usr/bin/printf' +const LOGIN_PREFLIGHT_TIMEOUT_MS = 500 +const LOGIN_PREFLIGHT_MARKER = 'ORCA_LOGIN_PREFLIGHT_OK' +const LOGIN_PREFLIGHT_MAX_BUFFER_BYTES = 1024 /** * Env escape hatch to force the plain (unwrapped) spawn. Set to `1`/`true` if a @@ -11,11 +16,100 @@ const MACOS_ENV_PATH = '/usr/bin/env' */ const DISABLE_ENV_VAR = 'ORCA_DISABLE_MACOS_LOGIN_SHELL' +let cachedLoginPreflightResult: boolean | null = null +let loginPreflightInFlight: Promise | null = null + function isDisabledByEnv(): boolean { const value = process.env[DISABLE_ENV_VAR] return value === '1' || value === 'true' } +function runLoginPreflight(username: string, accountHome: string): Promise { + return new Promise((resolve) => { + try { + const child = execFile( + MACOS_LOGIN_PATH, + ['-flpq', username, MACOS_PRINTF_PATH, LOGIN_PREFLIGHT_MARKER], + { + // Why: detached daemons can outlive their launch worktree. The PAM + // probe must not inherit a deleted cwd before PTY spawn repairs it. + cwd: accountHome, + encoding: 'utf8', + // Why: PAM policy can wait indefinitely. Bound both child lifetime and + // captured diagnostics without blocking the PTY host's event loop. + killSignal: 'SIGKILL', + maxBuffer: LOGIN_PREFLIGHT_MAX_BUFFER_BYTES, + timeout: LOGIN_PREFLIGHT_TIMEOUT_MS + }, + (error, stdout) => { + // login(1) can return zero after an EOF-driven failed prompt, so only the + // requested child program's output plus a clean exit proves PAM accepted it. + resolve(error === null && stdout === LOGIN_PREFLIGHT_MARKER) + } + ) + // Why: login(1) must see immediate EOF, not an interactive pipe, so a PAM + // rejection exits instead of waiting at `login:` until the timeout. + child.stdin?.end() + } catch { + resolve(false) + } + }) +} + +function loginPreflightSucceeds(username: string, accountHome: string): Promise { + if (cachedLoginPreflightResult !== null) { + return Promise.resolve(cachedLoginPreflightResult) + } + if (!loginPreflightInFlight) { + // Why: simultaneous pane restores share one PAM child instead of multiplying + // subprocesses at exactly the point terminal startup is already busiest. + loginPreflightInFlight = runLoginPreflight(username, accountHome).then((result) => { + cachedLoginPreflightResult = result + if (!result) { + console.warn('[pty] macOS login(1) preflight failed; spawning shells directly') + } + return result + }) + } + return loginPreflightInFlight +} + +/** + * Resolves the one-time PAM capability check before a fresh PTY is spawned. + * Callers await this at their async request boundary so existing terminals and + * the Electron main thread remain responsive while login(1) runs. + */ +export async function prepareMacosTccLoginShell(): Promise { + if (process.platform !== 'darwin' || isDisabledByEnv()) { + return + } + if (cachedLoginPreflightResult !== null) { + return + } + if (!existsSync(MACOS_LOGIN_PATH)) { + return + } + + let username: string + let accountHome: string + try { + const account = userInfo() + username = account.username + accountHome = account.homedir + } catch { + return + } + if (!username || !accountHome) { + return + } + await loginPreflightSucceeds(username, accountHome) +} + +export function resetMacosLoginShellPreflightForTests(): void { + cachedLoginPreflightResult = null + loginPreflightInFlight = null +} + /** * Wrap a macOS shell spawn in `/usr/bin/login -flpq …` so terminal children * get their own TCC identity instead of collapsing into Orca's bundle id — signed @@ -26,7 +120,8 @@ function isDisabledByEnv(): boolean { * under -p, so `/usr/bin/env SHELL=` re-asserts the shell Orca actually runs * without disturbing login's attribution (skipped when the shell path contains `=`). * - * No-op off macOS, when already wrapped, or when disabled via {@link DISABLE_ENV_VAR}. + * No-op off macOS, when already wrapped, when disabled via {@link DISABLE_ENV_VAR}, + * or when the login(1) PAM preflight rejects this process's user. */ export function wrapShellSpawnForMacosTccAttribution( file: string, @@ -52,6 +147,11 @@ export function wrapShellSpawnForMacosTccAttribution( if (!username) { return { file, args } } + // Why: an unprepared or failed host must fail open to a usable direct shell; + // production fresh-spawn boundaries await prepareMacosTccLoginShell first. + if (cachedLoginPreflightResult !== true) { + return { file, args } + } const shellEnvValue = env?.SHELL || file const interposedShellEnv =