sandbox.spec.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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, readFileSync, rmSync, writeFileSync } from 'node:fs'
  8. import { tmpdir } from 'node:os'
  9. import { join, resolve } from 'node:path'
  10. import { afterAll, describe, expect, it, vi } from 'vitest'
  11. import { Context } from '@deepseek-ai/cordis'
  12. import type { ShellRunResult, CollectedOutput } from '@deepseek-ai/dsh-shell'
  13. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  14. import { SANDBOX_UNAVAILABLE, SandboxProvider, SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'
  15. import type { ConfinedArgv, SandboxExecutionPolicy, SandboxMode, SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
  16. import { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy'
  17. import { SandboxBashExecutor } from '@deepseek-ai/dsh-bash-sandbox'
  18. import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
  19. import type { SubprocessHandle, SubprocessOutputReader } from '@deepseek-ai/dsh-subprocess'
  20. import { classifyDenial, classifyRunnerFailure, isRunnerSpawnFailure } from '../src/helpers.ts'
  21. import type { Config } from '@deepseek-ai/dsh-bash-sandbox'
  22. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-bash-sandbox-spec-'))
  23. afterAll(() => {
  24. rmSync(spillDir, { recursive: true, force: true })
  25. })
  26. /** One recorded provider call: the argv handed over and the policy it rode with. */
  27. interface ConfineCall {
  28. argv: string[]
  29. policy: SandboxPolicy
  30. }
  31. /** The Linux file-denial dialects the fake wraps carry — matches the unix-permission denials the tests below produce. */
  32. const UNIX_SIGNATURES = ['read-only file system', 'permission denied'] as const
  33. /** The runner-failure rule the fake wraps carry (a fake-runner: error line marks the sandbox itself failing). */
  34. const RUNNER_FAILURE = [{ fatalSignatures: ['fake-runner: '] }] as const
  35. /** Provider argv[0] forms that all share the caller-owned cwd spawn precondition. */
  36. const RUNNER_FORMS = [
  37. ['absolute', process.execPath],
  38. ['bare', 'node'],
  39. ['relative', './sandbox-runner'],
  40. ] as const
  41. /** A passthrough wrap: the caller's argv unchanged, asserted full — commands run unconfined, deterministically. */
  42. const passthrough = (argv: readonly string[]): ConfinedArgv =>
  43. ({ argv: [...argv], enforcement: 'full', denialSignatures: UNIX_SIGNATURES, runnerFailureRules: RUNNER_FAILURE })
  44. /**
  45. * Boot a context with a recording fake `ctx.sandbox` (behavior injectable
  46. * per test) and the executor under test on top of it.
  47. */
  48. async function setup(
  49. config: { mode?: SandboxMode; workspaceRoot?: string } & Config = {},
  50. behavior: (argv: readonly string[], policy: SandboxPolicy) => ConfinedArgv = passthrough,
  51. ) {
  52. const { mode, workspaceRoot, ...execConfig } = config
  53. const calls: ConfineCall[] = []
  54. class FakeSandboxProvider extends SandboxProvider {
  55. confine(argv: readonly string[], policy: SandboxPolicy): ConfinedArgv {
  56. calls.push({ argv: [...argv], policy })
  57. return behavior(argv, policy)
  58. }
  59. }
  60. const ctx = new Context()
  61. await ctx.plugin(SessionProjectionRegistry)
  62. await ctx.plugin(FakeSandboxProvider)
  63. await ctx.plugin(SandboxPolicyService, {
  64. ...mode !== undefined ? { mode } : {},
  65. ...workspaceRoot !== undefined ? { workspaceRoot } : {},
  66. })
  67. await ctx.plugin(LocalSubprocessRuntime)
  68. ;(ctx.subprocess as LocalSubprocessRuntime).internals = { spillDir }
  69. await ctx.plugin(SandboxBashExecutor, { graceMs: 200, ...execConfig })
  70. const bash = ctx.shell as SandboxBashExecutor
  71. return { ctx, bash, calls }
  72. }
  73. function output(text: string): CollectedOutput {
  74. return { text, truncated: false }
  75. }
  76. function runResult(exitCode: number | null, stderr: string): ShellRunResult {
  77. return { exitCode, signal: null, timedOut: false, aborted: false, timeoutMs: 1000, stdout: output(''), stderr: output(stderr) }
  78. }
  79. function executionPolicy(mode: SandboxMode, workspaceRoot = resolve(process.cwd())): SandboxExecutionPolicy {
  80. return { mode, workspaceRoot }
  81. }
  82. describe('the provider hand-off', () => {
  83. it('hands the provider the exact bash argv and the per-call policy, and runs the returned argv', async () => {
  84. const { bash, calls } = await setup()
  85. const result = await bash.run(bash.resolve({ command: 'echo \'a b\' "c\'d"' }))
  86. expect(result.stdout.text).toBe('a b c\'d\n')
  87. expect(result.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
  88. expect(calls).toEqual([{
  89. argv: ['bash', '-c', 'echo \'a b\' "c\'d"'],
  90. policy: { mode: 'read-only', workspaceRoot: resolve(process.cwd()) },
  91. }])
  92. })
  93. it('hands the provider\'s returned argv directly to ctx.subprocess.spawn', async () => {
  94. const returnedArgv = ['env', 'DSH_WRAP=1', 'bash', '-c', 'printf "%s" "$DSH_WRAP"']
  95. const { ctx, bash } = await setup({}, () => ({ argv: returnedArgv, enforcement: 'full', denialSignatures: UNIX_SIGNATURES, runnerFailureRules: RUNNER_FAILURE }))
  96. const spawn = vi.spyOn(ctx.subprocess, 'spawn')
  97. const result = await bash.run(bash.resolve({ command: 'printf "%s" "$DSH_WRAP"' }))
  98. expect(result.stdout.text).toBe('1')
  99. expect(spawn).toHaveBeenCalledTimes(1)
  100. expect(spawn.mock.calls[0]?.[0].argv).toEqual(returnedArgv)
  101. expect(result.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
  102. })
  103. it('starts a non-Bash runner before the confined inner Bash evaluates BASH_ENV', async () => {
  104. const dir = mkdtempSync(join(tmpdir(), 'dsh-bash-env-order-'))
  105. const hook = join(dir, 'hook.sh')
  106. const order = join(dir, 'order.txt')
  107. writeFileSync(hook, 'printf "hook\\n" >> "$DSH_ORDER_FILE"\n')
  108. const runnerScript = [
  109. 'const { appendFileSync } = require("node:fs");',
  110. 'const { spawnSync } = require("node:child_process");',
  111. 'appendFileSync(process.env.DSH_ORDER_FILE, "runner\\n");',
  112. 'const child = spawnSync(process.argv[1], process.argv.slice(2), { env: process.env, stdio: "inherit" });',
  113. 'process.exit(child.status ?? 125);',
  114. ].join('')
  115. const { bash } = await setup({}, argv => ({
  116. argv: [process.execPath, '-e', runnerScript, ...argv],
  117. enforcement: 'full',
  118. denialSignatures: UNIX_SIGNATURES,
  119. runnerFailureRules: RUNNER_FAILURE,
  120. }))
  121. try {
  122. const result = await bash.run(bash.resolve({
  123. command: 'true',
  124. env: { BASH_ENV: hook },
  125. dshEnv: { DSH_ORDER_FILE: order },
  126. }))
  127. expect(result.exitCode).toBe(0)
  128. expect(readFileSync(order, 'utf8')).toBe('runner\nhook\n')
  129. } finally {
  130. rmSync(dir, { recursive: true, force: true })
  131. }
  132. })
  133. it('workspace-write rides the policy, workspaceRoot falling back to process.cwd() when not configured', async () => {
  134. const { bash, calls } = await setup({ mode: 'workspace-write' })
  135. const result = await bash.run(bash.resolve({ command: 'true' }))
  136. expect(result.sandbox).toEqual({ mode: 'workspace-write', denied: false, enforcement: 'full' })
  137. expect(calls[0]?.policy).toEqual({ mode: 'workspace-write', workspaceRoot: resolve(process.cwd()) })
  138. })
  139. it('an explicit workspaceRoot on the policy wins', async () => {
  140. const { calls, bash } = await setup({ mode: 'workspace-write', workspaceRoot: '/ws', cwd: tmpdir() })
  141. await bash.run(bash.resolve({ command: 'true' }))
  142. expect(calls[0]?.policy.workspaceRoot).toBe(resolve('/ws'))
  143. })
  144. it('the provider is consulted per wrap (no caching in the consumer): run and start each hand off', async () => {
  145. const { bash, calls } = await setup()
  146. await bash.run(bash.resolve({ command: 'true' }))
  147. const task = bash.start(bash.resolve({ command: 'true' }))
  148. await task.done
  149. expect(calls).toHaveLength(2)
  150. })
  151. })
  152. describe('fail closed', () => {
  153. it('propagates the provider\'s structured SANDBOX_UNAVAILABLE on run() and start()', async () => {
  154. const { bash } = await setup({}, () => { throw new SandboxUnavailableError('read-only') })
  155. const spec = bash.resolve({ command: 'echo hi' })
  156. await expect(bash.run(spec)).rejects.toMatchObject({ name: 'SandboxUnavailableError', code: SANDBOX_UNAVAILABLE })
  157. expect(() => bash.start(spec)).toThrow(SandboxUnavailableError)
  158. })
  159. it('preserves an already-aborted foreground call as cancellation', async () => {
  160. const { bash } = await setup()
  161. const controller = new AbortController()
  162. const reason = new Error('caller cancelled before spawn')
  163. controller.abort(reason)
  164. await expect(bash.run(bash.resolve({ command: 'true', signal: controller.signal }))).rejects.toBe(reason)
  165. })
  166. it.each(RUNNER_FORMS)(
  167. 'keeps an invalid workdir ordinary with the %s provider-runner form',
  168. async (_form, runner) => {
  169. const { bash } = await setup({}, argv => ({
  170. argv: [runner, ...argv],
  171. enforcement: 'full',
  172. denialSignatures: UNIX_SIGNATURES,
  173. runnerFailureRules: RUNNER_FAILURE,
  174. }))
  175. const parent = mkdtempSync(join(tmpdir(), 'dsh-sandbox-missing-cwd-'))
  176. try {
  177. const failure = await bash.run(bash.resolve({ command: 'true', workdir: join(parent, 'missing') }))
  178. .catch((error: unknown) => error)
  179. expect(failure).toMatchObject({ code: 'ENOENT' })
  180. expect(failure).not.toBeInstanceOf(SandboxUnavailableError)
  181. } finally {
  182. rmSync(parent, { recursive: true, force: true })
  183. }
  184. },
  185. )
  186. it('keeps an invalid workdir ordinary when danger-full-access bypasses the provider', async () => {
  187. const { bash } = await setup({ mode: 'danger-full-access' })
  188. const parent = mkdtempSync(join(tmpdir(), 'dsh-sandbox-missing-cwd-'))
  189. try {
  190. const failure = await bash.run(bash.resolve({ command: 'true', workdir: join(parent, 'missing') }))
  191. .catch((error: unknown) => error)
  192. expect(failure).toMatchObject({ code: 'ENOENT' })
  193. expect(failure).not.toBeInstanceOf(SandboxUnavailableError)
  194. } finally {
  195. rmSync(parent, { recursive: true, force: true })
  196. }
  197. })
  198. it('keeps Node-shaped synchronous ENOEXEC ordinary in run() and start()', async () => {
  199. const runner = join(spillDir, 'malformed-runner')
  200. const { ctx, bash } = await setup({}, argv => ({
  201. argv: [runner, ...argv],
  202. enforcement: 'full',
  203. denialSignatures: UNIX_SIGNATURES,
  204. runnerFailureRules: RUNNER_FAILURE,
  205. }))
  206. vi.spyOn(ctx.subprocess, 'spawn').mockImplementation(() => {
  207. throw Object.assign(new Error('spawn ENOEXEC'), { code: 'ENOEXEC', syscall: 'spawn' })
  208. })
  209. const foreground = await bash.run(bash.resolve({ command: 'true' })).catch((error: unknown) => error)
  210. expect(foreground).toMatchObject({ code: 'ENOEXEC', syscall: 'spawn' })
  211. expect(foreground).not.toBeInstanceOf(SandboxUnavailableError)
  212. let background: unknown
  213. try {
  214. bash.start(bash.resolve({ command: 'true' }))
  215. } catch (error) {
  216. background = error
  217. }
  218. expect(background).toMatchObject({ code: 'ENOEXEC', syscall: 'spawn' })
  219. expect(background).not.toBeInstanceOf(SandboxUnavailableError)
  220. })
  221. it('classifies a synchronous SubprocessRuntime EACCES with the exact runner path', async () => {
  222. const runner = join(spillDir, 'unexecutable-runner')
  223. const { ctx, bash } = await setup({}, argv => ({
  224. argv: [runner, ...argv],
  225. enforcement: 'full',
  226. denialSignatures: UNIX_SIGNATURES,
  227. runnerFailureRules: RUNNER_FAILURE,
  228. }))
  229. // This pins an alternative SubprocessRuntime's synchronous seam, not the
  230. // shipped local behavior.
  231. vi.spyOn(ctx.subprocess, 'spawn').mockImplementation(() => {
  232. throw Object.assign(new Error('spawn EACCES'), { code: 'EACCES', syscall: 'spawn', path: runner })
  233. })
  234. await expect(bash.run(bash.resolve({ command: 'true' })))
  235. .rejects.toMatchObject({ name: 'SandboxUnavailableError', code: SANDBOX_UNAVAILABLE })
  236. expect(() => bash.start(bash.resolve({ command: 'true' })))
  237. .toThrow(expect.objectContaining({ name: 'SandboxUnavailableError', code: SANDBOX_UNAVAILABLE }))
  238. })
  239. it('keeps a synchronous cwd-owned ENOENT as the original start() error', async () => {
  240. const runner = './sandbox-runner'
  241. const { ctx, bash } = await setup({}, argv => ({
  242. argv: [runner, ...argv],
  243. enforcement: 'full',
  244. denialSignatures: UNIX_SIGNATURES,
  245. runnerFailureRules: RUNNER_FAILURE,
  246. }))
  247. const parent = mkdtempSync(join(tmpdir(), 'dsh-sandbox-missing-cwd-'))
  248. const workdir = join(parent, 'missing')
  249. const failure = Object.assign(new Error('spawn ENOENT'), { code: 'ENOENT', syscall: `spawn ${runner}`, path: runner })
  250. vi.spyOn(ctx.subprocess, 'spawn').mockImplementation(() => { throw failure })
  251. try {
  252. let thrown: unknown
  253. try {
  254. bash.start(bash.resolve({ command: 'true', workdir }))
  255. } catch (error) {
  256. thrown = error
  257. }
  258. expect(thrown).toBe(failure)
  259. expect(thrown).not.toBeInstanceOf(SandboxUnavailableError)
  260. } finally {
  261. rmSync(parent, { recursive: true, force: true })
  262. }
  263. })
  264. })
  265. describe('danger-full-access', () => {
  266. it('runs unwrapped: the provider is never consulted, facts carry no enforcement', async () => {
  267. const { bash, calls } = await setup({ mode: 'danger-full-access' })
  268. const result = await bash.run(bash.resolve({ command: 'echo free' }))
  269. expect(result.stdout.text).toBe('free\n')
  270. expect(result.sandbox).toEqual({ mode: 'danger-full-access', denied: false })
  271. expect(calls).toHaveLength(0)
  272. })
  273. it('start() passes through unwrapped and stamps nothing at settle', async () => {
  274. const { bash, calls } = await setup({ mode: 'danger-full-access' })
  275. const task = bash.start(bash.resolve({ command: 'echo free-bg' }))
  276. await task.done
  277. expect(task.sandbox).toBeUndefined()
  278. expect(task.readOutput().delta).toContain('free-bg')
  279. expect(calls).toHaveLength(0)
  280. })
  281. })
  282. describe('per-call sandbox policy (the session and escalation carrier)', () => {
  283. it('exposes the configured default as the capability fact, and resolve() stamps it', async () => {
  284. const { bash } = await setup()
  285. expect(bash.sandboxMode).toBe('read-only')
  286. expect(bash.resolve({ command: 'true' }).sandboxPolicy).toEqual(executionPolicy('read-only'))
  287. })
  288. it('an explicit policy outranks the default at resolve(), and the wrap follows its mode and root', async () => {
  289. const { bash, calls } = await setup()
  290. const explicit = executionPolicy('workspace-write', '/session/project')
  291. expect(bash.resolve({ command: 'true', sandboxPolicy: explicit }).sandboxPolicy).toEqual(explicit)
  292. await bash.run(bash.resolve({ command: 'true', sandboxPolicy: explicit }))
  293. await bash.run(bash.resolve({ command: 'true' }))
  294. expect(calls.map(call => call.policy)).toEqual([explicit, executionPolicy('read-only')])
  295. })
  296. it('an escalated run reports the mode it ACTUALLY ran under', async () => {
  297. const { bash } = await setup()
  298. const result = await bash.run(bash.resolve({ command: 'true', sandboxPolicy: executionPolicy('workspace-write') }))
  299. expect(result.sandbox).toEqual({ mode: 'workspace-write', denied: false, enforcement: 'full' })
  300. })
  301. it('escalating to danger-full-access bypasses the provider entirely — the grant, not a probe, is the authority there', async () => {
  302. const { bash, calls } = await setup()
  303. const result = await bash.run(bash.resolve({ command: 'echo free', sandboxPolicy: executionPolicy('danger-full-access') }))
  304. expect(result.stdout.text).toBe('free\n')
  305. expect(result.sandbox).toEqual({ mode: 'danger-full-access', denied: false })
  306. expect(calls).toHaveLength(0)
  307. })
  308. it('overlapping background jobs settle with their OWN modes (an escalated task next to a default one)', async () => {
  309. // With per-call policy, tasks under different modes are in flight at
  310. // once — anything keyed off the configured default would misreport the
  311. // escalated one at its settle stamp.
  312. const { bash } = await setup()
  313. const escalated = bash.start(bash.resolve({ command: 'sleep 0.3; echo "x: Permission denied" >&2; exit 1', sandboxPolicy: executionPolicy('workspace-write') }))
  314. const plain = bash.start(bash.resolve({ command: 'true' }))
  315. await plain.done
  316. await escalated.done
  317. expect(escalated.sandbox).toEqual({ mode: 'workspace-write', denied: true, enforcement: 'full' })
  318. expect(plain.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
  319. })
  320. it('an escalated danger-full-access background job carries no facts (nothing confined it)', async () => {
  321. const { bash, calls } = await setup()
  322. const task = bash.start(bash.resolve({ command: 'echo bg-free', sandboxPolicy: executionPolicy('danger-full-access') }))
  323. await task.done
  324. expect(task.sandbox).toBeUndefined()
  325. expect(task.readOutput().delta).toContain('bg-free')
  326. expect(calls).toHaveLength(0)
  327. })
  328. })
  329. describe('classifyDenial', () => {
  330. it('never classifies a clean exit or a signal kill as a denial', () => {
  331. expect(classifyDenial(runResult(0, 'Permission denied'), UNIX_SIGNATURES)).toBe(false)
  332. expect(classifyDenial(runResult(null, 'Permission denied'), UNIX_SIGNATURES)).toBe(false)
  333. })
  334. it('classifies failed runs by the wrap\'s own dialect, conservatively', () => {
  335. expect(classifyDenial(runResult(1, 'touch: cannot touch /x: Read-only file system'), UNIX_SIGNATURES)).toBe(true)
  336. expect(classifyDenial(runResult(1, 'sh: /x: Permission denied'), UNIX_SIGNATURES)).toBe(true)
  337. // Bare EPERM is not a Linux runner's dialect: mount/kill/ptrace fail with
  338. // it unsandboxed too, and the mode vocabulary governs file effects only —
  339. // claiming a file denial here would tell the model the sandbox blocked
  340. // something it never governed.
  341. expect(classifyDenial(runResult(1, 'mount: Operation not permitted'), UNIX_SIGNATURES)).toBe(false)
  342. expect(classifyDenial(runResult(1, 'No such file or directory'), UNIX_SIGNATURES)).toBe(false)
  343. })
  344. it('matches exactly the active backend\'s dialect: EPERM classifies under Seatbelt, EACCES does not under bwrap', () => {
  345. // The same stderr flips meaning with the backend: under Seatbelt, EPERM
  346. // text IS how the kernel refuses a governed file write; under bwrap's
  347. // EROFS-only dialect, `Permission denied` is ordinary DAC, not the
  348. // sandbox — per-wrap signatures are what keep both classifications honest.
  349. expect(classifyDenial(runResult(1, 'bash: /etc/x: Operation not permitted'), ['operation not permitted'])).toBe(true)
  350. expect(classifyDenial(runResult(1, 'sh: /x: Permission denied'), ['read-only file system'])).toBe(false)
  351. })
  352. })
  353. describe('isRunnerSpawnFailure', () => {
  354. it.each(['EACCES', 'ENOENT'])(
  355. 'attributes executable-class spawn code %s to argv[0] once cwd ambiguity is eliminated',
  356. (code) => {
  357. const runner = join(spillDir, 'runner')
  358. const error = Object.assign(new Error('spawn failed'), { code, syscall: `spawn ${runner}`, path: runner })
  359. expect(isRunnerSpawnFailure(error, runner, process.cwd())).toBe(true)
  360. },
  361. )
  362. it.each(['ENOEXEC', 'ENOTDIR', 'EPERM'])(
  363. 'keeps unproven executable code %s ordinary despite synthetic argv[0] fields',
  364. (code) => {
  365. const runner = join(spillDir, 'runner')
  366. const error = Object.assign(new Error('spawn failed'), { code, syscall: `spawn ${runner}`, path: runner })
  367. expect(isRunnerSpawnFailure(error, runner, process.cwd())).toBe(false)
  368. },
  369. )
  370. it('requires a usable caller cwd before classifying absolute, bare, or relative runners', () => {
  371. const missingWorkdir = join(spillDir, 'missing-workdir')
  372. for (const [, runner] of RUNNER_FORMS) {
  373. const error = Object.assign(new Error('spawn failed'), { code: 'ENOENT', syscall: `spawn ${runner}`, path: runner })
  374. expect(isRunnerSpawnFailure(error, runner, missingWorkdir)).toBe(false)
  375. }
  376. const fileWorkdir = join(spillDir, 'not-a-workdir')
  377. writeFileSync(fileWorkdir, '')
  378. const error = Object.assign(new Error('spawn failed'), { code: 'ENOTDIR', syscall: 'spawn node', path: 'node' })
  379. expect(isRunnerSpawnFailure(error, 'node', fileWorkdir)).toBe(false)
  380. })
  381. it('rejects resource, non-spawn, mismatched-program, and unstructured failures', () => {
  382. const missingRunner = join(spillDir, 'definitely-missing-runner')
  383. const spawnError = (code: unknown, syscall: unknown = `spawn ${missingRunner}`, path: unknown = missingRunner) =>
  384. Object.assign(new Error('spawn failed'), { code, syscall, path })
  385. const spawnErrorWithoutPath = (syscall: string) =>
  386. Object.assign(new Error('spawn failed'), { code: 'ENOENT', syscall })
  387. expect(isRunnerSpawnFailure(spawnError('EMFILE'), missingRunner, process.cwd())).toBe(false)
  388. expect(isRunnerSpawnFailure(spawnError('ENOMEM'), missingRunner, process.cwd())).toBe(false)
  389. expect(isRunnerSpawnFailure(spawnError(2), missingRunner, process.cwd())).toBe(false)
  390. expect(isRunnerSpawnFailure(spawnError('ENOENT', 'open'), missingRunner, process.cwd())).toBe(false)
  391. expect(isRunnerSpawnFailure(spawnError('ENOENT', 1), missingRunner, process.cwd())).toBe(false)
  392. expect(isRunnerSpawnFailure(spawnError('ENOENT', 'spawn', process.execPath), missingRunner, process.cwd())).toBe(false)
  393. expect(isRunnerSpawnFailure(spawnError('ENOENT', 'spawn', 1), missingRunner, process.cwd())).toBe(false)
  394. expect(isRunnerSpawnFailure(spawnError('ENOENT', 'spawn', ''), missingRunner, process.cwd())).toBe(false)
  395. expect(isRunnerSpawnFailure(spawnErrorWithoutPath('spawn'), missingRunner, process.cwd())).toBe(false)
  396. expect(isRunnerSpawnFailure(spawnErrorWithoutPath('spawn other-runner'), missingRunner, process.cwd())).toBe(false)
  397. expect(isRunnerSpawnFailure(undefined, missingRunner, process.cwd())).toBe(false)
  398. expect(isRunnerSpawnFailure(null, missingRunner, process.cwd())).toBe(false)
  399. expect(isRunnerSpawnFailure(spawnError('ENOENT'), undefined, process.cwd())).toBe(false)
  400. })
  401. it('accepts only syscall and error-path facts that identify the exact runner program', () => {
  402. const runner = join(spillDir, 'runner with spaces')
  403. const spawnError = (syscall: string, path?: string) =>
  404. Object.assign(new Error('spawn failed'), { code: 'ENOENT', syscall, path })
  405. expect(isRunnerSpawnFailure(spawnError('spawn', runner), runner, process.cwd())).toBe(true)
  406. expect(isRunnerSpawnFailure(spawnError(`spawn ${runner}`, runner), runner, process.cwd())).toBe(true)
  407. expect(isRunnerSpawnFailure(spawnError(`spawn ${runner}`), runner, process.cwd())).toBe(true)
  408. expect(isRunnerSpawnFailure(spawnError('spawn other-runner', runner), runner, process.cwd())).toBe(false)
  409. })
  410. })
  411. describe('classifyRunnerFailure', () => {
  412. it('ignores empty and whitespace-only fatal signatures instead of treating exit status or notice text as evidence', () => {
  413. const notice = 'landlock-run: partial enforcement (older Landlock ABI)'
  414. const emptyRule = [{ allowedExitCodes: [125], fatalSignatures: ['', ' ', '\t'] }]
  415. expect(classifyRunnerFailure(125, '', emptyRule)).toBeUndefined()
  416. expect(classifyRunnerFailure(125, notice, emptyRule)).toBeUndefined()
  417. })
  418. it('keeps valid fatal signatures active beside an ignored empty entry', () => {
  419. const notice = 'landlock-run: partial enforcement (older Landlock ABI)'
  420. const fatal = 'landlock-run: ruleset creation failed'
  421. const rules = [{
  422. allowedExitCodes: [125],
  423. fatalSignatures: ['', ' ', 'landlock-run: '],
  424. informationalLines: [notice],
  425. }]
  426. expect(classifyRunnerFailure(125, `${notice}\nchild diagnostic\n${fatal}`, rules)).toEqual({ detail: fatal })
  427. })
  428. it('requires Landlock exit 125 plus a non-notice fatal line and returns that original line', () => {
  429. const notice = 'landlock-run: partial enforcement (older Landlock ABI)'
  430. const rules = [{ allowedExitCodes: [125], fatalSignatures: ['landlock-run: '], informationalLines: [notice] }]
  431. expect(classifyRunnerFailure(1, notice, rules)).toBeUndefined()
  432. expect(classifyRunnerFailure(2, notice, rules)).toBeUndefined()
  433. expect(classifyRunnerFailure(125, notice, rules)).toBeUndefined()
  434. expect(classifyRunnerFailure(125, notice.toUpperCase(), rules)).toBeUndefined()
  435. expect(classifyRunnerFailure(125, `${notice}: extra detail`, rules))
  436. .toEqual({ detail: `${notice}: extra detail` })
  437. expect(classifyRunnerFailure(125, `${notice}\nlandlock-run: exec failed: No such file or directory`, rules))
  438. .toEqual({ detail: 'landlock-run: exec failed: No such file or directory' })
  439. })
  440. it.each([
  441. 'landlock-run: usage error: missing `-- <argv>...` command',
  442. 'landlock-run: landlock is not enforced by this kernel (ABI unsupported or disabled)',
  443. 'landlock-run: cannot open rule path: /gone: No such file or directory',
  444. 'landlock-run: landlock ruleset error: Invalid argument',
  445. 'landlock-run: exec failed: Permission denied',
  446. 'landlock-run: out of memory',
  447. 'landlock-run: future fatal diagnostic',
  448. ])('keeps known and future Landlock fatal diagnostics fail-closed: %s', (fatal) => {
  449. const rules = [{
  450. allowedExitCodes: [125],
  451. fatalSignatures: ['landlock-run: '],
  452. informationalLines: ['landlock-run: partial enforcement (older Landlock ABI)'],
  453. }]
  454. expect(classifyRunnerFailure(125, fatal, rules)).toEqual({ detail: fatal })
  455. })
  456. })
  457. describe('result facts', () => {
  458. it.each([126, 127])('keeps a successfully launched wrapped child exit %i as an ordinary outcome', async (exitCode) => {
  459. const { bash } = await setup({}, argv => ({
  460. argv: ['env', ...argv],
  461. enforcement: 'full',
  462. denialSignatures: UNIX_SIGNATURES,
  463. runnerFailureRules: RUNNER_FAILURE,
  464. }))
  465. const result = await bash.run(bash.resolve({ command: `exit ${exitCode}` }))
  466. expect(result.exitCode).toBe(exitCode)
  467. expect(result.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
  468. })
  469. it('reports a real permission failure as a sandbox denial with the mode it ran under', async () => {
  470. const { bash } = await setup()
  471. const deniedRoot = mkdtempSync(join(tmpdir(), 'dsh-sandbox-denied-'))
  472. try {
  473. const lockedDir = join(deniedRoot, 'locked')
  474. mkdirSync(lockedDir)
  475. chmodSync(lockedDir, 0o555)
  476. const result = await bash.run(bash.resolve({ command: `echo x > ${lockedDir}/f` }))
  477. expect(result.exitCode).not.toBe(0)
  478. expect(result.sandbox).toEqual({ mode: 'read-only', denied: true, enforcement: 'full' })
  479. } finally {
  480. rmSync(deniedRoot, { recursive: true, force: true })
  481. }
  482. })
  483. it('carries the provider\'s partial-enforcement fact through unchanged', async () => {
  484. const { bash } = await setup({}, argv => ({ argv: [...argv], enforcement: 'partial', denialSignatures: UNIX_SIGNATURES, runnerFailureRules: RUNNER_FAILURE }))
  485. const result = await bash.run(bash.resolve({ command: 'true' }))
  486. expect(result.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'partial' })
  487. })
  488. })
  489. describe('background sandbox facts', () => {
  490. it.each(RUNNER_FORMS)('keeps an invalid-workdir rejection ordinary for the %s provider-runner form', async (_form, runner) => {
  491. const { bash } = await setup({}, argv => ({
  492. argv: [runner, ...argv],
  493. enforcement: 'full',
  494. denialSignatures: UNIX_SIGNATURES,
  495. runnerFailureRules: RUNNER_FAILURE,
  496. }))
  497. const parent = mkdtempSync(join(tmpdir(), 'dsh-sandbox-missing-cwd-'))
  498. try {
  499. const task = bash.start(bash.resolve({ command: 'true', workdir: join(parent, 'missing') }))
  500. await task.done
  501. expect(task.status).toBe('killed')
  502. expect(task.readOutput().delta).toContain('subprocess failed before reporting an outcome:')
  503. expect(task.sandbox).toEqual({
  504. mode: 'read-only',
  505. denied: false,
  506. enforcement: 'full',
  507. })
  508. const accounting = (bash as unknown as { processFacts: Map<unknown, unknown> }).processFacts
  509. expect(accounting.size).toBe(0)
  510. } finally {
  511. rmSync(parent, { recursive: true, force: true })
  512. }
  513. })
  514. it('does not invent runner evidence when a provider rejection has no structured reason', async () => {
  515. const { ctx, bash } = await setup()
  516. const emptyReader: SubprocessOutputReader = {
  517. readFrom: () => ({ text: '', nextOffset: 0, lossy: false }),
  518. }
  519. vi.spyOn(ctx.subprocess, 'spawn').mockReturnValue({
  520. stdin: undefined,
  521. stdout: undefined,
  522. stderr: undefined,
  523. collected: { stdout: emptyReader, stderr: emptyReader },
  524. // Arbitrary subprocess providers can reject without a value or public stage.
  525. // oxlint-disable-next-line typescript/prefer-promise-reject-errors
  526. done: Promise.reject(undefined),
  527. terminate: vi.fn(),
  528. waitForExit: async () => true,
  529. } satisfies SubprocessHandle)
  530. const task = bash.start(bash.resolve({ command: 'true' }))
  531. await task.done
  532. expect(task.readOutput().delta).toContain('subprocess failed before reporting an outcome: undefined')
  533. expect(task.sandbox).toEqual({
  534. mode: 'read-only',
  535. denied: false,
  536. enforcement: 'full',
  537. })
  538. })
  539. it('stamps a settled denial: nonzero exit + permission stderr under a confined mode', async () => {
  540. const { bash } = await setup()
  541. const task = bash.start(bash.resolve({ command: 'echo "x: Permission denied" >&2; exit 1' }))
  542. await task.done
  543. expect(task.sandbox).toEqual({ mode: 'read-only', denied: true, enforcement: 'full' })
  544. })
  545. it('a foreground runner failure throws the fail-closed error, never a task result', async () => {
  546. // The wrap's runner prefix on a failed run means the SANDBOX broke and
  547. // the command never ran — the late twin of the confine-time throw, with
  548. // the matched fatal stderr line carried as the cause.
  549. const { bash } = await setup()
  550. const run = bash.run(bash.resolve({ command: 'echo "fake-runner: ruleset rejected" >&2; exit 125' }))
  551. await expect(run).rejects.toThrow(expect.objectContaining({ code: SANDBOX_UNAVAILABLE }))
  552. await expect(run).rejects.toThrow('fake-runner: ruleset rejected')
  553. })
  554. it('a foreground runner failure outranks denial: runner error text may contain denial words', async () => {
  555. const { bash } = await setup()
  556. await expect(bash.run(bash.resolve({ command: 'echo "fake-runner: cannot open rule path: /x: Permission denied" >&2; exit 125' })))
  557. .rejects.toThrow(expect.objectContaining({ code: SANDBOX_UNAVAILABLE }))
  558. })
  559. it('a settled background runner failure stamps runnerFailed (no error channel remains), not denied', async () => {
  560. const { bash } = await setup()
  561. const task = bash.start(bash.resolve({ command: 'echo "fake-runner: cannot open rule path: /x: Permission denied" >&2; exit 125' }))
  562. await task.done
  563. expect(task.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full', runnerFailed: true })
  564. })
  565. it('overlapping background jobs keep their OWN wrap facts (per-task, not latest-wrap)', async () => {
  566. // Facts belong to each wrap and may vary between calls. The slow task settles after the
  567. // quick task starts; a shared latest-wrap field would classify and stamp it with the wrong
  568. // task's dialect and enforcement.
  569. const wraps: Array<Pick<ConfinedArgv, 'enforcement' | 'denialSignatures'>> = [
  570. { enforcement: 'partial', denialSignatures: ['permission denied'] },
  571. { enforcement: 'full', denialSignatures: ['read-only file system'] },
  572. ]
  573. let call = 0
  574. const { bash } = await setup({}, (argv) => {
  575. const wrap = wraps[Math.min(call++, wraps.length - 1)] as Pick<ConfinedArgv, 'enforcement' | 'denialSignatures'>
  576. return { argv: [...argv], ...wrap, runnerFailureRules: RUNNER_FAILURE }
  577. })
  578. const slow = bash.start(bash.resolve({ command: 'sleep 0.4; echo "x: Permission denied" >&2; exit 1' }))
  579. const quick = bash.start(bash.resolve({ command: 'true' }))
  580. await quick.done
  581. await slow.done
  582. expect(slow.sandbox).toEqual({ mode: 'read-only', denied: true, enforcement: 'partial' })
  583. expect(quick.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
  584. })
  585. it('a signal-killed task is never a denial (null exit code)', async () => {
  586. const { bash } = await setup()
  587. const task = bash.start(bash.resolve({ command: 'echo "Permission denied" >&2; sleep 30' }))
  588. // Let the stderr land before the kill so the classifier sees the
  589. // signature and must still refuse it on the null exit code alone.
  590. await vi.waitFor(() => { expect(task.readOutput().delta).toContain('Permission denied') })
  591. task.kill()
  592. await task.done
  593. expect(task.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
  594. })
  595. it('disposal kills wrapped background jobs (inherited HMR safety)', async () => {
  596. const { ctx, bash } = await setup()
  597. const task = bash.start(bash.resolve({ command: 'sleep 30' }))
  598. await ctx.fiber.dispose()
  599. expect(task.status).toBe('killed')
  600. })
  601. })