sandbox.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /**
  2. * Consumer-side `SandboxBashExecutor` tests. A fake Cordis sandbox service makes wrapping,
  3. * policy hand-off, fail-closed propagation, classification, and fact stamping deterministic;
  4. * real-provider integration lives in `tests/landlock.e2e.ts`. A mode-0555 directory supplies
  5. * the Unix denial signature used by the classifier without requiring a real sandbox runner.
  6. */
  7. import { chmodSync, mkdirSync, mkdtempSync } from 'node:fs'
  8. import { tmpdir } from 'node:os'
  9. import { join, resolve } from 'node:path'
  10. import { describe, expect, it, vi } from 'vitest'
  11. import { Context } from 'cordis'
  12. import type { BashRunResult, CollectedOutput } from '@deepseek-ai/dsh-bash'
  13. import { SANDBOX_UNAVAILABLE, SandboxProvider, SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'
  14. import type { ConfinedArgv, SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
  15. import { SandboxBashExecutor } from '@deepseek-ai/dsh-bash-sandbox'
  16. import { classifyDenial, classifyRunnerFailure, shellQuote } from '../src/helpers.ts'
  17. import type { Config } from '@deepseek-ai/dsh-bash-sandbox'
  18. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-bash-sandbox-spec-'))
  19. /** One recorded provider call: the argv handed over and the policy it rode with. */
  20. interface ConfineCall {
  21. argv: string[]
  22. policy: SandboxPolicy
  23. }
  24. /** The Linux file-denial dialects the fake wraps carry — matches the unix-permission denials the tests below produce. */
  25. const UNIX_SIGNATURES = ['read-only file system', 'permission denied'] as const
  26. /** The runner-failure prefix the fake wraps carry (a fake-runner: error line marks the sandbox itself failing). */
  27. const RUNNER_FAILURE = ['fake-runner: '] as const
  28. /** A passthrough wrap: the caller's argv unchanged, asserted full — commands run unconfined, deterministically. */
  29. const passthrough = (argv: readonly string[]): ConfinedArgv =>
  30. ({ argv: [...argv], enforcement: 'full', denialSignatures: UNIX_SIGNATURES, runnerFailureSignatures: RUNNER_FAILURE })
  31. /**
  32. * Boot a context with a recording fake `ctx.sandbox` (behavior injectable
  33. * per test) and the executor under test on top of it.
  34. */
  35. async function setup(config: Config = {}, behavior: (argv: readonly string[], policy: SandboxPolicy) => ConfinedArgv = passthrough) {
  36. const calls: ConfineCall[] = []
  37. class FakeSandboxProvider extends SandboxProvider {
  38. confine(argv: readonly string[], policy: SandboxPolicy): ConfinedArgv {
  39. calls.push({ argv: [...argv], policy })
  40. return behavior(argv, policy)
  41. }
  42. }
  43. const ctx = new Context()
  44. await ctx.plugin(FakeSandboxProvider)
  45. await ctx.plugin(SandboxBashExecutor, { graceMs: 200, ...config })
  46. const bash = ctx.bash as SandboxBashExecutor
  47. bash.internals = { spillDir }
  48. return { ctx, bash, calls }
  49. }
  50. function output(text: string): CollectedOutput {
  51. return { text, truncated: false }
  52. }
  53. function runResult(exitCode: number | null, stderr: string): BashRunResult {
  54. return { exitCode, signal: null, timedOut: false, aborted: false, timeoutMs: 1000, stdout: output(''), stderr: output(stderr) }
  55. }
  56. describe('the provider hand-off', () => {
  57. it('hands the provider the exact bash argv and the per-call policy, and runs the returned argv', async () => {
  58. const { bash, calls } = await setup()
  59. const result = await bash.run(bash.resolve({ command: 'echo \'a b\' "c\'d"' }))
  60. expect(result.stdout.text).toBe('a b c\'d\n')
  61. expect(result.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
  62. expect(calls).toEqual([{
  63. argv: ['bash', '-c', 'echo \'a b\' "c\'d"'],
  64. policy: { mode: 'read-only', workspaceRoot: resolve(process.cwd()) },
  65. }])
  66. })
  67. it('a wrapped argv from the provider is what actually spawns (prefix survives, quoting round-trips)', async () => {
  68. // The fake wraps with `env MARKER=...` — a real (if tiny) runner prefix:
  69. // the sentinel only prints if the executor spawned the WRAPPED argv.
  70. const { bash } = await setup({}, argv => ({ argv: ['env', 'DSH_WRAP=1', ...argv], enforcement: 'full', denialSignatures: UNIX_SIGNATURES, runnerFailureSignatures: RUNNER_FAILURE }))
  71. const result = await bash.run(bash.resolve({ command: 'printf "%s" "$DSH_WRAP"' }))
  72. expect(result.stdout.text).toBe('1')
  73. expect(result.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
  74. })
  75. it('workspace-write rides the policy, workspaceRoot falling back to cwd when not configured', async () => {
  76. const { bash, calls } = await setup({ mode: 'workspace-write', cwd: tmpdir() })
  77. const result = await bash.run(bash.resolve({ command: 'true' }))
  78. expect(result.sandbox).toEqual({ mode: 'workspace-write', denied: false, enforcement: 'full' })
  79. expect(calls[0]?.policy).toEqual({ mode: 'workspace-write', workspaceRoot: resolve(tmpdir()) })
  80. })
  81. it('an explicit workspaceRoot wins over cwd', async () => {
  82. const { calls, bash } = await setup({ mode: 'workspace-write', workspaceRoot: '/ws', cwd: tmpdir() })
  83. await bash.run(bash.resolve({ command: 'true' }))
  84. expect(calls[0]?.policy.workspaceRoot).toBe(resolve('/ws'))
  85. })
  86. it('the provider is consulted per wrap (no caching in the consumer): run and start each hand off', async () => {
  87. const { bash, calls } = await setup()
  88. await bash.run(bash.resolve({ command: 'true' }))
  89. const task = bash.start(bash.resolve({ command: 'true' }))
  90. await task.done
  91. expect(calls).toHaveLength(2)
  92. })
  93. it('shellQuote survives embedded single quotes (the argv re-assembly primitive)', () => {
  94. expect(shellQuote('a\'b')).toBe(String.raw`'a'\''b'`)
  95. })
  96. })
  97. describe('fail closed', () => {
  98. it('propagates the provider\'s structured SANDBOX_UNAVAILABLE on run() and start()', async () => {
  99. const { bash } = await setup({}, () => { throw new SandboxUnavailableError('read-only') })
  100. const spec = bash.resolve({ command: 'echo hi' })
  101. await expect(bash.run(spec)).rejects.toMatchObject({ name: 'SandboxUnavailableError', code: SANDBOX_UNAVAILABLE })
  102. expect(() => bash.start(spec)).toThrow(SandboxUnavailableError)
  103. })
  104. })
  105. describe('danger-full-access', () => {
  106. it('runs unwrapped: the provider is never consulted, facts carry no enforcement', async () => {
  107. const { bash, calls } = await setup({ mode: 'danger-full-access' })
  108. const result = await bash.run(bash.resolve({ command: 'echo free' }))
  109. expect(result.stdout.text).toBe('free\n')
  110. expect(result.sandbox).toEqual({ mode: 'danger-full-access', denied: false })
  111. expect(calls).toHaveLength(0)
  112. })
  113. it('start() passes through unwrapped and stamps nothing at settle', async () => {
  114. const { bash, calls } = await setup({ mode: 'danger-full-access' })
  115. const task = bash.start(bash.resolve({ command: 'echo free-bg' }))
  116. await task.done
  117. expect(task.sandbox).toBeUndefined()
  118. expect(task.readOutput().delta).toContain('free-bg')
  119. expect(calls).toHaveLength(0)
  120. })
  121. })
  122. describe('per-call sandboxMode override (the escalation mechanism)', () => {
  123. it('exposes the configured default as the capability fact, and resolve() stamps it', async () => {
  124. const { bash } = await setup()
  125. expect(bash.sandboxMode).toBe('read-only')
  126. expect(bash.resolve({ command: 'true' }).sandboxMode).toBe('read-only')
  127. })
  128. it('an explicit override outranks the default at resolve(), and the wrap policy follows it', async () => {
  129. const { bash, calls } = await setup()
  130. expect(bash.resolve({ command: 'true', sandboxMode: 'workspace-write' }).sandboxMode).toBe('workspace-write')
  131. await bash.run(bash.resolve({ command: 'true', sandboxMode: 'workspace-write' }))
  132. await bash.run(bash.resolve({ command: 'true' }))
  133. expect(calls.map(call => call.policy.mode)).toEqual(['workspace-write', 'read-only'])
  134. })
  135. it('an escalated run reports the mode it ACTUALLY ran under', async () => {
  136. const { bash } = await setup()
  137. const result = await bash.run(bash.resolve({ command: 'true', sandboxMode: 'workspace-write' }))
  138. expect(result.sandbox).toEqual({ mode: 'workspace-write', denied: false, enforcement: 'full' })
  139. })
  140. it('escalating to danger-full-access bypasses the provider entirely — the grant, not a probe, is the authority there', async () => {
  141. const { bash, calls } = await setup()
  142. const result = await bash.run(bash.resolve({ command: 'echo free', sandboxMode: 'danger-full-access' }))
  143. expect(result.stdout.text).toBe('free\n')
  144. expect(result.sandbox).toEqual({ mode: 'danger-full-access', denied: false })
  145. expect(calls).toHaveLength(0)
  146. })
  147. it('overlapping background tasks settle with their OWN modes (an escalated task next to a default one)', async () => {
  148. // With per-call policy, tasks under different modes are in flight at
  149. // once — anything keyed off the configured default would misreport the
  150. // escalated one at its settle stamp.
  151. const { bash } = await setup()
  152. const escalated = bash.start(bash.resolve({ command: 'sleep 0.3; echo "x: Permission denied" >&2; exit 1', sandboxMode: 'workspace-write' }))
  153. const plain = bash.start(bash.resolve({ command: 'true' }))
  154. await plain.done
  155. await escalated.done
  156. expect(escalated.sandbox).toEqual({ mode: 'workspace-write', denied: true, enforcement: 'full' })
  157. expect(plain.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
  158. })
  159. it('an escalated danger-full-access background task carries no facts (nothing confined it)', async () => {
  160. const { bash, calls } = await setup()
  161. const task = bash.start(bash.resolve({ command: 'echo bg-free', sandboxMode: 'danger-full-access' }))
  162. await task.done
  163. expect(task.sandbox).toBeUndefined()
  164. expect(task.readOutput().delta).toContain('bg-free')
  165. expect(calls).toHaveLength(0)
  166. })
  167. })
  168. describe('classifyDenial', () => {
  169. it('never classifies a clean exit or a signal kill as a denial', () => {
  170. expect(classifyDenial(runResult(0, 'Permission denied'), UNIX_SIGNATURES)).toBe(false)
  171. expect(classifyDenial(runResult(null, 'Permission denied'), UNIX_SIGNATURES)).toBe(false)
  172. })
  173. it('classifies failed runs by the wrap\'s own dialect, conservatively', () => {
  174. expect(classifyDenial(runResult(1, 'touch: cannot touch /x: Read-only file system'), UNIX_SIGNATURES)).toBe(true)
  175. expect(classifyDenial(runResult(1, 'sh: /x: Permission denied'), UNIX_SIGNATURES)).toBe(true)
  176. // Bare EPERM is not a Linux runner's dialect: mount/kill/ptrace fail with
  177. // it unsandboxed too, and the mode vocabulary governs file effects only —
  178. // claiming a file denial here would tell the model the sandbox blocked
  179. // something it never governed.
  180. expect(classifyDenial(runResult(1, 'mount: Operation not permitted'), UNIX_SIGNATURES)).toBe(false)
  181. expect(classifyDenial(runResult(1, 'No such file or directory'), UNIX_SIGNATURES)).toBe(false)
  182. })
  183. it('matches exactly the active backend\'s dialect: EPERM classifies under Seatbelt, EACCES does not under bwrap', () => {
  184. // The same stderr flips meaning with the backend: under Seatbelt, EPERM
  185. // text IS how the kernel refuses a governed file write; under bwrap's
  186. // EROFS-only dialect, `Permission denied` is ordinary DAC, not the
  187. // sandbox — per-wrap signatures are what keep both classifications honest.
  188. expect(classifyDenial(runResult(1, 'bash: /etc/x: Operation not permitted'), ['operation not permitted'])).toBe(true)
  189. expect(classifyDenial(runResult(1, 'sh: /x: Permission denied'), ['read-only file system'])).toBe(false)
  190. })
  191. })
  192. describe('classifyRunnerFailure', () => {
  193. it('matches the dialect case-insensitively on BOTH sides — the seam declares it so, and producers compose signatures from runtime data (an argv0 path, the shell\'s `No such file or directory`)', () => {
  194. const signatures = ['exec: /Opt/Runners/bwrap: not found', '/Opt/Runners/bwrap: No such file or directory']
  195. expect(classifyRunnerFailure(runResult(127, 'bash: /Opt/Runners/bwrap: No such file or directory'), signatures)).toBe(true)
  196. expect(classifyRunnerFailure(runResult(127, 'BASH: LINE 1: EXEC: /OPT/RUNNERS/BWRAP: NOT FOUND'), signatures)).toBe(true)
  197. })
  198. })
  199. describe('result facts', () => {
  200. it('reports a real permission failure as a sandbox denial with the mode it ran under', async () => {
  201. const { bash } = await setup()
  202. const lockedDir = join(mkdtempSync(join(tmpdir(), 'dsh-sandbox-denied-')), 'locked')
  203. mkdirSync(lockedDir)
  204. chmodSync(lockedDir, 0o555)
  205. const result = await bash.run(bash.resolve({ command: `echo x > ${lockedDir}/f` }))
  206. expect(result.exitCode).not.toBe(0)
  207. expect(result.sandbox).toEqual({ mode: 'read-only', denied: true, enforcement: 'full' })
  208. })
  209. it('carries the provider\'s partial-enforcement fact through unchanged', async () => {
  210. const { bash } = await setup({}, argv => ({ argv: [...argv], enforcement: 'partial', denialSignatures: UNIX_SIGNATURES, runnerFailureSignatures: RUNNER_FAILURE }))
  211. const result = await bash.run(bash.resolve({ command: 'true' }))
  212. expect(result.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'partial' })
  213. })
  214. })
  215. describe('background sandbox facts', () => {
  216. it('stamps facts and releases accounting when background spawn fails', async () => {
  217. const { bash } = await setup()
  218. const missingWorkdir = join(mkdtempSync(join(tmpdir(), 'dsh-sandbox-missing-cwd-')), 'missing')
  219. const task = bash.start(bash.resolve({ command: 'true', workdir: missingWorkdir }))
  220. await task.done
  221. expect(task.status).toBe('killed')
  222. expect(task.readOutput().delta).toContain('spawn failed:')
  223. expect(task.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
  224. const accounting = (bash as unknown as { processFacts: Map<unknown, unknown> }).processFacts
  225. expect(accounting.size).toBe(0)
  226. })
  227. it('stamps a settled denial: nonzero exit + permission stderr under a confined mode', async () => {
  228. const { bash } = await setup()
  229. const task = bash.start(bash.resolve({ command: 'echo "x: Permission denied" >&2; exit 1' }))
  230. await task.done
  231. expect(task.sandbox).toEqual({ mode: 'read-only', denied: true, enforcement: 'full' })
  232. })
  233. it('a foreground runner failure throws the fail-closed error, never a task result', async () => {
  234. // The wrap's runner prefix on a failed run means the SANDBOX broke and
  235. // the command never ran — the late twin of the confine-time throw, with
  236. // the runner's own first stderr line carried as the cause.
  237. const { bash } = await setup()
  238. const run = bash.run(bash.resolve({ command: 'echo "fake-runner: ruleset rejected" >&2; exit 125' }))
  239. await expect(run).rejects.toThrow(expect.objectContaining({ code: SANDBOX_UNAVAILABLE }))
  240. await expect(run).rejects.toThrow('fake-runner: ruleset rejected')
  241. })
  242. it('a foreground runner failure outranks denial: runner error text may contain denial words', async () => {
  243. const { bash } = await setup()
  244. await expect(bash.run(bash.resolve({ command: 'echo "fake-runner: cannot open rule path: /x: Permission denied" >&2; exit 125' })))
  245. .rejects.toThrow(expect.objectContaining({ code: SANDBOX_UNAVAILABLE }))
  246. })
  247. it('a settled background runner failure stamps runnerFailed (no error channel remains), not denied', async () => {
  248. const { bash } = await setup()
  249. const task = bash.start(bash.resolve({ command: 'echo "fake-runner: cannot open rule path: /x: Permission denied" >&2; exit 125' }))
  250. await task.done
  251. expect(task.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full', runnerFailed: true })
  252. })
  253. it('overlapping background tasks keep their OWN wrap facts (per-task, not latest-wrap)', async () => {
  254. // Facts belong to each wrap and may vary between calls. The slow task settles after the
  255. // quick task starts; a shared latest-wrap field would classify and stamp it with the wrong
  256. // task's dialect and enforcement.
  257. const wraps: Array<Pick<ConfinedArgv, 'enforcement' | 'denialSignatures'>> = [
  258. { enforcement: 'partial', denialSignatures: ['permission denied'] },
  259. { enforcement: 'full', denialSignatures: ['read-only file system'] },
  260. ]
  261. let call = 0
  262. const { bash } = await setup({}, (argv) => {
  263. const wrap = wraps[Math.min(call++, wraps.length - 1)] as Pick<ConfinedArgv, 'enforcement' | 'denialSignatures'>
  264. return { argv: [...argv], ...wrap, runnerFailureSignatures: RUNNER_FAILURE }
  265. })
  266. const slow = bash.start(bash.resolve({ command: 'sleep 0.4; echo "x: Permission denied" >&2; exit 1' }))
  267. const quick = bash.start(bash.resolve({ command: 'true' }))
  268. await quick.done
  269. await slow.done
  270. expect(slow.sandbox).toEqual({ mode: 'read-only', denied: true, enforcement: 'partial' })
  271. expect(quick.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
  272. })
  273. it('a signal-killed task is never a denial (null exit code)', async () => {
  274. const { bash } = await setup()
  275. const task = bash.start(bash.resolve({ command: 'echo "Permission denied" >&2; sleep 30' }))
  276. // Let the stderr land before the kill so the classifier sees the
  277. // signature and must still refuse it on the null exit code alone.
  278. await vi.waitFor(() => { expect(task.readOutput().delta).toContain('Permission denied') })
  279. task.kill()
  280. await task.done
  281. expect(task.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
  282. })
  283. it('disposal kills wrapped background tasks (inherited HMR safety)', async () => {
  284. const { ctx, bash } = await setup()
  285. const task = bash.start(bash.resolve({ command: 'sleep 30' }))
  286. await ctx.fiber.dispose()
  287. expect(task.status).toBe('killed')
  288. })
  289. })