1
0

runtime.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import { mkdtemp, mkdir, readFile, rm, symlink } from 'node:fs/promises'
  2. import { homedir } from 'node:os'
  3. import { createServer, type Socket } from 'node:net'
  4. import { join } from 'node:path'
  5. import { Context } from '@deepseek-ai/cordis'
  6. import { describe, expect, it, onTestFinished } from 'vitest'
  7. import type { CodeBindingFunction, CodeBindingNamespace, CodeRunRequest } from '@deepseek-ai/dsh-code-runtime'
  8. import type { Config } from '../src/index.ts'
  9. import { mountRuntime } from './setup.ts'
  10. async function setup(config: Config = {}, mode: 'read-only' | 'workspace-write' | 'danger-full-access' = 'danger-full-access') {
  11. const root = await mkdtemp(join(homedir(), '.dsh-node-runtime-test-'))
  12. const cwd = join(root, 'workspace')
  13. await mkdir(cwd)
  14. const ctx = new Context()
  15. onTestFinished(async () => { await ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) })
  16. const runtime = await mountRuntime(ctx, config, { mode, workspaceRoot: cwd })
  17. const run = (request: CodeRunRequest) => runtime.run(runtime.resolve(request))
  18. return { ctx, runtime, root, cwd, run }
  19. }
  20. function bindings(functions: Record<string, CodeBindingFunction>): CodeBindingNamespace[] {
  21. return [{ global: 'tools', functions, errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' } }]
  22. }
  23. describe('Node program process', () => {
  24. it('runs erasable TypeScript in the resolved directory with an empty environment', async () => {
  25. const { run, cwd } = await setup()
  26. const result = await run({ program: 'const n: number = 6; console.log("ready"); return { n: n * 7, cwd: process.cwd(), env: { ...process.env } };', bindings: [] })
  27. expect(result.error).toBeUndefined()
  28. expect(result.value).toEqual({ n: 42, cwd, env: {} })
  29. expect(result.logs).toEqual(['ready'])
  30. expect(result.sandbox).toEqual({ mode: 'danger-full-access', denied: false })
  31. })
  32. it('returns binding values and preserves typed binding rejection', async () => {
  33. const { run } = await setup()
  34. const result = await run({
  35. program: 'const value = await tools.echo({ n: 42 }); let rejected; try { await tools.fail({}) } catch (e) { rejected = [e instanceof ToolCallError,e.name,e.toolName,e.message]; } return {value,rejected};',
  36. bindings: bindings({ echo: async args => args as { n: number }, fail: async () => { throw new Error('denied') } }),
  37. })
  38. expect(result.error).toBeUndefined()
  39. expect(result.value).toEqual({ value: { n: 42 }, rejected: [true, 'ToolCallError', 'fail', 'denied'] })
  40. })
  41. it('retains raw native stdout and stderr separately from control frames', async () => {
  42. const { run } = await setup()
  43. const result = await run({ program: 'const fs = await import("node:fs"); fs.writeSync(1,"native-out你好"); fs.writeSync(2,"native-err🙂"); return 42;', bindings: [] })
  44. expect(result.error).toBeUndefined()
  45. expect(result.value).toBe(42)
  46. expect(result.logs.join('')).toContain('native-out你好')
  47. expect(result.logs.join('')).toContain('native-err🙂')
  48. })
  49. it.each(['throw new Error("broken")', 'enum E { A }'])('reports program failure for %s', async (program) => {
  50. const { run } = await setup()
  51. expect((await run({ program, bindings: [] })).error?.kind).toBe('exception')
  52. })
  53. it('rejects lossy program output', async () => {
  54. const { run } = await setup()
  55. expect((await run({ program: 'return { value: undefined }', bindings: [] })).error?.kind).toBe('invalid-output')
  56. })
  57. it('enforces the combined output cap', async () => {
  58. const { run } = await setup({ maxOutputBytes: 80 })
  59. const result = await run({ program: 'console.log("x".repeat(500)); return 42;', bindings: [] })
  60. expect(result.error?.kind).toBe('output-limit')
  61. const bytes = Buffer.byteLength(JSON.stringify(result.logs)) + Buffer.byteLength(JSON.stringify(result.error?.message))
  62. expect(bytes).toBeLessThanOrEqual(80)
  63. })
  64. it('uses the default deadline and caps explicit requests', async () => {
  65. const { runtime } = await setup()
  66. expect(runtime.resolve({ program: '', bindings: [] }).timeoutMs).toBe(120_000)
  67. expect(runtime.resolve({ program: '', bindings: [], timeoutMs: 900_000 }).timeoutMs).toBe(600_000)
  68. for (const timeoutMs of [0, -1, NaN, Infinity]) expect(() => runtime.resolve({ program: '', bindings: [], timeoutMs })).toThrow()
  69. await expect(runtime.run({ program: '', bindings: [], cwd: process.cwd(), timeoutMs: 1000 })).rejects.toThrow('sandbox policy')
  70. })
  71. it.each(['for (;;) {}', 'await new Promise(() => {})'])('ends an unfinished program at its elapsed deadline: %s', async (program) => {
  72. const { run } = await setup({ timeoutMs: 600, graceMs: 50 })
  73. expect((await run({ program, bindings: [] })).error?.kind).toBe('timeout')
  74. })
  75. it('does not pause the deadline while a binding is pending', async () => {
  76. const { run } = await setup({ timeoutMs: 1000, graceMs: 50 })
  77. const result = await run({ program: 'void tools.wait({}); for (;;) {}', bindings: bindings({ wait: () => new Promise(() => {}) }) })
  78. expect(result.error?.kind).toBe('timeout')
  79. })
  80. it('cancels a live program and closes its managed process', async () => {
  81. const { run } = await setup()
  82. const entered = Promise.withResolvers<undefined>()
  83. const controller = new AbortController()
  84. const active = run({ program: 'await tools.enter({}); for (;;) {}', signal: controller.signal, bindings: bindings({ enter: async () => { entered.resolve(undefined); return null } }) })
  85. await entered.promise
  86. controller.abort('stop')
  87. expect((await active).error).toEqual({ kind: 'abort', message: 'stop' })
  88. })
  89. it('closes a still-running descendant before returning the program result', async () => {
  90. const { run } = await setup()
  91. const connected = Promise.withResolvers<undefined>()
  92. const disconnected = Promise.withResolvers<undefined>()
  93. let peer: Socket | undefined
  94. const server = createServer((socket) => {
  95. peer = socket
  96. // A terminated peer can reset its connection instead of sending FIN.
  97. socket.on('error', () => {})
  98. socket.once('close', () => { disconnected.resolve(undefined) })
  99. connected.resolve(undefined)
  100. })
  101. onTestFinished(async () => {
  102. peer?.destroy()
  103. if (server.listening) await new Promise<void>((resolve, reject) => {
  104. server.close((error) => { if (error) reject(error); else resolve() })
  105. })
  106. })
  107. await new Promise<void>((resolve, reject) => {
  108. server.once('error', reject)
  109. server.listen(0, '127.0.0.1', resolve)
  110. })
  111. const address = server.address()
  112. if (address === null || typeof address === 'string') throw new Error('expected bound TCP listener')
  113. const child = `require('node:net').connect(${address.port},'127.0.0.1')`
  114. const result = await run({
  115. program: `const {spawn}=await import("node:child_process"); spawn(process.execPath,["-e",${JSON.stringify(child)}],{stdio:"ignore"}); await tools.connected({}); return 42;`,
  116. bindings: bindings({ connected: async () => { await connected.promise; return null } }),
  117. })
  118. expect(result.error).toBeUndefined()
  119. expect(result.value).toBe(42)
  120. await disconnected.promise
  121. })
  122. it('applies the configured V8 old-generation ceiling to each fresh Node process', async () => {
  123. const limits: number[] = []
  124. for (const maxOldGenerationSizeMb of [32, 64]) {
  125. const { run } = await setup({ maxOldGenerationSizeMb })
  126. const result = await run({ program: 'return (await import("node:v8")).getHeapStatistics().heap_size_limit;', bindings: [] })
  127. expect(result.error).toBeUndefined()
  128. if (typeof result.value !== 'number') throw new Error('expected V8 heap limit')
  129. limits.push(result.value)
  130. }
  131. expect(Number(limits[1]) - Number(limits[0])).toBe(32 * 1024 * 1024)
  132. })
  133. it('disposes active programs and rejects later execution', async () => {
  134. const { ctx, run, runtime } = await setup()
  135. const spec = runtime.resolve({ program: '', bindings: [] })
  136. const entered = Promise.withResolvers<undefined>()
  137. const active = run({ program: 'await tools.enter({}); await new Promise(() => {})', bindings: bindings({ enter: async () => { entered.resolve(undefined); return null } }) })
  138. await entered.promise
  139. await ctx.fiber.dispose()
  140. expect((await active).error?.kind).toBe('abort')
  141. await expect(runtime.run(spec)).rejects.toThrow('disposal')
  142. expect(() => runtime.resolve({ program: '', bindings: [] })).toThrow('disposal')
  143. expect(runtime.isolation).toBe('process')
  144. })
  145. it.each([
  146. 'const fs = await import("node:fs"); const b=Buffer.alloc(4); b.writeUInt32BE(4294967295); fs.writeSync(7,b); await new Promise(()=>{});',
  147. 'const fs = await import("node:fs"); const body=Buffer.from(JSON.stringify({type:"call",id:1,global:"tools",name:"undeclared",args:[]})); const h=Buffer.alloc(4); h.writeUInt32BE(body.length); fs.writeSync(7,Buffer.concat([h,body])); await new Promise(()=>{});',
  148. ])('refuses hostile program control traffic', async (program) => {
  149. const { run } = await setup()
  150. expect((await run({ program, bindings: [] })).error?.kind).toBe('protocol')
  151. })
  152. it('applies read-only confinement to direct Node filesystem writes', async () => {
  153. const { run, cwd } = await setup({}, 'read-only')
  154. const path = join(cwd, 'denied.txt')
  155. const result = await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(path)}, 'denied')`, bindings: [] })
  156. expect(result.error?.kind).toBe('exception')
  157. expect(result.sandbox).toMatchObject({ mode: 'read-only', denied: true })
  158. await expect(readFile(path)).rejects.toMatchObject({ code: 'ENOENT' })
  159. })
  160. it('permits workspace writes and denies a symlink to a sibling outside it', async () => {
  161. const { run, cwd, root } = await setup({}, 'workspace-write')
  162. const target = join(cwd, 'allowed.txt')
  163. expect((await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(target)}, 'allowed'); return true`, bindings: [] })).value).toBe(true)
  164. expect(await readFile(target, 'utf8')).toBe('allowed')
  165. const outside = join(root, 'outside')
  166. await mkdir(outside)
  167. await symlink(outside, join(cwd, 'escape'), process.platform === 'win32' ? 'junction' : 'dir')
  168. const result = await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(join(cwd, 'escape', 'denied.txt'))}, 'denied')`, bindings: [] })
  169. expect(result.error?.kind).toBe('exception')
  170. expect(result.sandbox).toMatchObject({ mode: 'workspace-write', denied: true })
  171. await expect(readFile(join(outside, 'denied.txt'))).rejects.toMatchObject({ code: 'ENOENT' })
  172. })
  173. })
  174. it('preserves empty console entries and bounds native output overflow', async () => {
  175. const { run } = await setup({ maxOutputBytes: 100 })
  176. const lines = await run({ program: 'console.log("a"); console.log(""); console.log("b")', bindings: [] })
  177. expect(lines.logs).toEqual(['a', '', 'b'])
  178. const overflow = await run({ program: 'const fs=await import("node:fs"); fs.writeSync(1,"HEAD-"+"x".repeat(100000));', bindings: [] })
  179. expect(overflow.error?.kind).toBe('output-limit')
  180. expect(overflow.logs.join('')).toContain('HEAD-')
  181. const bytes = Buffer.byteLength(JSON.stringify(overflow.logs)) + Buffer.byteLength(JSON.stringify(overflow.error?.message))
  182. expect(bytes).toBeLessThanOrEqual(100)
  183. })