sandbox.spec.ts 18 KB

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