run.spec.ts 15 KB

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