Skip to content

Studio: minimal OS sandbox for Python and Terminal tools on Linux and macOS - #10526

Merged
oobabooga merged 76 commits into
mainfrom
studio-minimal-sandbox
Sep 16, 2026
Merged

oobabooga merged 76 commits into
mainfrom
studio-minimal-sandbox

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

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.py says so at line 7127: "Network policy is enforced by the AST host check and the bash blocklist". A model-authored script can read ~/.aws/credentials right 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:

  • writes anywhere outside the session workdir, /tmp and /dev/shm
  • reads of the user's home beyond the runtime paths the interpreter itself needs, so ~/.ssh, ~/.aws, ~/.config/gcloud, browser cookies and unrelated documents are gone
  • host process visibility, via a fresh PID namespace
  • AF_VSOCK, io_uring, and nested user namespaces

Not blocked, and the execution record states it rather than staying quiet:

  • network egress. 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 carries network_policy = "unrestricted" so the badge cannot read as more than this is. The static analysis in tools.py remains 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.
  • reads of system directories such as /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_sandbox boolean:

mode behaviour
auto (default) isolate if the host can, otherwise run exactly as today with the result labelled "no OS isolation"
required (opt in) refuse rather than run unisolated, with an actionable reason
full the existing bypass, unchanged

auto is the default and is the one mode that can never refuse. This matters because Ubuntu 23.10 and newer ship kernel.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 auto on a host without a sandbox, the planner hands back the argv, cwd, env and pre-exec it was given, unchanged. win32, freebsd and an unavailable Linux all come back byte identical, with no preexec_fn or pass_fds added on Windows and creationflags preserved.

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:

reason:      the bubblewrap live probe failed (exit 1): bwrap: setting up uid map: Permission denied
remediation: This host denies unprivileged user namespaces
             (kernel.apparmor_restrict_unprivileged_userns=1, the default on Ubuntu 23.10
             and newer), so bubblewrap cannot build a sandbox even though it is installed.
             Grant bwrap the userns permission with an AppArmor profile
             (/etc/apparmor.d/bwrap-userns-restrict from the apparmor-profiles package).
             Python and Terminal still run, with software safeguards only and no OS isolation.

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.

check where result
Real confinement through prepare_tool_launch container 21 of 21 pass
auto runs, argv unchanged AppArmor-restricted host pass
required refuses, names the fix AppArmor-restricted host pass
full unchanged AppArmor-restricted host pass
Windows, freebsd, unavailable Linux passthrough simulated byte identical
Full regression plus 4 new suites AppArmor-restricted host 1305 passed, 13 skipped, 0 failed

Inside the jail: all four credential canaries unreadable, writes to /etc, /usr and / 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: the profile now runs on Darwin, and the enforcement claim is narrower than the Linux one. On a macos-15 runner the profile compiles under sandbox-exec and $HOME is 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.
  • The unprivileged user namespace path is unproven. The container runs as root, because no combination of container flags lets an unprivileged process create a user namespace on a host with the AppArmor restriction (I tested seccomp, apparmor and cap-add variants; all fail at 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.
  • Nine tests in test_sandbox_files_and_storage_roots.py fail 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.
  • Relative to the other attempts, this claims less: it is Preview on both platforms, qualified is never set, and the network is out of scope entirely.

Relationship to the other sandbox work

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:

  • the setup prompt that offers to install bubblewrap and the AppArmor profile, asking first and never changing host security policy silently
  • routes and request-model wiring, so tool_execution_mode can be set per request
  • the UI: the per-call badge, the capability pill and the required toggle
  • sandbox_startup.py has no caller yet, so the startup notice does not print

Every 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:

  1. Load a model, enable Code, and run a Python tool call. It should work as before.
  2. Ask it to read ~/.ssh/id_rsa. It should fail with a file-not-found rather than printing a key.
  3. Ask it to pip install something. It should succeed, because the network is intentionally not confined.

On Ubuntu 24.04 or newer with the stock AppArmor setting:

  1. The same tool calls should still work, unchanged.
  2. Sandbox details should report OS isolation unavailable and name the AppArmor restriction.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-16T21:58:22.020626Z df48f3c Manual request
🔒 Security Review ✅ Completed 2026-09-10T03:48:49.485620Z 3303126 New commits

Security findings

Advisory findings (2)

ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@oobabooga

Copy link
Copy Markdown
Member

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 auto reaches effective_mode = os_isolated and a different set of tests runs.

A tool call's temp files were lost. tools.py points TMPDIR at <workdir>/unsloth-tmp so a file written through tempfile is still there when the call returns and is offered as a download card. The backends overrode it with the private tmpfs, which dies with the mount namespace. tempfile.mkstemp() in a sandboxed call wrote to a path that no longer existed by the time the result was rendered; on main the same code produces __FILES__:[{"name": "unsloth-tmp/tmp....csv"}]. Both backends now keep a caller TMPDIR that is inside the workdir and fall back to the private tmp otherwise.

The cache bind left a .cache tree in every session workdir. bwrap creates a missing bind destination itself, and that one sits under the workdir bind, so the directories were created on the host. _holds_no_user_files ignores empty directories, so the delete prompt was not affected, but test_the_executor_leaves_nothing_in_the_sandbox and two others were. The mount points are now made in prepare and reclaimed on cleanup, innermost first and only while empty, so a .cache a tool call wrote is left alone.

A backgrounded process no longer outlives the foreground command. --unshare-pid means the namespace goes down with the leader, so ( sleep 7; echo late ) & echo done returns done at once and the late output is not collected. This is what process_isolation means and it is stricter than the unisolated path, so it is now in LIMITATIONS as detached_processes_die_with_the_call rather than undone. The five tests in test_tool_output_streaming.py that stage "the leader exited while a grandchild holds stdout" cannot stage it inside a PID namespace at all; they now assert the invariant both paths owe (the call did not block on the grandchild, and the grandchild did not survive) and the mechanism string only off the isolated path.

Three tests in the new files were also only ever green on a fallback host: test_the_child_still_lands_in_its_own_session asked the payload whether it was a session leader, which it is not under --unshare-pid (the process tools.py holds and signals is bwrap, and that one does lead its own session, verified by a timeout that returned "Execution timed out" with the parent intact); test_the_environment_the_shim_depends_on_survives[sandboxed] was correct and caught the TMPDIR bug above; and test_optional_read_literals_never_follow_a_symlink compared against an exact one-element list, which _sbpl_spellings never produces for a tmp_path under /tmp, /var or /etc, so it would have failed on Linux and on macOS.

Verified after the fix, on the same host: ~/.ssh, ~/.aws/credentials and ~/.config/gcloud unreadable, a write to /etc refused, /proc showing two pids, numpy importing, $HF_HOME/hub still the shared host cache, and 464 passed with only the two pre-existing locale failures this machine has on the merge base.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +7212 to +7216
global _last_tool_execution_record
if record is None:
return
_last_tool_execution_record = record
logger.info("tool execution mode: %s", record.as_dict())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +10599 to +10600
*,
tool_execution_mode: str = "auto",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +384 to +386
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,)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
@oobabooga

Copy link
Copy Markdown
Member

@codex review

@oobabooga

Copy link
Copy Markdown
Member

@codex security review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +520 to +523
argv += [
"--bind-try",
os.path.join(model_cache, name),
os.path.join(inner_cache, name),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛡️ 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.

Comment on lines +521 to +523
"--bind-try",
os.path.join(model_cache, name),
os.path.join(inner_cache, name),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛡️ Codex Security Review

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: b967ef0730

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

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.

@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: df48f3cbd9

ℹ️ 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".

@oobabooga

Copy link
Copy Markdown
Member

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 after

Before 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 command

The 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 files

Full-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 validation

I 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 main, I ran the focused sandbox, streaming, MCP, and tool-loop coverage against the resulting branch:

672 passed
11 skipped

The PR checkout remained clean after validation.

Primary live Studio validation on Linux

I 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:

  • creating and editing CSV, PNG, text, JSON, Python, and ZIP files;
  • displaying an existing chart inline and downloading generated files through the browser;
  • updating existing data without losing the conversation workspace;
  • retaining files after a cache-disabled browser refresh;
  • importing packages and running unit tests in a separate Python process;
  • downloading and parsing an HTTPS response without installing the package;
  • cancelling a running 120-second Python tool call and successfully running another tool call afterward;
  • starting a new conversation and confirming it could not see the previous conversation's files.

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 check

I 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 limitations

Model-written prose links to generated files can still appear as [blocked]. The file cards download correctly, and inline Markdown chart images render correctly. This appears separate from the isolation boundary exercised by the PR.

The live tests did not cover Safari/WebKit, Desktop packaging, MLX inference or training, upgrade and migration flows, or native Windows/WSL execution.

Conclusion

The 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 CI

Staging 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants