1
0

runtime.spec.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import { mkdtemp, mkdir, readFile, rm, symlink } from 'node:fs/promises'
  2. import { homedir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { Context } from '@deepseek-ai/cordis'
  5. import { describe, expect, it, onTestFinished } from 'vitest'
  6. import type { CodeBindingFunction, CodeBindingNamespace, CodeRunRequest } from '@deepseek-ai/dsh-code-runtime'
  7. import type { Config } from '../src/index.ts'
  8. import { mountRuntime } from './setup.ts'
  9. async function setup(config: Config = {}, mode: 'read-only' | 'workspace-write' | 'danger-full-access' = 'danger-full-access') {
  10. const root = await mkdtemp(join(homedir(), '.dsh-node-runtime-test-'))
  11. const cwd = join(root, 'workspace')
  12. await mkdir(cwd)
  13. const ctx = new Context()
  14. onTestFinished(async () => { await ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) })
  15. const runtime = await mountRuntime(ctx, config, { mode, workspaceRoot: cwd })
  16. const run = (request: CodeRunRequest) => runtime.run(runtime.resolve(request))
  17. return { ctx, runtime, root, cwd, run }
  18. }
  19. function bindings(functions: Record<string, CodeBindingFunction>): CodeBindingNamespace[] {
  20. return [{ global: 'tools', functions, errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' } }]
  21. }
  22. describe('Node program process', () => {
  23. it('runs erasable TypeScript in the resolved directory with an empty environment', async () => {
  24. const { run, cwd } = await setup()
  25. const result = await run({ program: 'const n: number = 6; console.log("ready"); return { n: n * 7, cwd: process.cwd(), env: { ...process.env } };', bindings: [] })
  26. expect(result.error).toBeUndefined()
  27. expect(result.value).toEqual({ n: 42, cwd, env: {} })
  28. expect(result.logs).toEqual(['ready'])
  29. expect(result.sandbox).toEqual({ mode: 'danger-full-access', denied: false })
  30. })
  31. it('returns binding values and preserves typed binding rejection', async () => {
  32. const { run } = await setup()
  33. const result = await run({
  34. 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};',
  35. bindings: bindings({ echo: async args => args as { n: number }, fail: async () => { throw new Error('denied') } }),
  36. })
  37. expect(result.error).toBeUndefined()
  38. expect(result.value).toEqual({ value: { n: 42 }, rejected: [true, 'ToolCallError', 'fail', 'denied'] })
  39. })
  40. it('retains raw native stdout and stderr separately from control frames', async () => {
  41. const { run } = await setup()
  42. const result = await run({ program: 'const fs = await import("node:fs"); fs.writeSync(1,"native-out你好"); fs.writeSync(2,"native-err🙂"); return 42;', bindings: [] })
  43. expect(result.error).toBeUndefined()
  44. expect(result.value).toBe(42)
  45. expect(result.logs.join('')).toContain('native-out你好')
  46. expect(result.logs.join('')).toContain('native-err🙂')
  47. })
  48. it.each(['throw new Error("broken")', 'enum E { A }'])('reports program failure for %s', async (program) => {
  49. const { run } = await setup()
  50. expect((await run({ program, bindings: [] })).error?.kind).toBe('exception')
  51. })
  52. it('rejects lossy program output', async () => {
  53. const { run } = await setup()
  54. expect((await run({ program: 'return { value: undefined }', bindings: [] })).error?.kind).toBe('invalid-output')
  55. })
  56. it('enforces the combined output cap', async () => {
  57. const { run } = await setup({ maxOutputBytes: 80 })
  58. const result = await run({ program: 'console.log("x".repeat(500)); return 42;', bindings: [] })
  59. expect(result.error?.kind).toBe('output-limit')
  60. const bytes = Buffer.byteLength(JSON.stringify(result.logs)) + Buffer.byteLength(JSON.stringify(result.error?.message))
  61. expect(bytes).toBeLessThanOrEqual(80)
  62. })
  63. it('uses the default deadline and caps explicit requests', async () => {
  64. const { runtime } = await setup()
  65. expect(runtime.resolve({ program: '', bindings: [] }).timeoutMs).toBe(120_000)
  66. expect(runtime.resolve({ program: '', bindings: [], timeoutMs: 900_000 }).timeoutMs).toBe(600_000)
  67. for (const timeoutMs of [0, -1, NaN, Infinity]) expect(() => runtime.resolve({ program: '', bindings: [], timeoutMs })).toThrow()
  68. await expect(runtime.run({ program: '', bindings: [], cwd: process.cwd(), timeoutMs: 1000 })).rejects.toThrow('sandbox policy')
  69. })
  70. it.each(['for (;;) {}', 'await new Promise(() => {})'])('ends an unfinished program at its elapsed deadline: %s', async (program) => {
  71. const { run } = await setup({ timeoutMs: 600, graceMs: 50 })
  72. expect((await run({ program, bindings: [] })).error?.kind).toBe('timeout')
  73. })
  74. it('does not pause the deadline while a binding is pending', async () => {
  75. const { run } = await setup({ timeoutMs: 1000, graceMs: 50 })
  76. const result = await run({ program: 'void tools.wait({}); for (;;) {}', bindings: bindings({ wait: () => new Promise(() => {}) }) })
  77. expect(result.error?.kind).toBe('timeout')
  78. })
  79. it('cancels a live program and closes its managed process', async () => {
  80. const { run } = await setup()
  81. const entered = Promise.withResolvers<undefined>()
  82. const controller = new AbortController()
  83. const active = run({ program: 'await tools.enter({}); for (;;) {}', signal: controller.signal, bindings: bindings({ enter: async () => { entered.resolve(undefined); return null } }) })
  84. await entered.promise
  85. controller.abort('stop')
  86. expect((await active).error).toEqual({ kind: 'abort', message: 'stop' })
  87. })
  88. it('disposes active programs and rejects later execution', async () => {
  89. const { ctx, run, runtime } = await setup()
  90. const spec = runtime.resolve({ program: '', bindings: [] })
  91. const entered = Promise.withResolvers<undefined>()
  92. const active = run({ program: 'await tools.enter({}); await new Promise(() => {})', bindings: bindings({ enter: async () => { entered.resolve(undefined); return null } }) })
  93. await entered.promise
  94. await ctx.fiber.dispose()
  95. expect((await active).error?.kind).toBe('abort')
  96. await expect(runtime.run(spec)).rejects.toThrow('disposal')
  97. expect(() => runtime.resolve({ program: '', bindings: [] })).toThrow('disposal')
  98. expect(runtime.isolation).toBe('process')
  99. })
  100. it.each([
  101. 'const fs = await import("node:fs"); const b=Buffer.alloc(4); b.writeUInt32BE(4294967295); fs.writeSync(7,b); await new Promise(()=>{});',
  102. '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(()=>{});',
  103. ])('refuses hostile program control traffic', async (program) => {
  104. const { run } = await setup()
  105. expect((await run({ program, bindings: [] })).error?.kind).toBe('protocol')
  106. })
  107. it('applies read-only confinement to direct Node filesystem writes', async () => {
  108. const { run, cwd } = await setup({}, 'read-only')
  109. const path = join(cwd, 'denied.txt')
  110. const result = await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(path)}, 'denied')`, bindings: [] })
  111. expect(result.error?.kind).toBe('exception')
  112. expect(result.sandbox).toMatchObject({ mode: 'read-only', denied: true })
  113. await expect(readFile(path)).rejects.toMatchObject({ code: 'ENOENT' })
  114. })
  115. it('permits workspace writes and denies a symlink to a sibling outside it', async () => {
  116. const { run, cwd, root } = await setup({}, 'workspace-write')
  117. const target = join(cwd, 'allowed.txt')
  118. expect((await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(target)}, 'allowed'); return true`, bindings: [] })).value).toBe(true)
  119. expect(await readFile(target, 'utf8')).toBe('allowed')
  120. const outside = join(root, 'outside')
  121. await mkdir(outside)
  122. await symlink(outside, join(cwd, 'escape'), process.platform === 'win32' ? 'junction' : 'dir')
  123. const result = await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(join(cwd, 'escape', 'denied.txt'))}, 'denied')`, bindings: [] })
  124. expect(result.error?.kind).toBe('exception')
  125. expect(result.sandbox).toMatchObject({ mode: 'workspace-write', denied: true })
  126. await expect(readFile(join(outside, 'denied.txt'))).rejects.toMatchObject({ code: 'ENOENT' })
  127. })
  128. })
  129. it('preserves empty console entries and bounds native output overflow', async () => {
  130. const { run } = await setup({ maxOutputBytes: 100 })
  131. const lines = await run({ program: 'console.log("a"); console.log(""); console.log("b")', bindings: [] })
  132. expect(lines.logs).toEqual(['a', '', 'b'])
  133. const overflow = await run({ program: 'const fs=await import("node:fs"); fs.writeSync(1,"HEAD-"+"x".repeat(100000));', bindings: [] })
  134. expect(overflow.error?.kind).toBe('output-limit')
  135. expect(overflow.logs.join('')).toContain('HEAD-')
  136. const bytes = Buffer.byteLength(JSON.stringify(overflow.logs)) + Buffer.byteLength(JSON.stringify(overflow.error?.message))
  137. expect(bytes).toBeLessThanOrEqual(100)
  138. })