run.spec.ts 16 KB

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