Repository navigation
Studio: minimal OS sandbox for Python and Terminal tools on Linux and macOS - #10526
Conversation
The contract only, so the two backends can land against a stable shape. Three modes: auto (isolate if the host can, otherwise run exactly as today and label the result), required (refuse rather than run unisolated), and full (the existing bypass, unchanged). auto is the default and is the one mode that can never refuse. Windows and every other platform take the unavailable path, which is main's behaviour byte for byte.
Bubblewrap on Linux, Seatbelt on macOS, reached through the launch contract added in the previous commit. No Node, no vendored dependency, no npm, no network proxy. What the boundary covers, and it is deliberately narrow so the label can be true: no writes outside the session workdir, /tmp and /dev/shm; no reads of the user's home beyond the runtime paths the interpreter itself needs, so ~/.ssh, ~/.aws, ~/.config/gcloud and unrelated documents are gone; a fresh PID namespace; AF_VSOCK, io_uring and nested user namespaces denied. The network is NOT confined, on purpose. pip install, model downloads and API calls inside a tool call keep working, and a script that can still reach a secret can still send it. The record says network_policy=unrestricted rather than staying quiet, because the badge should not read as more than this is. The static analysis in tools.py remains the only thing standing between a tool call and an outbound secret. Availability is never inferred from a binary existing. The probe launches a real sandbox through the same prepare() the product uses and checks that its negative controls fail -- an installed bubblewrap on a host that denies user namespaces looks identical to a working one until you try it. Nothing that ran yesterday stops running. In auto on a host without a sandbox the planner hands back the argv, cwd, env and pre-exec it was given, unchanged; Windows and every other platform take that path unconditionally. Measured: win32, freebsd and an unavailable linux all come back byte identical, with no preexec_fn or pass_fds added on Windows and creationflags preserved. Verified in a privileged container where bubblewrap works, since this workspace host denies unprivileged user namespaces: 21 checks through the real prepare_tool_launch, covering all four credential canaries unreadable, writes to /etc /usr and / refused, the workdir and private tmp writable, network still reachable, host processes hidden, and numpy, Pillow and a multiprocessing spawn pool all working inside the jail. That container runs as root, so the unprivileged-userns path itself is still unproven; CI on a runner without the AppArmor restriction is what closes it. macOS is unproven entirely -- no Darwin kernel ever loaded the profile, and the two tests that would prove it are skipped rather than passed.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
Security findingsAdvisory findings (2)
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 17feeaecd4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| f"the session workdir cannot be fully inspected: {exc.filename or resolved}" | ||
| ) from exc | ||
|
|
||
| for base, dirs, names in os.walk(resolved, followlinks = False, onerror = stop): |
There was a problem hiding this comment.
Bound workdir inspection around blocking filesystem calls
When a project workdir is on a stale NFS/sshfs mount or another wedged FUSE filesystem, os.walk can block in its internal scandir before yielding an entry, and the later lstat can block as well. The monotonic deadline is checked only between completed operations, so _WORKDIR_SCAN_SECONDS does not actually bound preparation; because the tool timeout starts only after Popen, both auto and required calls can hang indefinitely without reaching fallback. Perform this inspection in a killable helper or otherwise enforce the deadline around the blocking filesystem operations.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The deadline really is only checked between completed operations, but the consequence named here is not introduced by this branch: _python_exec already calls _snapshot_workdir_files(workdir) at tools.py:16279, before the planner runs at all, and that walk has a directory budget and no deadline either. On a wedged NFS or FUSE mount the call blocks there first, on main exactly as on this branch, so moving this one scan into a killable helper would not shorten the hang by a second. Worth doing at the shared owner, on both walks, in a change that can be tested against a real wedged mount rather than reasoned about.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6636af5235
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
|
||
| def prepare(plan: ToolLaunchPlan) -> PreparedSandboxLaunch: | ||
| """Turn a launch plan into the bwrap argv that will run it.""" | ||
| bwrap = shutil.which("bwrap") |
There was a problem hiding this comment.
Resolve bubblewrap only from a trusted system path
When Studio is launched from an activated virtualenv, its user-writable bin directory normally precedes system directories in PATH, so shutil.which("bwrap") can select a project- or package-supplied executable. _bwrap_supports then runs that executable with --help outside any sandbox and with Studio's inherited environment, allowing a crafted bwrap to execute with the server's full host permissions before the live probe can reject it. Resolve the helper from a fixed trusted path and verify that it is root-owned and not user-writable, as the macOS launcher does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. Anyone who can put a bwrap earlier on the SERVER's PATH already controls the process that reads it: the venv Studio runs from is the same place its own code lives, so there is no boundary being crossed, and a tool call cannot write to that PATH under the sandbox or through the safe environment, which builds PATH from scratch and never inherits user-writable entries. The macOS comparison does not carry either: /usr/bin/sandbox-exec is a fixed system path, and bwrap has no equivalent. It is legitimately at /nix/store/... on NixOS, at /usr/local/bin from a source build, and under a user prefix on a host without root, so an ownership and writability rule would refuse working hosts and fall them back to software safeguards for no gain.
…ail, and hold macOS to the Linux read rule
|
Three things this round found that were not in the review, all from running the branch on a host where bubblewrap actually works. The PR description's test table was collected on an AppArmor-restricted host, so every number in it is the fallback path; on this host A tool call's temp files were lost. The cache bind left a A backgrounded process no longer outlives the foreground command. Three tests in the new files were also only ever green on a fallback host: Verified after the fix, on the same host: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f411328033
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| global _last_tool_execution_record | ||
| if record is None: | ||
| return | ||
| _last_tool_execution_record = record | ||
| logger.info("tool execution mode: %s", record.as_dict()) |
There was a problem hiding this comment.
Propagate execution records with each tool result
When auto falls back to software safeguards, this only writes the record to a process-global variable and the server log; execute_tool() still returns a plain string, the production tool-event paths never read _last_tool_execution_record, and the startup-notice helpers likewise have no production caller. Consequently users receive an ordinary-looking result with no indication that their code ran without OS isolation, contrary to the promised per-call badge; attach the record to the corresponding tool event/result rather than leaving it in an unconsumed global.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one here. The badge, the capability pill and the Required toggle are named in the description as the follow-up this PR deliberately stops short of, alongside the routes and request-model wiring; the record exists and is logged so those can consume it without inventing a source. Nothing gets weaker in the meantime: before this branch there was no isolation and no record, and after it a fallback launch behaves exactly as main did. Wiring a UI surface in the same change that introduces the boundary would put the untested part of the diff in front of users first.
| *, | ||
| tool_execution_mode: str = "auto", |
There was a problem hiding this comment.
Wire Required mode through production requests
The new parameter always uses its "auto" default in production: the request models and frontend permission modes expose only ask, auto, off, and full, while the production callers in studio_tool_loop.py, llama_cpp.py, and safetensors_agentic.py pass disable_sandbox but never tool_execution_mode. Thus the startup message's instruction to select Required cannot be followed, and users on unsupported hosts have no way to request fail-closed execution; add a request/UI setting and forward it through every local tool loop.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one here either, same reason: the request models and the per-request mode are the named follow-up. The premise about the startup message does not hold yet in any case, since sandbox_startup.py has no caller and the notice never prints, which is also stated in the description. auto is the mode every caller gets and the one mode that cannot refuse, so nothing is failing closed on anyone in the meantime.
| system_roots = tuple(path for path in _SYSTEM_ROOTS if os.path.isdir(path)) | ||
| if os.path.isdir(_NIX_STORE) and _within(os.path.realpath(sys.executable), _NIX_STORE): | ||
| system_roots += (_NIX_STORE,) |
There was a problem hiding this comment.
Add the NixOS system profile to the sandbox PATH
On NixOS, this exposes /nix/store when Python comes from Nix but does not expose /run/current-system/sw or add its bin directory to the sanitized PATH; _get_shell_cmd() nevertheless launches every Terminal call as bare bash. A normal NixOS installation provides Bash through /run/current-system/sw/bin/bash (often with only /bin/sh as a compatibility link), so the Python-only live probe passes while every isolated Terminal call fails at execvp before executing the command. Bind the system profile and include its trusted bin path, or resolve and bind the actual Bash executable during preparation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The failure it describes is not introduced by this branch: _build_safe_env has always built PATH from the interpreter's directory plus /usr/local/bin:/usr/bin:/bin, and subprocess resolves the bare bash in _get_shell_cmd from that PATH, sandbox or no sandbox. On a NixOS host where bash lives only in /run/current-system/sw/bin, a Terminal call fails at execvp on main exactly as it would in here. NixOS Terminal support is a real gap and a separate change, one that has to touch _build_safe_env rather than the bind list. The observation worth keeping from this is narrower: /bin/sh on NixOS is a store symlink, so an interpreter that is NOT in the store leaves /nix/store unbound and that link dangling inside the jail. That only matters once bash resolves at all.
…nd give pip a writable target
…itable workdir, and probe under no-new-privs
|
@codex review |
|
@codex security review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ed367d2b2c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| argv += [ | ||
| "--bind-try", | ||
| os.path.join(model_cache, name), | ||
| os.path.join(inner_cache, name), |
There was a problem hiding this comment.
Reject symlinked model-cache source directories
When any allowed cache subdirectory such as ~/.cache/huggingface/hub is a symlink to another directory, --bind-try resolves that host-side source and mounts the target read-write at the inner cache path. A relocated or malicious cache entry can therefore expose an arbitrary home directory—or even a much broader host tree—to model-authored code with unrestricted network access, despite excluding the cache-root token files; validate each source as a plain directory whose resolved path remains within an approved model-cache root before binding it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. A sandboxed call cannot make any of those five names a symlink: the binds are hub, datasets, modules, xet and assets, and their parent, ~/.cache/huggingface, is never bound, so there is no writable path to the entries themselves. Inside a bound subdirectory a symlink is resolved in the jail, where the target is not mounted and therefore not visible. That leaves the user's own relocation, which is a supported and common Hugging Face layout (ln -s /mnt/big/hub ~/.cache/huggingface/hub), and a check that the resolved source stays under an approved cache root would refuse exactly that. The one writer who could plant a hostile symlink is an unconfined call, which already has the whole host at that moment; the sandbox does not claim to survive a prior Full access call and cannot.
There was a problem hiding this comment.
🛡️ Codex Security Review
Here are some automated security review suggestions for this pull request.
Reviewed commit: ed367d2b2c
ℹ️ About Codex security reviews in GitHub
This is an experimental Codex feature. Security reviews are triggered when:
- You comment "@codex security review"
- A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review
Once complete, Codex will leave suggestions, or a comment if no findings are found.
| "--bind-try", | ||
| os.path.join(model_cache, name), | ||
| os.path.join(inner_cache, name), |
There was a problem hiding this comment.
🛡️ Codex Security Review
Security: Keep the shared Hugging Face cache read-only
On Linux, when the default Hugging Face cache contains private or operationally valuable artifacts and a Python or Terminal tool runs under bwrap, these --bind-try entries mount hub, datasets, modules, xet, and assets read-write at the tool's $HF_HOME. Model-authored code can therefore read or exfiltrate gated models and datasets and overwrite or delete the host cache across sessions. The fresh evidence after the token fix is that these data subdirectories still use writable binds; excluding $HF_HOME/token does not protect their contents. Bind the shared cache read-only and use a per-session writable cache or overlay for downloads.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. A writable model cache is the deliberate hole this backend documents, in the module docstring and as model_cache_writable in LIMITATIONS: a read-only bind means every download in a tool call re-downloads gigabytes into a per-session directory that is discarded, which is how a sandbox gets switched off. There is no overlay available either, since an unprivileged bwrap cannot mount one. It is also not a step down from main: today a tool call can read and rm -rf the entire ~/.cache/huggingface by absolute path with nothing in its way, and this branch narrows what is reachable to five subdirectories and takes the token out. The read half of the finding is the stated trade; the write half is smaller than what ships today.
…name the macOS semaphore namespace
… control bytes SBPL cannot carry
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
|
Checked the auto/required/full split and confirmed the fallback path leaves argv, cwd and env untouched, so hosts without user namespaces keep today's behaviour. The one thing I want confirmed before review is the isolated path's behaviour change around detached processes dying with the call and TMPDIR handling, since those are visible to existing tool calls. |
|
@codex review |
|
To use Codex here, create a Codex account and connect to github. |
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
This PR adds operating-system isolation around Studio's Python and terminal tools. It limits tool calls to the conversation workspace while preserving the workflows people expect from a local coding agent. Behavior before and afterBefore this PR, Studio relied mainly on application-level command checks and workspace rules. Python and terminal subprocesses still ran with the host operating system's normal filesystem view. With this PR, ordinary tool calls run inside an operating-system sandbox when the platform supports it: Linux: Studio -> bubblewrap -> Python or terminal command
macOS: Studio -> Seatbelt -> Python or terminal commandThe sandbox permits the conversation's working directory and required runtime resources, but denies access to unrelated host files. Each conversation receives a separate persistent workspace: Conversation A -> its files remain available after later messages and refreshes
Conversation B -> starts with a different workspace and cannot see A's filesFull-access mode remains available when a user intentionally needs broader host access. In automatic mode, a host without a working operating-system sandbox continues with Studio's existing software safeguards. The effective mode is recorded in the backend log, but it is not currently surfaced in the ordinary Studio interface. Code-level validationI traced the Python and terminal launch paths, sandbox capability probing, filesystem and process restrictions, persistence, cancellation, timeouts, cleanup, and fallback behavior. I also compared representative behavior with the pre-PR implementation so inherited restrictions were not misidentified as regressions. After merging the latest 672 passed
11 skippedThe PR checkout remained clean after validation. Primary live Studio validation on LinuxI ran the main acceptance test interactively in Studio on Linux, using a local model with automatic tool execution enabled and full access disabled. I sent the prompts one at a time, inspected the tool calls and replies, refreshed and reselected the conversation where relevant, and downloaded the resulting files for inspection. This covered the user workflows the sandbox must preserve:
The generated chart rendered in the conversation and downloaded successfully. The CSV data and summary totals were correct, the unit tests passed in a separate Python process, the ZIP contained the expected project files, the PyPI JSON and parsed summary downloaded correctly, cancellation left the conversation usable, and the new conversation did not inherit the earlier workspace. The backend log recorded all 14 Python and terminal launches from this session as actively isolated by bubblewrap. None used full access or the software-only fallback. Supplemental macOS checkI then repeated the same workflows on an Apple Silicon Mac to check the platform-specific Seatbelt backend. This used the current PR head in a fresh environment, a freshly built frontend, native Playwright Chromium, and a local Qwen3.5-4B Q4_K_M model. The macOS run reproduced the Linux outcomes for file creation and downloads, browser refresh persistence, subprocess tests, HTTPS access, cancellation and recovery, and conversation separation. I independently checked the files, images, archive contents, downloads, hashes, and process termination. All 44 recorded Python and terminal launches used active macOS Seatbelt isolation, with no fallback to the software-only mode or full access. Observed limitationsModel-written prose links to generated files can still appear as The live tests did not cover Safari/WebKit, Desktop packaging, MLX inference or training, upgrade and migration flows, or native Windows/WSL execution. ConclusionThe change addresses a real gap: Python and terminal tools previously had a broader host view than their conversation workspace required. The isolation is applied at the shared process-launch layer, so it covers both tools without duplicating policy in individual commands. Within the paths exercised here, normal local-agent workflows continued to work while unrelated host files and other conversations remained isolated. I found no concrete sandbox regression or merge blocker, so this is ready to merge from my side. Staging CIStaging CI passed the relevant Linux, macOS, and Windows startup, UI, API, GGUF, and real-path coverage. The red jobs were baseline or timing failures, plus one temporary formatting failure already corrected; none implicated the sandbox. The Kaggle T4 jobs were skipped. |
Summary
Runs Studio's Python and Terminal tools inside a real OS sandbox on Linux and macOS: bubblewrap on Linux, Seatbelt on macOS. No Node, no vendored dependency, no npm, no network proxy.
Today those tools run on the host behind software safeguards only, and
tools.pysays so at line 7127: "Network policy is enforced by the AST host check and the bash blocklist". A model-authored script can read~/.aws/credentialsright now.This is deliberately not a fourth attempt at everything. It is Linux and macOS only. Windows keeps today's behaviour untouched.
What the boundary covers
Blocked:
/tmpand/dev/shm~/.ssh,~/.aws,~/.config/gcloud, browser cookies and unrelated documents are goneNot blocked, and the execution record states it rather than staying quiet:
pip install, model downloads and API calls inside a tool call keep working. A script that can still reach a secret can still send it. The record carriesnetwork_policy = "unrestricted"so the badge cannot read as more than this is. The static analysis intools.pyremains the only thing between a tool call and an outbound secret, which is why Studio: harden software sandbox against credential exfil and dynamic-path bypasses #5603 matters more after this lands, not less./usr/lib.Strictly stronger than today on every host where it engages, and identical to today where it does not.
Nothing that runs today stops running
Three modes replace the current
disable_sandboxboolean:auto(default)required(opt in)fullautois the default and is the one mode that can never refuse. This matters because Ubuntu 23.10 and newer shipkernel.apparmor_restrict_unprivileged_userns=1, which denies the user namespace bubblewrap needs even when bubblewrap is installed. That is a large share of current Linux desktops. Fail-closed by default would take working tools away from all of them.Measured, not asserted: in
autoon a host without a sandbox, the planner hands back the argv, cwd, env and pre-exec it was given, unchanged.win32,freebsdand an unavailable Linux all come back byte identical, with nopreexec_fnorpass_fdsadded on Windows andcreationflagspreserved.Availability is probed, never inferred
An installed bubblewrap on a host that denies user namespaces looks identical to a working one until you try it. So the probe launches a real sandbox through the same
prepare()the product uses, and checks that its negative controls fail. Every negative control has a matching positive control proven on the host first, because a read that fails for an unrelated reason proves nothing.When it does fail, the message names the cause. Previously a user in this position had nothing to act on:
How this was tested
This workspace host denies unprivileged user namespaces, so confinement measured here would be vacuous. The confinement tests run in a privileged container where bubblewrap works, driving the real
prepare_tool_launch.prepare_tool_launchautoruns, argv unchangedrequiredrefuses, names the fixfullunchangedInside the jail: all four credential canaries unreadable, writes to
/etc,/usrand/refused, workdir and private tmp writable, network reachable, host processes hidden, and numpy, Pillow and a multiprocessing spawn pool all working. Every one of the 13 skips is platform-gated and recorded as a skip rather than a pass.What is not proven
macos-15runner the profile compiles undersandbox-execand$HOMEis unreadable from inside, checked against a host-side positive control that reads the same canary. That is two rules, not the whole profile: the rest is still asserted about the generated SBPL text rather than about kernel behaviour.uid_map). That covers the mount layout, read and write confinement, network and PID isolation, but not the namespace path a real user's launch takes. CI on a runner without the restriction is what closes this.test_sandbox_files_and_storage_roots.pyfail on macOS. They fail identically at this PR's merge base (56b8a6e4a) on the same runner image, so they predate it, but this PR does not fix them either.qualifiedis never set, and the network is out of scope entirely.Relationship to the other sandbox work
@anthropic-ai/sandbox-runtimenpm helper: 18,464 lines, a Node runtime dependency, and fail-closed by default.This PR is 2,625 lines of product code and 2,084 lines of tests. It does not supersede #10441 on Windows, which is genuinely hard and where SRT is the better answer if its Windows support firms up.
Scope of this PR
Backend only. Deliberately out of scope here, and small follow-ups:
tool_execution_modecan be set per requestrequiredtogglesandbox_startup.pyhas no caller yet, so the startup notice does not printEvery existing caller gets
auto, which is why the change is inert until those land.How to test
On a host with working user namespaces, for example Ubuntu 22.04 or a container:
~/.ssh/id_rsa. It should fail with a file-not-found rather than printing a key.pip installsomething. It should succeed, because the network is intentionally not confined.On Ubuntu 24.04 or newer with the stock AppArmor setting: