runtime.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import { mkdtemp, mkdir, readFile, readdir, 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 Sandbox from '@deepseek-ai/dsh-sandbox-local'
  7. import { SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'
  8. import { describe, expect, it, onTestFinished, vi } from 'vitest'
  9. import type { PtcBindingFunction, PtcBindingNamespace, PtcRunRequest } from '@deepseek-ai/dsh-ptc-runtime'
  10. import type { Config } from '../src/index.ts'
  11. import { mountRuntime } from './setup.ts'
  12. /** Probe the sandbox independently so Node-runtime launch failures cannot skip enforcement tests. */
  13. const sandboxUsable = await (async () => {
  14. const probe = new Context()
  15. try {
  16. await probe.plugin(Sandbox, {})
  17. await probe.sandbox.confine([process.execPath, '--version'], { mode: 'read-only', workspaceRoot: process.cwd() })
  18. return true
  19. } catch (error: unknown) {
  20. if (error instanceof SandboxUnavailableError) return false
  21. throw error
  22. } finally { await probe.fiber.dispose() }
  23. })()
  24. async function setup(config: Config = {}, mode: 'read-only' | 'workspace-write' | 'danger-full-access' = 'danger-full-access') {
  25. const root = await mkdtemp(join(homedir(), '.dsh-node-runtime-test-'))
  26. const cwd = join(root, 'workspace')
  27. await mkdir(cwd)
  28. const ctx = new Context()
  29. onTestFinished(async () => { await ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) })
  30. const runtime = await mountRuntime(ctx, config, { mode, workspaceRoot: cwd })
  31. const run = (request: PtcRunRequest) => runtime.run(runtime.resolve(request))
  32. return { ctx, runtime, root, cwd, run }
  33. }
  34. function bindings(functions: Record<string, PtcBindingFunction>): PtcBindingNamespace[] {
  35. return [{ global: 'tools', functions, errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' } }]
  36. }
  37. describe('Node program process', () => {
  38. it('runs erasable TypeScript in the resolved directory with an empty environment', async () => {
  39. const { run, cwd } = await setup()
  40. const result = await run({ program: 'const n: number = 6; console.log("ready"); return { n: n * 7, cwd: process.cwd(), env: { ...process.env } };', bindings: [] })
  41. expect(result.error).toBeUndefined()
  42. expect(result.value).toEqual({ n: 42, cwd, env: {} })
  43. expect(result.logs).toEqual(['ready'])
  44. expect(result.sandbox).toEqual({ mode: 'danger-full-access', denied: false })
  45. })
  46. it('keeps native startup paths available for nested Node creation with an empty model environment', async () => {
  47. const { run } = await setup()
  48. const result = await run({
  49. 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 || "[]")};',
  50. bindings: [],
  51. })
  52. expect(result.error).toBeUndefined()
  53. const value = result.value as { env: string[]; status: number | null; error: string | null; childKeys: string[] }
  54. expect(value.env).toEqual([])
  55. expect(value.status).toBe(0)
  56. expect(value.error).toBeNull()
  57. const nativeKeys = ['PATH', 'PATHEXT', 'SYSTEMROOT', 'WINDIR', 'TEMP', 'TMP']
  58. // CoreFoundation initializes this entry independently when a macOS child starts.
  59. if (process.platform === 'darwin') nativeKeys.push('__CF_USER_TEXT_ENCODING')
  60. expect(value.childKeys.filter(key => !nativeKeys.includes(key.toUpperCase()))).toEqual([])
  61. })
  62. it.skipIf(process.platform !== 'win32' || !sandboxUsable)('uses the common Windows grant lock and private native temp without exposing ambient values', async () => {
  63. const { run, root } = await setup({}, 'workspace-write')
  64. const temp = join(root, 'node-temp')
  65. const tmp = join(root, 'win32-temp')
  66. await mkdir(temp)
  67. await mkdir(tmp)
  68. onTestFinished(() => { vi.unstubAllEnvs() })
  69. vi.stubEnv('TEMP', temp)
  70. vi.stubEnv('TMP', tmp)
  71. vi.stubEnv('DSH_TEST_RUNTIME_SECRET', 'must-not-inherit')
  72. const childCode = 'const fs=require("node:fs"); const path=require("node:path"); const temp=require("node:os").tmpdir(); const file=path.join(temp,"native-temp.txt"); fs.writeFileSync(file,"native-temp"); fs.writeFileSync("native-observation.json",JSON.stringify({file,temp,env:Object.keys(process.env)}));'
  73. const result = await run({
  74. program: `const {spawnSync}=await import("node:child_process"); const child=spawnSync(process.execPath,["-e",${JSON.stringify(childCode)}],{stdio:"inherit"}); if(child.status!==0) throw new Error(child.error?.message ?? "native child failed"); const native=JSON.parse((await import("node:fs")).readFileSync("native-observation.json","utf8")); return {env:Object.keys(process.env),native,observed:await tools.inspect({path:native.file})};`,
  75. bindings: bindings({ inspect: async (args) => {
  76. const path = (args as { path: string }).path
  77. expect(path.startsWith(`${temp}\\dsh-`)).toBe(true)
  78. return await readFile(path, 'utf8')
  79. } }),
  80. })
  81. expect(result.error).toBeUndefined()
  82. const value = result.value as { env: string[]; native: { env: string[]; temp: string }; observed: string }
  83. expect(value.env).toEqual([])
  84. expect(value.native.env).not.toContain('DSH_TEST_RUNTIME_SECRET')
  85. expect(value.native.temp.startsWith(`${temp}\\dsh-`)).toBe(true)
  86. expect(value.observed).toBe('native-temp')
  87. expect((await readdir(join(tmp, 'dsh-acl-locks'))).some(name => name.endsWith('.lock'))).toBe(true)
  88. })
  89. it('returns binding values and preserves typed binding rejection', async () => {
  90. const { run } = await setup()
  91. const result = await run({
  92. 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};',
  93. bindings: bindings({ echo: async args => args as { n: number }, fail: async () => { throw new Error('denied') } }),
  94. })
  95. expect(result.error).toBeUndefined()
  96. expect(result.value).toEqual({ value: { n: 42 }, rejected: [true, 'ToolCallError', 'fail', 'denied'] })
  97. })
  98. it('retains raw native stdout and stderr separately from control frames', async () => {
  99. const { run } = await setup()
  100. const result = await run({ program: 'const fs = await import("node:fs"); fs.writeSync(1,"native-out你好"); fs.writeSync(2,"native-err🙂"); return 42;', bindings: [] })
  101. expect(result.error).toBeUndefined()
  102. expect(result.value).toBe(42)
  103. expect(result.logs.join('')).toContain('native-out你好')
  104. expect(result.logs.join('')).toContain('native-err🙂')
  105. })
  106. it.each(['throw new Error("broken")', 'enum E { A }'])('reports program failure for %s', async (program) => {
  107. const { run } = await setup()
  108. expect((await run({ program, bindings: [] })).error?.kind).toBe('exception')
  109. })
  110. it('rejects lossy program output', async () => {
  111. const { run } = await setup()
  112. expect((await run({ program: 'return { value: undefined }', bindings: [] })).error?.kind).toBe('invalid-output')
  113. })
  114. it('enforces the combined output cap', async () => {
  115. const { run } = await setup({ maxOutputBytes: 80 })
  116. const result = await run({ program: 'console.log("x".repeat(500)); return 42;', bindings: [] })
  117. expect(result.error?.kind).toBe('output-limit')
  118. const bytes = Buffer.byteLength(JSON.stringify(result.logs)) + Buffer.byteLength(JSON.stringify(result.error?.message))
  119. expect(bytes).toBeLessThanOrEqual(80)
  120. })
  121. it('uses the default deadline and caps explicit requests', async () => {
  122. const { runtime } = await setup()
  123. expect(runtime.timeout).toEqual({ defaultMs: 120_000, maxMs: 600_000 })
  124. expect(runtime.executionInstructions).toBe('Each call runs in a fresh Node process. Node APIs are available through await import(...). Relative paths use the supplied working directory; process.env starts empty. Direct filesystem access follows this execution\'s sandbox policy.')
  125. expect(runtime.resolve({ program: '', bindings: [] }).timeoutMs).toBe(120_000)
  126. expect(runtime.resolve({ program: '', bindings: [], timeoutMs: 900_000 }).timeoutMs).toBe(600_000)
  127. expect(runtime.resolve({ program: '', bindings: [], timeoutMs: null }).timeoutMs).toBeNull()
  128. for (const timeoutMs of [0, -1, NaN, Infinity]) expect(() => runtime.resolve({ program: '', bindings: [], timeoutMs })).toThrow()
  129. await expect(runtime.run({ program: '', bindings: [], cwd: process.cwd(), timeoutMs: 1000 })).rejects.toThrow('sandbox policy')
  130. })
  131. it('advertises the capped default when the deployment maximum is lower', async () => {
  132. const { runtime } = await setup({ timeoutMs: 2000, maxTimeoutMs: 1000 })
  133. expect(runtime.timeout).toEqual({ defaultMs: 1000, maxMs: 1000 })
  134. expect(runtime.timeout.defaultMs).toBe(runtime.resolve({ program: '', bindings: [] }).timeoutMs)
  135. })
  136. it.each(['for (;;) {}', 'await new Promise(() => {})'])('ends an unfinished program at its elapsed deadline: %s', async (program) => {
  137. const { run } = await setup({ timeoutMs: 600, graceMs: 50 })
  138. expect((await run({ program, bindings: [] })).error?.kind).toBe('timeout')
  139. })
  140. it('retains console output emitted immediately before a non-yielding program', async () => {
  141. const { run } = await setup({ timeoutMs: 1000, graceMs: 50 })
  142. const result = await run({ program: 'console.log("before hot loop"); for (;;) {}', bindings: [] })
  143. expect(result.error?.kind).toBe('timeout')
  144. expect(result.logs).toEqual(['before hot loop'])
  145. })
  146. it('does not pause the deadline while a binding is pending', async () => {
  147. const { run } = await setup({ timeoutMs: 1000, graceMs: 50 })
  148. const result = await run({ program: 'void tools.wait({}); for (;;) {}', bindings: bindings({ wait: () => new Promise(() => {}) }) })
  149. expect(result.error?.kind).toBe('timeout')
  150. })
  151. it.each([{}, { timeoutMs: null }] as const)('cancels a live program and closes its managed process with %j', async (timing) => {
  152. const { run } = await setup()
  153. const entered = Promise.withResolvers<undefined>()
  154. const controller = new AbortController()
  155. const active = run({ ...timing, program: 'void tools.enter({}); for (;;) {}', signal: controller.signal, bindings: bindings({ enter: async () => { entered.resolve(undefined); return null } }) })
  156. await entered.promise
  157. controller.abort('stop')
  158. expect((await active).error).toEqual({ kind: 'abort', message: 'stop' })
  159. })
  160. it('closes a still-running descendant before returning the program result', async () => {
  161. const { run } = await setup()
  162. const connected = Promise.withResolvers<undefined>()
  163. const disconnected = Promise.withResolvers<undefined>()
  164. let peer: Socket | undefined
  165. const server = createServer((socket) => {
  166. peer = socket
  167. // A terminated peer can reset its connection instead of sending FIN.
  168. socket.on('error', () => {})
  169. socket.once('close', () => { disconnected.resolve(undefined) })
  170. connected.resolve(undefined)
  171. })
  172. onTestFinished(async () => {
  173. peer?.destroy()
  174. if (server.listening) await new Promise<void>((resolve, reject) => {
  175. server.close((error) => { if (error) reject(error); else resolve() })
  176. })
  177. })
  178. await new Promise<void>((resolve, reject) => {
  179. server.once('error', reject)
  180. server.listen(0, '127.0.0.1', resolve)
  181. })
  182. const address = server.address()
  183. if (address === null || typeof address === 'string') throw new Error('expected bound TCP listener')
  184. const child = `require('node:net').connect(${address.port},'127.0.0.1')`
  185. const result = await run({
  186. program: `const {spawn}=await import("node:child_process"); spawn(process.execPath,["-e",${JSON.stringify(child)}],{stdio:"ignore"}); await tools.connected({}); return 42;`,
  187. bindings: bindings({ connected: async () => { await connected.promise; return null } }),
  188. })
  189. expect(result.error).toBeUndefined()
  190. expect(result.value).toBe(42)
  191. await disconnected.promise
  192. })
  193. it('applies the configured V8 old-generation ceiling to each fresh Node process', async () => {
  194. const limits: number[] = []
  195. for (const maxOldGenerationSizeMb of [32, 64]) {
  196. const { run } = await setup({ maxOldGenerationSizeMb })
  197. const result = await run({ program: 'return (await import("node:v8")).getHeapStatistics().heap_size_limit;', bindings: [] })
  198. expect(result.error).toBeUndefined()
  199. if (typeof result.value !== 'number') throw new Error('expected V8 heap limit')
  200. limits.push(result.value)
  201. }
  202. expect(Number(limits[1]) - Number(limits[0])).toBe(32 * 1024 * 1024)
  203. })
  204. it.each([{}, { timeoutMs: null }] as const)('disposes active programs and rejects later execution with %j', async (timing) => {
  205. const { ctx, run, runtime } = await setup()
  206. const spec = runtime.resolve({ program: '', bindings: [] })
  207. const entered = Promise.withResolvers<undefined>()
  208. const active = run({ ...timing, program: 'await tools.enter({}); await new Promise(() => {})', bindings: bindings({ enter: async () => { entered.resolve(undefined); return null } }) })
  209. await entered.promise
  210. await ctx.fiber.dispose()
  211. expect((await active).error?.kind).toBe('abort')
  212. await expect(runtime.run(spec)).rejects.toThrow('disposal')
  213. expect(() => runtime.resolve({ program: '', bindings: [] })).toThrow('disposal')
  214. expect(runtime.isolation).toBe('process')
  215. })
  216. it.each([
  217. 'const fs = await import("node:fs"); const b=Buffer.alloc(4); b.writeUInt32BE(4294967295); fs.writeSync(7,b); await new Promise(()=>{});',
  218. '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(()=>{});',
  219. ])('refuses hostile program control traffic', async (program) => {
  220. const { run } = await setup()
  221. expect((await run({ program, bindings: [] })).error?.kind).toBe('protocol')
  222. })
  223. it.skipIf(!sandboxUsable)('applies read-only confinement to direct Node filesystem writes', async () => {
  224. const { run, cwd } = await setup({}, 'read-only')
  225. const path = join(cwd, 'denied.txt')
  226. const result = await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(path)}, 'denied')`, bindings: [] })
  227. expect(result.error?.kind).toBe('exception')
  228. expect(result.sandbox).toMatchObject({ mode: 'read-only', denied: true })
  229. await expect(readFile(path)).rejects.toMatchObject({ code: 'ENOENT' })
  230. })
  231. it.skipIf(process.platform === 'win32' || !sandboxUsable)('starts a confining launcher found only through the execution PATH', async () => {
  232. const { ctx, runtime, run, root } = await setup({}, 'read-only')
  233. const confine = ctx.sandbox.confine.bind(ctx.sandbox)
  234. const policy = runtime.resolve({ program: '', bindings: [] }).sandboxPolicy
  235. if (policy === undefined || policy.mode === 'danger-full-access') throw new Error('expected confined policy')
  236. const wrapped = await confine([process.execPath, '--version'], { ...policy, mode: policy.mode })
  237. const original = wrapped.argv[0]
  238. if (original === undefined) throw new Error('expected sandbox launcher')
  239. const executable = await ctx.subprocess.resolveExecutable(original)
  240. const alias = 'ptc-private-sandbox-launcher'
  241. await symlink(executable, join(root, alias))
  242. const previousPath = process.env.PATH
  243. const substitute = vi.spyOn(ctx.sandbox, 'confine').mockImplementation(async (argv, selected, signal) => {
  244. const result = await confine(argv, selected, signal)
  245. return { ...result, argv: [alias, ...result.argv.slice(1)] }
  246. })
  247. try {
  248. process.env.PATH = `${root}${delimiter}${previousPath ?? ''}`
  249. const result = await run({ program: 'return { env: Object.keys(process.env) };', bindings: [] })
  250. expect(result.error).toBeUndefined()
  251. expect(result.value).toEqual({ env: [] })
  252. } finally {
  253. substitute.mockRestore()
  254. if (previousPath === undefined) delete process.env.PATH
  255. else process.env.PATH = previousPath
  256. }
  257. })
  258. it.skipIf(!sandboxUsable)('permits workspace writes and denies a symlink to a sibling outside it', async () => {
  259. const { run, cwd, root } = await setup({}, 'workspace-write')
  260. const target = join(cwd, 'allowed.txt')
  261. expect((await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(target)}, 'allowed'); return true`, bindings: [] })).value).toBe(true)
  262. expect(await readFile(target, 'utf8')).toBe('allowed')
  263. const outside = join(root, 'outside')
  264. await mkdir(outside)
  265. await symlink(outside, join(cwd, 'escape'), process.platform === 'win32' ? 'junction' : 'dir')
  266. const result = await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(join(cwd, 'escape', 'denied.txt'))}, 'denied')`, bindings: [] })
  267. expect(result.error?.kind).toBe('exception')
  268. expect(result.sandbox).toMatchObject({ mode: 'workspace-write', denied: true })
  269. await expect(readFile(join(outside, 'denied.txt'))).rejects.toMatchObject({ code: 'ENOENT' })
  270. })
  271. })
  272. it('preserves empty console entries and bounds native output overflow', async () => {
  273. const { run } = await setup({ maxOutputBytes: 100 })
  274. const lines = await run({ program: 'console.log("a"); console.log(""); console.log("b")', bindings: [] })
  275. expect(lines.logs).toEqual(['a', '', 'b'])
  276. const overflow = await run({ program: 'const fs=await import("node:fs"); fs.writeSync(1,"HEAD-"+"x".repeat(100000));', bindings: [] })
  277. expect(overflow.error?.kind).toBe('output-limit')
  278. expect(overflow.logs.join('')).toContain('HEAD-')
  279. const bytes = Buffer.byteLength(JSON.stringify(overflow.logs)) + Buffer.byteLength(JSON.stringify(overflow.error?.message))
  280. expect(bytes).toBeLessThanOrEqual(100)
  281. })