sandbox.spec.ts 17 KB

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