Skip to content

Studio: OS-level sandbox for python and terminal tool execution (bubblewrap + Seatbelt) - #7101

Closed
danielhanchen wants to merge 32 commits into
mainfrom
danielhanchen/studio-os-sandbox
Closed

danielhanchen wants to merge 32 commits into
mainfrom
danielhanchen/studio-os-sandbox

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Wraps the Studio backend's python and terminal tool subprocesses in an OS-level sandbox: bubblewrap on Linux, Seatbelt (sandbox-exec) on macOS. LLM-driven tool execution is confined to the per-session workdir with a read-only view of the OS and interpreter, a fresh /tmp, and no network, instead of running with the full privileges of the Studio user.

This ports the sandbox core from #5468 (by @NilayYadav) onto current main and redoes the integration against today's tool-execution path. It is intentionally focused: the OS jail only. The existing in-process guard (code-safety AST scan, command blocklist, credential-free env, rlimits, /proc environ hardening) is unchanged and becomes a defense-in-depth layer underneath it.

Design

The OS sandbox is the primary boundary when available; when it cannot be applied the tool falls back to the existing guarded path with a warning, so behavior is never worse than today.

  • core/inference/sandbox.py (new)

    • sandbox_available(): cached, thread-safe, three-way probe (ok / fail / transient-timeout) that confirms the primitive can actually apply in this process context, not just that the binary exists. A transient probe timeout is not cached, so a one-off slow probe does not disable the sandbox for the whole process lifetime.
    • build_sandbox_argv(inner_argv, workdir): the Linux bwrap argv (--unshare-all, fresh /proc /dev /tmp, read-only OS + interpreter binds, rw workdir bind, narrowed /etc) or the macOS Seatbelt profile (deny default, narrow read allow, deny network, deny Keychain / LaunchServices browser-escape). RLIMIT_NPROC is reapplied inside the Linux user namespace by a small inner wrapper.
  • core/inference/tools.py

    • _python_exec / _bash_exec wrap the interpreter / shell argv with build_sandbox_argv when sandbox_available() and not Bypass Permissions.
    • _sandbox_preexec is split into _sandbox_preexec_impl(apply_no_new_privs, apply_nproc). The Linux bwrap path uses _sandbox_preexec_for_bwrap, which skips PR_SET_NO_NEW_PRIVS (set before execve it breaks the setuid bwrap helper) and the per-real-UID RLIMIT_NPROC (can EAGAIN bwrap's own fork on busy multi-tenant hosts). macOS keeps the full pre-exec.
    • _get_workdir canonicalizes the workdir with realpath so the child's cwd and the bwrap bind always match on symlinked-$HOME hosts.
    • UNSLOTH_STUDIO_SANDBOX_STRICT=1 (opt-in) makes execution fail closed when the sandbox cannot be applied. The default stays fail-open so locked-down installs (no bwrap, restricted kernels, nested containers) keep working.
  • run.py warms the availability probe at startup so the sandboxed / unsandboxed status is logged at boot and the first tool call does not pay the probe timeout.

  • install.sh installs bubblewrap best-effort on Linux. Missing bwrap is never fatal; it only downgrades tool execution to the in-process guard (or, under strict mode, refuses).

  • CI installs bubblewrap, relaxes the Ubuntu 24.04 unprivileged-userns AppArmor restriction, then probes. The enforcement tests are gated on that probe so they run for real where the sandbox applies and self-skip (green, with a warning) on a runner that genuinely cannot create user namespaces.

Tests

studio/backend/tests/test_sandbox.py (new): argv / profile construction, workdir realpath, NPROC clamping and inner-wrapper injection, sandbox_available() concurrency and transient-timeout caching, strict-mode fail-closed, unsandboxed fallback, and Seatbelt profile-injection guards. The live enforcement tests (workdir write, $HOME read deny, network deny) run under CI where the sandbox applies and skip elsewhere.

Local: python -m pytest -q tests/test_sandbox.py tests/test_bypass_permissions.py tests/test_sandbox_tools.py tests/test_secure_tools_execute.py -> 277 passed, 9 skipped (the skips are the live-enforcement tests, which require a working userns). ruff check clean.

Scope and follow-ups

This is the jail as-is: network is denied. Because pip install / Hugging Face / wandb need egress, a follow-up will add an egress allowlist (per-session filtering proxy) plus a per-session uv environment so package installs and training runs work inside the sandbox. Once the jail carries the confinement, the static classifier can be thinned to defense-in-depth.

Credit to @NilayYadav for the original sandbox implementation in #5468.

danielhanchen and others added 2 commits July 13, 2026 10:23
…lewrap + Seatbelt)

Wrap the Studio backend's python and terminal tool subprocesses in an
OS-level sandbox: bubblewrap on Linux, Seatbelt (sandbox-exec) on macOS. This
confines LLM-driven tool execution to the per-session workdir with a read-only
view of the OS and interpreter, a fresh /tmp, and no network, instead of
running with the full privileges of the Studio user.

This ports the sandbox core from PR #5468 onto current main and redoes the
integration against today's tool-execution path. The existing in-process guard
(code-safety AST scan, command blocklist, credential-free env, rlimits, /proc
environ hardening) is unchanged and becomes a defense-in-depth layer: the OS
sandbox is the primary boundary when available, and execution falls back to the
existing guarded path (with a warning) when it is not.

core/inference/sandbox.py (new):
- sandbox_available(): cached, thread-safe, three-way probe (ok / fail /
  transient-timeout) that confirms the primitive can actually apply in this
  process context, not just that the binary exists. A transient timeout is not
  cached, so a one-off slow probe does not disable the sandbox for the whole
  process lifetime.
- build_sandbox_argv(inner_argv, workdir): the Linux bwrap argv (--unshare-all,
  fresh /proc /dev /tmp, read-only OS + interpreter binds, rw workdir bind,
  narrowed /etc) or the macOS Seatbelt profile (deny default, narrow read allow,
  deny network, deny Keychain / LaunchServices browser-escape). NPROC is
  reapplied inside the Linux user namespace by a small inner wrapper.

core/inference/tools.py:
- _python_exec / _bash_exec wrap the interpreter / shell argv with
  build_sandbox_argv when sandbox_available() and not Bypass Permissions.
- _sandbox_preexec is split into _sandbox_preexec_impl(apply_no_new_privs,
  apply_nproc); the Linux bwrap path uses _sandbox_preexec_for_bwrap, which
  skips PR_SET_NO_NEW_PRIVS (breaks the setuid bwrap helper) and the
  per-real-UID RLIMIT_NPROC (can EAGAIN bwrap's fork on busy hosts). macOS keeps
  the full pre-exec.
- _get_workdir canonicalizes the workdir with realpath so the child's cwd and
  the bwrap bind always match on symlinked-$HOME hosts.
- UNSLOTH_STUDIO_SANDBOX_STRICT=1 (opt-in) makes execution fail closed when the
  sandbox cannot be applied; the default stays fail-open so locked-down installs
  keep working.

run.py warms the availability probe at startup. install.sh installs bubblewrap
best-effort on Linux (never fatal; missing bwrap only downgrades to the
in-process guard). CI installs bubblewrap, relaxes the Ubuntu 24.04 userns
AppArmor restriction, and gates the enforcement tests on a probe so they run
where the sandbox applies and skip (green) where it cannot.

Co-authored-by: Nilay <[email protected]>

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces an OS-level sandbox wrapper for tool execution using macOS Seatbelt and Linux bubblewrap. It integrates these sandboxes into the Python and Bash execution environments, adds background warming of the sandbox probe at startup, and provides a strict-mode opt-in to fail closed if sandboxing is unavailable. Comprehensive tests are also added. The review feedback recommends defensively guarding calls to site.getsitepackages and site.getusersitepackages to prevent potential crashes in custom Python environments where these functions might be missing or raise exceptions.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

_python_read_paths runs in the sandboxed exec path with no fallback, so an
AttributeError or unexpected exception from site.getsitepackages /
getusersitepackages (older virtualenv site.py, embedded / frozen Python) would
make every sandboxed tool call return an execution error. Guard both calls and
continue: sys.prefix / sys.base_prefix are bound regardless, so a venv's
site-packages under the prefix stays visible even when these helpers do not
resolve.

Regression: test_python_read_paths_survives_missing_site_helpers.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 5d25ef3439

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

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed main has no OS-level jail around the tool subprocesses in studio/backend/core/inference/tools.py, so this closes a real gap for python and terminal execution. It needs a rebase since it currently conflicts, and I will get it reviewed after that.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 31, 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-02T06:17:52.354177Z b770bc7 Manual request
ℹ️ 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.

@Etherll

Etherll commented Aug 31, 2026

Copy link
Copy Markdown
Collaborator

Pushed the lifecycle and sandbox hardening fixes in 17f8043. The focused suite reports 114 passed and 43 platform skips, lint is clean, and all current review threads are resolved. Fresh CodeQL is still queued, and the full cross-platform evidence is incomplete, so this is not ready yet.

@Etherll

Etherll commented Aug 31, 2026

Copy link
Copy Markdown
Collaborator

Status: BLOCKED pending GitHub mergeability, pre-commit, and review resolution.

The remediation commit 24e5436fc5562c01a687419d3b3f875bff00d0f6 was normally pushed to the exact PR branch from original head 17f804304c9fb2e16437282ad18e779f1a62ee67. No force push or merge was performed.

Fixes include a stable resolved helper path, capability-gated installer reporting, shared FastAPI lifespan warm-up for both CLI and direct uvicorn, and regression coverage.

Exact-head evidence:

  • Windows: 115 passed, 44 skipped
  • WSL with the real Linux helper: 32 passed, 5 skipped
  • Legacy permission coverage: 109 passed, 9 skipped
  • Control slice: 8 passed, 27 deselected
  • Ruff, diff hygiene, and POSIX shell syntax passed
  • Two fresh read-only remediation reviews found no issues
  • Hardened evidence gate passed with two native and two reasoned platform rows
  • CodeQL run 33415455086: actions, JavaScript, Python, and Rust all succeeded

GitHub still reports mergeable=CONFLICTING, mergeStateStatus=DIRTY, and reviewDecision=REVIEW_REQUIRED. The pre-commit.ci error page also reports a merge conflict. This conflicts with the live base c570180a32bd5aa97be1e8af6328aef45c8da75d being the merge-base, compare showing ahead 6 and behind 0, and local git merge-tree succeeding. Further GitHub-side mergeability, pre-commit, and review resolution is required.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Etherll commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@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: 1846ccf28d

ℹ️ 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 +257 to +263
roots = list(_LINUX_ROCM_ROOTS)
try:
with os.scandir(_LINUX_ROCM_OPT_ROOT) as entries:
roots.extend(
entry.path
for entry in entries
if entry.name.startswith("rocm-") and entry.is_dir(follow_symlinks = True)

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 Honor configured ROCm installation roots

When ROCm is installed at a path selected by ROCM_PATH or HIP_PATH outside /usr and the fixed /opt/rocm* layout (for example /opt/amd/rocm or /srv/rocm), this discovery never mounts its runtime libraries, while _build_safe_env() also drops those path variables. The child still receives /dev/kfd but cannot load libamdhip64/HSA even if the host loader cache references them, so sandboxed PyTorch reports no usable AMD GPU; validate and bind the active configured ROCm root or its loader-resolved library directories.

Useful? React with 👍 / 👎.

Comment on lines +775 to +778
for name, mod in list(sys.modules.items()):
if not (name.startswith("__editable___") and name.endswith("_finder")):
continue
paths.extend(getattr(mod, "MAPPING", {}).values())

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 Gate user-site editable mappings on the opt-in

When the server interpreter has processed a PEP 660 editable install from the user's site-packages, its __editable___..._finder module is already present in sys.modules, so this unconditional loop adds and mounts the mapped source tree even when UNSLOTH_STUDIO_SANDBOX_ALLOW_USER_SITE is unset. Because the later HOME check permits paths below HOME, sandboxed code can read that user checkout despite the documented opt-in boundary; exclude finder modules originating in the user site unless the opt-in is enabled.

Useful? React with 👍 / 👎.

Comment thread install.sh
Comment on lines +2456 to +2457
if bubblewrap_usable; then
step "sandbox" "bubblewrap found (OS-level tool sandbox enabled)"

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 Make the installer use the production sandbox capability check

On GPU hosts where device access depends on a supplementary group and the installed Bubblewrap lacks --keep-groups, this minimal probe succeeds and prints that the OS sandbox is enabled, but sandbox.py:_linux_probe() explicitly returns false for the same host and all subsequent tool calls run through the unsandboxed fallback. The installer should mirror or invoke the production probe before reporting that sandboxing is enabled, especially because operators may rely on this status when deciding whether strict mode is necessary.

Useful? React with 👍 / 👎.

Comment on lines +351 to +356
bwrap = shutil.which("bwrap")
if bwrap is None:
logger.warning("bwrap not found on PATH; tool execution will run unsandboxed")
return _ProbeResult(ok = False)
bwrap = os.path.realpath(os.path.abspath(bwrap))
keep_groups = _bwrap_supports_keep_groups(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 Reject user-writable Bubblewrap binaries

When the parent PATH resolves bwrap from a user- or project-writable directory, this code probes and caches that executable without checking its ownership or writability. A fake wrapper can make the probe succeed and then run the payload after -- without confinement; if the cached binary lies in the writable project workdir, one sandboxed call can also replace it for the next call. Resolve Bubblewrap only from a trusted non-writable installation or retain a verified executable handle rather than trusting arbitrary parent-PATH entries.

Useful? React with 👍 / 👎.

@Etherll

Etherll commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

@codex review

1 similar comment
@Etherll

Etherll commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@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: 35190f8ffe

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

for rp in python_read_paths:
if _is_under_top_ro(rp):
continue
args.extend(["--ro-bind-try", rp, rp])

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 Exclude Unix sockets from external runtime binds

When a PEP 660 editable source or other Python runtime outside the session workdir contains a Unix-domain socket serviced by a host process, this read-only bind exposes that socket inside the sandbox. _assert_no_external_hardlinks() traverses only the workdir, and a read-only mount does not prevent connecting to a socket; because the network namespace does not isolate filesystem-named Unix sockets, sandboxed code can communicate with the host service. Filter special nodes from external runtime trees or expose those trees through a private copy rather than binding them verbatim.

Useful? React with 👍 / 👎.

@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: 2f03521665

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

Comment on lines +6914 to +6923
for selector in (
"CUDA_DEVICE_ORDER",
"CUDA_VISIBLE_DEVICES",
"HIP_VISIBLE_DEVICES",
"ROCR_VISIBLE_DEVICES",
"GPU_DEVICE_ORDINAL",
"NVIDIA_VISIBLE_DEVICES",
"ONEAPI_DEVICE_SELECTOR",
"ZE_AFFINITY_MASK",
):

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 Preserve required ROCm architecture overrides

On AMD hosts using generic multi-architecture ROCm wheels for an otherwise unsupported GPU, HSA_OVERRIDE_GFX_VERSION can be the only setting that makes the device usable, but this new accelerator-environment allowlist drops it from every sandboxed Python and terminal child. The repository explicitly preserves this override for generic wheels in tests/studio/test_cli_hsa_spoof_launch_7331.py:174-182; without forwarding it, ROCr sees the physical unsupported architecture and GPU experiments fail only inside tool execution. Preserve the validated non-secret override alongside the other ROCm selectors.

Useful? React with 👍 / 👎.

Comment on lines +1293 to +1294
(allow ipc-posix-shm)
(allow ipc-posix-sem)

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 Do not expose the host POSIX shared-memory namespace

On macOS, when another same-user process has a named POSIX shared-memory object or semaphore, these unfiltered allows let sandboxed code open that host-global object by name despite the default-deny profile. This can disclose or corrupt data exchanged by training workers and other applications, and unlike Linux there is no IPC namespace here separating those names; deny these operations or constrain them to sandbox-owned IPC rather than granting all POSIX shared memory and semaphores.

Useful? React with 👍 / 👎.

logger = get_logger(__name__)

_SANDBOX_EXEC = "/usr/bin/sandbox-exec"
_BWRAP_PROBE_BIN = os.path.realpath(os.path.abspath(shutil.which("true") or "/usr/bin/true"))

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 the probe payload from a trusted path

When the server starts with a user- or project-writable directory early on PATH, shutil.which("true") can select an attacker-controlled executable for the availability probe. Although the Bubblewrap binary itself is now validated, this payload runs with the parent environment and a read-only bind of the entire host root; it can therefore read credentials or communicate through host filesystem sockets before returning. Use a fixed, ownership-validated system executable for the probe rather than trusting the parent PATH.

Useful? React with 👍 / 👎.

with _sandbox_identity_lock:
if _sandbox_identity_paths is not None:
return _sandbox_identity_paths
identity_dir = tempfile.mkdtemp(prefix = "unsloth-studio-sandbox-identity-")

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 Keep identity bind sources outside writable workdirs

When the host TMPDIR points inside the selected project workdir, this creates the cached synthetic passwd/group files inside the directory later bound writable into every sandbox. A first tool call can replace either cached path with a symlink to an arbitrary host file; on the next call Bubblewrap follows that source symlink for --ro-bind and exposes the target as /etc/passwd or /etc/group, while the workdir scan deliberately skips symlinks. Create these trusted bind sources in a backend-private location that cannot overlap a sandbox workdir and revalidate them without following links before each bind.

Useful? React with 👍 / 👎.

@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: 9a029b8219

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

Comment thread install.sh
Comment on lines +2526 to +2528
"$@" --ro-bind / / --unshare-all --die-with-parent \
--proc /proc --dev /dev --tmpfs /tmp "$TRUE_BIN" \
</dev/null >/dev/null 2>&1

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 Probe libseccomp before reporting the sandbox enabled

On a Linux host where Bubblewrap works but libseccomp.so.2 is absent, this probe succeeds and the installer reports that the OS sandbox is enabled, while the production probe in sandbox.py calls _linux_socket_seccomp_fd() and returns unavailable when that library cannot load. Fresh evidence beyond the earlier installer capability-check comment is that the production probe now requires the Unix-socket seccomp filter, but this newly expanded installer probe still executes Bubblewrap without --seccomp; mirror that dependency check before printing the enabled status.

Useful? React with 👍 / 👎.

Comment on lines +514 to +520
socket_comparison = _ScmpArgCmp(0, compare_equal, 1, 0) # AF_UNIX
socket_result = lib.seccomp_rule_add(
context,
ctypes.c_uint32(errno_action),
ctypes.c_int(socket_syscall),
ctypes.c_uint(1),
socket_comparison,

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 Preserve private Unix sockets for multiprocessing

On Linux whenever sandboxed code uses multiprocessing.resource_sharer—including PyTorch tensor transfer between DataLoader workers—this blanket socket(AF_UNIX, ...) denial makes the sharer's private listener fail with EPERM, so common multi-worker training and preprocessing break only inside tool execution. The NPROC handling elsewhere explicitly intends to support multiprocessing; isolate host pathname sockets without prohibiting sandbox-owned Unix listeners.

Useful? React with 👍 / 👎.

Comment on lines +1560 to +1562
" _soft, hard = resource.getrlimit(resource.RLIMIT_NPROC)\n"
" target = nproc if hard == resource.RLIM_INFINITY else min(nproc, hard)\n"
" resource.setrlimit(resource.RLIMIT_NPROC, (target, target))\n"

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 Apply process limits independently of the host UID

On multi-tenant Linux hosts where the Studio UID already owns at least UNSLOTH_STUDIO_SANDBOX_NPROC tasks, setting RLIMIT_NPROC after entering the user namespace still leaves subsequent thread and process creation failing with EAGAIN: Linux accounts this limit against the underlying real UID, and a user namespace does not create a separate process counter. Thus moving the call into the wrapper does not avoid the host-UID collision described by _linux_inner_rlimit_wrapper; use a per-sandbox PID cgroup or another namespace-independent limit.

Useful? React with 👍 / 👎.

Comment on lines +1625 to +1630
exe = os.path.abspath(os.path.normpath(sys.executable))
script = _LINUX_NPROC_WRAPPER_TEMPLATE.format(nproc = _resolve_nproc_limit())
# Isolated mode keeps the model-writable CWD and PYTHONPATH from shadowing
# stdlib modules imported by this trusted wrapper. execvp then launches the
# requested command with its normal environment and import behavior.
return [exe, "-I", "-c", script, *inner_argv]

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 Disable site hooks in the trusted rlimit wrapper

When the selected project workdir contains the active virtual environment, sandboxed code can write an importing .pth file into that writable venv and have it execute during the next wrapper startup. Python's -I mode still processes system/venv site-packages and their .pth hooks before running -c, so such a hook can fork or exec another payload before this wrapper applies RLIMIT_NPROC, bypassing the intended process cap; start the trusted wrapper without site initialization (for example with -S) before importing only the required stdlib modules.

Useful? React with 👍 / 👎.

@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: 7977abcdb6

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

Comment on lines +1074 to +1077
if entry.is_file(follow_symlinks = True):
stem, extension = os.path.splitext(entry.name)
if extension == ".py" and stem.isidentifier():
return True

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 Recognize native modules in namespace scans

When a plain .pth root contains a PEP 420 namespace whose only importable leaf is a compiled extension (for example ns/sub/_native.cpython-313-x86_64-linux-gnu.so), this scan ignores the extension and returns false. _plain_pth_import_paths() consequently omits the top-level namespace directory from the sandbox mounts, so an import that works in the parent fails only during sandboxed execution; apply the same EXTENSION_SUFFIXES recognition used for top-level files while traversing namespace trees.

Useful? React with 👍 / 👎.

@Etherll

Etherll commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@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: b770bc7ae0

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

continue
alias = os.path.abspath(os.path.normpath(path))
resolved_candidates.append(alias)
resolved_candidates.append(os.path.realpath(alias))

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 writable editable symlinks before mounting targets

When an editable package path lies inside the writable project workdir, one tool call can replace that path—or add an import-shaped plain-.pth child—with a symlink to a host path such as ~/.ssh/id_rsa. On the next call this unconditional realpath promotes the symlink target into the Python read set; the later HOME check permits descendants of HOME, so Bubblewrap binds the credential file and Seatbelt explicitly allows it, making it readable through the workdir symlink. Do not mount resolved targets of model-writable aliases when they escape the workdir or another trusted runtime root.

Useful? React with 👍 / 👎.

Comment thread install.sh
BWRAP_BIN="$(command -v bwrap 2>/dev/null)" || return 1
bubblewrap_path_trusted "$BWRAP_BIN" || return 1
PYTHON_BIN="$(command -v python3 2>/dev/null)" || return 1
bubblewrap_path_trusted "$PYTHON_BIN" || return 1

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 Avoid overwriting the validated Bubblewrap path

On every Linux/WSL install where both executables pass validation, this second call to bubblewrap_path_trusted overwrites the global BWRAP_BIN with the resolved Python path because the helper always assigns that variable. The subsequent probe therefore invokes python3 --ro-bind ... instead of Bubblewrap, fails, and always reports a working or newly installed Bubblewrap as unavailable; preserve the first validated path or return the resolved path without mutating BWRAP_BIN.

Useful? React with 👍 / 👎.

kind = "literal" if os.path.isfile(path) else "subpath"
return f'({kind} "{_safe_subpath(path)}")'

py_subpaths = [_path_clause(path) for path in python_read_paths]

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 Allow macOS Python to enumerate plain .pth roots

On macOS with a plain-path editable install, the child receives the editable source root on PYTHONPATH, but this profile derives read permissions only from _python_read_paths(), which intentionally contains the root's importable children rather than the root itself. Python's FileFinder enumerates each sys.path directory before resolving those children, and the profile's global file-read-metadata permission does not permit directory listing, so otherwise valid editable modules fail to import under Seatbelt. Permit reading the source directory entry itself without exposing sibling file contents, or provide an import path that does not require enumerating the unmounted root.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

Superseded by #10285.

This branch had the Linux Bubblewrap and macOS Seatbelt backends only. #10285 covers both of those plus a Windows backend (AppContainer for Required, a write-restricted token for Limited), a per-host capability probe so each machine reports what it can actually enforce, a network allowlist proxy for pip and Hugging Face, and fail-closed tiers with an execution record. It rewrites the same functions in os_sandbox.py and tools.py, so the two are not compatible side by side.

Closing here; the work continues on #10285.

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.

3 participants