|
| 1 | +import childProcess from 'node:child_process'; |
| 2 | +import module from 'node:module'; |
| 3 | +import util from 'node:util'; |
| 4 | +import { afterAll, afterEach, expect } from 'vitest'; |
| 5 | + |
| 6 | +// Unit tests must be hermetic with respect to the host's process table: a |
| 7 | +// worker may signal only itself and its own direct children. Anything else is |
| 8 | +// a pid the test made up (`child: { pid: 4242 }`), and on a real host that |
| 9 | +// number can belong to anyone — on CI it periodically belonged to a sibling |
| 10 | +// vitest fork, which died mid-file with no test attributed |
| 11 | +// ("Worker exited unexpectedly", #1824). Refusing the write here, in every |
| 12 | +// worker, turns that silent fork death into a named failure of the test that |
| 13 | +// sent it, on any host, deterministically. |
| 14 | +// |
| 15 | +// Both ways out of the process are covered, because the runner-disposal family |
| 16 | +// uses both: `process.kill` (including the negative pid that addresses a |
| 17 | +// child's process group) and a spawned `kill`/`pkill`/`killall`, whose `-P` |
| 18 | +// and `-f` forms reach processes this worker never spawned at all. |
| 19 | +// |
| 20 | +// Signal 0 is a liveness probe (`isProcessAlive`), not a signal; it stays free. |
| 21 | +// Tests that drive a real kill path against a fabricated pid mock the seam — |
| 22 | +// `signalPidsBestEffort` / `signalProcessGroupBestEffort` in |
| 23 | +// `src/utils/host-process.ts` for the direct writes, the exec/tool-provider |
| 24 | +// seam for a spawned `pkill` — the same way they already mock the liveness |
| 25 | +// reads. |
| 26 | + |
| 27 | +/** |
| 28 | + * Direct, *live* children only. |
| 29 | + * |
| 30 | + * A grandchild (a server started through a shell or `npx` wrapper) is not |
| 31 | + * tracked, so signalling its pid is refused even though the test legitimately |
| 32 | + * owns it; signal the direct child, or its process group via the negative pid, |
| 33 | + * or mock the seam. |
| 34 | + * |
| 35 | + * Authority ends when the child is reaped: a pid is only ever a claim on a slot |
| 36 | + * in the host's process table, and the kernel hands that slot to someone else |
| 37 | + * once it is free. So synchronous spawns (`spawnSync`, `execFileSync`) are never |
| 38 | + * remembered — they have already exited when the call returns — and async |
| 39 | + * children are dropped on `exit`. Cleanup that signals a child must gate on |
| 40 | + * `isProcessAlive` (as `stopProcess` in `client-metro.test.ts` already does); |
| 41 | + * "I spawned this pid once" is not ownership of whatever holds it now, which is |
| 42 | + * the exact hazard this file exists to close. |
| 43 | + */ |
| 44 | +const ownPids = new Set<number>([process.pid]); |
| 45 | + |
| 46 | +const KILL_BINARIES = new Set(['kill', 'pkill', 'killall']); |
| 47 | + |
| 48 | +const refused: string[] = []; |
| 49 | + |
| 50 | +function record(what: string): void { |
| 51 | + const state = expect.getState(); |
| 52 | + const where = new Error().stack?.split('\n').slice(3, 7).join('\n') ?? ''; |
| 53 | + refused.push(`${what} (${state.currentTestName ?? 'outside a test'})\n${where}`); |
| 54 | +} |
| 55 | + |
| 56 | +function rememberChild(child: unknown): void { |
| 57 | + const handle = child as { pid?: unknown; once?: (event: string, cb: () => void) => void } | null; |
| 58 | + const pid = handle?.pid; |
| 59 | + if (typeof pid !== 'number') return; |
| 60 | + ownPids.add(pid); |
| 61 | + // Both events are attached because a child that is never spawned at all |
| 62 | + // ('error') emits close without exit. |
| 63 | + handle?.once?.('exit', () => ownPids.delete(pid)); |
| 64 | + handle?.once?.('close', () => ownPids.delete(pid)); |
| 65 | +} |
| 66 | + |
| 67 | +function killBinaryName(command: unknown): string | undefined { |
| 68 | + // `exec` takes a shell command line; the rest take an executable path. |
| 69 | + const first = String(command).trim().split(/\s+/)[0] ?? ''; |
| 70 | + const name = first.split('/').pop() ?? ''; |
| 71 | + return KILL_BINARIES.has(name) ? name : undefined; |
| 72 | +} |
| 73 | + |
| 74 | +function refuseSpawnedKill(command: unknown, args: unknown): Error | undefined { |
| 75 | + const name = killBinaryName(command); |
| 76 | + if (!name) return undefined; |
| 77 | + const rendered = [String(command), ...(Array.isArray(args) ? args.map(String) : [])].join(' '); |
| 78 | + record(`spawn ${rendered}`); |
| 79 | + // Shaped like the binary being unavailable, which every caller of these |
| 80 | + // best-effort kills already tolerates. |
| 81 | + const error = new Error( |
| 82 | + `Refusing to spawn \`${rendered}\`: a unit test may not signal processes through ${name} (see afterEach failure).`, |
| 83 | + ) as NodeJS.ErrnoException; |
| 84 | + error.code = 'ENOENT'; |
| 85 | + return error; |
| 86 | +} |
| 87 | + |
| 88 | +function wrapSpawner<T extends (...args: never[]) => unknown>(real: T, remember: boolean): T { |
| 89 | + const wrapped = ((...args: Parameters<T>) => { |
| 90 | + const refusal = refuseSpawnedKill(args[0], args[1]); |
| 91 | + if (refusal) throw refusal; |
| 92 | + const child = real(...args); |
| 93 | + if (remember) rememberChild(child); |
| 94 | + return child; |
| 95 | + }) as unknown as T; |
| 96 | + // `util.promisify(execFile)` does not call the function at all: it resolves |
| 97 | + // through the custom-promisify symbol, so copying the original across would |
| 98 | + // hand every promisified caller an unguarded execFile. Wrap that path too. |
| 99 | + const custom = (real as unknown as Record<symbol, unknown>)[util.promisify.custom] as |
| 100 | + | ((...args: unknown[]) => unknown) |
| 101 | + | undefined; |
| 102 | + if (custom) { |
| 103 | + const wrappedCustom = (...args: unknown[]) => { |
| 104 | + const refusal = refuseSpawnedKill(args[0], args[1]); |
| 105 | + if (refusal) return Promise.reject(refusal); |
| 106 | + const promise = custom(...args); |
| 107 | + if (remember) rememberChild((promise as { child?: unknown } | null)?.child); |
| 108 | + return promise; |
| 109 | + }; |
| 110 | + Object.defineProperty(wrapped, util.promisify.custom, { value: wrappedCustom }); |
| 111 | + } |
| 112 | + return wrapped; |
| 113 | +} |
| 114 | + |
| 115 | +for (const name of ['spawn', 'fork', 'exec', 'execFile'] as const) { |
| 116 | + (childProcess as unknown as Record<string, unknown>)[name] = wrapSpawner( |
| 117 | + childProcess[name], |
| 118 | + true, |
| 119 | + ); |
| 120 | +} |
| 121 | +for (const name of ['spawnSync', 'execFileSync', 'execSync'] as const) { |
| 122 | + (childProcess as unknown as Record<string, unknown>)[name] = wrapSpawner( |
| 123 | + childProcess[name], |
| 124 | + false, |
| 125 | + ); |
| 126 | +} |
| 127 | +// Named ESM imports of the builtin (`import { spawn } from 'node:child_process'`) |
| 128 | +// bind to the CJS exports only after they are re-synced. |
| 129 | +module.syncBuiltinESMExports(); |
| 130 | + |
| 131 | +const realKill = process.kill.bind(process); |
| 132 | +process.kill = ((pid: number, signal: string | number = 'SIGTERM') => { |
| 133 | + if (signal === 0 || ownPids.has(Math.abs(pid))) return realKill(pid, signal as NodeJS.Signals); |
| 134 | + record(`${String(signal)} -> pid ${pid}`); |
| 135 | + // Behave like a dead pid: the caller's ESRCH handling runs, no signal leaves |
| 136 | + // this worker, and the record above fails the test in afterEach below. |
| 137 | + const error = new Error( |
| 138 | + `Refusing to send ${String(signal)} to pid ${pid}: this vitest worker did not spawn it (see afterEach failure).`, |
| 139 | + ) as NodeJS.ErrnoException; |
| 140 | + error.code = 'ESRCH'; |
| 141 | + throw error; |
| 142 | +}) as typeof process.kill; |
| 143 | + |
| 144 | +// Best-effort kill sites swallow the errors above, so the refusal is reported |
| 145 | +// here, attributed to the test (or file) that caused it, and never lost. |
| 146 | +function failOnRefusedSignals(scope: string): void { |
| 147 | + if (refused.length === 0) return; |
| 148 | + const count = refused.length; |
| 149 | + const report = refused.splice(0).join('\n'); |
| 150 | + throw new Error( |
| 151 | + `${scope} tried to signal ${count} process(es) this vitest worker did not spawn. ` + |
| 152 | + 'A unit test may signal only itself and its own direct children (and their process ' + |
| 153 | + 'groups); mock the seam instead — signalPidsBestEffort / signalProcessGroupBestEffort in ' + |
| 154 | + 'src/utils/host-process.ts, the exec or tool-provider seam for a spawned pkill, or ' + |
| 155 | + `vi.spyOn(process, 'kill'). If the pid is a descendant this test really owns, signal the ` + |
| 156 | + `direct child (or its group via the negative pid) rather than the grandchild.\n${report}`, |
| 157 | + ); |
| 158 | +} |
| 159 | + |
| 160 | +afterEach(() => failOnRefusedSignals('This test')); |
| 161 | +afterAll(() => failOnRefusedSignals('This file')); |
| 162 | + |
| 163 | +/** |
| 164 | + * Takes the pending refusals so a test can assert on them without the hooks |
| 165 | + * above failing it. Only `hermetic-signal-setup.test.ts`, which drives the |
| 166 | + * guard's own refusal paths on purpose, should call this. |
| 167 | + */ |
| 168 | +export function drainRefusedWritesForTest(): string[] { |
| 169 | + return refused.splice(0); |
| 170 | +} |
0 commit comments