sandbox.spec.ts 18 KB

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