Add experimental sandboxed execution mode to Bun Shell ($.sandbox)#31906
Draft
robobun wants to merge 2 commits into
Draft
Add experimental sandboxed execution mode to Bun Shell ($.sandbox)#31906robobun wants to merge 2 commits into
robobun wants to merge 2 commits into
Conversation
$.sandbox(options) returns a $-compatible shell that enforces a policy inside the interpreter, before any command or filesystem operation executes: builtin allow/deny lists with external binaries always blocked, filesystem access restricted to symlink-resolved absolute path prefixes (fs.read/fs.write, write implies read), a reserved network toggle that only accepts false, and limits.timeout / limits.maxOutputBytes that reject the promise and unwind the state machine at step boundaries. Path checks cover builtin operands, redirect opens, cd, glob walk roots, and conditional file tests, all canonicalized through realpath of the deepest existing ancestor so dot-dot segments and symlinks cannot escape the granted prefixes. Recursive traversal stays under checked roots because ls -R, rm -r, and the glob walker never follow symlinks, and cp rejects its dereference flags at parse time. Also adds the missing run_task_cold dispatch arm for ShellYesTask, which panicked the event loop (Unexpected Task tag: 12) whenever the quiet-mode yes builtin bounced its write loop.
Collaborator
Author
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Workflows to automatically generate PRs for you. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
$.sandbox(options)creates a restricted Bun Shell for safely running untrusted shell commands. Because Bun Shell implements its commands natively, the policy is enforced inside the interpreter, before any command or filesystem operation executes.The returned function is
$-compatible (interpolation,.cwd(),.env(),.quiet(),.text(), ...) and inherits cwd/env/throws from the shell it derives from. Marked experimental; the option surface is validated strictly (unknown keys throw) so it can grow toward overlay filesystems and network allowlists without breaking existing callers.Policy surface
commands.allow/commands.denyfilter the builtin set; unknown names throw with the list of valid builtins. Deny wins over allow.fs.read/fs.writegrant absolute path prefixes; a write prefix implies read, and omittingwritegives a read-only sandbox. Every checked path is resolved against the shell cwd and through symlinks (realpath of the deepest existing ancestor) before the prefix comparison, and policy prefixes get the same canonicalization at parse time.falseis accepted,truethrows instead of silently doing nothing.EventLoopTimerplus a wall-clock deadline checked at interpreter step boundaries, so synchronous write bursts that starve the event loop still observe the timeout. Rejects withShell command timed out after <n>ms (sandbox limits.timeout).Builtin::write_no_ioandIOWriter::enqueue), covering stdout, stderr, and file redirects. Rejects withShell command output exceeded <n> bytes (sandbox limits.maxOutputBytes). Both rejections carry the output captured so far.Enforcement points
Cmd::transition_to_execis the single command gate (builtin allow/deny, external block).cat/ls/rm/mv/cp/touch/mkdiroperands, redirect opens (<,>,>>),cdtargets, glob walk roots, and[[ -f ... ]]probes (which answer "does not exist" outside the grants).whichnever probes PATH in a sandbox; it resolves policy-permitted builtins only, so scripts cannot enumerate host binaries.ls -Rdescends by dirent kind,rm -rdeletes with NOFOLLOW semantics, the glob walker runs withfollow_symlinks = false, andcprejects-H/-Lat parse time. Subshells, pipelines, and command substitution share the sameInterpreter, so the policy applies to them with no extra plumbing.Script::next,Binary::next,Cmd::next, the builtin IO-writer callback) via a syntheticECANCELEDwrite error, so builtins release their readers/writers through existing error paths instead of being torn down mid-state.Blocked operations exit 1 with a
... not permitted in sandboxmessage on stderr, so they compose with&&/||/.nothrow()like any failing command.Also fixed
run_task_coldhad no dispatch arm forShellYesTask, so the quiet-modeyesbuiltin panicked the event loop withpanic: Unexpected Task tag: 12as soon as its write loop bounced through the task queue. The sandbox limit tests exercise exactly that path; the arm now routes toYesTask::run_from_main_thread.Out of scope, by design (documented)
cat/cpare POSIX-disabled natively today, so inside a sandbox they are blocked like external commands on those platforms.Bun.file(), buffers,Response) come from the trusted caller, not the untrusted script, and are not policy-checked.Verification
test/js/bun/shell/bunshell-sandbox.test.ts: 38 tests / 142 assertions covering option validation, allow/deny, the external-command block (includingbunitself andPATH=tricks), read/write prefix matrices for every filesystem builtin and redirect form, and escape attempts:..traversal, symlinked directories, files, and write targets, subshells, command substitution, pipelines, glob enumeration,cd, and[[ -f ]]probes, plus timeout and output-limit behavior with exact error messages.bunshell.test.ts(376 pass), instance/default/throw/shelloutput/yield/lazy/exec/file-io/brace, andcommands/. The only failures in this container are pre-existing and reproduce identically on a clean tree (ls permission-denied tests under root, shell-hang's 700ms spawn budget in a debug build).bun run rust:check-all: 10/10 target configurations compile.docs/runtime/shell.mdx; TypeScript declarations inpackages/bun-types/shell.d.ts(bun-types integration test passes).