sandbox.spec.ts 32 KB

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