1
0

runtime.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 { delimiter, join } from 'node:path'
  5. import { Context } from '@deepseek-ai/cordis'
  6. import { describe, expect, it, onTestFinished, vi } 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('keeps native startup paths available for nested Node creation with an empty model environment', async () => {
  33. const { run } = await setup()
  34. const result = await run({
  35. program: 'const {spawnSync}=await import("node:child_process"); const child=spawnSync(process.execPath,["-e","process.stdout.write(JSON.stringify(Object.keys(process.env)))"],{encoding:"utf8"}); return {env:Object.keys(process.env),status:child.status,error:child.error?.message ?? null,childKeys:JSON.parse(child.stdout || "[]")};',
  36. bindings: [],
  37. })
  38. expect(result.error).toBeUndefined()
  39. const value = result.value as { env: string[]; status: number | null; error: string | null; childKeys: string[] }
  40. expect(value.env).toEqual([])
  41. expect(value.status).toBe(0)
  42. expect(value.error).toBeNull()
  43. const nativeKeys = ['PATH', 'PATHEXT', 'SYSTEMROOT', 'WINDIR']
  44. // CoreFoundation initializes this entry independently when a macOS child starts.
  45. if (process.platform === 'darwin') nativeKeys.push('__CF_USER_TEXT_ENCODING')
  46. expect(value.childKeys.filter(key => !nativeKeys.includes(key.toUpperCase()))).toEqual([])
  47. })
  48. it('returns binding values and preserves typed binding rejection', async () => {
  49. const { run } = await setup()
  50. const result = await run({
  51. 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};',
  52. bindings: bindings({ echo: async args => args as { n: number }, fail: async () => { throw new Error('denied') } }),
  53. })
  54. expect(result.error).toBeUndefined()
  55. expect(result.value).toEqual({ value: { n: 42 }, rejected: [true, 'ToolCallError', 'fail', 'denied'] })
  56. })
  57. it('retains raw native stdout and stderr separately from control frames', async () => {
  58. const { run } = await setup()
  59. const result = await run({ program: 'const fs = await import("node:fs"); fs.writeSync(1,"native-out你好"); fs.writeSync(2,"native-err🙂"); return 42;', bindings: [] })
  60. expect(result.error).toBeUndefined()
  61. expect(result.value).toBe(42)
  62. expect(result.logs.join('')).toContain('native-out你好')
  63. expect(result.logs.join('')).toContain('native-err🙂')
  64. })
  65. it.each(['throw new Error("broken")', 'enum E { A }'])('reports program failure for %s', async (program) => {
  66. const { run } = await setup()
  67. expect((await run({ program, bindings: [] })).error?.kind).toBe('exception')
  68. })
  69. it('rejects lossy program output', async () => {
  70. const { run } = await setup()
  71. expect((await run({ program: 'return { value: undefined }', bindings: [] })).error?.kind).toBe('invalid-output')
  72. })
  73. it('enforces the combined output cap', async () => {
  74. const { run } = await setup({ maxOutputBytes: 80 })
  75. const result = await run({ program: 'console.log("x".repeat(500)); return 42;', bindings: [] })
  76. expect(result.error?.kind).toBe('output-limit')
  77. const bytes = Buffer.byteLength(JSON.stringify(result.logs)) + Buffer.byteLength(JSON.stringify(result.error?.message))
  78. expect(bytes).toBeLessThanOrEqual(80)
  79. })
  80. it('uses the default deadline and caps explicit requests', async () => {
  81. const { runtime } = await setup()
  82. expect(runtime.resolve({ program: '', bindings: [] }).timeoutMs).toBe(120_000)
  83. expect(runtime.resolve({ program: '', bindings: [], timeoutMs: 900_000 }).timeoutMs).toBe(600_000)
  84. for (const timeoutMs of [0, -1, NaN, Infinity]) expect(() => runtime.resolve({ program: '', bindings: [], timeoutMs })).toThrow()
  85. await expect(runtime.run({ program: '', bindings: [], cwd: process.cwd(), timeoutMs: 1000 })).rejects.toThrow('sandbox policy')
  86. })
  87. it.each(['for (;;) {}', 'await new Promise(() => {})'])('ends an unfinished program at its elapsed deadline: %s', async (program) => {
  88. const { run } = await setup({ timeoutMs: 600, graceMs: 50 })
  89. expect((await run({ program, bindings: [] })).error?.kind).toBe('timeout')
  90. })
  91. it('retains console output emitted immediately before a non-yielding program', async () => {
  92. const { run } = await setup({ timeoutMs: 1000, graceMs: 50 })
  93. const result = await run({ program: 'console.log("before hot loop"); for (;;) {}', bindings: [] })
  94. expect(result.error?.kind).toBe('timeout')
  95. expect(result.logs).toEqual(['before hot loop'])
  96. })
  97. it('does not pause the deadline while a binding is pending', async () => {
  98. const { run } = await setup({ timeoutMs: 1000, graceMs: 50 })
  99. const result = await run({ program: 'void tools.wait({}); for (;;) {}', bindings: bindings({ wait: () => new Promise(() => {}) }) })
  100. expect(result.error?.kind).toBe('timeout')
  101. })
  102. it('cancels a live program and closes its managed process', async () => {
  103. const { run } = await setup()
  104. const entered = Promise.withResolvers<undefined>()
  105. const controller = new AbortController()
  106. const active = run({ program: 'await tools.enter({}); for (;;) {}', signal: controller.signal, bindings: bindings({ enter: async () => { entered.resolve(undefined); return null } }) })
  107. await entered.promise
  108. controller.abort('stop')
  109. expect((await active).error).toEqual({ kind: 'abort', message: 'stop' })
  110. })
  111. it('closes a still-running descendant before returning the program result', async () => {
  112. const { run } = await setup()
  113. const connected = Promise.withResolvers<undefined>()
  114. const disconnected = Promise.withResolvers<undefined>()
  115. let peer: Socket | undefined
  116. const server = createServer((socket) => {
  117. peer = socket
  118. // A terminated peer can reset its connection instead of sending FIN.
  119. socket.on('error', () => {})
  120. socket.once('close', () => { disconnected.resolve(undefined) })
  121. connected.resolve(undefined)
  122. })
  123. onTestFinished(async () => {
  124. peer?.destroy()
  125. if (server.listening) await new Promise<void>((resolve, reject) => {
  126. server.close((error) => { if (error) reject(error); else resolve() })
  127. })
  128. })
  129. await new Promise<void>((resolve, reject) => {
  130. server.once('error', reject)
  131. server.listen(0, '127.0.0.1', resolve)
  132. })
  133. const address = server.address()
  134. if (address === null || typeof address === 'string') throw new Error('expected bound TCP listener')
  135. const child = `require('node:net').connect(${address.port},'127.0.0.1')`
  136. const result = await run({
  137. program: `const {spawn}=await import("node:child_process"); spawn(process.execPath,["-e",${JSON.stringify(child)}],{stdio:"ignore"}); await tools.connected({}); return 42;`,
  138. bindings: bindings({ connected: async () => { await connected.promise; return null } }),
  139. })
  140. expect(result.error).toBeUndefined()
  141. expect(result.value).toBe(42)
  142. await disconnected.promise
  143. })
  144. it('applies the configured V8 old-generation ceiling to each fresh Node process', async () => {
  145. const limits: number[] = []
  146. for (const maxOldGenerationSizeMb of [32, 64]) {
  147. const { run } = await setup({ maxOldGenerationSizeMb })
  148. const result = await run({ program: 'return (await import("node:v8")).getHeapStatistics().heap_size_limit;', bindings: [] })
  149. expect(result.error).toBeUndefined()
  150. if (typeof result.value !== 'number') throw new Error('expected V8 heap limit')
  151. limits.push(result.value)
  152. }
  153. expect(Number(limits[1]) - Number(limits[0])).toBe(32 * 1024 * 1024)
  154. })
  155. it('disposes active programs and rejects later execution', async () => {
  156. const { ctx, run, runtime } = await setup()
  157. const spec = runtime.resolve({ program: '', bindings: [] })
  158. const entered = Promise.withResolvers<undefined>()
  159. const active = run({ program: 'await tools.enter({}); await new Promise(() => {})', bindings: bindings({ enter: async () => { entered.resolve(undefined); return null } }) })
  160. await entered.promise
  161. await ctx.fiber.dispose()
  162. expect((await active).error?.kind).toBe('abort')
  163. await expect(runtime.run(spec)).rejects.toThrow('disposal')
  164. expect(() => runtime.resolve({ program: '', bindings: [] })).toThrow('disposal')
  165. expect(runtime.isolation).toBe('process')
  166. })
  167. it.each([
  168. 'const fs = await import("node:fs"); const b=Buffer.alloc(4); b.writeUInt32BE(4294967295); fs.writeSync(7,b); await new Promise(()=>{});',
  169. '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(()=>{});',
  170. ])('refuses hostile program control traffic', async (program) => {
  171. const { run } = await setup()
  172. expect((await run({ program, bindings: [] })).error?.kind).toBe('protocol')
  173. })
  174. it('applies read-only confinement to direct Node filesystem writes', async () => {
  175. const { run, cwd } = await setup({}, 'read-only')
  176. const path = join(cwd, 'denied.txt')
  177. const result = await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(path)}, 'denied')`, bindings: [] })
  178. expect(result.error?.kind).toBe('exception')
  179. expect(result.sandbox).toMatchObject({ mode: 'read-only', denied: true })
  180. await expect(readFile(path)).rejects.toMatchObject({ code: 'ENOENT' })
  181. })
  182. it.skipIf(process.platform === 'win32')('starts a confining launcher found only through the execution PATH', async () => {
  183. const { ctx, runtime, run, root } = await setup({}, 'read-only')
  184. const confine = ctx.sandbox.confine.bind(ctx.sandbox)
  185. const policy = runtime.resolve({ program: '', bindings: [] }).sandboxPolicy
  186. if (policy === undefined || policy.mode === 'danger-full-access') throw new Error('expected confined policy')
  187. const wrapped = confine([process.execPath, '--version'], { ...policy, mode: policy.mode })
  188. const original = wrapped.argv[0]
  189. if (original === undefined) throw new Error('expected sandbox launcher')
  190. const executable = await ctx.subprocess.resolveExecutable(original)
  191. const alias = 'ptc-private-sandbox-launcher'
  192. await symlink(executable, join(root, alias))
  193. const previousPath = process.env.PATH
  194. const substitute = vi.spyOn(ctx.sandbox, 'confine').mockImplementation((argv, selected) => {
  195. const result = confine(argv, selected)
  196. return { ...result, argv: [alias, ...result.argv.slice(1)] }
  197. })
  198. try {
  199. process.env.PATH = `${root}${delimiter}${previousPath ?? ''}`
  200. const result = await run({ program: 'return { env: Object.keys(process.env) };', bindings: [] })
  201. expect(result.error).toBeUndefined()
  202. expect(result.value).toEqual({ env: [] })
  203. } finally {
  204. substitute.mockRestore()
  205. if (previousPath === undefined) delete process.env.PATH
  206. else process.env.PATH = previousPath
  207. }
  208. })
  209. it('permits workspace writes and denies a symlink to a sibling outside it', async () => {
  210. const { run, cwd, root } = await setup({}, 'workspace-write')
  211. const target = join(cwd, 'allowed.txt')
  212. expect((await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(target)}, 'allowed'); return true`, bindings: [] })).value).toBe(true)
  213. expect(await readFile(target, 'utf8')).toBe('allowed')
  214. const outside = join(root, 'outside')
  215. await mkdir(outside)
  216. await symlink(outside, join(cwd, 'escape'), process.platform === 'win32' ? 'junction' : 'dir')
  217. const result = await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(join(cwd, 'escape', 'denied.txt'))}, 'denied')`, bindings: [] })
  218. expect(result.error?.kind).toBe('exception')
  219. expect(result.sandbox).toMatchObject({ mode: 'workspace-write', denied: true })
  220. await expect(readFile(join(outside, 'denied.txt'))).rejects.toMatchObject({ code: 'ENOENT' })
  221. })
  222. })
  223. it('preserves empty console entries and bounds native output overflow', async () => {
  224. const { run } = await setup({ maxOutputBytes: 100 })
  225. const lines = await run({ program: 'console.log("a"); console.log(""); console.log("b")', bindings: [] })
  226. expect(lines.logs).toEqual(['a', '', 'b'])
  227. const overflow = await run({ program: 'const fs=await import("node:fs"); fs.writeSync(1,"HEAD-"+"x".repeat(100000));', bindings: [] })
  228. expect(overflow.error?.kind).toBe('output-limit')
  229. expect(overflow.logs.join('')).toContain('HEAD-')
  230. const bytes = Buffer.byteLength(JSON.stringify(overflow.logs)) + Buffer.byteLength(JSON.stringify(overflow.error?.message))
  231. expect(bytes).toBeLessThanOrEqual(100)
  232. })