run.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import { mkdtempSync, readFileSync, statSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { dirname, join } from 'node:path'
  4. import { describe, expect, it, vi } from 'vitest'
  5. import { killGroup, OutputCollector, runBash } from '@deepseek-ai/dsh-bash-local'
  6. import type { RunningBash } from '@deepseek-ai/dsh-bash-local'
  7. const { failNextClose } = vi.hoisted(() => ({ failNextClose: { value: false } }))
  8. vi.mock('node:fs', async (importOriginal) => {
  9. const actual = await importOriginal<typeof import('node:fs')>()
  10. return {
  11. ...actual,
  12. closeSync(fd: number): void {
  13. if (failNextClose.value) {
  14. failNextClose.value = false
  15. throw Object.assign(new Error('simulated EIO on close'), { code: 'EIO' })
  16. }
  17. actual.closeSync(fd)
  18. },
  19. }
  20. })
  21. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-bash-spec-'))
  22. function spec(command: string, overrides: Partial<Parameters<typeof runBash>[0]> = {}) {
  23. return {
  24. command,
  25. cwd: process.cwd(),
  26. timeoutMs: 0,
  27. maxOutputBytes: 64_000,
  28. ...overrides,
  29. }
  30. }
  31. /** Poll until a pid no longer exists (kill(pid, 0) throws ESRCH). */
  32. async function waitGone(pid: number, timeoutMs = 5_000): Promise<void> {
  33. const deadline = Date.now() + timeoutMs
  34. while (Date.now() < deadline) {
  35. try {
  36. process.kill(pid, 0)
  37. } catch {
  38. return
  39. }
  40. await new Promise(resolve => setTimeout(resolve, 20))
  41. }
  42. throw new Error(`pid ${pid} still alive after ${timeoutMs}ms`)
  43. }
  44. async function waitForStdout(running: RunningBash, expected: string, timeoutMs = 5_000): Promise<void> {
  45. const deadline = Date.now() + timeoutMs
  46. while (Date.now() < deadline) {
  47. if (running.stdout.snapshot().text.includes(expected)) return
  48. await new Promise(resolve => setTimeout(resolve, 20))
  49. }
  50. throw new Error(`stdout did not include ${JSON.stringify(expected)} after ${timeoutMs}ms`)
  51. }
  52. describe('runBash', () => {
  53. it('captures stdout on success', async () => {
  54. const result = await runBash(spec('echo hello')).done
  55. expect(result.exitCode).toBe(0)
  56. expect(result.signal).toBeNull()
  57. expect(result.timedOut).toBe(false)
  58. expect(result.aborted).toBe(false)
  59. expect(result.stdout.text).toBe('hello\n')
  60. expect(result.stdout.truncated).toBe(false)
  61. expect(result.stderr.text).toBe('')
  62. })
  63. it('captures stderr separately', async () => {
  64. const result = await runBash(spec('echo oops >&2')).done
  65. expect(result.exitCode).toBe(0)
  66. expect(result.stdout.text).toBe('')
  67. expect(result.stderr.text).toBe('oops\n')
  68. })
  69. it('captures both streams', async () => {
  70. const result = await runBash(spec('echo out; echo err >&2')).done
  71. expect(result.stdout.text).toBe('out\n')
  72. expect(result.stderr.text).toBe('err\n')
  73. })
  74. it('reports non-zero exit codes', async () => {
  75. const result = await runBash(spec('exit 42')).done
  76. expect(result.exitCode).toBe(42)
  77. expect(result.signal).toBeNull()
  78. })
  79. it('applies model-friendly env overrides', async () => {
  80. const result = await runBash(spec('echo "$NO_COLOR/$TERM/$PAGER"')).done
  81. expect(result.stdout.text).toBe('1/dumb/cat\n')
  82. })
  83. it('runs in the requested cwd', async () => {
  84. const result = await runBash(spec('pwd', { cwd: '/tmp' })).done
  85. expect(result.stdout.text.trim()).toMatch(/\/tmp$/)
  86. })
  87. it('kills with SIGTERM on timeout', async () => {
  88. const start = Date.now()
  89. const result = await runBash(spec('sleep 60', { timeoutMs: 100 })).done
  90. expect(Date.now() - start).toBeLessThan(5_000)
  91. expect(result.timedOut).toBe(true)
  92. expect(result.signal).toBe('SIGTERM')
  93. expect(result.exitCode).toBeNull()
  94. })
  95. it('escalates to SIGKILL when SIGTERM is trapped', async () => {
  96. const running = runBash(spec('trap \'\' TERM; echo ready; sleep 60'), { graceMs: 200 })
  97. await waitForStdout(running, 'ready\n')
  98. running.kill()
  99. const result = await running.done
  100. expect(result.signal).toBe('SIGKILL')
  101. })
  102. it('kills the whole process group (grandchildren die too)', async () => {
  103. // The subshell writes the sleep's pid then waits on it; killing the
  104. // group must take the sleep down with bash.
  105. const pidFile = join(spillDir, `grandchild-${Date.now()}.pid`)
  106. const running = runBash(spec(`sleep 60 & echo $! > ${pidFile}; wait`))
  107. await new Promise(resolve => setTimeout(resolve, 300))
  108. const grandchild = Number(readFileSync(pidFile, 'utf8').trim())
  109. expect(grandchild).toBeGreaterThan(0)
  110. running.kill()
  111. const result = await running.done
  112. expect(result.signal).toBe('SIGTERM')
  113. await waitGone(grandchild)
  114. })
  115. it('aborts via AbortSignal mid-run', async () => {
  116. const controller = new AbortController()
  117. const running = runBash(spec('sleep 60', { signal: controller.signal }))
  118. setTimeout(() => { controller.abort('user cancelled') }, 50)
  119. const result = await running.done
  120. expect(result.aborted).toBe(true)
  121. expect(result.signal).toBe('SIGTERM')
  122. })
  123. it('throws when the signal is already aborted before spawn', () => {
  124. const controller = new AbortController()
  125. controller.abort('too late')
  126. expect(() => runBash(spec('echo hi', { signal: controller.signal })))
  127. .toThrow(/aborted before spawn: too late/)
  128. })
  129. it('rejects with a spawn error for a nonexistent cwd', async () => {
  130. await expect(runBash(spec('echo hi', { cwd: '/nonexistent-dir-dsh-test' })).done)
  131. .rejects.toThrow(/ENOENT/)
  132. })
  133. it('kill() is idempotent (second call does not restart escalation)', async () => {
  134. const running = runBash(spec('sleep 60'))
  135. running.kill()
  136. running.kill()
  137. const result = await running.done
  138. expect(result.signal).toBe('SIGTERM')
  139. })
  140. })
  141. describe('stdin and extra env (set by in-process plugins)', () => {
  142. it('writes stdin to the command and closes it', async () => {
  143. const result = await runBash(spec('cat', { stdin: 'hello from stdin\n' })).done
  144. expect(result.exitCode).toBe(0)
  145. expect(result.stdout.text).toBe('hello from stdin\n')
  146. })
  147. it('a command that reads stdin sees EOF when none is supplied', async () => {
  148. // No stdin → fd 0 is /dev/null, so `cat` reads EOF and exits 0 with no
  149. // output (it does NOT block).
  150. const result = await runBash(spec('cat')).done
  151. expect(result.exitCode).toBe(0)
  152. expect(result.stdout.text).toBe('')
  153. })
  154. it('gives fd 0 the exact pre-seam type: /dev/null when no stdin, a pipe when supplied', async () => {
  155. // The no-stdin path must stay observationally identical to the pre-seam
  156. // `ignore` default: a command that probes stdin's file type sees a char
  157. // device (/dev/null). Regressing to an always-open pipe would make fd 0 a
  158. // socket (node's spawn pipe is an AF_UNIX socket, not a FIFO), flipping
  159. // `test -c /dev/stdin` for every model-driven call. When bytes ARE supplied,
  160. // fd 0 is that pipe (a socket), as it must be to carry them.
  161. const none = await runBash(spec('test -c /dev/stdin && echo char || echo other')).done
  162. expect(none.stdout.text).toBe('char\n')
  163. const piped = await runBash(spec('test -S /dev/stdin && echo socket || echo other', { stdin: 'x' })).done
  164. expect(piped.stdout.text).toBe('socket\n')
  165. })
  166. it('merges extra env entries onto the scrubbed environment', async () => {
  167. const result = await runBash(spec('echo "$DSH_EXTRA_ONE/$DSH_EXTRA_TWO"', {
  168. env: { DSH_EXTRA_ONE: 'alpha', DSH_EXTRA_TWO: 'beta' },
  169. })).done
  170. expect(result.stdout.text).toBe('alpha/beta\n')
  171. })
  172. it('an explicit extra env entry overrides the model-friendly override and the scrub', async () => {
  173. // TERM is a model-friendly OVERRIDE (dumb); an explicit extra entry wins.
  174. // DSH_OVERRIDE_KEY matches the credential scrub pattern, yet an explicit
  175. // entry is still honored — the scrub only drops AMBIENT process.env creds.
  176. const result = await runBash(spec('echo "$TERM/$DSH_OVERRIDE_KEY"', {
  177. env: { TERM: 'xterm-256color', DSH_OVERRIDE_KEY: 'explicit-wins' },
  178. })).done
  179. expect(result.stdout.text).toBe('xterm-256color/explicit-wins\n')
  180. })
  181. it('does not crash or reject when the child ignores a large stdin (EPIPE)', async () => {
  182. // The child exits immediately without reading; closing our end of a stdin
  183. // pipe still holding ~1MiB triggers EPIPE on the write. The handler must
  184. // swallow it: `done` resolves normally with the child's real exit.
  185. const big = 'x'.repeat(1024 * 1024)
  186. const result = await runBash(spec('exit 7', { stdin: big })).done
  187. expect(result.exitCode).toBe(7)
  188. expect(result.aborted).toBe(false)
  189. })
  190. })
  191. describe('output truncation and spill', () => {
  192. it('keeps the tail and spills the full stream to disk', async () => {
  193. // 200 numbered lines of ~10 bytes; cap at 500 bytes keeps a late tail.
  194. const result = await runBash(
  195. spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', { maxOutputBytes: 500 }),
  196. { spillDir },
  197. ).done
  198. expect(result.stdout.truncated).toBe(true)
  199. expect(result.stdout.text.length).toBeLessThanOrEqual(500)
  200. expect(result.stdout.text).toContain('line-0200')
  201. expect(result.stdout.text).not.toContain('line-0001')
  202. expect(result.stdout.spillPath).toBeDefined()
  203. const full = readFileSync(result.stdout.spillPath!, 'utf8')
  204. expect(full).toContain('line-0001')
  205. expect(full).toContain('line-0200')
  206. })
  207. it('does not truncate output exactly at the cap', async () => {
  208. const result = await runBash(
  209. spec('printf "%.0sx" $(seq 1 500)', { maxOutputBytes: 500 }),
  210. { spillDir },
  211. ).done
  212. expect(result.stdout.truncated).toBe(false)
  213. expect(result.stdout.text.length).toBe(500)
  214. expect(result.stdout.spillPath).toBeUndefined()
  215. })
  216. it('settles with the tail and no spill path when final spill close fails', async () => {
  217. failNextClose.value = true
  218. const result = await runBash(
  219. spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', { maxOutputBytes: 500 }),
  220. { spillDir },
  221. ).done
  222. expect(failNextClose.value).toBe(false)
  223. expect(result.exitCode).toBe(0)
  224. expect(result.stdout.truncated).toBe(true)
  225. expect(result.stdout.text).toContain('line-0200')
  226. expect(result.stdout.spillPath).toBeUndefined()
  227. })
  228. })
  229. describe('OutputCollector', () => {
  230. it('keeps the tail of a single oversized chunk', () => {
  231. const collector = new OutputCollector(10, 'test', spillDir)
  232. collector.push(Buffer.from('0123456789abcdef'))
  233. const out = collector.finalize()
  234. expect(out.text).toBe('6789abcdef')
  235. expect(out.truncated).toBe(true)
  236. expect(readFileSync(out.spillPath!, 'utf8')).toBe('0123456789abcdef')
  237. })
  238. it('readFrom returns increments and flags lossy reads', () => {
  239. const collector = new OutputCollector(10, 'test', spillDir)
  240. collector.push(Buffer.from('aaaaa'))
  241. const first = collector.readFrom(0)
  242. expect(first.text).toBe('aaaaa')
  243. expect(first.lossy).toBe(false)
  244. expect(first.nextOffset).toBe(5)
  245. collector.push(Buffer.from('bbbbb'))
  246. const second = collector.readFrom(first.nextOffset)
  247. expect(second.text).toBe('bbbbb')
  248. expect(second.lossy).toBe(false)
  249. // Push enough to slide the window past the last offset.
  250. collector.push(Buffer.from('c'.repeat(20)))
  251. const third = collector.readFrom(second.nextOffset)
  252. expect(third.lossy).toBe(true)
  253. expect(third.text).toBe('c'.repeat(10))
  254. expect(third.spillPath).toBeDefined()
  255. })
  256. it('tracks totalBytes across drops', () => {
  257. const collector = new OutputCollector(4, 'test', spillDir)
  258. collector.push(Buffer.from('aaaa'))
  259. collector.push(Buffer.from('bbbb'))
  260. expect(collector.totalBytes).toBe(8)
  261. expect(collector.finalize().text).toBe('bbbb')
  262. })
  263. it('contains close failures and drops the spill path', () => {
  264. const collector = new OutputCollector(4, 'closefail', spillDir)
  265. collector.push(Buffer.from('aaaa'))
  266. collector.push(Buffer.from('bbbb'))
  267. expect(collector.snapshot().spillPath).toBeDefined()
  268. failNextClose.value = true
  269. let out: ReturnType<typeof collector.finalize>
  270. expect(() => { out = collector.finalize() }).not.toThrow()
  271. expect(failNextClose.value).toBe(false)
  272. expect(out!.text).toBe('bbbb')
  273. expect(out!.truncated).toBe(true)
  274. expect(out!.spillPath).toBeUndefined()
  275. })
  276. })
  277. describe('killGroup', () => {
  278. it('ignores non-positive pids', () => {
  279. expect(() => { killGroup(-1, 'SIGTERM') }).not.toThrow()
  280. expect(() => { killGroup(0, 'SIGTERM') }).not.toThrow()
  281. })
  282. it('swallows ESRCH for vanished groups', async () => {
  283. const running = runBash(spec('true'))
  284. await running.done
  285. expect(() => { killGroup(running.pid, 'SIGTERM') }).not.toThrow()
  286. })
  287. })
  288. describe('abort edge cases', () => {
  289. it('reports a fallback reason for reason-less pre-aborted signals', () => {
  290. // Real AbortControllers always set a DOMException reason; signal-like
  291. // objects from other libraries may not — the fallback covers them.
  292. const bare = {
  293. aborted: true,
  294. reason: undefined,
  295. addEventListener() {},
  296. removeEventListener() {},
  297. } as unknown as AbortSignal
  298. expect(() => runBash(spec('echo hi', { signal: bare })))
  299. .toThrow(/aborted before spawn: aborted/)
  300. })
  301. it('reports an externally self-killed command without the timeout marker', async () => {
  302. const result = await runBash(spec('kill -TERM $$')).done
  303. expect(result.signal).toBe('SIGTERM')
  304. expect(result.timedOut).toBe(false)
  305. expect(result.aborted).toBe(false)
  306. })
  307. })
  308. describe('review fixes: env scrubbing and spill hardening', () => {
  309. it('scrubs credential-shaped env vars from child processes', async () => {
  310. process.env.DSH_TEST_API_KEY = 'super-secret'
  311. process.env.DSH_TEST_TOKEN = 'also-secret'
  312. process.env.DSH_TEST_PLAIN = 'visible'
  313. try {
  314. const result = await runBash(spec('echo "[${DSH_TEST_API_KEY:-absent}|${DSH_TEST_TOKEN:-absent}|${DSH_TEST_PLAIN:-absent}]"')).done
  315. expect(result.stdout.text.trim()).toBe('[absent|absent|visible]')
  316. } finally {
  317. delete process.env.DSH_TEST_API_KEY
  318. delete process.env.DSH_TEST_TOKEN
  319. delete process.env.DSH_TEST_PLAIN
  320. }
  321. })
  322. it('creates spill files with owner-only permissions and random names', async () => {
  323. const result = await runBash(
  324. spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', { maxOutputBytes: 500 }),
  325. { spillDir },
  326. ).done
  327. const path = result.stdout.spillPath!
  328. expect(path).toMatch(/dsh-bash-\d+-\d+-[0-9a-f]{12}-stdout\.log$/)
  329. const mode = statSync(path).mode & 0o777
  330. expect(mode).toBe(0o600)
  331. })
  332. it('defaults spills into a private per-process directory', async () => {
  333. const result = await runBash(
  334. spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', { maxOutputBytes: 500 }),
  335. ).done
  336. const dir = dirname(result.stdout.spillPath!)
  337. expect(dir).toMatch(/dsh-bash-/)
  338. const mode = statSync(dir).mode & 0o777
  339. expect(mode).toBe(0o700)
  340. })
  341. it('killGroup never throws, even for EPERM-style failures', () => {
  342. const spy = vi.spyOn(process, 'kill').mockImplementation(() => {
  343. throw Object.assign(new Error('EPERM'), { code: 'EPERM' })
  344. })
  345. try {
  346. expect(() => { killGroup(12345, 'SIGTERM') }).not.toThrow()
  347. } finally {
  348. spy.mockRestore()
  349. }
  350. })
  351. it('honors AbortSignal on background-style runs (no timeout)', async () => {
  352. const controller = new AbortController()
  353. const running = runBash(spec('sleep 60', { timeoutMs: 0, signal: controller.signal }))
  354. setTimeout(() => { controller.abort() }, 50)
  355. const result = await running.done
  356. expect(result.aborted).toBe(true)
  357. expect(result.signal).toBe('SIGTERM')
  358. })
  359. })