subagent-subprocess.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { EventEmitter } from 'node:events'
  3. import { existsSync } from 'node:fs'
  4. import { mkdtemp, rm, stat, writeFile } from 'node:fs/promises'
  5. import { tmpdir } from 'node:os'
  6. import { join } from 'node:path'
  7. import type { ChildProcess } from 'node:child_process'
  8. import {
  9. buildChildEnv,
  10. createIsolatedConfigDir,
  11. disposeChildProcess,
  12. exitsWithin,
  13. SENSITIVE_ENV_PATTERN,
  14. spawnFailure,
  15. waitForExit,
  16. } from '../src/index.ts'
  17. // `rm` is real-passthrough except for one deterministic failure. Permission-based recursive-rm
  18. // failures are not portable and disappear under root, so this is the sanctioned filesystem seam.
  19. vi.mock('node:fs/promises', async (importOriginal) => {
  20. const actual = await importOriginal<typeof import('node:fs/promises')>()
  21. return { ...actual, rm: vi.fn(actual.rm) }
  22. })
  23. /**
  24. * Unit tests for the shared out-of-process machinery. The env scrub and the
  25. * isolated-config-dir helpers run against the REAL process env and REAL
  26. * filesystem (one exception: the rm-failure path injects its rejection at the
  27. * mocked fs boundary, see above); the exit waits and the dispose ladder run
  28. * against a scriptable fake child so each escalation tier's timing is driven
  29. * deterministically (the ACP backend's suite exercises the same ladder
  30. * against real subprocesses end to end).
  31. */
  32. /** What fells a scripted {@link FakeChild}. */
  33. type LethalTrigger = 'eof' | NodeJS.Signals
  34. /** Per-scenario script for a {@link FakeChild}. */
  35. interface FakeChildScript {
  36. /**
  37. * The one trigger that makes the child exit (SIGKILL always does,
  38. * uncatchable, like a real process). Omitted: only SIGKILL fells it.
  39. */
  40. diesOn?: LethalTrigger
  41. /** Delay (ms) between the lethal trigger and the exit event. */
  42. delayMs?: number
  43. /** `false` models a child spawned without a stdin pipe. */
  44. stdin?: boolean
  45. }
  46. /**
  47. * A scriptable stand-in for a ChildProcess carrying exactly the surface the
  48. * helpers read: `exitCode`/`signalCode`, `stdin.end()`, `kill()`, and the
  49. * `exit` event.
  50. */
  51. class FakeChild extends EventEmitter {
  52. exitCode: number | null = null
  53. signalCode: NodeJS.Signals | null = null
  54. readonly kills: NodeJS.Signals[] = []
  55. stdinEnded = false
  56. readonly stdin: { end: () => void } | null
  57. constructor(private readonly script: FakeChildScript = {}) {
  58. super()
  59. this.stdin = script.stdin === false
  60. ? null
  61. : { end: () => { this.stdinEnded = true; this.maybeDie('eof') } }
  62. }
  63. kill(signal: NodeJS.Signals): boolean {
  64. this.kills.push(signal)
  65. this.maybeDie(signal)
  66. return true
  67. }
  68. private maybeDie(trigger: LethalTrigger): void {
  69. // SIGKILL is uncatchable — it always fells the child; any other trigger
  70. // only when the scenario scripts it as the lethal one.
  71. if (trigger !== 'SIGKILL' && this.script.diesOn !== trigger) return
  72. setTimeout(() => {
  73. if (trigger === 'eof') this.exitCode = 0
  74. else this.signalCode = trigger
  75. this.emit('exit', this.exitCode, this.signalCode)
  76. }, this.script.delayMs ?? 0)
  77. }
  78. }
  79. /** The helpers take a real ChildProcess; the fake carries the read surface. */
  80. function asChild(fake: FakeChild): ChildProcess {
  81. return fake as unknown as ChildProcess
  82. }
  83. describe('buildChildEnv / SENSITIVE_ENV_PATTERN', () => {
  84. it('drops credential-shaped ambient vars (KEY/SECRET/TOKEN, case-insensitive)', () => {
  85. process.env.DSH_PROC_TEST_API_KEY = 'leak'
  86. process.env.dsh_proc_test_secret = 'leak'
  87. process.env.DSH_PROC_TEST_TOKEN = 'leak'
  88. try {
  89. const env = buildChildEnv({})
  90. expect(env.DSH_PROC_TEST_API_KEY).toBeUndefined()
  91. expect(env.dsh_proc_test_secret).toBeUndefined()
  92. expect(env.DSH_PROC_TEST_TOKEN).toBeUndefined()
  93. } finally {
  94. delete process.env.DSH_PROC_TEST_API_KEY
  95. delete process.env.dsh_proc_test_secret
  96. delete process.env.DSH_PROC_TEST_TOKEN
  97. }
  98. })
  99. it('forwards normal ambient vars', () => {
  100. expect(SENSITIVE_ENV_PATTERN.test('PATH')).toBe(false)
  101. expect(buildChildEnv({}).PATH).toBe(process.env.PATH)
  102. })
  103. it('layers extras AFTER the scrub, so a deliberate credential-shaped name survives', () => {
  104. process.env.DSH_PROC_TEST_EXTRA_TOKEN = 'ambient-leak'
  105. try {
  106. const env = buildChildEnv({ DSH_PROC_TEST_EXTRA_TOKEN: 'explicit' })
  107. // The ambient value was scrubbed; ONLY the explicit opt-in reaches the child.
  108. expect(env.DSH_PROC_TEST_EXTRA_TOKEN).toBe('explicit')
  109. } finally {
  110. delete process.env.DSH_PROC_TEST_EXTRA_TOKEN
  111. }
  112. })
  113. it('an extra overrides the ambient value of a non-credential var', () => {
  114. process.env.DSH_PROC_TEST_PLAIN = 'ambient'
  115. try {
  116. expect(buildChildEnv({ DSH_PROC_TEST_PLAIN: 'override' }).DSH_PROC_TEST_PLAIN).toBe('override')
  117. } finally {
  118. delete process.env.DSH_PROC_TEST_PLAIN
  119. }
  120. })
  121. })
  122. describe('spawnFailure', () => {
  123. it('resolves (never rejects) with the first error event', async () => {
  124. const fake = new FakeChild()
  125. const failure = spawnFailure(asChild(fake))
  126. const err = new Error('spawn ENOENT')
  127. fake.emit('error', err)
  128. await expect(failure).resolves.toBe(err)
  129. })
  130. it('never settles for a child that spawns cleanly and exits', async () => {
  131. const fake = new FakeChild({ diesOn: 'SIGTERM' })
  132. const failure = spawnFailure(asChild(fake))
  133. fake.kill('SIGTERM')
  134. await waitForExit(asChild(fake))
  135. // A clean lifecycle emits `exit`, never `error` — the capture stays
  136. // pending forever, so a race against it is decided by the other arms.
  137. const settled = await Promise.race([
  138. failure.then(() => 'settled'),
  139. new Promise<string>(resolve => setTimeout(() => { resolve('pending') }, 30)),
  140. ])
  141. expect(settled).toBe('pending')
  142. })
  143. })
  144. describe('waitForExit / exitsWithin', () => {
  145. it('resolves immediately for a child that already exited by code', async () => {
  146. const fake = new FakeChild()
  147. fake.exitCode = 0
  148. await expect(waitForExit(asChild(fake))).resolves.toBeUndefined()
  149. })
  150. it('resolves immediately for a child that already died by signal', async () => {
  151. const fake = new FakeChild()
  152. fake.signalCode = 'SIGTERM'
  153. await expect(waitForExit(asChild(fake))).resolves.toBeUndefined()
  154. })
  155. it('resolves on the exit event of a live child', async () => {
  156. const fake = new FakeChild({ diesOn: 'SIGTERM', delayMs: 5 })
  157. const exited = waitForExit(asChild(fake))
  158. fake.kill('SIGTERM')
  159. await expect(exited).resolves.toBeUndefined()
  160. expect(fake.signalCode).toBe('SIGTERM')
  161. })
  162. it('exitsWithin resolves true immediately for an already-exited child (no listener attached)', async () => {
  163. const fake = new FakeChild()
  164. fake.exitCode = 0
  165. await expect(exitsWithin(asChild(fake), 1000)).resolves.toBe(true)
  166. expect(fake.listenerCount('exit')).toBe(0)
  167. })
  168. it('exitsWithin resolves true when the child exits inside the window', async () => {
  169. const fake = new FakeChild({ diesOn: 'SIGTERM', delayMs: 5 })
  170. fake.kill('SIGTERM')
  171. await expect(exitsWithin(asChild(fake), 1000)).resolves.toBe(true)
  172. // The once-listener fired and the grace timer was cleared — nothing lingers.
  173. expect(fake.listenerCount('exit')).toBe(0)
  174. })
  175. it('exitsWithin resolves false on timeout for a child that never exits', async () => {
  176. const fake = new FakeChild() // nothing short of SIGKILL fells it; no signal sent
  177. await expect(exitsWithin(asChild(fake), 20)).resolves.toBe(false)
  178. // The timeout arm removed its exit listener: repeated waits (a poll loop,
  179. // the ladder's tiers) never accumulate listeners on the same child.
  180. expect(fake.listenerCount('exit')).toBe(0)
  181. })
  182. })
  183. describe('disposeChildProcess', () => {
  184. it('returns immediately for an already-exited child (no EOF, no signals)', async () => {
  185. const fake = new FakeChild()
  186. fake.exitCode = 0
  187. await disposeChildProcess(asChild(fake), { disposeEofGraceMs: 1000, disposeGraceMs: 1000 })
  188. expect(fake.stdinEnded).toBe(false)
  189. expect(fake.kills).toEqual([])
  190. })
  191. it('returns immediately for a child already dead by signal', async () => {
  192. const fake = new FakeChild()
  193. fake.signalCode = 'SIGKILL'
  194. await disposeChildProcess(asChild(fake), { disposeEofGraceMs: 1000, disposeGraceMs: 1000 })
  195. expect(fake.stdinEnded).toBe(false)
  196. expect(fake.kills).toEqual([])
  197. })
  198. it('tier 1: a cooperative child quiesces on stdin EOF — no signal is ever sent', async () => {
  199. const fake = new FakeChild({ diesOn: 'eof', delayMs: 5 })
  200. await disposeChildProcess(asChild(fake), { disposeEofGraceMs: 1000, disposeGraceMs: 1000 })
  201. expect(fake.stdinEnded).toBe(true)
  202. expect(fake.kills).toEqual([])
  203. expect(fake.exitCode).toBe(0)
  204. })
  205. it('tier 2: a child that ignores EOF but honors SIGTERM dies on the middle rung', async () => {
  206. const fake = new FakeChild({ diesOn: 'SIGTERM', delayMs: 5 })
  207. await disposeChildProcess(asChild(fake), { disposeEofGraceMs: 20, disposeGraceMs: 1000 })
  208. expect(fake.stdinEnded).toBe(true)
  209. expect(fake.kills).toEqual(['SIGTERM'])
  210. expect(fake.signalCode).toBe('SIGTERM')
  211. })
  212. it('tier 3: a SIGTERM-trapping child is SIGKILLed, and dispose resolves only after the exit', async () => {
  213. const fake = new FakeChild({ delayMs: 5 }) // only SIGKILL fells it
  214. await disposeChildProcess(asChild(fake), { disposeEofGraceMs: 20, disposeGraceMs: 20 })
  215. expect(fake.kills).toEqual(['SIGTERM', 'SIGKILL'])
  216. // Quiescence, not a request: at resolution the child has ACTUALLY exited
  217. // (the exit event landed, despite the scripted post-SIGKILL delay).
  218. expect(fake.signalCode).toBe('SIGKILL')
  219. })
  220. it('walks the ladder for a child spawned without a stdin pipe', async () => {
  221. const fake = new FakeChild({ stdin: false, diesOn: 'SIGTERM', delayMs: 5 })
  222. await disposeChildProcess(asChild(fake), { disposeEofGraceMs: 20, disposeGraceMs: 1000 })
  223. expect(fake.kills).toEqual(['SIGTERM'])
  224. })
  225. })
  226. describe('createIsolatedConfigDir', () => {
  227. it('creates a fresh private mkdtemp dir under the OS temp root', async () => {
  228. const dir = await createIsolatedConfigDir('dsh-subagent-subprocess-test-')
  229. try {
  230. expect(dir.path.startsWith(join(tmpdir(), 'dsh-subagent-subprocess-test-'))).toBe(true)
  231. const st = await stat(dir.path)
  232. expect(st.isDirectory()).toBe(true)
  233. // Private (0700) per the defensive-patterns temp-dir rule.
  234. expect(st.mode & 0o777).toBe(0o700)
  235. } finally {
  236. await dir.remove()
  237. }
  238. })
  239. it('creates a distinct dir per call (per-run isolation)', async () => {
  240. const a = await createIsolatedConfigDir('dsh-subagent-subprocess-test-')
  241. const b = await createIsolatedConfigDir('dsh-subagent-subprocess-test-')
  242. try {
  243. expect(a.path).not.toBe(b.path)
  244. } finally {
  245. await a.remove()
  246. await b.remove()
  247. }
  248. })
  249. it('remove() deletes a fresh dir recursively and is idempotent', async () => {
  250. const dir = await createIsolatedConfigDir('dsh-subagent-subprocess-test-')
  251. await writeFile(join(dir.path, 'settings.json'), '{}')
  252. await dir.remove()
  253. expect(existsSync(dir.path)).toBe(false)
  254. // Second remove: nothing left to delete, still resolves.
  255. await expect(dir.remove()).resolves.toBeUndefined()
  256. })
  257. it('returns a pinned dir verbatim and NEVER removes it', async () => {
  258. const pinned = await mkdtemp(join(tmpdir(), 'dsh-subagent-subprocess-pinned-'))
  259. try {
  260. const dir = await createIsolatedConfigDir('ignored-prefix-', pinned)
  261. expect(dir.path).toBe(pinned)
  262. await dir.remove()
  263. // The deployment owns a pinned dir's lifecycle — remove() must not touch it.
  264. expect(existsSync(pinned)).toBe(true)
  265. } finally {
  266. await rm(pinned, { recursive: true, force: true })
  267. }
  268. })
  269. it('does not create a missing pinned path (the deployment owns its lifecycle)', async () => {
  270. const missing = join(tmpdir(), `dsh-subagent-subprocess-missing-${process.pid}`)
  271. const dir = await createIsolatedConfigDir('ignored-prefix-', missing)
  272. expect(dir.path).toBe(missing)
  273. expect(existsSync(missing)).toBe(false)
  274. await dir.remove()
  275. expect(existsSync(missing)).toBe(false)
  276. })
  277. it('remove() is best-effort: an rm rejection resolves instead of rejecting', async () => {
  278. const dir = await createIsolatedConfigDir('dsh-subagent-subprocess-locked-')
  279. try {
  280. // The swallow contract is error-kind agnostic; EACCES stands in for the
  281. // family (EBUSY, a vanished mount, …) that best-effort must absorb.
  282. vi.mocked(rm).mockRejectedValueOnce(Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' }))
  283. await expect(dir.remove()).resolves.toBeUndefined()
  284. // The injected rejection consumed the only rm call — nothing was deleted.
  285. expect(existsSync(dir.path)).toBe(true)
  286. } finally {
  287. await rm(dir.path, { recursive: true, force: true })
  288. }
  289. })
  290. })