Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: minimal OS sandbox for Python and Terminal tools on Linux and macOS (#11209)

oobabooga588c7df9498a
diff --git a/.github/workflows/studio-backend-ci.yml b/.github/workflows/studio-backend-ci.yml
index 97e974133da..3899fa75728 100644
--- a/.github/workflows/studio-backend-ci.yml
+++ b/.github/workflows/studio-backend-ci.yml
@@ -62,6 +62,7 @@ on:
- '.github/workflows/docker-publish.yml'
- '.pre-commit-config.yaml'
- '.github/workflows/studio-backend-ci.yml'
+ - '.github/scripts/retry-with-apt-lock.sh'
# tests/python/test_amd_extras_contract.py asserts against this file.
- '.github/workflows/security-audit.yml'
push:
@@ -80,6 +81,7 @@ on:
- '.github/workflows/docker-publish.yml'
- '.pre-commit-config.yaml'
- '.github/workflows/studio-backend-ci.yml'
+ - '.github/scripts/retry-with-apt-lock.sh'
- '.github/workflows/security-audit.yml'
concurrency:
@@ -270,6 +272,31 @@ jobs:
pyproject.toml
studio/backend/requirements/*.txt
+ - name: Install bubblewrap, so the sandbox tests run instead of skipping
+ # Bound apt retries; 25 minutes covers both calls' 1450s worst case.
+ timeout-minutes: 25
+ env:
+ RETRY_ATTEMPTS: '2'
+ RETRY_ATTEMPT_TIMEOUT: '300'
+ run: |
+ bash .github/scripts/retry-with-apt-lock.sh sudo sh -c \
+ 'apt-get install -y --no-install-recommends bubblewrap || { apt-get update && apt-get install -y --no-install-recommends bubblewrap; }'
+ # Ubuntu 24.04 restricts user namespaces. Apply the recommended bwrap
+ # AppArmor profile without disabling the host restriction.
+ if [ "$(cat /proc/sys/kernel/apparmor_restrict_unprivileged_userns 2>/dev/null || echo 0)" = "1" ]; then
+ bash .github/scripts/retry-with-apt-lock.sh sudo sh -c \
+ 'apt-get install -y --no-install-recommends apparmor-profiles || { apt-get update && apt-get install -y --no-install-recommends apparmor-profiles; }'
+ # The package ships the profile disabled, under extra-profiles; it has to be copied in to load.
+ [ -f /etc/apparmor.d/bwrap-userns-restrict ] || sudo install -m 644 /usr/share/apparmor/extra-profiles/bwrap-userns-restrict /etc/apparmor.d/ || true
+ sudo apparmor_parser -r /etc/apparmor.d/bwrap-userns-restrict || true
+ fi
+ # Report unavailable isolation so host-dependent skips are explicit.
+ if bwrap --ro-bind / / --unshare-user true; then
+ echo "bubblewrap can build a sandbox on this runner"
+ else
+ echo "::warning::bubblewrap cannot build a sandbox here; confinement tests will skip"
+ fi
+
- name: Install backend test dependencies (CPU only)
run: |
python -m pip install --upgrade pip
diff --git a/install.sh b/install.sh
index ee3ca5df0e5..34c1f2deda6 100755
--- a/install.sh
+++ b/install.sh
@@ -1347,6 +1347,8 @@ _is_pkg_installed() {
command -v dpkg >/dev/null 2>&1 && dpkg -s "$1" >/dev/null 2>&1 ;;
pciutils)
command -v lspci >/dev/null 2>&1 ;;
+ bubblewrap)
+ command -v bwrap >/dev/null 2>&1 ;;
*) command -v "$1" >/dev/null 2>&1 ;;
esac
}
@@ -3177,12 +3179,65 @@ _check_linux_deps() {
return 0
}
+# Keep in step with os_sandbox._BWRAP_APPARMOR_FIX.
+_BWRAP_APPARMOR_FIX="sudo apt-get install -y apparmor-profiles && sudo install -m 644 /usr/share/apparmor/extra-profiles/bwrap-userns-restrict /etc/apparmor.d/ && sudo apparmor_parser -r /etc/apparmor.d/bwrap-userns-restrict"
+
+# The command that installs bubblewrap here; keep in step with os_sandbox._BWRAP_INSTALL_COMMANDS.
+_bwrap_install_command() {
+ if command -v apt-get >/dev/null 2>&1; then echo "sudo apt-get install -y bubblewrap"
+ elif command -v dnf >/dev/null 2>&1; then echo "sudo dnf install -y bubblewrap"
+ elif command -v pacman >/dev/null 2>&1; then echo "sudo pacman -S --needed bubblewrap"
+ elif command -v zypper >/dev/null 2>&1; then echo "sudo zypper install -y bubblewrap"
+ elif command -v apk >/dev/null 2>&1; then echo "sudo apk add bubblewrap"
+ fi
+}
+
+# Wanted, never required: bubblewrap runs Python and Terminal tool calls in an OS sandbox, and without it they run with software safeguards. Optional like the build tools, so it never asks for sudo: installed when the installer already runs as root, otherwise the one command is printed.
+_check_linux_tool_sandbox() {
+ _bw_restrict=""
+ # read, not cat: a builtin, so a minimal image without coreutils still gets the right advice.
+ read -r _bw_restrict <"${_BW_USERNS_SYSCTL:-/proc/sys/kernel/apparmor_restrict_unprivileged_userns}" 2>/dev/null || true
+ if ! command -v bwrap >/dev/null 2>&1 && command -v apt-get >/dev/null 2>&1; then
+ ( _SMART_APT_OPTIONAL=true; _smart_apt_install bubblewrap ) || true
+ fi
+ if ! command -v bwrap >/dev/null 2>&1; then
+ step "sandbox" "bubblewrap not installed: tool calls run with software safeguards" "$C_WARN"
+ _bw_cmd="$(_bwrap_install_command)"
+ # One copy-paste on Ubuntu 23.10+: installing bwrap alone still leaves it blocked there.
+ case "$_bw_restrict:$_bw_cmd" in
+ 1:*apt-get*) _bw_cmd="$_bw_cmd && $_BWRAP_APPARMOR_FIX" ;;
+ esac
+ if [ -n "$_bw_cmd" ]; then
+ substep "To run them in an OS sandbox: $_bw_cmd"
+ else
+ substep "To run them in an OS sandbox, install bubblewrap with your package manager."
+ fi
+ return 0
+ fi
+ # The runtime's namespaces, not --unshare-all: that adds the network namespace, which tool calls never get.
+ if bwrap --unshare-user --unshare-pid --unshare-ipc --unshare-uts --unshare-cgroup --ro-bind / / true </dev/null >/dev/null 2>&1; then
+ step "sandbox" "bubblewrap works: tool calls run in an OS sandbox"
+ return 0
+ fi
+ if [ "$_bw_restrict" = 1 ]; then
+ step "sandbox" "AppArmor blocks bubblewrap: tool calls run with software safeguards" "$C_WARN"
+ # Ubuntu ships this profile disabled in apparmor-profiles; it lets /usr/bin/bwrap create the namespace and strips its children's capabilities.
+ substep "To enable it, load Ubuntu's own bwrap profile:"
+ substep " $_BWRAP_APPARMOR_FIX"
+ else
+ step "sandbox" "bubblewrap cannot create a sandbox here: tool calls run with software safeguards" "$C_WARN"
+ substep "Containers usually block user namespaces; outside one, check user.max_user_namespaces."
+ fi
+ return 0
+}
+
case "$OS" in
macos)
_check_macos_deps || exit 1
;;
linux|wsl)
_check_linux_deps || exit 1
+ _check_linux_tool_sandbox || true
;;
esac
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index fdc3ccf9f88..9d4619e71a9 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -37361,7 +37361,14 @@ class LlamaCppBackend:
# outlives the closure.
_last_result_budget: list = ["<not passed>"]
- def _invoke_tool(_output_callback, _decision = decision):
+ # Only a call the user answered: the executor lets it reach the host paths it names.
+ _host_access_approved = _decision not in (None, "deny")
+
+ def _invoke_tool(
+ _output_callback,
+ _decision = decision,
+ _approved = _host_access_approved,
+ ):
# execute_tool is injectable and may be monkey-patched with the
# pre-PR signature; forward output_callback only if it's accepted.
kwargs = dict(
@@ -37377,6 +37384,8 @@ class LlamaCppBackend:
# forced recall correctly refused.
if accepts_kwarg(execute_tool, "conversation_branch"):
kwargs["conversation_branch"] = _extend_live_branch(conversation)
+ if _approved and accepts_kwarg(execute_tool, "host_access_approved"):
+ kwargs["host_access_approved"] = True
# And the room actually left: the model picks its own top_k and
# the result lands in the current tool exchange, which rolling
# truncation protects, so a top_k the window cannot hold ends
diff --git a/studio/backend/core/inference/os_sandbox.py b/studio/backend/core/inference/os_sandbox.py
new file mode 100644
index 00000000000..79003997324
--- /dev/null
+++ b/studio/backend/core/inference/os_sandbox.py
@@ -0,0 +1,955 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Studio tool launch contract and the OS-isolation backends (bwrap, Seatbelt)."""
+
+from __future__ import annotations
+import errno
+import functools
+import hashlib
+import os
+import platform
+import re
+import shutil
+import stat
+import subprocess
+import sys
+import threading
+import time
+from dataclasses import dataclass, field
+from typing import Any, BinaryIO, Callable, Literal
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+ToolExecutionMode = Literal["auto", "required", "full"]
+TOOL_EXECUTION_MODES = ("auto", "required", "full")
+
+PROFILE_VERSION = "unsloth-sandbox-v1"
+
+# tools.py re-adds this only to an UNISOLATED launch, and only if it already exists.
+SESSION_PACKAGES_RELPATH = ".unsloth-packages"
+
+
+def with_session_packages(env: dict, workdir: str) -> dict:
+ """Reuse existing session packages without letting their binaries shadow PATH."""
+ packages = os.path.join(workdir, SESSION_PACKAGES_RELPATH)
+ if not os.path.isdir(packages):
+ return env
+ updated = dict(env)
+ # Block a planted usercustomize.py; in safe mode the trusted sitecustomize shim stays first on PYTHONPATH.
+ updated["PYTHONNOUSERSITE"] = "1"
+ # pip --target puts console scripts in Scripts on Windows and bin elsewhere.
+ scripts = "Scripts" if os.name == "nt" else "bin"
+ for key, value in (
+ ("PYTHONPATH", packages),
+ ("PATH", os.path.join(packages, scripts)),
+ ):
+ updated[key] = os.pathsep.join(part for part in (updated.get(key, ""), value) if part)
+ return updated
+
+
+_SOFTWARE_SAFEGUARDS = (
+ "process_guard",
+ "command_and_code_analysis",
+ "sanitized_environment",
+ "resource_limits",
+ "descriptor_closure",
+ "workdir_policy",
+ "streaming",
+ "timeout",
+ "cancellation",
+ "reaping",
+ "cleanup",
+)
+_OS_ISOLATION_SAFEGUARDS = _SOFTWARE_SAFEGUARDS + ("filesystem_isolation", "process_isolation")
+_FULL_SAFEGUARDS = ("timeout", "cancellation", "reaping", "cleanup")
+
+
+class SandboxUnavailableError(RuntimeError):
+ """OS isolation is unavailable or the requested launch was refused."""
+
+ def __init__(
+ self,
+ message: str = "",
+ *,
+ remediation: str = "",
+ ) -> None:
+ super().__init__(message)
+ self.remediation = remediation
+
+
+class WorkdirUnsafeError(SandboxUnavailableError):
+ """Distinguished by type: a transient probe failure must not re-open the channel the scan found."""
+
+
+class SandboxBuildError(SandboxUnavailableError):
+ """Refused, never fallen back: the errno is reachable from inside the jail."""
+
+
+@dataclass(frozen = True)
+class SandboxCapability:
+ """``available`` is never inferred from the binary existing: user namespaces may still be denied."""
+
+ backend: str
+ available: bool
+ reason: str
+ environment: str = "unknown"
+ protection_state: str = "unavailable"
+ profile_id: str = "none"
+ limitations: tuple[str, ...] = ()
+ probe_generation: str = ""
+ environment_fingerprint: str = ""
+ remediation: str = ""
+
+
+@dataclass(frozen = True)
+class ToolExecutionRecord:
+ """Record the requested policy and the isolation and safeguards actually applied."""
+
+ requested_mode: ToolExecutionMode
+ effective_mode: str
+ environment: str
+ backend: str
+ profile_id: str
+ probe_generation: str
+ os_isolation: bool
+ retained_safeguards: tuple[str, ...]
+ limitations: tuple[str, ...] = ()
+ network_policy: str = "unrestricted"
+
+ def as_dict(self) -> dict[str, object]:
+ return {
+ "requested_mode": self.requested_mode,
+ "effective_mode": self.effective_mode,
+ "environment": self.environment,
+ "backend": self.backend,
+ "profile_id": self.profile_id,
+ "probe_generation": self.probe_generation,
+ "os_isolation": self.os_isolation,
+ "retained_safeguards": list(self.retained_safeguards),
+ "limitations": list(self.limitations),
+ "network_policy": self.network_policy,
+ }
+
+
+@dataclass(frozen = True)
+class ToolLaunchPlan:
+ argv: tuple[str, ...]
+ workdir: str
+ env: dict[str, str]
+ preexec_fn: Callable[[], None] | None = None
+ requested_mode: ToolExecutionMode = "auto"
+ timeout_seconds: int | None = None
+ close_fds: bool = True
+ terminate_descendants: bool = True
+ # Set by the trusted tool owner, never inferred from model args.
+ execution_kind: Literal["python", "terminal"] | None = None
+
+
+@dataclass
+class PreparedSandboxLaunch:
+ argv: tuple[str, ...]
+ workdir: str
+ env: dict[str, str]
+ preexec_fn: Callable[[], None] | None
+ backend: str
+ execution_record: ToolExecutionRecord | None = None
+ pass_fds: tuple[int, ...] = ()
+ owned_files: list[BinaryIO] = field(default_factory = list)
+ cleanup_paths: list[str] = field(default_factory = list)
+ timeout_seconds: int | None = None
+ close_fds: bool = True
+ terminate_descendants: bool = True
+ cleanup_callbacks: list[Callable[[], None]] = field(default_factory = list)
+ cleanup_diagnostics: list[str] = field(default_factory = list)
+ launch_limitations: tuple[str, ...] = ()
+
+ def cleanup(self) -> None:
+ while self.cleanup_callbacks:
+ callback = self.cleanup_callbacks.pop()
+ try:
+ callback()
+ except Exception as exc: # noqa: BLE001 - cleanup continues in LIFO order
+ diagnostic = f"{type(exc).__name__}: {exc}"
+ self.cleanup_diagnostics.append(diagnostic)
+ logger.warning("Sandbox cleanup failed: %s", diagnostic, exc_info = True)
+ while self.owned_files:
+ try:
+ self.owned_files.pop().close()
+ except Exception as exc: # noqa: BLE001 - cleanup must continue
+ diagnostic = f"{type(exc).__name__}: {exc}"
+ self.cleanup_diagnostics.append(diagnostic)
+ logger.warning("Could not close sandbox-owned file: %s", diagnostic, exc_info = True)
+ while self.cleanup_paths:
+ path = self.cleanup_paths.pop()
+ try:
+ shutil.rmtree(path)
+ except OSError:
+ self.cleanup_diagnostics.append(f"could not remove private sandbox path: {path}")
+ logger.warning("Could not remove private sandbox path %s", path, exc_info = True)
+
+
+def spawn_prepared_launch(prepared: PreparedSandboxLaunch, **popen_kwargs: Any) -> object:
+ return subprocess.Popen(prepared.argv, **popen_kwargs)
+
+
+# `auto` launches on this, `required` refuses; one name so both readers agree.
+WORKDIR_SCAN_INCOMPLETE = "workdir_scan_incomplete"
+WORKDIR_SCAN_ENTRIES = 50_000
+WORKDIR_SCAN_SECONDS = 5.0
+CACHE_SCAN_ENTRIES = 50_000
+CACHE_SCAN_SECONDS = 3.0
+_SCAN_JOIN_GRACE_SECONDS = 0.5
+
+TOOL_TEMP_DIRNAME = "unsloth-tmp"
+TOOL_TEMP_MODE = 0o700
+
+
+class _ScanBudgetExceeded(Exception):
+ """The walk ran out of budget: not a hazard, so it must not refuse an `auto` launch."""
+
+
+def directory_signature(path: str) -> tuple:
+ """Identity plus mtime for one directory, the unit a cached verdict is re-checked in."""
+ try:
+ info = os.stat(path)
+ except OSError:
+ return (path, None)
+ return (path, info.st_dev, info.st_ino, info.st_mtime_ns)
+
+
+def directory_witness_matches(witness: "list[tuple]") -> bool:
+ """Whether every directory a finished scan visited is still as it left it."""
+ return all(directory_signature(entry[0]) == entry for entry in witness)
+
+
+def _host_channel_hazard(
+ root: str,
+ max_entries: int,
+ seconds: float,
+ witness: "list[tuple] | None" = None,
+) -> str | None:
+ """Return a host-access hazard under *root*, or None."""
+ deadline = time.monotonic() + seconds
+ entries = 0
+ # Only an unaccounted hard link leads outside; cp -al, git clone --local and pip make nlink > 1.
+ links: dict[tuple[int, int], list] = {}
+ unreadable: list[str] = []
+
+ for base, dirs, names in os.walk(
+ root, followlinks = False, onerror = lambda exc: unreadable.append(exc.filename or root)
+ ):
+ if witness is not None:
+ witness.append(directory_signature(base))
+ if unreadable:
+ return f"{unreadable[0]} cannot be fully inspected"
+ for name in (*dirs, *names):
+ entries += 1
+ if entries > max_entries or time.monotonic() > deadline:
+ raise _ScanBudgetExceeded(
+ f"could not be fully checked for host channels "
+ f"(over {max_entries} entries or {seconds:.0f}s)"
+ )
+ path = os.path.join(base, name)
+ try:
+ info = os.lstat(path)
+ except OSError:
+ return f"changed during its safety scan: {path}"
+ if stat.S_ISLNK(info.st_mode):
+ continue
+ if stat.S_ISDIR(info.st_mode):
+ # Misses a same-filesystem bind mount; Linux also asks the mount table.
+ if os.path.ismount(path):
+ return f"contains a nested host mount: {path}"
+ continue
+ if not stat.S_ISREG(info.st_mode):
+ return f"contains a device or IPC node: {path}"
+ if info.st_nlink > 1:
+ found = links.setdefault((info.st_dev, info.st_ino), [0, info.st_nlink, path])
+ found[0] += 1
+ if unreadable:
+ return f"{unreadable[0]} cannot be fully inspected"
+ for found, total, path in links.values():
+ if found < total:
+ return f"contains a file hard-linked from outside it: {path}"
+ return None
+
+
+_scan_lock = threading.Lock()
+# root -> (worker, answer, budget, deadline) of the walk in flight, so a concurrent launch shares it.
+_scan_pending: "dict[str, tuple[threading.Thread, list, list, float]]" = {}
+
+
+def _hazard_within_wall_clock(
+ root: str,
+ max_entries: int,
+ seconds: float,
+ prepare: "Callable[[float], None] | None" = None,
+) -> str | None:
+ """Scan on a worker so the budget is wall-clock: scandir/lstat on a stalled mount cannot be interrupted."""
+ with _scan_lock:
+ pending = _scan_pending.get(root)
+ if pending is not None and not pending[0].is_alive():
+ del _scan_pending[root]
+ pending = None
+ if pending is None:
+ answer: list[str | None] = []
+ budget: list[str] = []
+ deadline = time.monotonic() + seconds
+
+ def inspect() -> None:
+ try:
+ if prepare is not None:
+ prepare(deadline)
+ answer.append(
+ _host_channel_hazard(
+ root, max_entries, max(0.1, deadline - time.monotonic())
+ )
+ )
+ except _ScanBudgetExceeded as exc:
+ budget.append(str(exc))
+ except Exception as exc: # noqa: BLE001 - reported, never raised at the caller
+ budget.append(f"could not be checked for host channels: {exc}")
+
+ worker = threading.Thread(target = inspect, name = "unsloth-workdir-scan", daemon = True)
+ # Register under the lock, or a concurrent caller starts a second walk.
+ pending = (worker, answer, budget, deadline)
+ _scan_pending[root] = pending
+ worker.start()
+ worker, answer, budget, deadline = pending
+
+ # Waits only out the walk's own budget: a walk a previous launch gave up on is past it already.
+ worker.join(max(0.0, deadline + _SCAN_JOIN_GRACE_SECONDS - time.monotonic()))
+ with _scan_lock:
+ # By identity: another caller may already have replaced the entry.
+ if not worker.is_alive() and _scan_pending.get(root) is pending:
+ del _scan_pending[root]
+ if budget:
+ raise _ScanBudgetExceeded(budget[0])
+ if not answer:
+ raise _ScanBudgetExceeded(
+ f"did not finish its host-channel check within {seconds:.0f}s (a wedged mount?)"
+ )
+ return answer[0]
+
+
+def _looks_like_our_scratch_dir(path: str) -> bool:
+ """Whether this directory was created the way tools.py creates one."""
+ try:
+ info = os.stat(path)
+ except OSError:
+ return False
+ if hasattr(os, "getuid") and info.st_uid != os.getuid():
+ return False
+ if sys.platform == "win32":
+ return True
+ return stat.S_IMODE(info.st_mode) == TOOL_TEMP_MODE
+
+
+def _ipc_endpoint_is_dead(path: str) -> bool:
+ """Whether nothing is listening on this socket; False for anything the probe cannot settle."""
+ verdict = _unix_socket_is_refused(path)
+ if verdict is None:
+ # sun_path is 108 bytes: reach long paths through a temporary symlink alias.
+ import tempfile
+ alias_dir = None
+ try:
+ alias_dir = tempfile.mkdtemp(prefix = "unsloth-ipc-")
+ alias = os.path.join(alias_dir, "d")
+ os.symlink(os.path.dirname(path), alias)
+ verdict = _unix_socket_is_refused(os.path.join(alias, os.path.basename(path)))
+ except OSError:
+ verdict = None
+ finally:
+ if alias_dir is not None:
+ shutil.rmtree(alias_dir, ignore_errors = True)
+ return bool(verdict)
+
+
+def _unix_socket_is_refused(path: str) -> bool | None:
+ """True if nothing is listening, False if something is, None if undecided."""
+ import socket
+
+ probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ try:
+ probe.settimeout(0.2)
+ probe.connect(path)
+ except OSError as exc:
+ if exc.errno == errno.ECONNREFUSED:
+ return True
+ # errno None is CPython's own path-too-long check, not a live endpoint.
+ if exc.errno is None or exc.errno in (errno.ENAMETOOLONG, errno.ENOENT):
+ return None
+ return False
+ finally:
+ probe.close()
+ return False
+
+
+def clear_stale_tool_ipc(workdir: str, deadline: "float | None" = None) -> tuple[str, ...]:
+ """Remove dead sockets from Studio's own 0700 scratch dir; FIFOs are never swept (idle is their normal state)."""
+ scratch = os.path.join(workdir, TOOL_TEMP_DIRNAME)
+ removed: list[str] = []
+ try:
+ if not os.path.isdir(scratch) or os.path.islink(scratch):
+ return ()
+ if not _looks_like_our_scratch_dir(scratch):
+ return ()
+ for base, dirs, names in os.walk(scratch, followlinks = False):
+ dirs[:] = [name for name in dirs if not os.path.ismount(os.path.join(base, name))]
+ for name in names:
+ if deadline is not None and time.monotonic() > deadline:
+ logger.info("Stopped sweeping the tool scratch directory at its deadline")
+ return tuple(removed)
+ path = os.path.join(base, name)
+ try:
+ entry = os.lstat(path)
+ except OSError:
+ continue
+ mode = entry.st_mode
+ if not stat.S_ISSOCK(mode):
+ continue
+ if entry.st_nlink > 1:
+ # Another link exists: removing this name would hide the walk's hard-link finding.
+ continue
+ if not _ipc_endpoint_is_dead(path):
+ logger.info(
+ "Leaving a live IPC endpoint in the tool scratch directory: %s", path
+ )
+ continue
+ try:
+ os.unlink(path)
+ except OSError:
+ continue
+ removed.append(path)
+ except OSError:
+ return tuple(removed)
+ if removed:
+ logger.info(
+ "Removed %d stale IPC endpoint(s) left in the tool scratch directory: %s",
+ len(removed),
+ ", ".join(removed[:5]),
+ )
+ return tuple(removed)
+
+
+def scan_workdir_for_host_channels(workdir: str) -> tuple[str, ...]:
+ """Scan the writable workdir: a hazard fails the call, an overrun budget is recorded, not refused."""
+ try:
+ hazard = _hazard_within_wall_clock(
+ workdir,
+ WORKDIR_SCAN_ENTRIES,
+ WORKDIR_SCAN_SECONDS,
+ prepare = lambda deadline: clear_stale_tool_ipc(workdir, deadline),
+ )
+ except _ScanBudgetExceeded as exc:
+ logger.warning("The session workdir %s: %s", workdir, exc)
+ return (WORKDIR_SCAN_INCOMPLETE,)
+ if hazard is not None:
+ raise WorkdirUnsafeError(f"the session workdir {hazard}")
+ return ()
+
+
+def cache_share_hazard(path: str, witness: "list[tuple] | None" = None) -> str | None:
+ """Return a reason not to share this writable cache component, or None."""
+ try:
+ return _host_channel_hazard(path, CACHE_SCAN_ENTRIES, CACHE_SCAN_SECONDS, witness)
+ except _ScanBudgetExceeded as exc:
+ return str(exc)
+
+
+_LINUX_REQUIRED_BINARIES = ("bwrap",)
+_FALLBACK_NOTE = "Python and Terminal still run, with software safeguards only and no OS isolation."
+
+
[email protected]_cache(maxsize = 1)
+def _linux_userns_blocked_by_apparmor() -> bool:
+ """Whether Ubuntu's apparmor_restrict_unprivileged_userns denies bwrap's user namespace (cached)."""
+ try:
+ with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", encoding = "utf-8") as f:
+ if f.read().strip() != "1":
+ return False
+ except OSError:
+ return False
+ # The sysctl alone is not proof: a profile may permit bwrap.
+ try:
+ probe = subprocess.run(
+ ["unshare", "--user", "--map-root-user", "true"],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.DEVNULL,
+ timeout = 10,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return False
+ return probe.returncode != 0
+
+
[email protected]_cache(maxsize = 1)
+def editable_source_roots() -> tuple[str, ...]:
+ """Editable code outside site-packages, from PEP 610 records shared by .pth and PEP 660 installs."""
+ roots: list[str] = []
+ try:
+ from importlib import metadata
+ import json
+ from urllib.parse import unquote, urlparse
+ except Exception: # noqa: BLE001 - never fail a launch over this
+ return ()
+ try:
+ distributions = list(metadata.distributions())
+ except Exception: # noqa: BLE001
+ return ()
+ for dist in distributions:
+ try:
+ raw = dist.read_text("direct_url.json")
+ if not raw:
+ continue
+ record = json.loads(raw)
+ if not record.get("dir_info", {}).get("editable"):
+ continue
+ parsed = urlparse(record.get("url", ""))
+ if parsed.scheme != "file":
+ continue
+ path = os.path.abspath(unquote(parsed.path))
+ except Exception: # noqa: BLE001 - a malformed record is not a launch failure
+ continue
+ if path in ("/", "/usr") or not os.path.isdir(path):
+ continue
+ for importable in _importable_entries(path, _declared_names(dist)):
+ if importable not in roots:
+ roots.append(importable)
+ return tuple(roots)
+
+
+def model_library_roots() -> tuple[str, ...]:
+ """Registered model folders the approval gate reads silently; NOT the whole read-silent set, which has /etc."""
+ try:
+ from . import tool_path_approval
+ from utils.paths.storage_roots import well_known_model_dirs
+ candidates = (
+ *tool_path_approval._scan_folder_roots(),
+ *well_known_model_dirs(),
+ )
+ except Exception: # noqa: BLE001 - never fail a launch over the approval gate
+ return ()
+ state = studio_state_roots()
+ forbidden = _never_a_model_library()
+ kept: list[str] = []
+ for path in candidates:
+ if not path or not os.path.isabs(path):
+ continue
+ real = os.path.realpath(path)
+ # Refuse a registered folder that is a root, a home, the homes parent, or a system directory.
+ if _is_filesystem_root(real) or not os.path.isdir(real):
+ continue
+ if os.path.normcase(real) in forbidden:
+ continue
+ # The approval gate still asks for a credential inside a model folder; a whole-folder grant would not.
+ if tool_path_approval._references_sensitive_path(real + os.sep):
+ continue
+ if any(_paths_overlap(real, root) for root in state):
+ continue
+ if real not in kept:
+ kept.append(real)
+ return tuple(kept)
+
+
+def _is_filesystem_root(path: str, pathmod: Any = None) -> bool:
+ """Whether *path* is a filesystem root; not ``path == os.sep``, which misses Windows drive roots."""
+ return (pathmod or os.path).dirname(path) == path
+
+
+_NEVER_A_MODEL_LIBRARY = (
+ "/",
+ "/etc",
+ "/usr",
+ "/var",
+ "/opt",
+ "/bin",
+ "/lib",
+ "/home",
+ "/Users",
+ "/root",
+ "/tmp",
+)
+
+_WINDOWS_SYSTEM_VARS = (
+ "SystemRoot",
+ "windir",
+ "ProgramFiles",
+ "ProgramFiles(x86)",
+ "ProgramW6432",
+ "ProgramData",
+ "PUBLIC",
+)
+
+
+def _never_a_model_library() -> frozenset[str]:
+ """Normcased real paths no registered folder may grant, root included."""
+ paths = list(_NEVER_A_MODEL_LIBRARY)
+ try:
+ home = os.path.realpath(os.path.expanduser("~"))
+ except OSError:
+ home = ""
+ if home:
+ paths.extend((home, os.path.dirname(home)))
+ for name in _WINDOWS_SYSTEM_VARS:
+ value = (os.environ.get(name) or "").strip()
+ if value and os.path.isabs(value):
+ paths.append(os.path.realpath(value))
+ return frozenset(os.path.normcase(path) for path in paths if path)
+
+
+def _paths_overlap(first: str, second: str) -> bool:
+ """Whether either path is the other, or contains it."""
+ try:
+ common = os.path.commonpath([first, second])
+ except ValueError:
+ return False
+ return common in (first, second)
+
+
+def studio_state_roots() -> tuple[str, ...]:
+ """Studio's persisted-state home (auth.db); denied because it may sit under a granted root such as Docker's /opt."""
+ roots: list[str] = []
+ try:
+ from utils.paths.storage_roots import studio_root
+ roots.append(os.path.realpath(str(studio_root())))
+ except Exception: # noqa: BLE001 - a launch never fails over this
+ pass
+ for name in ("UNSLOTH_STUDIO_HOME", "STUDIO_HOME"):
+ value = (os.environ.get(name) or "").strip()
+ if value:
+ roots.append(os.path.realpath(os.path.expanduser(value)))
+ return tuple(dict.fromkeys(path for path in roots if path and path != os.sep))
+
+
[email protected]_cache(maxsize = 1)
+def editable_import_roots() -> tuple[str, ...]:
+ """Import roots need listing: bwrap creates empty parents, Seatbelt needs literal grants."""
+ return tuple(dict.fromkeys(os.path.dirname(path) for path in editable_source_roots()))
+
+
+def _declared_names(dist) -> frozenset[str]:
+ """Declared names also identify PEP 420 namespaces, which have no __init__.py."""
+ names: set[str] = set()
+ try:
+ raw = dist.read_text("top_level.txt") or ""
+ names.update(line.strip() for line in raw.splitlines() if line.strip())
+ except Exception: # noqa: BLE001 - a missing or unreadable record is not fatal
+ pass
+ try:
+ project = (dist.metadata["Name"] or "").strip()
+ except Exception: # noqa: BLE001
+ project = ""
+ if project:
+ names.add(re.sub(r"[-_.]+", "_", project).lower())
+ return frozenset(name for name in names if name and "/" not in name and name != "..")
+
+
+def _within_root(path: str, root: str) -> bool:
+ """Whether *path* stays under *root* once resolved, by whole components."""
+ resolved, base = os.path.realpath(path), os.path.realpath(root)
+ return resolved == base or resolved.startswith(base.rstrip(os.sep) + os.sep)
+
+
+def _importable_entries(
+ project_root: str, declared: frozenset[str] = frozenset()
+) -> tuple[str, ...]:
+ """Grant package entries, never the checkout's .env, .git or unrelated fixtures."""
+ import_roots = [
+ entry
+ for entry in sys.path
+ if entry
+ and (
+ os.path.abspath(entry) == project_root
+ or os.path.abspath(entry).startswith(project_root + os.sep)
+ )
+ ]
+ # A PEP 660 finder puts nothing on sys.path, so fall back to the common layouts.
+ guessed = [
+ fallback
+ for fallback in (project_root, os.path.join(project_root, "src"))
+ if fallback not in import_roots and os.path.isdir(fallback)
+ ]
+ found: list[str] = []
+ for import_root in (*import_roots, *guessed):
+ try:
+ names = sorted(os.listdir(import_root))
+ except OSError:
+ continue
+ for name in names:
+ if name.startswith(".") or name.endswith((".egg-info", ".dist-info")):
+ continue
+ entry = os.path.join(import_root, name)
+ declared_here = name in declared or name.removesuffix(".py") in declared
+ if import_root in guessed and not declared_here:
+ continue
+ # Both backends grant resolved targets, so a declared symlink must stay in the checkout.
+ if not _within_root(entry, project_root):
+ continue
+ package = os.path.isdir(entry) and (
+ declared_here or os.path.exists(os.path.join(entry, "__init__.py"))
+ )
+ module = name.endswith(".py") and (declared_here or os.path.isfile(entry))
+ if (package or module) and entry not in found:
+ found.append(entry)
+ return tuple(found)
+
+
+# Measured on Ubuntu 24.04: apparmor-profiles ships this profile disabled, under extra-profiles.
+_BWRAP_APPARMOR_FIX = (
+ "sudo apt-get install -y apparmor-profiles && sudo install -m 644 "
+ "/usr/share/apparmor/extra-profiles/bwrap-userns-restrict /etc/apparmor.d/ && "
+ "sudo apparmor_parser -r /etc/apparmor.d/bwrap-userns-restrict"
+)
+
+# First match wins: an apt host with dnf also on PATH is still apt-managed.
+_BWRAP_INSTALL_COMMANDS = (
+ ("apt-get", "sudo apt-get install -y bubblewrap"),
+ ("dnf", "sudo dnf install -y bubblewrap"),
+ ("pacman", "sudo pacman -S --needed bubblewrap"),
+ ("zypper", "sudo zypper install -y bubblewrap"),
+ ("apk", "sudo apk add bubblewrap"),
+)
+
+
+def bwrap_install_command() -> str | None:
+ """The one command that installs bubblewrap here, or None on an unknown package manager."""
+ for manager, command in _BWRAP_INSTALL_COMMANDS:
+ if shutil.which(manager):
+ return command
+ return None
+
+
+def linux_unavailable_remediation() -> str:
+ missing = [name for name in _LINUX_REQUIRED_BINARIES if shutil.which(name) is None]
+ if missing:
+ command = bwrap_install_command()
+ # Installing bwrap alone leaves it blocked on Ubuntu 23.10+; keep it one copy-paste.
+ if command and "apt-get" in command and _linux_userns_blocked_by_apparmor():
+ command = f"{command} && {_BWRAP_APPARMOR_FIX}"
+ how = (
+ f"run `{command}`"
+ if command
+ else "install bubblewrap with your distribution's package manager"
+ )
+ return (
+ f"bubblewrap (bwrap) is not installed. To isolate tool calls, {how}; Studio picks "
+ f"it up within a minute, no restart needed. {_FALLBACK_NOTE}"
+ )
+ if _linux_userns_blocked_by_apparmor():
+ return (
+ "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. Load "
+ f"Ubuntu's own bwrap profile, which covers only /usr/bin/bwrap: `{_BWRAP_APPARMOR_FIX}`. "
+ f"{_FALLBACK_NOTE}"
+ )
+ return f"This host cannot start an OS sandbox. {_FALLBACK_NOTE}"
+
+
+def _runtime_identity() -> str:
+ """Changes with the interpreter or this module, so a swapped venv re-probes."""
+ digest = hashlib.sha256()
+ for path in (sys.executable, __file__):
+ resolved = os.path.realpath(path)
+ digest.update(resolved.encode())
+ try:
+ info = os.stat(resolved)
+ digest.update(str((info.st_size, info.st_mtime_ns)).encode())
+ except OSError:
+ digest.update(b"missing")
+ digest.update((PROFILE_VERSION + sys.platform + platform.release()).encode())
+ digest.update((os.path.abspath(sys.executable) + sys.prefix).encode())
+ if sys.platform == "linux":
+ try:
+ from . import sandbox_linux
+ digest.update(sandbox_linux.bwrap_identity().encode())
+ except Exception as exc: # noqa: BLE001 - an unavailable backend still needs a cache key
+ digest.update(f"untrusted-bwrap:{exc}".encode())
+ return digest.hexdigest()
+
+
+def _unavailable(reason: str, remediation: str, identity: str) -> SandboxCapability:
+ return SandboxCapability(
+ backend = "none",
+ available = False,
+ reason = reason,
+ environment = sys.platform,
+ protection_state = "unavailable",
+ limitations = ("no_os_isolation",),
+ probe_generation = hashlib.sha256((identity + "unavailable").encode()).hexdigest(),
+ environment_fingerprint = identity,
+ remediation = remediation,
+ )
+
+
+def capability_snapshot(*, force: bool = False) -> SandboxCapability:
+ identity = _runtime_identity()
+ if sys.platform == "linux":
+ from . import sandbox_linux
+ backend = sandbox_linux
+ elif sys.platform == "darwin":
+ from . import sandbox_macos
+ backend = sandbox_macos
+ else:
+ return _unavailable(
+ "OS isolation for Studio tools is available on Linux and macOS only.",
+ f"No sandbox backend exists for this platform. {_FALLBACK_NOTE}",
+ identity,
+ )
+
+ from .sandbox_probe import probe
+
+ available, reason = probe(backend, force = force)
+ if not available:
+ remediation = (
+ linux_unavailable_remediation()
+ if sys.platform == "linux"
+ else f"This host cannot start an OS sandbox. {_FALLBACK_NOTE}"
+ )
+ return _unavailable(reason, remediation, identity)
+ return SandboxCapability(
+ backend = backend.BACKEND_NAME,
+ available = True,
+ reason = reason,
+ environment = sys.platform,
+ protection_state = "preview",
+ profile_id = backend.PROFILE_ID,
+ limitations = backend.LIMITATIONS,
+ probe_generation = hashlib.sha256((identity + "available").encode()).hexdigest(),
+ environment_fingerprint = identity,
+ remediation = (
+ "Python and Terminal run with OS isolation. The network is not confined; a tool "
+ "call can still reach the internet."
+ ),
+ )
+
+
+def _record(
+ plan: ToolLaunchPlan,
+ capability: SandboxCapability,
+ *,
+ effective_mode: str,
+ os_isolation: bool,
+ backend: str,
+ profile_id: str,
+ safeguards: tuple[str, ...],
+ limitations: tuple[str, ...],
+) -> ToolExecutionRecord:
+ return ToolExecutionRecord(
+ requested_mode = plan.requested_mode,
+ effective_mode = effective_mode,
+ environment = capability.environment,
+ backend = backend,
+ profile_id = profile_id,
+ probe_generation = capability.probe_generation,
+ os_isolation = os_isolation,
+ retained_safeguards = tuple(
+ item for item in safeguards if item != "timeout" or plan.timeout_seconds is not None
+ ),
+ limitations = limitations,
+ )
+
+
+def _software_only_limitations() -> tuple[str, ...]:
+ limitations = ["no_os_isolation", "host_files_readable", "unrestricted_network"]
+ if sys.platform != "win32":
+ limitations.append("detached_descendant_cleanup_unverified")
+ return tuple(limitations)
+
+
+def prepare_tool_launch(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:
+ """Unavailable hosts fall back in auto; unsafe workdirs and build failures refuse."""
+ if plan.requested_mode not in TOOL_EXECUTION_MODES:
+ raise SandboxUnavailableError(f"unknown tool execution mode: {plan.requested_mode!r}")
+
+ if plan.requested_mode == "full":
+ return PreparedSandboxLaunch(
+ argv = plan.argv,
+ workdir = plan.workdir,
+ env = plan.env,
+ preexec_fn = plan.preexec_fn,
+ backend = "none",
+ timeout_seconds = plan.timeout_seconds,
+ close_fds = plan.close_fds,
+ terminate_descendants = plan.terminate_descendants,
+ execution_record = ToolExecutionRecord(
+ requested_mode = plan.requested_mode,
+ effective_mode = "full",
+ environment = sys.platform,
+ backend = "none",
+ profile_id = "full-access",
+ probe_generation = "",
+ os_isolation = False,
+ retained_safeguards = tuple(
+ item
+ for item in _FULL_SAFEGUARDS
+ if item != "timeout" or plan.timeout_seconds is not None
+ ),
+ limitations = ("security_restrictions_disabled",),
+ ),
+ )
+
+ capability = capability_snapshot()
+
+ if not capability.available:
+ if plan.requested_mode == "required":
+ raise SandboxUnavailableError(
+ f"OS_ISOLATION_UNAVAILABLE: {capability.reason}",
+ remediation = capability.remediation,
+ )
+ return PreparedSandboxLaunch(
+ argv = plan.argv,
+ workdir = plan.workdir,
+ env = plan.env,
+ preexec_fn = plan.preexec_fn,
+ backend = "software-safeguards",
+ timeout_seconds = plan.timeout_seconds,
+ close_fds = plan.close_fds,
+ terminate_descendants = plan.terminate_descendants,
+ execution_record = _record(
+ plan,
+ capability,
+ effective_mode = "software_safeguards",
+ os_isolation = False,
+ backend = "software-safeguards",
+ profile_id = "software-safeguards-v1",
+ safeguards = _SOFTWARE_SAFEGUARDS,
+ limitations = _software_only_limitations(),
+ ),
+ )
+
+ if sys.platform == "linux":
+ from . import sandbox_linux as backend
+ else:
+ from . import sandbox_macos as backend
+
+ try:
+ prepared = backend.prepare(plan)
+ if plan.requested_mode == "required" and WORKDIR_SCAN_INCOMPLETE in (
+ prepared.launch_limitations
+ ):
+ # `auto` degrades on an overrun scan; `required` fails closed, since the unvisited part may hold a hazard.
+ prepared.cleanup()
+ raise WorkdirUnsafeError(
+ "the session workdir is too large to check for host channels, "
+ "and `required` cannot promise a boundary it did not verify. "
+ "Start a new chat, or use `auto` to run with software safeguards."
+ )
+ except OSError as exc:
+ # Must be typed: raw, tools.py's general except would fall back to software safeguards.
+ raise SandboxBuildError(f"the sandbox could not be built on this host: {exc}") from exc
+ prepared.execution_record = _record(
+ plan,
+ capability,
+ effective_mode = "os_isolated",
+ os_isolation = True,
+ backend = capability.backend,
+ profile_id = capability.profile_id,
+ safeguards = _OS_ISOLATION_SAFEGUARDS,
+ limitations = capability.limitations + prepared.launch_limitations,
+ )
+ return prepared
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index c20daa8274e..e7e54b05883 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -1521,7 +1521,14 @@ def run_safetensors_tool_loop(
# stream while the tool blocks (the SSE route turns heartbeats into
# keepalives). execute_tool is injectable; pass output_callback
# only when it accepts it.
- def _invoke_tool(_output_callback, _decision = decision):
+ # Only a call the user answered: the executor lets it reach the host paths it names.
+ _host_access_approved = _decision not in (None, "deny")
+
+ def _invoke_tool(
+ _output_callback,
+ _decision = decision,
+ _approved = _host_access_approved,
+ ):
kwargs = dict(
cancel_event = cancel_event,
timeout = eff_timeout,
@@ -1532,6 +1539,8 @@ def run_safetensors_tool_loop(
)
if _accepts_kwarg(execute_tool, "conversation_branch"):
kwargs["conversation_branch"] = request_branch
+ if _approved and _accepts_kwarg(execute_tool, "host_access_approved"):
+ kwargs["host_access_approved"] = True
# And the room the model has left, as the GGUF loop does: without a
# budget the tool's clamp is skipped and a model-chosen top_k of 8
# appends roughly 4K tokens to an already full prompt.
diff --git a/studio/backend/core/inference/sandbox_landlock.py b/studio/backend/core/inference/sandbox_landlock.py
new file mode 100644
index 00000000000..251609ed60c
--- /dev/null
+++ b/studio/backend/core/inference/sandbox_landlock.py
@@ -0,0 +1,153 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Landlock ABI 6 scoping to block host abstract AF_UNIX sockets; best effort, pre-6.12 kernels record a limitation."""
+
+from __future__ import annotations
+
+import ctypes
+import functools
+import os
+import select
+import signal
+import struct
+from typing import Callable
+
+_NR_LANDLOCK_CREATE_RULESET = 444
+_NR_LANDLOCK_RESTRICT_SELF = 446
+_LANDLOCK_CREATE_RULESET_VERSION = 1 << 0
+_LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET = 1 << 0
+# The size is the version check: an older kernel answers E2BIG.
+_RULESET_ATTR = struct.pack("=QQQ", 0, 0, _LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET)
+_PR_SET_NO_NEW_PRIVS = 38
+# Built at import, never in the forked child: see apply_abstract_scope.
+_RULESET_ATTR_BUFFER = ctypes.create_string_buffer(_RULESET_ATTR, len(_RULESET_ATTR))
+_RULESET_ATTR_REF = ctypes.byref(_RULESET_ATTR_BUFFER)
+_RULESET_ATTR_SIZE = ctypes.c_size_t(len(_RULESET_ATTR))
+_ZERO_FLAGS = ctypes.c_uint32(0)
+_PROBE_TIMEOUT_SECONDS = 5.0
+
+try:
+ # Resolved at import, never in the forked child, where an import can deadlock.
+ _libc = ctypes.CDLL(None, use_errno = True)
+ _libc.syscall.restype = ctypes.c_long
+except (OSError, TypeError, AttributeError): # pragma: no cover
+ # TypeError is Windows, where CDLL(None) is not the running process.
+ _libc = None
+
+
[email protected]_cache(maxsize = 1)
+def abstract_scope_supported() -> bool:
+ """Cache whether a child can apply the scope; probed in a child because restrict_self is irreversible."""
+ if _libc is None:
+ return False
+ if not _abi_reports_scope():
+ return False
+ # Bind in the unscoped parent, so the child must not reach it once scoped.
+ import socket as _socket
+
+ name = b"\0unsloth-scope-" + os.urandom(6).hex().encode()
+ listener = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM)
+ try:
+ listener.bind(name)
+ listener.listen(1)
+ except OSError:
+ listener.close()
+ return False
+ read_fd, write_fd = os.pipe()
+ pid = os.fork()
+ if pid == 0: # pragma: no cover - the child never returns
+ try:
+ os.close(read_fd)
+ listener.close()
+ apply_abstract_scope()
+ client = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM)
+ client.settimeout(2)
+ try:
+ client.connect(name)
+ os.write(write_fd, b"n") # reached it, so nothing was applied
+ except OSError:
+ os.write(write_fd, b"y") # refused, so the scope is in force
+ except BaseException:
+ try:
+ os.write(write_fd, b"n")
+ except OSError:
+ pass
+ finally:
+ os._exit(0)
+ os.close(write_fd)
+ answer = b""
+ try:
+ # Bound the read and kill a stalled child; a timeout leaves the scope unproven.
+ if select.select([read_fd], [], [], _PROBE_TIMEOUT_SECONDS)[0]:
+ answer = os.read(read_fd, 1)
+ except OSError:
+ answer = b""
+ finally:
+ os.close(read_fd)
+ listener.close()
+ _reap(pid)
+ return answer == b"y"
+
+
+def _reap(pid: int) -> None:
+ """SIGKILL then wait; harmless for an already-exited child."""
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ try:
+ os.waitpid(pid, 0)
+ except OSError:
+ pass
+
+
+def _abi_reports_scope() -> bool:
+ """NULL attr only reports the ABI version and changes nothing."""
+ if _libc is None:
+ return False
+ try:
+ version = _libc.syscall(
+ _NR_LANDLOCK_CREATE_RULESET,
+ None,
+ ctypes.c_size_t(0),
+ ctypes.c_uint32(_LANDLOCK_CREATE_RULESET_VERSION),
+ )
+ except (OSError, AttributeError, TypeError):
+ return False
+ return version >= 6
+
+
+def apply_abstract_scope() -> None:
+ """Apply in the forked child without raising or logging; the probe checks success."""
+ if _libc is None:
+ return
+ ctypes.set_errno(0)
+ ruleset = _libc.syscall(
+ _NR_LANDLOCK_CREATE_RULESET,
+ _RULESET_ATTR_REF,
+ _RULESET_ATTR_SIZE,
+ _ZERO_FLAGS,
+ )
+ if ruleset < 0:
+ return
+ try:
+ # Required before restrict_self for an unprivileged caller; set here too.
+ _libc.prctl(_PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)
+ _libc.syscall(_NR_LANDLOCK_RESTRICT_SELF, ctypes.c_int(int(ruleset)), _ZERO_FLAGS)
+ finally:
+ try:
+ os.close(int(ruleset))
+ except OSError:
+ pass
+
+
+def with_abstract_scope(preexec_fn: "Callable[[], None] | None") -> "Callable[[], None]":
+ """*preexec_fn* first (it is the setsid the kill paths signal), then the scope."""
+
+ def preexec() -> None:
+ if preexec_fn is not None:
+ preexec_fn()
+ apply_abstract_scope()
+
+ return preexec
diff --git a/studio/backend/core/inference/sandbox_linux.py b/studio/backend/core/inference/sandbox_linux.py
new file mode 100644
index 00000000000..c15375a74d3
--- /dev/null
+++ b/studio/backend/core/inference/sandbox_linux.py
@@ -0,0 +1,790 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Bubblewrap backend. Bind parent directories, never single .so files: dlopen() reaches ones enumeration misses."""
+
+from __future__ import annotations
+
+import os
+import shutil
+import stat
+import site
+import subprocess
+import sys
+import sysconfig
+import tempfile
+import threading
+import time
+from functools import lru_cache
+
+from loggers import get_logger
+
+from . import sandbox_landlock, sandbox_seccomp
+from .os_sandbox import (
+ CACHE_SCAN_SECONDS,
+ PROFILE_VERSION,
+ SESSION_PACKAGES_RELPATH,
+ PreparedSandboxLaunch,
+ SandboxUnavailableError,
+ ToolLaunchPlan,
+ WorkdirUnsafeError,
+ cache_share_hazard,
+ directory_witness_matches,
+ editable_source_roots,
+ scan_workdir_for_host_channels,
+ model_library_roots,
+ studio_state_roots,
+)
+
+logger = get_logger(__name__)
+
+BACKEND_NAME = "bubblewrap"
+PROFILE_ID = f"linux-bwrap-{PROFILE_VERSION}"
+LIMITATIONS = (
+ "unrestricted_network",
+ "system_paths_readable",
+ "model_cache_writable",
+ # --dev builds a fresh /dev, so a sandboxed tool call is CPU-only.
+ "gpu_devices_hidden",
+ # --unshare-pid: a backgrounded process dies with the foreground command.
+ "detached_processes_die_with_the_call",
+ # Without the Landlock scope (Linux 6.12+) abstract AF_UNIX sockets reach the session bus and X.
+ *(() if sandbox_landlock.abstract_scope_supported() else ("host_abstract_sockets_reachable",)),
+ # Read-only mounts do not block socket connect(); system roots are not scanned per call.
+ "host_pathname_sockets_reachable",
+ "shared_kernel",
+)
+
+_SYSTEM_ROOTS = (
+ "/usr/bin",
+ "/usr/sbin",
+ "/usr/lib",
+ "/usr/lib64",
+ "/usr/libexec",
+ "/usr/local/bin",
+ "/usr/local/lib",
+ "/usr/local/lib64",
+ "/usr/local/libexec",
+ "/usr/local/sbin",
+ "/usr/local/share",
+ "/usr/share",
+ "/opt",
+ "/usr/include",
+ "/usr/local/include",
+ "/bin",
+ "/sbin",
+ "/lib",
+ "/lib64",
+)
+
+
+def _trusted_bwrap_path() -> str:
+ """Resolve bubblewrap to a system-owned executable that the Studio user cannot replace."""
+ candidate = shutil.which("bwrap")
+ if candidate is None:
+ raise SandboxUnavailableError("bubblewrap (bwrap) is not installed on this host")
+ resolved = os.path.realpath(candidate)
+ try:
+ executable = os.stat(resolved, follow_symlinks = False)
+ if (
+ not stat.S_ISREG(executable.st_mode)
+ or executable.st_uid != 0
+ or executable.st_mode & (stat.S_IWGRP | stat.S_IWOTH)
+ or not os.access(resolved, os.X_OK)
+ ):
+ raise OSError("the executable is not root-owned, executable, and non-writable")
+ parent = os.path.dirname(resolved)
+ while True:
+ directory = os.stat(parent, follow_symlinks = False)
+ if (
+ not stat.S_ISDIR(directory.st_mode)
+ or directory.st_uid != 0
+ or directory.st_mode & (stat.S_IWGRP | stat.S_IWOTH)
+ ):
+ raise OSError(f"its directory is replaceable: {parent}")
+ ancestor = os.path.dirname(parent)
+ if ancestor == parent:
+ break
+ parent = ancestor
+ except OSError as exc:
+ raise SandboxUnavailableError(
+ "bubblewrap must come from a trusted system installation; install it with the "
+ f"distribution package manager ({exc})"
+ ) from exc
+ return resolved
+
+
+def bwrap_identity() -> str:
+ """Stable identity included in capability-cache keys."""
+ path = _trusted_bwrap_path()
+ info = os.stat(path, follow_symlinks = False)
+ return repr((path, info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_mode))
+
+
+# /etc is fresh in the jail; without these nothing dynamically linked starts.
+_ETC_FILES = (
+ "/etc/alternatives",
+ "/etc/ld.so.cache",
+ "/etc/ld.so.conf",
+ "/etc/ld.so.conf.d",
+ "/etc/localtime",
+ "/etc/nsswitch.conf",
+)
+# Bound only when it passes _trusted_system_file.
+_ETC_FILES_IF_TRUSTED = ("/etc/gitconfig",)
+# PUBLIC halves one by one, never /etc/ssl or /etc/pki whole: both hold private keys.
+_NETWORK_FILES = (
+ "/etc/resolv.conf",
+ "/etc/hosts",
+ "/etc/host.conf",
+ "/etc/gai.conf",
+ "/etc/services",
+ "/etc/protocols",
+ "/etc/ssl/certs",
+ "/etc/ssl/cert.pem",
+ "/etc/ssl/openssl.cnf",
+ "/etc/pki/tls/certs",
+ "/etc/pki/tls/cert.pem",
+ "/etc/pki/tls/openssl.cnf",
+ "/etc/pki/ca-trust",
+ "/etc/ca-certificates",
+ "/etc/ca-certificates.conf",
+ "/etc/crypto-policies",
+ "/var/lib/ca-certificates",
+)
+# Bound at the jail's own HOME with HF_HOME pinned to match.
+_MODEL_CACHE_RELPATH = os.path.join(".cache", "huggingface")
+# Excludes $HF_HOME/token and executable modules; the writable hub is a deliberate tradeoff (#5603).
+_MODEL_CACHE_SUBDIRS = ("hub", "datasets", "xet", "assets")
+# NixOS keeps glibc here, so a store interpreter cannot link without it.
+_NIX_STORE = "/nix/store"
+
+
+def _trusted_system_file(path: str) -> bool:
+ """Require a root-owned, non-user-writable regular file with no symlink hops."""
+ try:
+ info = os.lstat(path)
+ except OSError:
+ return False
+ if not stat.S_ISREG(info.st_mode):
+ return False
+ return info.st_uid == 0 and not info.st_mode & (stat.S_IWGRP | stat.S_IWOTH)
+
+
+def _within(path: str, root: str) -> bool:
+ path, root = os.path.abspath(path), os.path.abspath(root)
+ try:
+ return os.path.commonpath((path, root)) == root
+ except ValueError:
+ return False
+
+
+# A WRITABLE cache must never BE or CONTAIN these, or tool code could modify the user's home.
+_CACHE_FORBIDDEN_CHILDREN = (
+ ".ssh",
+ ".aws",
+ ".config/gcloud",
+ ".kube",
+ ".docker",
+ ".gnupg",
+ ".netrc",
+ ".git-credentials",
+)
+
+
+def _too_broad_for_a_cache(path: str) -> bool:
+ """Whether ``path`` is a home or system directory rather than a cache."""
+ real = os.path.realpath(path)
+ if real == os.sep or os.path.dirname(real) == real:
+ return True
+ home = os.path.realpath(os.path.expanduser("~"))
+ if home and home != os.sep and (_within(home, real) or real == home):
+ return True
+ if real in ("/home", "/Users", "/root", "/etc", "/var", "/usr", "/opt", "/tmp"):
+ return True
+ # A directory already holding credentials is not a cache, whatever it is called.
+ return any(os.path.exists(os.path.join(real, child)) for child in _CACHE_FORBIDDEN_CHILDREN)
+
+
+def _holds_studio_state(path: str) -> bool:
+ """Whether ``path`` IS, or CONTAINS, a Studio state root."""
+ real = os.path.realpath(path)
+ return any(_within(real, root) or _within(root, real) for root in studio_state_roots())
+
+
+def _without_state_inside(paths: tuple[str, ...]) -> tuple[str, ...]:
+ """Carve Studio state out of a runtime path that contains it; a runtime INSIDE the state (the managed venv) stays."""
+ state = studio_state_roots()
+ kept: list[str] = []
+ for path in paths:
+ real = os.path.realpath(path)
+ if any(_within(root, real) for root in state):
+ kept.extend(_without_studio_state((path,)))
+ else:
+ kept.append(path)
+ return tuple(dict.fromkeys(kept))
+
+
+def _without_studio_state(roots: tuple[str, ...], depth: int = 4) -> tuple[str, ...]:
+ """Bind a system root's children instead of the root when Studio's own state lives inside it."""
+ state = studio_state_roots()
+ if not state:
+ return roots
+ kept: list[str] = []
+ for root in roots:
+ real = os.path.realpath(root)
+ if any(_within(real, path) for path in state):
+ continue # the root IS Studio state
+ if not any(_within(path, real) for path in state):
+ kept.append(root)
+ continue
+ if depth <= 0:
+ # Fails CLOSED: restoring an ancestor of the state directory would hand over auth/auth.db.
+ logger.warning(
+ "Not binding %s read-only: Studio's own state is nested too "
+ "deeply inside it to exclude",
+ root,
+ )
+ continue
+ try:
+ children = sorted(os.path.join(root, name) for name in os.listdir(root))
+ except OSError:
+ continue # unreadable: bind nothing rather than everything
+ kept.extend(
+ _without_studio_state(
+ tuple(path for path in children if _bindable_child(path, real)), depth - 1
+ )
+ )
+ return tuple(dict.fromkeys(kept))
+
+
+def _bindable_child(path: str, root: str) -> bool:
+ """A bind-source subdirectory of ``root``; symlinks leaving ``root`` are dropped, since they resolve on the HOST."""
+ try:
+ if not stat.S_ISDIR(os.lstat(path).st_mode):
+ return stat.S_ISDIR(os.stat(path).st_mode) and _within(os.path.realpath(path), root)
+ except OSError:
+ return False
+ return True
+
+
+@lru_cache(maxsize = 8)
+def _bwrap_long_options(identity: tuple[str, int, int]) -> frozenset[str]:
+ """Keyed by file identity so a package upgrade under a running Studio is re-read."""
+ try:
+ completed = subprocess.run(
+ [identity[0], "--help"],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = 5,
+ close_fds = True,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return frozenset()
+ return frozenset(
+ token.strip().rstrip(",")
+ for line in f"{completed.stdout}\n{completed.stderr}".splitlines()
+ for token in line.split()
+ if token.startswith("--")
+ )
+
+
+def _bwrap_supports(bwrap: str, option: str) -> bool:
+ try:
+ info = os.stat(bwrap)
+ identity = (bwrap, info.st_ino, info.st_mtime_ns)
+ except OSError:
+ identity = (bwrap, 0, 0)
+ return option in _bwrap_long_options(identity)
+
+
+def _host_mount_points() -> tuple[str, ...]:
+ """Every host mount point; unreadable is a refusal. Not resolved: realpath blocks on stale NFS."""
+ points: list[str] = []
+ try:
+ with open("/proc/self/mountinfo", encoding = "utf-8") as stream:
+ for line in stream:
+ fields = line.split()
+ if len(fields) < 5:
+ raise SandboxUnavailableError("cannot parse the host mount table")
+ raw = (
+ fields[4]
+ .replace("\\040", " ")
+ .replace("\\011", "\t")
+ .replace("\\012", "\n")
+ .replace("\\134", "\\")
+ )
+ points.append(raw)
+ except OSError as exc:
+ raise SandboxUnavailableError("cannot read the host mount table") from exc
+ return tuple(points)
+
+
+def _runtime_paths_under(workdir: str) -> tuple[str, ...]:
+ """Protect Studio's runtime after the writable workdir bind; external symlink targets get no bind."""
+ canonical_root = os.path.realpath(workdir)
+ inside: list[str] = []
+ # Standalone Python may have no bin/; the probe executes this file on the host.
+ candidates = [sys.executable, *editable_source_roots()]
+ for prefix in (sys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix):
+ candidates.extend(
+ os.path.join(prefix, name)
+ for name in ("bin", "include", "lib", "lib64", "libexec", "pyvenv.cfg", "ssl")
+ )
+ for candidate in candidates:
+ if not os.path.exists(candidate):
+ continue
+ written, resolved = os.path.abspath(candidate), os.path.realpath(candidate)
+ # Protect both target and name: otherwise the writable alias can be replaced.
+ if _within(written, canonical_root) and not _within(resolved, canonical_root):
+ if candidate is sys.executable:
+ # Refuse: protecting this alias would expose its external target.
+ raise WorkdirUnsafeError(
+ f"the session workdir holds a link to the Python that runs Studio: {written}"
+ )
+ continue
+ for path in (written, resolved):
+ if _within(path, canonical_root) and path not in inside:
+ inside.append(path)
+ return tuple(inside)
+
+
+def _validate_workdir(workdir: str) -> tuple[str, tuple[str, ...]]:
+ """Re-read the mount table: os.path.ismount misses a same-filesystem bind mount."""
+ resolved = os.path.realpath(workdir)
+ if not os.path.isdir(resolved) or os.path.dirname(resolved) == resolved:
+ raise WorkdirUnsafeError("the session workdir is not a safe canonical directory")
+ for mount in _host_mount_points():
+ if mount != resolved and _within(mount, resolved):
+ raise WorkdirUnsafeError(f"the session workdir contains a nested host mount: {mount}")
+ return resolved, scan_workdir_for_host_channels(resolved)
+
+
+def _runtime_read_paths(
+ workdir: str,
+ system_roots: tuple[str, ...],
+ alias: str | None = None,
+) -> tuple[str, ...]:
+ """Find runtime roots from the interpreter; exclude both workdir spellings BEFORE resolving."""
+ # All four: uv's base_prefix and base_exec_prefix are different spellings.
+ prefixes = (sys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix)
+ candidates: list[str] = [
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "sandbox_site"),
+ ]
+ # Subdirectories, never the prefix: ``python -m venv .`` makes sys.prefix the project root.
+ for prefix in prefixes:
+ candidates.extend(
+ os.path.join(prefix, name)
+ for name in ("bin", "include", "lib", "lib64", "libexec", "pyvenv.cfg", "ssl")
+ )
+ try:
+ paths = sysconfig.get_paths()
+ candidates.extend(
+ paths[key]
+ for key in ("stdlib", "platstdlib", "purelib", "platlib", "include", "platinclude")
+ if paths.get(key)
+ )
+ except (KeyError, OSError):
+ pass
+ # Editable installs live outside site-packages; added as CANDIDATES so the exclusions below apply.
+ candidates.extend(editable_source_roots())
+ # Bind argv[0]'s file, not its parent, which may be the user's home.
+ candidates.append(sys.executable)
+ try:
+ candidates.extend(site.getsitepackages())
+ except AttributeError:
+ pass
+ multiarch = sysconfig.get_config_var("MULTIARCH")
+ if multiarch:
+ candidates.extend(os.path.join(prefix, "lib", multiarch) for prefix in prefixes)
+
+ selected: list[str] = []
+ for candidate in candidates:
+ if not candidate or not os.path.isabs(candidate):
+ continue
+ # Check the candidate as WRITTEN, against both workdir spellings, or a symlinked venv/lib exposes its target.
+ written = os.path.abspath(candidate)
+ if any(_within(written, root) for root in (workdir, alias) if root):
+ continue
+ for path in (os.path.abspath(candidate), os.path.realpath(candidate)):
+ if path == os.path.sep:
+ raise SandboxUnavailableError(
+ f"this interpreter would require binding the filesystem root: {candidate}"
+ )
+ if not os.path.exists(path):
+ continue
+ if any(_within(path, root) for root in (*system_roots, *selected)):
+ continue
+ selected.append(path)
+ return tuple(selected)
+
+
+def _identity_files() -> tuple[str, str, str]:
+ """Synthesise one-entry passwd and group so getpwuid() works without the host database."""
+ directory = tempfile.mkdtemp(prefix = "unsloth-sandbox-identity-")
+ uid, gid = os.getuid(), os.getgid()
+ passwd, group = os.path.join(directory, "passwd"), os.path.join(directory, "group")
+ try:
+ with open(passwd, "w", encoding = "utf-8") as stream:
+ stream.write(f"studio:x:{uid}:{gid}:Studio sandbox:/nonexistent:/bin/sh\n")
+ with open(group, "w", encoding = "utf-8") as stream:
+ stream.write(f"studio:x:{gid}:\n")
+ os.chmod(passwd, 0o600)
+ os.chmod(group, 0o600)
+ except Exception:
+ shutil.rmtree(directory, ignore_errors = True)
+ raise
+ return directory, passwd, group
+
+
+def _tmpdir(plan: ToolLaunchPlan, workdir: str) -> str:
+ """The caller's TMPDIR spelling when inside the workdir: the private /tmp dies with the namespace."""
+ requested = plan.env.get("TMPDIR") or ""
+ if not requested:
+ return "/tmp"
+ return requested if _within(os.path.realpath(requested), workdir) else "/tmp"
+
+
+def _pythonpath(plan: ToolLaunchPlan, packages: str) -> str:
+ """Appended, never prepended: a package must not shadow tools.py's sandbox_site shim."""
+ inherited = plan.env.get("PYTHONPATH") or ""
+ return os.pathsep.join(part for part in (inherited, packages) if part)
+
+
+def _path(plan: ToolLaunchPlan, packages: str) -> str:
+ """Caller's PATH plus the writable package ``bin`` LAST, so a planted binary cannot shadow a safe command."""
+ inherited = plan.env.get("PATH") or ""
+ return os.pathsep.join(part for part in (inherited, os.path.join(packages, "bin")) if part)
+
+
+# Bounded wait on a thread: NFS/FUSE can block isdir/scandir; an uninspected cache is not shared.
+_CACHE_INSPECT_SECONDS = CACHE_SCAN_SECONDS + 2.0
+
+
+def _inspect_cache_component(
+ name: str,
+ path: str,
+ witness: "list[tuple] | None" = None,
+) -> "str | None":
+ """The hazard for one component, or a reason it could not be inspected."""
+ if not os.path.isdir(path):
+ return "is not a directory"
+ nested = next((m for m in _host_mount_points() if m != path and _within(m, path)), None)
+ if nested is not None:
+ return f"contains a nested host mount: {nested}"
+ return cache_share_hazard(path, witness)
+
+
+# Retain timed-out workers until they finish, preventing a thread leak on a wedged path.
+_cache_scan_pending: "dict[str, threading.Thread]" = {}
+# Request threads must reserve and remove workers atomically.
+_cache_scan_lock = threading.Lock()
+
+
+# Memoized per-component verdict; reuse re-stats every directory the scan visited, not just the root.
+_CACHE_VERDICT_TTL_SECONDS = 300.0
+_cache_verdicts: "dict[str, tuple[float, tuple, list[tuple], str | None]]" = {}
+
+
+def _cache_component_signature(path: str) -> tuple:
+ try:
+ info = os.stat(path)
+ except OSError:
+ return ()
+ return (info.st_dev, info.st_ino, info.st_mtime_ns, info.st_size)
+
+
+def reset_cache_verdicts() -> None:
+ """Drop every memoized component verdict; called when a launch fails."""
+ with _cache_scan_lock:
+ _cache_verdicts.clear()
+
+
+def _cache_hazard_within_deadline(name: str, path: str) -> "str | None":
+ """Memo hit or walk, both on the bounded worker: revalidating stats the cache too, and NFS/FUSE can block a stat."""
+ answer: list[str | None] = []
+
+ def check() -> None:
+ try:
+ answer.append(_cache_hazard_memoized(name, path))
+ except Exception as exc: # noqa: BLE001 - a launch never fails over this
+ answer.append(f"could not be inspected: {exc}")
+
+ with _cache_scan_lock:
+ pending = _cache_scan_pending.get(path)
+ if pending is not None:
+ if pending.is_alive():
+ return "was still being inspected when a previous launch gave up (a wedged mount?)"
+ del _cache_scan_pending[path]
+ worker = threading.Thread(target = check, name = f"unsloth-cache-scan-{name}", daemon = True)
+ # Start under the lock, or another caller can replace the not-yet-alive worker.
+ _cache_scan_pending[path] = worker
+ worker.start()
+ worker.join(_CACHE_INSPECT_SECONDS)
+ if not answer:
+ return f"could not be inspected within {_CACHE_INSPECT_SECONDS:.0f}s (a wedged mount?)"
+ with _cache_scan_lock:
+ # By identity: another caller may already have replaced it.
+ if _cache_scan_pending.get(path) is worker:
+ del _cache_scan_pending[path]
+ return answer[0]
+
+
+def _cache_hazard_memoized(name: str, path: str) -> "str | None":
+ signature = _cache_component_signature(path)
+ now = time.monotonic()
+ with _cache_scan_lock:
+ cached = _cache_verdicts.get(path)
+ if cached is not None:
+ expires, cached_signature, witness, verdict = cached
+ # Outside the lock: a stalled stat here must not hold up every other launch.
+ if now < expires and cached_signature == signature and directory_witness_matches(witness):
+ return verdict
+ with _cache_scan_lock:
+ if _cache_verdicts.get(path) is cached:
+ del _cache_verdicts[path]
+ witness: "list[tuple]" = []
+ verdict = _inspect_cache_component(name, path, witness)
+ # Re-read the signature: the component may have changed during the walk.
+ if _cache_component_signature(path) == signature:
+ with _cache_scan_lock:
+ _cache_verdicts[path] = (now + _CACHE_VERDICT_TTL_SECONDS, signature, witness, verdict)
+ return verdict
+
+
+def _model_cache_binds(workdir: str) -> dict[str, str]:
+ """Inner cache subdirectory -> host directory, per component (HF_HUB_CACHE=/mnt/models is NOT /mnt/models/hub)."""
+ binds: dict[str, str] = {}
+ try:
+ from utils.hf_cache_settings import get_hf_cache_paths
+
+ paths = get_hf_cache_paths()
+ home = os.path.abspath(str(paths.cache_home))
+ resolved = {"hub": str(paths.hub_cache), "xet": str(paths.xet_cache)}
+ except Exception: # noqa: BLE001 - a launch never fails over a cache lookup
+ logger.debug("could not resolve the configured Hugging Face cache", exc_info = True)
+ user_home = os.path.expanduser("~")
+ if not os.path.isabs(user_home):
+ return binds
+ home = os.path.join(user_home, _MODEL_CACHE_RELPATH)
+ resolved = {}
+ for name in _MODEL_CACHE_SUBDIRS:
+ # Canonical: the mount table lists real paths.
+ path = os.path.realpath(resolved.get(name) or os.path.join(home, name))
+ if _within(path, workdir):
+ continue
+ # A cache at or above the Studio root would share auth/auth.db WRITABLE.
+ if _too_broad_for_a_cache(path):
+ logger.warning(
+ "Not sharing the %s cache into the sandbox: %s is a home or "
+ "system directory rather than a cache",
+ name,
+ path,
+ )
+ continue
+ if _holds_studio_state(path):
+ logger.warning(
+ "Not sharing the %s cache into the sandbox: it is at or above "
+ "Studio's own state directory",
+ name,
+ )
+ continue
+ # Writable caches need the workdir's host-channel checks, including nested bind mounts.
+ hazard = _cache_hazard_within_deadline(name, path)
+ if hazard is not None:
+ logger.warning("Not sharing the %s cache into the sandbox: it %s", name, hazard)
+ continue
+ binds[name] = path
+ return binds
+
+
+def _make_cache_mountpoints(workdir: str, names: tuple[str, ...]) -> None:
+ """Create missing mount points with O_NOFOLLOW (bwrap would follow a planted symlink on the HOST); never remove them."""
+ levels = _MODEL_CACHE_RELPATH.split(os.sep)
+ fds: list[int] = [os.open(workdir, os.O_RDONLY | os.O_DIRECTORY)]
+ try:
+ for name in (*levels, *names):
+ try:
+ os.mkdir(name, dir_fd = fds[-1])
+ except FileExistsError:
+ pass
+ except OSError as exc:
+ raise WorkdirUnsafeError(
+ f"the session workdir's model cache path cannot be prepared: {exc}"
+ ) from exc
+ # Verified even when not descended into: a bad leaf fails after Popen, where auto cannot fall back.
+ try:
+ opened = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd = fds[-1])
+ except OSError as exc:
+ raise WorkdirUnsafeError(
+ f"the session workdir's model cache path is not a plain directory: {name}"
+ ) from exc
+ if name in levels:
+ fds.append(opened)
+ else:
+ os.close(opened)
+ finally:
+ for fd in fds:
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+
+
+def prepare(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:
+ bwrap = _trusted_bwrap_path()
+ if not plan.argv:
+ raise SandboxUnavailableError("a sandboxed launch needs a command to run")
+ workdir, workdir_limitations = _validate_workdir(plan.workdir)
+ # The caller's spelling (tools.py built the script path from it); the canonical form is the bind SOURCE.
+ inner = os.path.abspath(plan.workdir)
+ system_roots = _without_studio_state(
+ 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,)
+ runtime_paths = _without_state_inside(_runtime_read_paths(workdir, system_roots, inner))
+ silent_roots = tuple(
+ root
+ for root in model_library_roots()
+ if not _within(root, workdir) and not any(_within(root, r) for r in system_roots)
+ )
+ model_cache = _model_cache_binds(workdir)
+ # A runtime under /tmp has to be restored after the tmpfs replaces it.
+ tmp_runtime_paths = tuple(path for path in runtime_paths if _within(path, "/tmp"))
+ workdir_runtime_paths = _runtime_paths_under(workdir)
+
+ disable_userns = _bwrap_supports(bwrap, "--disable-userns")
+ try:
+ seccomp = sandbox_seccomp.filter_file(block_userns = not disable_userns)
+ except RuntimeError as exc:
+ raise SandboxUnavailableError(str(exc)) from exc
+ try:
+ identity_dir, passwd, group = _identity_files()
+ except Exception:
+ seccomp.close()
+ raise
+ try:
+ argv: list[str] = [
+ bwrap,
+ "--die-with-parent",
+ "--new-session",
+ # Every namespace except the network one: tool calls download models.
+ "--unshare-user",
+ "--unshare-pid",
+ "--unshare-ipc",
+ "--unshare-uts",
+ "--unshare-cgroup",
+ # bwrap 0.6.1 lacks this; the seccomp filter refuses nested user namespaces there.
+ *(("--disable-userns",) if disable_userns else ()),
+ "--cap-drop",
+ "ALL",
+ "--seccomp",
+ str(seccomp.fileno()),
+ "--proc",
+ "/proc",
+ "--dev",
+ "/dev",
+ "--dir",
+ "/dev/shm",
+ "--dir",
+ "/tmp",
+ "--dir",
+ "/etc",
+ ]
+ for root in system_roots:
+ argv += ["--ro-bind-try", root, root]
+ # -try: a missing model folder must not fail the launch.
+ for root in silent_roots:
+ argv += ["--ro-bind-try", root, root]
+ trusted = tuple(p for p in _ETC_FILES_IF_TRUSTED if _trusted_system_file(p))
+ for path in (*_ETC_FILES, *trusted, *_NETWORK_FILES):
+ argv += ["--ro-bind-try", path, path]
+ argv += ["--ro-bind", passwd, "/etc/passwd", "--ro-bind", group, "/etc/group"]
+ for path in runtime_paths:
+ if path not in tmp_runtime_paths:
+ argv += ["--ro-bind", path, path]
+ # Mount points for both spellings must exist before / goes read-only.
+ argv += ["--dir", workdir]
+ if inner != workdir:
+ argv += ["--dir", inner]
+ argv += ["--remount-ro", "/"]
+ argv += ["--tmpfs", "/dev/shm", "--tmpfs", "/tmp"]
+ for path in tmp_runtime_paths:
+ argv += ["--ro-bind", path, path]
+ argv += ["--bind", workdir, inner]
+ if inner != workdir:
+ argv += ["--bind", workdir, workdir]
+ # Protect both runtime spellings AFTER both writable binds.
+ for path in workdir_runtime_paths:
+ argv += ["--ro-bind", path, path]
+ if inner != workdir:
+ argv += ["--ro-bind", path, inner + path[len(workdir) :]]
+ argv += ["--chdir", inner]
+ if model_cache:
+ inner_cache = os.path.join(inner, _MODEL_CACHE_RELPATH)
+ _make_cache_mountpoints(inner, tuple(model_cache))
+ for name, host_path in model_cache.items():
+ # --bind-try: a failed bind lands after Popen, where auto has no fallback.
+ argv += ["--bind-try", host_path, os.path.join(inner_cache, name)]
+ argv += ["--setenv", "HF_HOME", inner_cache]
+ packages = os.path.join(inner, SESSION_PACKAGES_RELPATH)
+ argv += [
+ "--setenv",
+ "HOME",
+ inner,
+ "--setenv",
+ "TMPDIR",
+ _tmpdir(plan, workdir),
+ "--setenv",
+ "PIP_TARGET",
+ packages,
+ "--setenv",
+ "PYTHONPATH",
+ _pythonpath(plan, packages),
+ "--setenv",
+ "PATH",
+ _path(plan, packages),
+ "--",
+ ]
+ argv += list(plan.argv)
+
+ return PreparedSandboxLaunch(
+ argv = tuple(argv),
+ workdir = workdir,
+ env = dict(plan.env),
+ # --new-session covers the inner side only; tools.py's killpg still needs the outer setsid.
+ preexec_fn = sandbox_landlock.with_abstract_scope(plan.preexec_fn),
+ backend = BACKEND_NAME,
+ pass_fds = (seccomp.fileno(),),
+ owned_files = [seccomp],
+ cleanup_paths = [identity_dir],
+ timeout_seconds = plan.timeout_seconds,
+ close_fds = plan.close_fds,
+ terminate_descendants = plan.terminate_descendants,
+ launch_limitations = workdir_limitations,
+ )
+ except Exception:
+ seccomp.close()
+ shutil.rmtree(identity_dir, ignore_errors = True)
+ raise
+
+
+def probe_argv(
+ workdir: str,
+ payload_argv: tuple[str, ...],
+ env: dict[str, str] | None = None,
+) -> PreparedSandboxLaunch:
+ """Built through the real argv builder, so the probe cannot qualify a sandbox nothing runs."""
+ return prepare(
+ ToolLaunchPlan(
+ argv = tuple(payload_argv),
+ workdir = workdir,
+ env = dict(env or {}),
+ requested_mode = "required",
+ )
+ )
diff --git a/studio/backend/core/inference/sandbox_macos.py b/studio/backend/core/inference/sandbox_macos.py
new file mode 100644
index 00000000000..fbbfbd34477
--- /dev/null
+++ b/studio/backend/core/inference/sandbox_macos.py
@@ -0,0 +1,730 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Default-deny Seatbelt profiles for sandbox-exec; file rules do not block AF_UNIX connect, so sockets get their own."""
+
+from __future__ import annotations
+import json
+import os
+import posixpath
+import shutil
+import site
+import stat
+import subprocess
+import sys
+import sysconfig
+import tempfile
+import threading
+
+from .os_sandbox import (
+ PROFILE_VERSION,
+ SESSION_PACKAGES_RELPATH,
+ PreparedSandboxLaunch,
+ SandboxUnavailableError,
+ ToolLaunchPlan,
+ WorkdirUnsafeError,
+ editable_import_roots,
+ editable_source_roots,
+ model_library_roots,
+ scan_workdir_for_host_channels,
+ studio_state_roots,
+)
+
+BACKEND_NAME = "macos-seatbelt"
+PROFILE_ID = f"macos-seatbelt-{PROFILE_VERSION}"
+LIMITATIONS = (
+ "deprecated_undocumented_sbpl",
+ "unrestricted_network",
+ # No /proc and no pidfds, so a descendant outliving the leader is not swept.
+ "detached_descendant_cleanup_unverified",
+ "pytorch_posix_shm_namespace_shared",
+ # Unfiltered: a wrong guess at torch's and OpenMP's names breaks them.
+ "posix_semaphore_namespace_shared",
+ # kern.proc.pid./pgrp. leak host kinfo_proc, but that sysctl is how ps works.
+ "host_process_metadata_readable",
+ # Only RootDomainUserClient: Metal's user clients stay ungranted, so MPS cannot initialise.
+ "gpu_devices_hidden",
+)
+
+SANDBOX_EXEC = "/usr/bin/sandbox-exec"
+
+_REJECTED_CONTROLS = frozenset(chr(code) for code in (*range(0x20), 0x7F))
+
+
+_READ_ROOTS = (
+ "/Library/Apple/System/Library/Frameworks",
+ "/Library/Apple/System/Library/PrivateFrameworks",
+ "/Library/Apple/usr/lib",
+ "/System/Library/Frameworks",
+ "/System/Library/PrivateFrameworks",
+ "/System/Library/SubFrameworks",
+ "/System/iOSSupport/System/Library/Frameworks",
+ "/System/iOSSupport/System/Library/PrivateFrameworks",
+ "/System/iOSSupport/System/Library/SubFrameworks",
+ "/usr/lib",
+ "/usr/share",
+ "/bin",
+ "/usr/bin",
+ "/private/var/db/timezone",
+ "/private/etc/localtime",
+ "/private/etc/master.passwd",
+ "/private/etc/passwd",
+ "/private/etc/protocols",
+ "/private/etc/services",
+ "/private/etc/hosts",
+ "/private/etc/resolv.conf",
+ "/System/Library/CoreServices/.SystemVersionPlatform.plist",
+ "/System/Library/CoreServices/SystemVersion.plist",
+ # /usr/bin/git and friends are xcode-select shims and fail without these.
+ "/private/var/db/xcode_select_link",
+ "/Library/Developer/CommandLineTools",
+ "/Applications/Xcode.app/Contents/Developer",
+)
+# SYSTEM keychains only; the login keychain stays unreadable.
+_TLS_TRUST_PATHS = (
+ # Allow public TLS components individually; /etc/ssl can also hold private keys.
+ "/private/etc/ssl/cert.pem",
+ "/private/etc/ssl/certs",
+ "/private/etc/ssl/openssl.cnf",
+ "/System/Library/Keychains",
+ "/Library/Keychains",
+ "/System/Library/Security",
+ "/private/var/db/mds",
+ "/Library/Preferences/com.apple.security.plist",
+ "/Library/Preferences/com.apple.security.revocation.plist",
+)
+_OPTIONAL_READ_ROOTS = (
+ "/usr/local/bin",
+ "/usr/local/lib",
+ "/usr/local/sbin",
+ "/usr/local/opt",
+ "/usr/local/Cellar",
+ "/opt/homebrew/bin",
+ "/opt/homebrew/lib",
+ "/opt/homebrew/sbin",
+ "/opt/homebrew/opt",
+ "/opt/homebrew/Cellar",
+)
+# Homebrew prefixes are user-owned; check target containment rather than ownership.
+_OPTIONAL_ROOT_PREFIXES = ("/usr/local", "/opt/homebrew")
+# Allow missing optional files so git gets ENOENT, not a fatal EPERM.
+_OPTIONAL_READ_LITERALS = (
+ "/etc/gitconfig",
+ "/etc/gitattributes",
+ # A Homebrew git reads its own prefix, and the binary on PATH decides which.
+ "/usr/local/etc/gitconfig",
+ "/usr/local/etc/gitattributes",
+ "/opt/homebrew/etc/gitconfig",
+ "/opt/homebrew/etc/gitattributes",
+ "/Library/Preferences/com.apple.dt.Xcode.plist",
+)
+# Exec-denied: each hands work to a daemon outside the sandbox.
+_DENIED_EXECUTABLES = (
+ "/usr/bin/open",
+ "/usr/bin/osascript",
+ "/usr/bin/security",
+ "/bin/launchctl",
+ "/usr/bin/sandbox-exec",
+)
+_DEVICES = ("/dev/null", "/dev/zero", "/dev/random", "/dev/urandom")
+# connect() to a unix socket is network-outbound, not a file operation.
+_MDNSRESPONDER_SOCKET = "/private/var/run/mDNSResponder"
+# com.apple.SecurityServer is deliberately ABSENT: it would expose the login Keychain.
+_MACH_SERVICES = (
+ "com.apple.system.opendirectoryd.libinfo",
+ "com.apple.PowerManagement.control",
+ "com.apple.trustd",
+ "com.apple.trustd.agent",
+ "com.apple.ocspd",
+ "com.apple.dnssd.service",
+ "com.apple.networkd",
+ "com.apple.bsd.dirhelper",
+ "com.apple.SystemConfiguration.configd",
+ "com.apple.SystemConfiguration.DNSConfiguration",
+)
+# An omission is a silent breakage (empty os.cpu_count()), so be generous.
+_SYSCTL_NAMES = (
+ "hw.activecpu",
+ "hw.busfrequency_compat",
+ "hw.byteorder",
+ "hw.cacheconfig",
+ "hw.cachelinesize_compat",
+ "hw.cpufamily",
+ "hw.cpufrequency_compat",
+ "hw.cputype",
+ "hw.l1dcachesize_compat",
+ "hw.l1icachesize_compat",
+ "hw.l2cachesize_compat",
+ "hw.l3cachesize_compat",
+ "hw.logicalcpu",
+ "hw.logicalcpu_max",
+ "hw.machine",
+ "hw.memsize",
+ "hw.model",
+ "hw.ncpu",
+ "hw.nperflevels",
+ "hw.packages",
+ "hw.pagesize",
+ "hw.pagesize_compat",
+ "hw.physicalcpu",
+ "hw.physicalcpu_max",
+ "hw.tbfrequency_compat",
+ "hw.vectorunit",
+ "kern.argmax",
+ "kern.hostname",
+ "kern.maxfilesperproc",
+ "kern.maxproc",
+ "kern.osproductversion",
+ "kern.osrelease",
+ "kern.ostype",
+ "kern.osvariant_status",
+ "kern.osversion",
+ "kern.secure_kernel",
+ "kern.sysv.semmns",
+ "kern.usrstack64",
+ "kern.version",
+ "machdep.cpu.brand_string",
+ "sysctl.proc_cputype",
+ "vm.loadavg",
+)
+_SYSCTL_PREFIXES = (
+ "hw.optional.arm.",
+ "hw.optional.armv8_",
+ "hw.perflevel",
+ "kern.proc.pgrp.",
+ "kern.proc.pid.",
+)
+# fmt: on
+
+_developer_paths_cache: tuple[str, ...] | None = None
+_developer_paths_lock = threading.Lock()
+
+
+def available() -> tuple[bool, str]:
+ """Presence and executability only; whether a profile loads is the probe's."""
+ try:
+ info = os.stat(SANDBOX_EXEC, follow_symlinks = False)
+ except OSError as exc:
+ return False, f"the system Seatbelt launcher is unavailable: {exc}"
+ if (
+ not stat.S_ISREG(info.st_mode)
+ or info.st_uid != 0
+ or info.st_mode & (stat.S_IWGRP | stat.S_IWOTH)
+ ):
+ return False, f"{SANDBOX_EXEC} is not a root-owned, non-user-writable regular file"
+ if not os.access(SANDBOX_EXEC, os.X_OK):
+ return False, f"{SANDBOX_EXEC} is not executable"
+ return True, "the system Seatbelt launcher is present and executable"
+
+
+def _sbpl_string(value: str) -> str:
+ """An SBPL string literal with non-ASCII left RAW: TinyScheme has no u-escape, so json's default breaks accented paths."""
+ return json.dumps(value, ensure_ascii = False)
+
+
+def _validated(path: str) -> str:
+ if not path or not posixpath.isabs(path) or any(c in path for c in _REJECTED_CONTROLS):
+ # TinyScheme cannot interpret JSON's \b, \f or \u00XX control escapes.
+ raise SandboxUnavailableError(
+ f"Seatbelt paths must be absolute and free of control characters: {path!r}"
+ )
+ try:
+ # Reject surrogateescaped bytes before encoding the profile into argv.
+ path.encode("utf-8")
+ except UnicodeEncodeError as exc:
+ raise SandboxUnavailableError(
+ f"Seatbelt paths must be encodable as UTF-8: {path!r}"
+ ) from exc
+ return path
+
+
+def _within(path: str, root: str) -> bool:
+ """Whether ``path`` is ``root`` or sits under it, by whole path components."""
+ return path == root or path.startswith(root.rstrip("/") + "/")
+
+
+def _within_any(path: str, roots: "tuple[str, ...]") -> bool:
+ """``_within`` across both /private alias spellings; a miss is an active denial, not a missing grant."""
+ candidates = _sbpl_spellings(path)
+ return any(
+ _within(candidate, root_spelling)
+ for candidate in candidates
+ for root in roots
+ for root_spelling in _sbpl_spellings(root)
+ )
+
+
+def _rule(operations: str, filters: list[str]) -> str:
+ """A filterless rule is UNCONDITIONAL, so reaching here empty means a list collapsed."""
+ if not filters:
+ raise SandboxUnavailableError(
+ f"the Seatbelt profile would apply {operations!r} unconditionally: no paths survived"
+ )
+ return f"({operations} " + " ".join(filters) + ")"
+
+
+def _sbpl_spellings(path: str, *, resolve: bool = True) -> tuple[str, ...]:
+ """Both /private aliases even when absent; ``resolve = False`` keeps symlink targets out."""
+ selected = [posixpath.abspath(_validated(path))]
+ if resolve:
+ # Validated: a newline in a symlink target would end up inside a quoted string.
+ canonical = _validated(os.path.realpath(path))
+ if canonical not in selected:
+ selected.append(canonical)
+ for spelling in tuple(selected):
+ for short in ("/etc", "/tmp", "/var"):
+ if spelling == short or spelling.startswith(short + "/"):
+ selected.append("/private" + spelling)
+ private = "/private" + short
+ if spelling == private or spelling.startswith(private + "/"):
+ selected.append(spelling[len("/private") :])
+ return tuple(dict.fromkeys(selected))
+
+
+def _path_filters(paths: tuple[str, ...]) -> list[str]:
+ """``(literal ...)`` per spelling, plus ``(subpath ...)`` for directories."""
+ filters: list[str] = []
+ # Keyed by kind, so a file's literal cannot suppress a directory's subpath.
+ seen: set[tuple[str, str]] = set()
+ for path in paths:
+ if not os.path.exists(path):
+ continue
+ kinds = ("literal", "subpath") if os.path.isdir(path) else ("literal",)
+ for spelling in _sbpl_spellings(path):
+ encoded = _sbpl_string(spelling)
+ for kind in kinds:
+ if (kind, encoded) not in seen:
+ seen.add((kind, encoded))
+ filters.append(f"({kind} {encoded})")
+ return filters
+
+
+def _literal_filters(paths: tuple[str, ...], *, resolve: bool = True) -> list[str]:
+ """Existence not required: for a deny, dropping the rule is the wrong way to fail."""
+ filters: list[str] = []
+ seen: set[str] = set()
+ for path in paths:
+ for spelling in _sbpl_spellings(path, resolve = resolve):
+ encoded = _sbpl_string(spelling)
+ if encoded not in seen:
+ seen.add(encoded)
+ filters.append(f"(literal {encoded})")
+ return filters
+
+
+def _ancestor_filters(spellings: tuple[str, ...]) -> list[str]:
+ """Allow ancestor metadata for path resolution, without directory listing."""
+ filters: list[str] = []
+ seen: set[str] = set()
+ for spelling in spellings:
+ current = posixpath.dirname(_validated(spelling))
+ while current:
+ encoded = _sbpl_string(current)
+ if encoded not in seen:
+ seen.add(encoded)
+ filters.append(f"(literal {encoded})")
+ parent = posixpath.dirname(current)
+ if parent == current:
+ break
+ current = parent
+ return filters
+
+
+def _trusted_system_dir(path: str) -> bool:
+ """Require a root-owned directory writable only by root before granting reads."""
+ try:
+ info = os.stat(path)
+ except OSError:
+ return False
+ if not stat.S_ISDIR(info.st_mode):
+ return False
+ return info.st_uid == 0 and not info.st_mode & (stat.S_IWGRP | stat.S_IWOTH)
+
+
+def _developer_paths() -> tuple[str, ...]:
+ """Versioned on many hosts (/Applications/Xcode_16.4.app), so the static list cannot name it."""
+ global _developer_paths_cache
+ with _developer_paths_lock:
+ if _developer_paths_cache is not None:
+ return _developer_paths_cache
+ found: list[str] = []
+ if sys.platform == "darwin" and os.path.exists("/usr/bin/xcode-select"):
+ try:
+ # DEVELOPER_DIR could redirect this recursive grant into the user's home.
+ environment = {k: v for k, v in os.environ.items() if k != "DEVELOPER_DIR"}
+ result = subprocess.run(
+ ["/usr/bin/xcode-select", "-p"],
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ timeout = 10,
+ check = False,
+ env = environment,
+ )
+ candidate = result.stdout.strip()
+ if result.returncode == 0 and candidate and _trusted_system_dir(candidate):
+ for spelling in (os.path.realpath(candidate), candidate):
+ if spelling not in found:
+ found.append(spelling)
+ # xcselect validates against the enclosing app bundle.
+ marker = ".app/Contents/Developer"
+ for spelling in list(found):
+ if spelling.endswith(marker):
+ bundle = spelling[: -len(marker) + len(".app")]
+ if os.path.isdir(bundle) and bundle not in found:
+ found.append(bundle)
+ except (OSError, subprocess.SubprocessError):
+ pass
+ _developer_paths_cache = tuple(found)
+ return _developer_paths_cache
+
+
+def runtime_read_paths(workdir: str | None = None) -> tuple[str, ...]:
+ """Exclude candidates under either workdir spelling BEFORE resolving, or a venv/lib symlink grants ~/.ssh."""
+ candidates: list[str] = [
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "sandbox_site"),
+ ]
+ # Subdirectories, never the prefix (``python -m venv .`` would expose .env); all four prefixes for uv.
+ for prefix in (sys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix):
+ candidates.extend(
+ posixpath.join(prefix, name)
+ for name in ("bin", "include", "lib", "lib64", "libexec", "pyvenv.cfg", "ssl")
+ )
+ # A framework build loads its dyld image from the FILE <prefix>/Python.
+ candidates.append(posixpath.join(prefix, "Python"))
+ try:
+ paths = sysconfig.get_paths()
+ candidates.extend(
+ paths[key]
+ for key in ("stdlib", "platstdlib", "purelib", "platlib", "include", "platinclude")
+ if paths.get(key)
+ )
+ except (KeyError, OSError):
+ pass
+ # Editable source roots are outside site-packages; candidates inherit every guard below.
+ candidates.extend(editable_source_roots())
+ # Keep argv[0]'s spelling without granting its possibly private parent.
+ candidates.append(sys.executable)
+ try:
+ candidates.extend(site.getsitepackages())
+ except AttributeError:
+ pass
+
+ selected: list[str] = []
+ for candidate in candidates:
+ if not candidate or not posixpath.isabs(candidate):
+ continue
+ written = posixpath.abspath(candidate)
+ if workdir is not None and any(
+ _within(written, root) for root in (workdir, os.path.realpath(workdir))
+ ):
+ continue
+ for path in (posixpath.abspath(candidate), os.path.realpath(candidate)):
+ # "/" or "/usr" as a read ROOT hands back most of the host.
+ if path in ("/", "/usr") or not os.path.exists(path):
+ continue
+ if path not in selected and not any(_within(path, root) for root in selected):
+ selected.append(path)
+ return tuple(selected)
+
+
+def _contained_optional_roots() -> tuple[str, ...]:
+ """Optional search roots whose resolved target stays inside an approved prefix."""
+ kept: list[str] = []
+ for root in _OPTIONAL_READ_ROOTS:
+ resolved = os.path.realpath(root)
+ if any(
+ _within(root, prefix) and _within(resolved, prefix)
+ for prefix in _OPTIONAL_ROOT_PREFIXES
+ ):
+ kept.append(root)
+ return tuple(kept)
+
+
+def runtime_paths_under(workdir: str) -> tuple[str, ...]:
+ """Protect Studio's runtime under every writable spelling of the workdir."""
+ roots: list[str] = []
+ for root in (posixpath.abspath(workdir), os.path.realpath(workdir)):
+ if root not in roots:
+ roots.append(root)
+ canonical_root = os.path.realpath(workdir)
+ inside: list[str] = []
+ # Include standalone Python and the framework's top-level dyld image.
+ candidates = [sys.executable, *editable_source_roots()]
+ for prefix in (sys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix):
+ candidates.extend(
+ posixpath.join(prefix, name)
+ for name in ("bin", "include", "lib", "lib64", "libexec", "pyvenv.cfg", "ssl", "Python")
+ )
+ for candidate in candidates:
+ if not os.path.exists(candidate):
+ continue
+ resolved = os.path.realpath(candidate)
+ if not _within(resolved, canonical_root):
+ if candidate is sys.executable and _within(
+ posixpath.abspath(candidate), canonical_root
+ ):
+ # A replaceable interpreter alias would let the next host probe execute tool code.
+ raise WorkdirUnsafeError(
+ "the session workdir holds a link to the Python that runs Studio: "
+ f"{posixpath.abspath(candidate)}"
+ )
+ continue
+ # Protect the alias name as well as its target, or the tool can replace the alias.
+ written = posixpath.abspath(candidate)
+ for form in (resolved, written):
+ if not _within(form, canonical_root):
+ continue
+ relative = posixpath.relpath(form, canonical_root)
+ for other in roots:
+ spelling = posixpath.join(other, relative)
+ if spelling not in inside:
+ inside.append(spelling)
+ return tuple(inside)
+
+
+def _state_filters(paths: tuple[str, ...]) -> list[str]:
+ """Like ``_path_filters``, but a state root that does not exist yet is still denied, as a directory."""
+ filters = _path_filters(tuple(path for path in paths if os.path.exists(path)))
+ for path in paths:
+ if os.path.exists(path):
+ continue
+ for spelling in _sbpl_spellings(path):
+ encoded = _sbpl_string(spelling)
+ filters.extend((f"(literal {encoded})", f"(subpath {encoded})"))
+ return filters
+
+
+def _studio_state_rules(
+ runtime_paths: tuple[str, ...], developer_paths: tuple[str, ...], workdir: str, private_tmp: str
+) -> list[str]:
+ """Deny Studio's own state, then restore only paths the profile already needs (the venv may live there)."""
+ state = studio_state_roots()
+ if not state:
+ return []
+ needed = tuple(
+ path
+ for path in (*runtime_paths, *developer_paths, workdir, private_tmp)
+ if path and _within_any(path, state)
+ )
+ # file-read-data, NOT file-read*: denying stat on the workdir's ancestors breaks os.makedirs.
+ rules = [_rule("deny file-read-data file-map-executable", _state_filters(state))]
+ if needed:
+ # file-read-data named, not only file-read*: a rule on the exact operation beats one on its wildcard, whatever the order.
+ rules.append(
+ _rule(
+ "allow file-read* file-read-data file-test-existence file-map-executable",
+ _path_filters(needed),
+ )
+ )
+ return [rule for rule in rules if rule]
+
+
+def build_profile(
+ *,
+ workdir: str,
+ private_tmp: str,
+ runtime_paths: tuple[str, ...],
+ developer_paths: tuple[str, ...] = (),
+) -> str:
+ """Writes and spawns nothing, so a test can assert on the text anywhere."""
+ readable_paths = (
+ *_READ_ROOTS,
+ *_TLS_TRUST_PATHS,
+ *_contained_optional_roots(),
+ *developer_paths,
+ *_DEVICES,
+ *runtime_paths,
+ # Model folders the approval gate already reads silently.
+ *model_library_roots(),
+ workdir,
+ private_tmp,
+ )
+ read_filters = ['(literal "/")', *_path_filters(readable_paths)]
+ # Optional literals and mDNSResponder's socket still need parent stat.
+ metadata_filters = _ancestor_filters(
+ tuple(
+ spelling
+ for path in readable_paths + (_MDNSRESPONDER_SOCKET,)
+ for spelling in _sbpl_spellings(path)
+ )
+ + tuple(
+ spelling
+ for path in _OPTIONAL_READ_LITERALS
+ for spelling in _sbpl_spellings(path, resolve = False)
+ )
+ )
+ write_filters = _path_filters((workdir, private_tmp))
+ device_filters = _path_filters(_DEVICES)
+ # The workdir too: an AF_UNIX bind is network-bind, not a file operation.
+ tmp_subpaths = tuple(
+ f"(subpath {_sbpl_string(spelling)})"
+ for path in (private_tmp, workdir)
+ for spelling in _sbpl_spellings(path)
+ )
+ mdns_filters = _literal_filters((_MDNSRESPONDER_SOCKET,))
+ # resolve = False: a symlinked /etc/gitconfig must not grant the home. Editable roots as literals, not subpaths.
+ optional_filters = _literal_filters(
+ _OPTIONAL_READ_LITERALS + editable_import_roots(), resolve = False
+ )
+ sysctl_filters = [
+ *(f"(sysctl-name {_sbpl_string(name)})" for name in _SYSCTL_NAMES),
+ *(f"(sysctl-name-prefix {_sbpl_string(name)})" for name in _SYSCTL_PREFIXES),
+ ]
+ lines = [
+ "(version 1)",
+ "(deny default)",
+ # Scoped to the same Seatbelt instance, so a tool cannot poke at Studio.
+ "(allow process-fork)",
+ "(allow process-exec)",
+ "(allow signal (target same-sandbox))",
+ "(allow process-info* (target same-sandbox))",
+ _rule("deny process-exec", _literal_filters(_DENIED_EXECUTABLES)),
+ _rule("allow file-read-metadata", metadata_filters),
+ _rule("allow file-read* file-test-existence", read_filters),
+ _rule("allow file-read* file-test-existence", optional_filters),
+ _rule("allow file-map-executable", read_filters),
+ # AFTER the read allowances (Seatbelt is last-match-wins), or a Studio home under a read root leaks auth.db.
+ *_studio_state_rules(runtime_paths, developer_paths, workdir, private_tmp),
+ _rule("allow file-write*", write_filters),
+ # AFTER the allowance (last-match-wins): Studio's runtime stays read-only even under the workdir.
+ *(
+ [_rule("deny file-write*", _path_filters(runtime_under))]
+ if (runtime_under := runtime_paths_under(workdir))
+ else []
+ ),
+ _rule("allow file-read* file-test-existence file-write-data", device_filters),
+ # bash process substitution opens /dev/fd/63.
+ '(allow file-read* (regex #"^/dev/fd/[0-9]+$"))',
+ '(allow file-write* (regex #"^/dev/fd/[0-9]+$"))',
+ _rule("allow file-ioctl", device_filters),
+ "(allow ipc-posix-sem)",
+ # write-data: libomp writes its registration into the segment.
+ "(allow ipc-posix-shm-read-data ipc-posix-shm-write-create "
+ "ipc-posix-shm-write-data ipc-posix-shm-write-unlink "
+ '(ipc-posix-name-regex #"^/__KMP_REGISTERED_LIB_[0-9]+$"))',
+ "(allow ipc-posix-shm-read-data ipc-posix-shm-write-create "
+ "ipc-posix-shm-write-data ipc-posix-shm-write-unlink "
+ '(ipc-posix-name-regex #"^/torch_[0-9]+_[0-9]+_[0-9]+$"))',
+ "(allow ipc-posix-shm-read-data ipc-posix-shm-write-create "
+ "ipc-posix-shm-write-data ipc-posix-shm-write-unlink "
+ '(ipc-posix-name-regex #"^/psm_[0-9a-f]+$"))',
+ # Unfiltered: configd resolvers create route and AF_SYSTEM sockets; network authority only, never filesystem.
+ "(allow system-socket)",
+ # IP only: an unfiltered bind covers AF_UNIX at paths no file rule governs.
+ '(allow network-bind (local ip "*:*"))',
+ "(allow network-inbound)",
+ # Filtered to ip: an unfiltered outbound covers AF_UNIX, e.g. /var/run/docker.sock.
+ '(allow network-outbound (remote ip "*:*"))',
+ # One path filter per endpoint; combining paths breaks multiprocessing on macOS 15.
+ *(f"(allow network-bind (local unix-socket {path}))" for path in tmp_subpaths),
+ *(f"(allow network-outbound (remote unix-socket {path}))" for path in tmp_subpaths),
+ # Both filter forms: which one a macOS release matches is untestable here.
+ _rule("allow network-outbound", mdns_filters),
+ *(f"(allow network-outbound (remote unix-socket {path}))" for path in mdns_filters),
+ _rule("allow sysctl-read", sysctl_filters),
+ '(allow iokit-open (iokit-registry-entry-class "RootDomainUserClient"))',
+ "(allow mach-lookup\n"
+ + "\n".join(f" (global-name {_sbpl_string(name)})" for name in _MACH_SERVICES)
+ + ")",
+ ]
+ return "\n".join(lines) + "\n"
+
+
+def _tmpdir(env: dict[str, str], workdir: str, private_tmp: str) -> str:
+ """The caller's TMPDIR when inside the workdir: ``private_tmp`` is deleted when the call ends."""
+ requested = env.get("TMPDIR") or ""
+ if requested and _within(posixpath.abspath(requested), workdir):
+ return requested
+ return private_tmp
+
+
+def _sandbox_environment(env: dict[str, str], workdir: str, private_tmp: str) -> dict[str, str]:
+ """HOME and TMPDIR must point inside the sandbox; DYLD_* is the linker-injection surface."""
+ sanitized = {
+ key: value
+ for key, value in env.items()
+ if not key.startswith("DYLD_")
+ and key
+ not in {
+ "DISPLAY",
+ "SSH_AUTH_SOCK",
+ "XPC_SERVICE_NAME",
+ "WAYLAND_DISPLAY",
+ "PULSE_SERVER",
+ }
+ }
+ tmpdir = _tmpdir(env, workdir, private_tmp)
+ # Appended, so an installed package cannot shadow the sandbox_site shim.
+ packages = posixpath.join(workdir, SESSION_PACKAGES_RELPATH)
+ sanitized.update(
+ {
+ "HOME": workdir,
+ "TMPDIR": tmpdir,
+ "TMP": tmpdir,
+ "TEMP": tmpdir,
+ "XDG_RUNTIME_DIR": private_tmp,
+ "PIP_TARGET": packages,
+ # <target>/bin LAST: it is tool-writable and must not shadow a command approval treats as safe.
+ "PATH": os.pathsep.join(
+ part for part in (env.get("PATH") or "", posixpath.join(packages, "bin")) if part
+ ),
+ "PYTHONPATH": os.pathsep.join(
+ part for part in (env.get("PYTHONPATH") or "", packages) if part
+ ),
+ }
+ )
+ developer_paths = _developer_paths()
+ if developer_paths and "DEVELOPER_DIR" not in sanitized:
+ # xcselect honours DEVELOPER_DIR before the xcode_select link.
+ sanitized["DEVELOPER_DIR"] = developer_paths[0]
+ return sanitized
+
+
+def prepare(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:
+ ok, reason = available()
+ if not ok:
+ # A user-writable argv[0] must not reach Popen even if the probe missed it.
+ raise SandboxUnavailableError(reason)
+ try:
+ workdir = _validated(os.path.abspath(plan.workdir))
+ except SandboxUnavailableError as exc:
+ # Workdir refusals must not select auto's unisolated fallback.
+ raise WorkdirUnsafeError(str(exc)) from exc
+ if not os.path.isdir(workdir):
+ raise WorkdirUnsafeError(f"the session workdir does not exist: {workdir}")
+ if posixpath.dirname(workdir) == workdir:
+ # "/" would make the entire filesystem the writable set.
+ raise WorkdirUnsafeError(f"the session workdir cannot be a filesystem root: {workdir}")
+ # file-write* on the workdir writes through external hard links to the host inode.
+ workdir_limitations = scan_workdir_for_host_channels(workdir)
+ # /tmp, not /var/folders, keeping it out of the confidential per-user container.
+ private_tmp = tempfile.mkdtemp(
+ prefix = "us-seatbelt-", dir = "/tmp" if sys.platform == "darwin" else None
+ )
+ try:
+ runtime_paths = tuple(
+ path for path in runtime_read_paths(workdir) if not _within(path, workdir)
+ )
+ profile = build_profile(
+ workdir = workdir,
+ private_tmp = private_tmp,
+ runtime_paths = runtime_paths,
+ developer_paths = _developer_paths(),
+ )
+ return PreparedSandboxLaunch(
+ argv = (SANDBOX_EXEC, "-p", profile, "--", *plan.argv),
+ workdir = workdir,
+ env = _sandbox_environment(plan.env, workdir, private_tmp),
+ # Preserved: it is the os.setsid() tools.py's killpg teardown signals.
+ preexec_fn = plan.preexec_fn,
+ backend = BACKEND_NAME,
+ cleanup_paths = [private_tmp],
+ timeout_seconds = plan.timeout_seconds,
+ close_fds = plan.close_fds,
+ terminate_descendants = plan.terminate_descendants,
+ launch_limitations = workdir_limitations,
+ )
+ except Exception:
+ shutil.rmtree(private_tmp, ignore_errors = True)
+ raise
diff --git a/studio/backend/core/inference/sandbox_probe.py b/studio/backend/core/inference/sandbox_probe.py
new file mode 100644
index 00000000000..491f1ccd632
--- /dev/null
+++ b/studio/backend/core/inference/sandbox_probe.py
@@ -0,0 +1,394 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Validate isolation against controls first verified on the host; outside writes are checked from the host."""
+
+from __future__ import annotations
+import ctypes
+import os
+import shutil
+import socket
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from typing import Any
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+_PR_SET_NO_NEW_PRIVS = 38
+try:
+ # Resolved at import: an import after the fork can deadlock on the import lock.
+ _libc = ctypes.CDLL(None, use_errno = True) if sys.platform == "linux" else None
+except OSError: # pragma: no cover - a libc that will not load
+ _libc = None
+
+# ALONE on stdout: a payload that printed it early and died would satisfy "in".
+PROBE_TOKEN = "UNSLOTH_SANDBOX_PROBE_OK"
+_SENTINEL_TOKEN = "unsloth-host-sentinel-must-not-be-readable"
+# Finding this on the host afterwards is the escape; the write need not raise.
+_OUTSIDE_WRITE_TOKEN = "unsloth-sandbox-escaped-to-the-host"
+
+PROBE_TIMEOUT_SECONDS = 30.0
+# Correctness does not rest on the TTL: the key carries the runtime identity and a failed launch invalidates.
+_CACHE_TTL_SECONDS = 900.0
+# UNAVAILABLE keeps a short TTL: the user fixing their host does not move the cache key.
+_CACHE_TTL_UNAVAILABLE_SECONDS = 60.0
+_CACHE_MAX_ENTRIES = 8
+
+# ``sun_path`` is 108 bytes and multiprocessing appends about 32.
+_MAX_PROBE_BASE_LEN = 59
+
+_cache_lock = threading.Lock()
+_cache: dict[tuple[str, str], tuple[float, bool, str]] = {}
+
+
+def reset_probe_cache() -> None:
+ """Forget every cached verdict. For tests only."""
+ with _cache_lock:
+ _cache.clear()
+
+
+def _cache_get(key: tuple[str, str]) -> tuple[bool, str] | None:
+ now = time.monotonic()
+ with _cache_lock:
+ entry = _cache.get(key)
+ if entry is None:
+ return None
+ expires_at, available, reason = entry
+ if expires_at <= now:
+ _cache.pop(key, None)
+ return None
+ return available, reason
+
+
+def _cache_put(key: tuple[str, str], available: bool, reason: str) -> None:
+ with _cache_lock:
+ ttl = _CACHE_TTL_SECONDS if available else _CACHE_TTL_UNAVAILABLE_SECONDS
+ _cache[key] = (time.monotonic() + ttl, available, reason)
+ while len(_cache) > _CACHE_MAX_ENTRIES:
+ _cache.pop(next(iter(_cache)))
+
+
+_PREAMBLE = '''import multiprocessing.reduction, os, socket, subprocess, sys
+
+
+def must_raise(label, fn):
+ """A negative control: the host proved it works, so in here it must not."""
+ try:
+ fn()
+ except OSError:
+ return
+ raise AssertionError(label)
+'''
+
+
+def _negative_controls(
+ sentinel: str, escape: str, outside: str, interpreter_writable: bool, abstract: "bytes | None"
+) -> str:
+ """Attempt direct and symlink sentinel reads, an outside write, and socket access."""
+ interpreter_leg = ""
+ if interpreter_writable:
+ interpreter_leg = (
+ '\nmust_raise("opened the interpreter for writing", '
+ 'lambda: open(sys.executable, "ab").close())\n'
+ )
+ abstract_leg = ""
+ if abstract is not None:
+ abstract_leg = (
+ f'\nmust_raise("connected to a host abstract unix socket", lambda: '
+ f"socket.socket(socket.AF_UNIX, socket.SOCK_STREAM).connect({abstract!r}))\n"
+ )
+ return f"""
+must_raise("read the host sentinel", lambda: open({sentinel!r}, "rb").close())
+must_raise("followed a workdir symlink to the host sentinel",
+ lambda: open({escape!r}, "rb").close())
+{interpreter_leg}{abstract_leg}
+# Allowed to succeed against a private tmpfs; the host checks afterwards that
+# nothing arrived. See _negative_controls.
+try:
+ with open({outside!r}, "w", encoding = "utf-8") as handle:
+ handle.write({_OUTSIDE_WRITE_TOKEN!r})
+except OSError:
+ pass
+"""
+
+
+def _positive_controls(workdir: str) -> str:
+ return f"""
+private = os.path.join({workdir!r}, "private.txt")
+with open(private, "w", encoding = "utf-8") as handle:
+ handle.write("sandbox-write-ok")
+with open(private, encoding = "utf-8") as handle:
+ if handle.read() != "sandbox-write-ok":
+ raise AssertionError("workdir read-back did not match what was written")
+
+# numpy/torch in a tool call fork workers, and a sandbox that breaks the
+# socketpair breaks every one of them.
+left, right = socket.socketpair()
+try:
+ left.sendall(b"ping")
+ if right.recv(4) != b"ping":
+ raise AssertionError("socketpair did not deliver")
+ right.sendall(b"pong")
+ if left.recv(4) != b"pong":
+ raise AssertionError("socketpair did not deliver in reverse")
+ # Descriptor passing through the resource sharer, which is how Pool and
+ # ProcessPoolExecutor hand file handles between processes.
+ duplicated = multiprocessing.reduction.DupFd(left.fileno()).detach()
+ os.close(duplicated)
+finally:
+ left.close()
+ right.close()
+
+# A child interpreter, because tool code shells out to python constantly.
+child = subprocess.run(
+ [sys.executable, "-I", "-S", "-c", "print(42)"],
+ stdin = subprocess.DEVNULL,
+ capture_output = True,
+ timeout = 20,
+)
+if child.returncode != 0 or child.stdout.strip() != b"42":
+ raise AssertionError("a python child could not run: " + repr(child.stderr[-200:]))
+"""
+
+
+def _payload(
+ workdir: str,
+ sentinel: str,
+ escape: str,
+ outside: str,
+ interpreter_writable: bool,
+ abstract: "bytes | None",
+) -> str:
+ """Passed as source on the command line, independent of how the backend exposes the workdir."""
+ return (
+ _PREAMBLE
+ + _negative_controls(sentinel, escape, outside, interpreter_writable, abstract)
+ + _positive_controls(workdir)
+ + f"\nprint({PROBE_TOKEN!r})\n"
+ )
+
+
+def _no_new_privs() -> None:
+ """Logged, not swallowed: failing to set it makes the probe MORE permissive than the launch."""
+ if _libc is None:
+ return
+ if _libc.prctl(_PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
+ logger.warning("The sandbox probe could not set PR_SET_NO_NEW_PRIVS")
+
+
+def _abstract_control() -> "tuple[bytes | None, Any]":
+ """Nothing without a scope to test, or when the host cannot reach its own socket."""
+ if sys.platform != "linux":
+ return None, None
+ from . import sandbox_landlock
+
+ if not sandbox_landlock.abstract_scope_supported():
+ return None, None
+ name = b"\0unsloth-probe-" + os.urandom(8).hex().encode()
+ listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ try:
+ listener.bind(name)
+ listener.listen(1)
+ control = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ control.settimeout(5)
+ try:
+ control.connect(name)
+ finally:
+ control.close()
+ except OSError:
+ listener.close()
+ return None, None
+ return name, listener
+
+
+def _host_saw_the_write(outside: str) -> bool:
+ """Checked on the host: a private tmpfs lets the write succeed inside while nothing arrives here."""
+ try:
+ with open(outside, encoding = "utf-8") as handle:
+ return _OUTSIDE_WRITE_TOKEN in handle.read()
+ except OSError:
+ return False
+
+
+def _host_payload(workdir: str) -> str:
+ return _PREAMBLE + _positive_controls(workdir) + f"\nprint({PROBE_TOKEN!r})\n"
+
+
+def _probe_base() -> str:
+ """A scratch root short enough for the fd-passing control's AF_UNIX address."""
+ # Private roots FIRST: TMPDIR may sit under a read-only bind and fail the negative read control.
+ roots: list[str | None] = [root for root in ("/tmp", "/var/tmp") if os.path.isdir(root)]
+ roots.append(None) # None = the platform default
+ fallback = None
+ for root in roots:
+ try:
+ base = tempfile.mkdtemp(prefix = "unsloth-probe-", dir = root)
+ except OSError:
+ continue
+ if len(base) <= _MAX_PROBE_BASE_LEN:
+ if fallback is not None:
+ shutil.rmtree(fallback, ignore_errors = True)
+ return base
+ if fallback is None:
+ fallback = base
+ else:
+ shutil.rmtree(base, ignore_errors = True)
+ if fallback is not None:
+ return fallback
+ return tempfile.mkdtemp(prefix = "unsloth-probe-")
+
+
+def _host_positive_controls(workdir: str, sentinel: str, outside: str, env: dict[str, str]) -> str:
+ """Prove every control would come out the other way on the host; returns why not, or ""."""
+ try:
+ with open(sentinel, encoding = "utf-8") as handle:
+ if handle.read() != _SENTINEL_TOKEN:
+ return "the probe sentinel did not contain what was written to it"
+ except OSError as exc:
+ return f"the host itself could not read the probe sentinel ({exc})"
+ try:
+ with open(outside, "w", encoding = "utf-8") as handle:
+ handle.write("host-write-ok")
+ os.unlink(outside)
+ except OSError as exc:
+ return f"the host itself could not write outside the probe workdir ({exc})"
+ try:
+ completed = subprocess.run(
+ (sys.executable, "-I", "-S", "-c", _host_payload(workdir)),
+ cwd = workdir,
+ env = env,
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ timeout = PROBE_TIMEOUT_SECONDS,
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ return f"the host itself could not run the probe's positive controls ({exc})"
+ if completed.returncode != 0 or completed.stdout.strip() != PROBE_TOKEN.encode():
+ detail = (completed.stderr or b"").decode("utf-8", "replace").strip()[-300:]
+ return (
+ "the host itself could not pass the probe's positive controls "
+ f"(exit {completed.returncode}): {detail or 'no output'}"
+ )
+ return ""
+
+
+def probe(backend: Any, *, force: bool = False) -> tuple[bool, str]:
+ """Never raises: every failure becomes ``(False, reason)``."""
+ backend_name = str(getattr(backend, "BACKEND_NAME", "unknown"))
+ try:
+ from .os_sandbox import ToolLaunchPlan, _runtime_identity
+ key = (backend_name, _runtime_identity())
+ except Exception as exc: # noqa: BLE001 - a probe never breaks its caller
+ return False, f"the sandbox probe could not identify this runtime: {exc}"
+
+ if not force:
+ cached = _cache_get(key)
+ if cached is not None:
+ return cached
+
+ available, reason = _run_probe(backend, backend_name, ToolLaunchPlan)
+ _cache_put(key, available, reason)
+ return available, reason
+
+
+def _run_probe(backend: Any, backend_name: str, plan_cls: Any) -> tuple[bool, str]:
+ """The verdict is reached INSIDE the try: cleanup first would report every escape as a pass."""
+ base = None
+ prepared = None
+ abstract_listener = None
+ try:
+ base = _probe_base()
+ workdir = os.path.join(base, "work")
+ os.mkdir(workdir)
+ # The host's would test a directory the sandbox must not expose.
+ temp_dir = os.path.join(workdir, "tmp")
+ os.mkdir(temp_dir)
+ sentinel = os.path.join(base, "host-sentinel.txt")
+ with open(sentinel, "w", encoding = "utf-8") as handle:
+ handle.write(_SENTINEL_TOKEN)
+ escape = os.path.join(workdir, "escape")
+ os.symlink(sentinel, escape)
+ outside = os.path.join(base, "outside-write.txt")
+ env = {
+ "PATH": os.environ.get("PATH", "/usr/local/bin:/usr/bin:/bin"),
+ "HOME": workdir,
+ "TMPDIR": temp_dir,
+ "LANG": os.environ.get("LANG", "C.UTF-8"),
+ "PYTHONIOENCODING": "utf-8",
+ }
+
+ blocked = _host_positive_controls(workdir, sentinel, outside, env)
+ if blocked:
+ return False, blocked
+
+ # A leg the host cannot fail either proves nothing, so it is dropped, not passed.
+ interpreter_writable = os.access(sys.executable, os.W_OK)
+ # Proven reachable from out here first, so a refusal inside is the scope.
+ abstract, abstract_listener = _abstract_control()
+
+ plan = plan_cls(
+ argv = (
+ sys.executable,
+ "-I",
+ "-S",
+ "-c",
+ _payload(workdir, sentinel, escape, outside, interpreter_writable, abstract),
+ ),
+ workdir = workdir,
+ env = env,
+ # A setuid bwrap dies under no_new_privs, so without this the probe qualifies a launch that fails after Popen.
+ preexec_fn = _no_new_privs,
+ requested_mode = "required",
+ execution_kind = "python",
+ )
+ prepared = backend.prepare(plan)
+ completed = subprocess.run(
+ prepared.argv,
+ cwd = prepared.workdir,
+ env = prepared.env,
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ preexec_fn = prepared.preexec_fn,
+ pass_fds = tuple(prepared.pass_fds),
+ timeout = PROBE_TIMEOUT_SECONDS,
+ )
+ if completed.returncode != 0 or completed.stdout.strip() != PROBE_TOKEN.encode():
+ detail = (completed.stderr or b"").decode("utf-8", "replace").strip()[-300:]
+ if not detail:
+ detail = (completed.stdout or b"").decode("utf-8", "replace").strip()[-300:]
+ return False, (
+ f"the {backend_name} live probe failed "
+ f"(exit {completed.returncode}): {detail or 'no output'}"
+ )
+ if _host_saw_the_write(outside):
+ return False, (
+ f"the {backend_name} live probe wrote through to the host: a file created "
+ "outside the sandbox workdir arrived on the real filesystem"
+ )
+ caveat = (
+ ""
+ if interpreter_writable
+ else " (the interpreter is not host-writable, so that leg was skipped)"
+ )
+ return True, f"the {backend_name} live isolation probe passed{caveat}"
+ except subprocess.TimeoutExpired:
+ return False, f"the {backend_name} live probe timed out after {PROBE_TIMEOUT_SECONDS:.0f}s"
+ except Exception as exc: # noqa: BLE001 - see the docstring on probe()
+ logger.debug("sandbox probe for %s could not run", backend_name, exc_info = True)
+ return False, f"the {backend_name} live probe could not run: {type(exc).__name__}: {exc}"
+ finally:
+ if abstract_listener is not None:
+ abstract_listener.close()
+ if prepared is not None:
+ try:
+ prepared.cleanup()
+ except Exception: # noqa: BLE001 - cleanup failure is not a verdict
+ logger.debug("sandbox probe cleanup failed", exc_info = True)
+ if base is not None:
+ shutil.rmtree(base, ignore_errors = True)
diff --git a/studio/backend/core/inference/sandbox_seccomp.py b/studio/backend/core/inference/sandbox_seccomp.py
new file mode 100644
index 00000000000..07fb95100ed
--- /dev/null
+++ b/studio/backend/core/inference/sandbox_seccomp.py
@@ -0,0 +1,110 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Seccomp filter for bwrap: blocks AF_VSOCK, io_uring, keyrings and nested user namespaces; AF_UNIX/AF_INET allowed on purpose."""
+
+from __future__ import annotations
+
+import errno
+import platform
+import struct
+import sys
+import tempfile
+from typing import BinaryIO
+
+# machine -> (AUDIT_ARCH, socket, socketpair); anything else is refused.
+_ABIS = {
+ "x86_64": (0xC000003E, 41, 53),
+ "amd64": (0xC000003E, 41, 53),
+ "aarch64": (0xC00000B7, 198, 199),
+ "arm64": (0xC00000B7, 198, 199),
+}
+_USERNS_SYSCALLS = {
+ "x86_64": (56, 272, 435),
+ "amd64": (56, 272, 435),
+ "aarch64": (220, 97, 435),
+ "arm64": (220, 97, 435),
+}
+_IO_URING = (425, 426, 427)
+# Denied rather than joining an empty keyring, since joining needs the syscall being removed.
+_KEYRING_SYSCALLS = {
+ "x86_64": (248, 249, 250),
+ "amd64": (248, 249, 250),
+ "aarch64": (217, 218, 219),
+ "arm64": (217, 218, 219),
+}
+_X32_SYSCALL_BIT = 0x40000000
+_CLONE_NEWUSER = 0x10000000
+_AF_VSOCK = 40
+
+# struct seccomp_data: nr@0, arch@4, args[0]@16.
+_LOAD, _JEQ, _JSET, _RET = 0x20, 0x15, 0x45, 0x06
+_KILL = 0x80000000
+_EPERM = 0x00050000 | errno.EPERM
+_ENOSYS = 0x00050000 | errno.ENOSYS
+_ALLOW = 0x7FFF0000
+
+
+def program(machine: str, *, block_userns: bool = False) -> tuple[tuple[int, int, int, int], ...]:
+ key = machine.lower()
+ if key not in _ABIS or sys.byteorder != "little":
+ raise RuntimeError(
+ "the Studio sandbox seccomp filter requires little-endian x86_64 or aarch64"
+ )
+ audit_arch, socket_nr, socketpair_nr = _ABIS[key]
+ code: list[tuple[int, int, int, int]] = [
+ (_LOAD, 0, 0, 4),
+ (_JEQ, 1, 0, audit_arch),
+ (_RET, 0, 0, _KILL), # an ABI switch would read args at other offsets
+ (_LOAD, 0, 0, 0),
+ ]
+ if block_userns:
+ # clone3() must report ENOSYS so glibc falls back to clone(), whose flags are checked.
+ clone_nr, unshare_nr, clone3_nr = _USERNS_SYSCALLS[key]
+ code += [
+ # unshare() is filtered on its flags, not refused: only CLONE_NEWUSER is the target.
+ (_JEQ, 0, 4, unshare_nr),
+ (_LOAD, 0, 0, 16),
+ (_JSET, 0, 1, _CLONE_NEWUSER),
+ (_RET, 0, 0, _EPERM),
+ (_LOAD, 0, 0, 0),
+ (_JEQ, 0, 1, clone3_nr),
+ (_RET, 0, 0, _ENOSYS),
+ (_JEQ, 0, 4, clone_nr),
+ (_LOAD, 0, 0, 16),
+ (_JSET, 0, 1, _CLONE_NEWUSER),
+ (_RET, 0, 0, _EPERM),
+ (_LOAD, 0, 0, 0),
+ ]
+ if key in ("x86_64", "amd64"):
+ # x32 numbers alias the 64-bit table, so an unfiltered x32 call bypasses this filter.
+ code += [(_JSET, 0, 1, _X32_SYSCALL_BIT), (_RET, 0, 0, _KILL)]
+ for number in (*_IO_URING, *_KEYRING_SYSCALLS[key]):
+ code += [(_JEQ, 0, 1, number), (_RET, 0, 0, _EPERM)]
+ code += [
+ (_JEQ, 1, 0, socket_nr),
+ (_JEQ, 0, 3, socketpair_nr),
+ (_LOAD, 0, 0, 16),
+ (_JEQ, 0, 1, _AF_VSOCK),
+ (_RET, 0, 0, _EPERM),
+ (_RET, 0, 0, _ALLOW),
+ ]
+ return tuple(code)
+
+
+def program_bytes(*, block_userns: bool = False, machine: str | None = None) -> bytes:
+ instructions = program(machine or platform.machine(), block_userns = block_userns)
+ return b"".join(struct.pack("=HBBI", *instruction) for instruction in instructions)
+
+
+def filter_file(*, block_userns: bool = False) -> BinaryIO:
+ """Rewound because bwrap reads ``--seccomp FD`` to EOF."""
+ stream = tempfile.TemporaryFile(prefix = "unsloth-sandbox-seccomp-")
+ try:
+ stream.write(program_bytes(block_userns = block_userns))
+ stream.flush()
+ stream.seek(0)
+ except Exception:
+ stream.close()
+ raise
+ return stream
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index e6e6df11dde..03aea307589 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -1754,7 +1754,14 @@ async def stream_with_studio_tools(
reprompts = max_reprompts
continue
- def _invoke(output_callback: Any, call = decision) -> str:
+ # Only a call the user answered: the executor lets it reach the host paths it names.
+ host_access_approved = verdict not in (None, "deny")
+
+ def _invoke(
+ output_callback: Any,
+ call = decision,
+ approved = host_access_approved,
+ ) -> str:
kwargs: dict[str, Any] = {
"cancel_event": cancel_event,
"timeout": None if tool_call_timeout >= 9999 else tool_call_timeout,
@@ -1768,6 +1775,8 @@ async def stream_with_studio_tools(
# leaves the replaced response in them.
if accepts_kwarg(execute_tool, "conversation_branch"):
kwargs["conversation_branch"] = request_branch
+ if approved and accepts_kwarg(execute_tool, "host_access_approved"):
+ kwargs["host_access_approved"] = True
# And a budget, so the tool's clamp is not skipped. Unsloth cannot measure an external model's window,
# and a custom OpenAI-compatible endpoint can be a small local server, so a model-chosen 8 chunks is
# roughly 4K tokens replayed on every later call. Unmeasurable means one recall's worth. Explicitly
diff --git a/studio/backend/core/inference/tool_confinement.py b/studio/backend/core/inference/tool_confinement.py
index 9945aad18b8..19cc94f9a25 100644
--- a/studio/backend/core/inference/tool_confinement.py
+++ b/studio/backend/core/inference/tool_confinement.py
@@ -112,6 +112,11 @@ class Confinement:
def wrap(self, argv: list[str]) -> list[str]:
return [*self.wrapper, *argv] if self.wrapper else argv
+ @property
+ def confines(self) -> bool:
+ """Whether this confines anything; ``unconfined-by-owner`` is a placeholder and must not skip the generic sandbox."""
+ return self.preexec is not None or bool(self.wrapper)
+
def unconfined_tools_allowed() -> bool:
return (os.environ.get(_OVERRIDE_ENV) or "").strip().lower() in ("1", "true", "yes", "on")
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 2f6002c31fc..9420cc11fea 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -78,6 +78,8 @@ from core.inference.tool_confinement import ToolConfinementUnavailable, account_
from pathlib import Path
from utils.paths.storage_roots import RetiredAccountError, ensure_dir
+from . import os_sandbox
+
from loggers import get_logger
logger = get_logger(__name__)
@@ -9124,7 +9126,8 @@ def _is_trusted_windows_program_dir(path: str) -> bool:
# not dot-named: the walks skip dot-dirs, which would hide a model's /tmp write. not "tmp": too common in a workspace,
# and adopting one is what broke the walks.
-_SANDBOX_TEMP_DIRNAME = "unsloth-tmp"
+# Shared with os_sandbox: a drifted name would silently disable the scan's exemption.
+_SANDBOX_TEMP_DIRNAME = os_sandbox.TOOL_TEMP_DIRNAME
def _sandbox_temp_dir(workdir: str) -> str:
@@ -9536,6 +9539,187 @@ def _bypass_preexec():
pass
+# Never read back by the executors, so a concurrent call can only make this stale.
+_last_tool_execution_record: "os_sandbox.ToolExecutionRecord | None" = None
+
+
+def _note_tool_execution(record) -> None:
+ """Built from a live probe, never from model output, so it is safe to show as a badge."""
+ global _last_tool_execution_record
+ if record is None:
+ return
+ _last_tool_execution_record = record
+ logger.info("tool execution mode: %s", record.as_dict())
+
+
+def _requested_execution_mode(tool_execution_mode: str, disable_sandbox: bool) -> str:
+ """Require disable_sandbox for full access; checked here because managed accounts skip the planner."""
+ if tool_execution_mode not in os_sandbox.TOOL_EXECUTION_MODES:
+ raise os_sandbox.SandboxUnavailableError(
+ f"TOOL_EXECUTION_MODE_INVALID: {tool_execution_mode!r} is not a tool "
+ f"execution mode ({', '.join(os_sandbox.TOOL_EXECUTION_MODES)})",
+ remediation = "Use 'auto' or 'required'.",
+ )
+ if disable_sandbox:
+ return "full"
+ if tool_execution_mode == "full":
+ raise os_sandbox.SandboxUnavailableError(
+ "TOOL_EXECUTION_MODE_INVALID: full access is not requestable through "
+ "tool_execution_mode",
+ remediation = "Full access is granted with disable_sandbox (Bypass Permissions).",
+ )
+ return tool_execution_mode
+
+
+_with_session_packages = os_sandbox.with_session_packages
+
+
+def _software_safeguards_launch(plan, fault: str):
+ """Prepare an unisolated launch, retaining session packages and recording *fault*."""
+ full = plan.requested_mode == "full"
+ return os_sandbox.PreparedSandboxLaunch(
+ argv = plan.argv,
+ workdir = plan.workdir,
+ env = _with_session_packages(plan.env, plan.workdir),
+ preexec_fn = plan.preexec_fn,
+ backend = "software-safeguards",
+ timeout_seconds = plan.timeout_seconds,
+ close_fds = plan.close_fds,
+ terminate_descendants = plan.terminate_descendants,
+ execution_record = os_sandbox.ToolExecutionRecord(
+ requested_mode = plan.requested_mode,
+ # Do not claim software safeguards for a launch that skipped them.
+ effective_mode = "full" if full else "software_safeguards",
+ environment = sys.platform,
+ backend = "software-safeguards",
+ profile_id = "full-access" if full else "software-safeguards-v1",
+ probe_generation = "",
+ os_isolation = False,
+ retained_safeguards = tuple(
+ item
+ for item in (
+ os_sandbox._FULL_SAFEGUARDS if full else os_sandbox._SOFTWARE_SAFEGUARDS
+ )
+ if item != "timeout" or plan.timeout_seconds is not None
+ ),
+ limitations = (
+ ("security_restrictions_disabled", fault)
+ if full
+ else (*os_sandbox._software_only_limitations(), fault)
+ ),
+ ),
+ )
+
+
+def _reaches_host_paths(kind: str, text: str) -> bool:
+ """Whether the call names a host path outside the silent roots: the check that put it in front of the user."""
+ try:
+ if kind == "python":
+ tree, error = _parse_python(text)
+ return error is None and _python_reaches_outside_sandbox(tree, text)
+ # Decoded like the approval classifier, or cat $'/home/u/x' prompts yet stays isolated.
+ decoded = _decode_ansi_c(text, keep_one_word = True)
+ command = decoded.replace("\r\n", ";").replace("\n", ";").replace("\r", ";")
+ for variant in {command, _expand_shell_assignments(_expand_param_defaults(command))}:
+ lexer = shlex.shlex(variant, posix = True, punctuation_chars = ";&|()")
+ lexer.whitespace_split = True
+ if _terminal_reaches_outside_sandbox(list(lexer), variant):
+ return True
+ except Exception: # noqa: BLE001 - unclassifiable stays isolated
+ return False
+ return False
+
+
+def _prepare_tool_launch(plan, *, host_access_approved: bool = False):
+ """Allow auto fallback for unavailable backends or unexpected planner errors; unsafe workdirs and build failures refuse."""
+ if host_access_approved and plan.requested_mode == "auto":
+ return _software_safeguards_launch(plan, "user_approved_host_access")
+ try:
+ prepared = os_sandbox.prepare_tool_launch(plan)
+ if plan.preexec_fn is not None and prepared.preexec_fn is None:
+ # Preserve setsid so timeout cleanup cannot kill the server's process group.
+ logger.warning(
+ "Sandbox backend %s dropped the launch pre-exec; restoring it",
+ prepared.backend,
+ )
+ prepared.preexec_fn = plan.preexec_fn
+ if prepared.execution_record is not None and not prepared.execution_record.os_isolation:
+ # The other door: os_sandbox returns its own fallback through here.
+ prepared.env = _with_session_packages(prepared.env, plan.workdir)
+ return prepared
+ except (os_sandbox.WorkdirUnsafeError, os_sandbox.SandboxBuildError):
+ # These failures can be tool-induced; fallback would let code remove its own boundary.
+ raise
+ except os_sandbox.SandboxUnavailableError:
+ # Any other refusal means the backend stopped being available.
+ if plan.requested_mode == "required" or (
+ plan.requested_mode not in os_sandbox.TOOL_EXECUTION_MODES
+ ):
+ raise
+ logger.warning(
+ "The sandbox backend is no longer available, running with software safeguards",
+ exc_info = True,
+ )
+ return _software_safeguards_launch(plan, "sandbox_became_unavailable")
+ except Exception as exc: # noqa: BLE001 - auto falls back on unexpected planner errors
+ logger.warning("Sandbox planning failed, running with software safeguards", exc_info = True)
+ if plan.requested_mode == "required":
+ raise os_sandbox.SandboxUnavailableError(
+ f"OS_ISOLATION_UNAVAILABLE: the sandbox planner failed: {exc}",
+ remediation = os_sandbox.linux_unavailable_remediation()
+ if sys.platform == "linux"
+ else "This host cannot start an OS sandbox.",
+ ) from exc
+ return _software_safeguards_launch(plan, "sandbox_planner_error")
+
+
+# Launcher stderr prefixes for refusing to build the sandbox, not payload failures.
+_LAUNCHER_FAILURE_MARKERS = {
+ "bubblewrap": "bwrap: ",
+ "macos-seatbelt": "sandbox-exec: ",
+}
+
+
+def _forget_sandbox_capability_if_the_backend_failed(prepared, output: str) -> None:
+ """Drop a stale probe verdict found at exec, so it costs one call rather than the cache's lifetime."""
+ if prepared is None or prepared.backend == "software-safeguards":
+ return
+ if not output.startswith("Exit code "):
+ return
+ # Keyed on the backend that ran: Seatbelt reports `sandbox-exec:`, not `bwrap:`.
+ marker = _LAUNCHER_FAILURE_MARKERS.get(prepared.backend)
+ if marker is None or marker not in output[:400]:
+ return
+ logger.warning("The sandbox backend failed at launch; re-probing the capability")
+ try:
+ from .sandbox_probe import reset_probe_cache
+ reset_probe_cache()
+ if sys.platform == "linux":
+ from .sandbox_linux import reset_cache_verdicts
+ reset_cache_verdicts()
+ except Exception: # noqa: BLE001 - a cache reset never breaks a tool result
+ logger.debug("could not reset the sandbox probe cache", exc_info = True)
+
+
+def _sandbox_refusal(exc) -> str:
+ """The remediation is part of the answer: the reader can fix the host."""
+ remediation = getattr(exc, "remediation", "") or ""
+ return _truncate(f"Execution error: {exc}{(' ' + remediation) if remediation else ''}")
+
+
+def _apply_prepared_launch(prepared, popen_kwargs: dict) -> dict:
+ """The OUTER process needs its own session: every kill path is killpg based."""
+ popen_kwargs["cwd"] = prepared.workdir
+ popen_kwargs["env"] = prepared.env
+ if sys.platform != "win32":
+ popen_kwargs["preexec_fn"] = prepared.preexec_fn
+ popen_kwargs["close_fds"] = prepared.close_fds
+ if prepared.pass_fds:
+ # Empty for every fallback, so Windows never sees a kwarg it rejects.
+ popen_kwargs["pass_fds"] = tuple(prepared.pass_fds)
+ return popen_kwargs
+
+
# Hardening the Unsloth parent is done once (PR_SET_DUMPABLE is process-global and sticky); guarded so repeated bypass
# calls do not re-issue the prctl.
_parent_proc_hardened = False
@@ -12832,6 +13016,9 @@ def execute_tool(
context_tokens = _UNSET_CONTEXT_TOKENS,
search_images: bool = False,
result_budget_tokens: int | None = None,
+ *,
+ tool_execution_mode: str = "auto",
+ host_access_approved: bool = False,
) -> str:
"""Execute a tool by name with the given arguments; returns a string.
@@ -12844,7 +13031,11 @@ def execute_tool(
tools; web_search / MCP are unchanged. ``output_callback``: optional ``callable(str)`` invoked
with incremental stdout/stderr chunks while python/terminal executions run. Purely
observational: the returned result string is identical with or without it. ``website_policy``:
- hidden server-validated domain limits for web_search.
+ hidden server-validated domain limits for web_search. ``tool_execution_mode`` controls OS
+ isolation for python/terminal: ``"auto"`` isolates when available and otherwise preserves
+ existing behavior, while ``"required"`` refuses unisolated execution. Full access remains
+ controlled by ``disable_sandbox``; ``"full"`` here is refused. ``host_access_approved``: the user approved this
+ call at the confirmation prompt (see ``_prepare_tool_launch``).
"""
from state.tool_policy import require_tool_access
@@ -13044,6 +13235,8 @@ def execute_tool(
disable_sandbox = disable_sandbox,
output_callback = output_callback,
thread_id = thread_id,
+ tool_execution_mode = tool_execution_mode,
+ host_access_approved = host_access_approved,
)
if name == "terminal":
with _session_in_flight(session_id):
@@ -13055,6 +13248,8 @@ def execute_tool(
disable_sandbox = disable_sandbox,
output_callback = output_callback,
thread_id = thread_id,
+ tool_execution_mode = tool_execution_mode,
+ host_access_approved = host_access_approved,
)
# Same in-flight guard as the two above: it writes into the session workdir, so a chat deleted mid-call must not
# unlink it underneath.
@@ -19385,11 +19580,15 @@ def _python_exec(
disable_sandbox: bool = False,
output_callback = None,
thread_id: str | None = None,
+ *,
+ tool_execution_mode: str = "auto",
+ host_access_approved: bool = False,
) -> str:
"""Execute Python code in a subprocess sandbox. disable_sandbox (Bypass Permissions): skip the
safety analysis and rlimit pre-exec, and use the host env minus secrets. output_callback:
optional callable(str) streamed each stdout line as it is produced; the returned result is
- unchanged."""
+ unchanged. tool_execution_mode selects automatic or required OS isolation; disable_sandbox
+ keeps full access as a separate explicit choice."""
if not code or not code.strip():
return "No code provided."
@@ -19422,6 +19621,8 @@ def _python_exec(
tmp_path = None
_scratch_name = None
+ # Bound before the try so the finally can release even when prepare raised.
+ prepared = None
try:
workdir = _get_workdir(session_id)
confinement = _account_confinement()
@@ -19456,25 +19657,51 @@ def _python_exec(
popen_kwargs = dict(
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
+ # close_fds leaves 0-2 open, so an unset stdin would be the server's.
+ stdin = subprocess.DEVNULL,
text = True,
# Decode child output as utf-8 (it emits utf-8 via PYTHONIOENCODING); replace so non-ASCII output never
# crashes the read on Windows.
encoding = "utf-8",
errors = "replace",
- cwd = workdir,
- env = safe_env,
)
- if sys.platform != "win32":
- popen_kwargs["preexec_fn"] = _bypass_preexec if disable_sandbox else _sandbox_preexec
- else:
+ if sys.platform == "win32":
popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
# -u forces unbuffered child stdout so a bare print() streams live
# instead of sitting in the pipe's block buffer until exit. Applied
# unconditionally to stay byte-identical with and without streaming;
# unlike PYTHONUNBUFFERED=1 it never pollutes the child's os.environ.
- argv = _apply_confinement(confinement, popen_kwargs, [sys.executable, "-u", tmp_path])
- proc = subprocess.Popen(argv, **popen_kwargs)
+ requested_mode = _requested_execution_mode(tool_execution_mode, disable_sandbox)
+ base_preexec = (
+ None
+ if sys.platform == "win32"
+ else (_bypass_preexec if disable_sandbox else _sandbox_preexec)
+ )
+ # Managed accounts keep their own boundary as the outer contract; `confines`, not `is not None` (placeholder).
+ if confinement is None or not confinement.confines:
+ prepared = _prepare_tool_launch(
+ os_sandbox.ToolLaunchPlan(
+ argv = (sys.executable, "-u", tmp_path),
+ workdir = workdir,
+ env = safe_env,
+ preexec_fn = base_preexec,
+ requested_mode = requested_mode,
+ timeout_seconds = timeout,
+ execution_kind = "python",
+ ),
+ host_access_approved = host_access_approved and _reaches_host_paths("python", code),
+ )
+ _note_tool_execution(prepared.execution_record)
+ proc = os_sandbox.spawn_prepared_launch(
+ prepared, **_apply_prepared_launch(prepared, popen_kwargs)
+ )
+ else:
+ popen_kwargs.update(cwd = workdir, env = safe_env)
+ if sys.platform != "win32":
+ popen_kwargs["preexec_fn"] = base_preexec
+ argv = _apply_confinement(confinement, popen_kwargs, [sys.executable, "-u", tmp_path])
+ proc = subprocess.Popen(argv, **popen_kwargs)
# Capture the group before any watcher can reap the leader (see _capture_process_group); None on Windows.
pgid = _capture_process_group(proc)
@@ -19534,8 +19761,11 @@ def _python_exec(
if session_id:
result += _created_file_sentinels(workdir, _before, _scratch_name, call_token)
+ _forget_sandbox_capability_if_the_backend_failed(prepared, result)
return result
+ except os_sandbox.SandboxUnavailableError as e:
+ return _sandbox_refusal(e)
except Exception as e:
# An exception message carries whatever the failure put in it, so it is capped like the result would have
# been.
@@ -19545,6 +19775,9 @@ def _python_exec(
if _scratch_name:
with _scratch_lock:
_active_scratch.discard(_scratch_name)
+ # Private mounts and descriptors, released on every exit path.
+ if prepared is not None:
+ prepared.cleanup()
_forget_tool_pid(locals().get("proc"))
if tmp_path and os.path.exists(tmp_path):
try:
@@ -19561,11 +19794,14 @@ def _bash_exec(
disable_sandbox: bool = False,
output_callback = None,
thread_id: str | None = None,
+ *,
+ tool_execution_mode: str = "auto",
+ host_access_approved: bool = False,
) -> str:
"""Execute a bash command in a subprocess sandbox. disable_sandbox (Bypass Permissions): skip
the command blocklist and rlimit pre-exec, and use the host env minus secrets.
output_callback: optional callable(str) streamed each stdout line as it is produced; the
- returned result is unchanged."""
+ returned result is unchanged. tool_execution_mode follows _python_exec."""
if not command or not command.strip():
return "No command provided."
@@ -19599,6 +19835,7 @@ def _bash_exec(
spill_dir = None
spill_scope = None
call_token = None
+ prepared = None
_scratch_name = None
try:
try:
@@ -19617,25 +19854,51 @@ def _bash_exec(
popen_kwargs = dict(
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
+ # See _python_exec: the server's stdin must not reach a tool call.
+ stdin = subprocess.DEVNULL,
text = True,
# Match _python_exec: decode utf-8 with "replace" so invalid output bytes never raise UnicodeDecodeError
# (which the streaming reader thread would swallow), keeping both paths byte-identical.
encoding = "utf-8",
errors = "replace",
- cwd = workdir,
- env = safe_env,
)
- if sys.platform != "win32":
- popen_kwargs["preexec_fn"] = _bypass_preexec if disable_sandbox else _sandbox_preexec
- else:
+ if sys.platform == "win32":
popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
shell_argv, _scratch_name = _shell_argv(command, workdir, confinement)
if _scratch_name:
with _scratch_lock:
_active_scratch.add(_scratch_name)
- argv = _apply_confinement(confinement, popen_kwargs, shell_argv)
- proc = subprocess.Popen(argv, **popen_kwargs)
+ requested_mode = _requested_execution_mode(tool_execution_mode, disable_sandbox)
+ base_preexec = (
+ None
+ if sys.platform == "win32"
+ else (_bypass_preexec if disable_sandbox else _sandbox_preexec)
+ )
+ if confinement is None or not confinement.confines:
+ prepared = _prepare_tool_launch(
+ os_sandbox.ToolLaunchPlan(
+ argv = tuple(shell_argv),
+ workdir = workdir,
+ env = safe_env,
+ preexec_fn = base_preexec,
+ requested_mode = requested_mode,
+ timeout_seconds = timeout,
+ execution_kind = "terminal",
+ ),
+ host_access_approved = host_access_approved
+ and _reaches_host_paths("terminal", command),
+ )
+ _note_tool_execution(prepared.execution_record)
+ proc = os_sandbox.spawn_prepared_launch(
+ prepared, **_apply_prepared_launch(prepared, popen_kwargs)
+ )
+ else:
+ popen_kwargs.update(cwd = workdir, env = safe_env)
+ if sys.platform != "win32":
+ popen_kwargs["preexec_fn"] = base_preexec
+ argv = _apply_confinement(confinement, popen_kwargs, shell_argv)
+ proc = subprocess.Popen(argv, **popen_kwargs)
# Capture the group before any watcher can poll/reap the leader (see _python_exec); None on Windows.
pgid = _capture_process_group(proc)
@@ -19685,14 +19948,20 @@ def _bash_exec(
# Only for a chat that has an id (see _python_exec).
if session_id:
result += _created_file_sentinels(workdir, _before, _scratch_name, call_token)
+ _forget_sandbox_capability_if_the_backend_failed(prepared, result)
return result
+ except os_sandbox.SandboxUnavailableError as e:
+ return _sandbox_refusal(e)
except Exception as e:
# An exception message carries whatever the failure put in it, so it is capped like the result would have
# been.
return _truncate(f"Execution error: {e}")
finally:
_call_finished(call_token)
+ # Private mounts and descriptors, released on every exit path.
+ if prepared is not None:
+ prepared.cleanup()
_forget_tool_pid(locals().get("proc"))
if _scratch_name:
with _scratch_lock:
diff --git a/studio/backend/tests/test_account_tool_confinement.py b/studio/backend/tests/test_account_tool_confinement.py
index 3eb68b4daa3..485ea4becdd 100644
--- a/studio/backend/tests/test_account_tool_confinement.py
+++ b/studio/backend/tests/test_account_tool_confinement.py
@@ -279,9 +279,15 @@ def test_confined_child_keeps_interpreter_and_system_tools(tmp_path):
@pytest.mark.skipif(not LANDLOCK, reason = "Landlock not available on this kernel")
-def test_owner_child_remains_unconfined(tmp_path):
+def test_owner_bypass_remains_unconfined(tmp_path):
files = _seed(tmp_path)
- out = run_as(OWNER, tools._bash_exec, f"cat {files['alice']}", session_id = "chat")
+ out = run_as(
+ OWNER,
+ tools._bash_exec,
+ f"cat {files['alice']}",
+ session_id = "chat",
+ disable_sandbox = True,
+ )
assert "ALICE_PRIVATE" in out
diff --git a/studio/backend/tests/test_bypass_permissions.py b/studio/backend/tests/test_bypass_permissions.py
index 8ffbe26ba0d..ff0ae15035c 100644
--- a/studio/backend/tests/test_bypass_permissions.py
+++ b/studio/backend/tests/test_bypass_permissions.py
@@ -134,11 +134,18 @@ def captured_popen(monkeypatch):
return cap
+def _carries(preexec, expected) -> bool:
+ """A backend that isolates COMPOSES its pre-exec onto the plan's rather than replacing it, so on such a host the identity is one closure down."""
+ if preexec is expected:
+ return True
+ return any(cell.cell_contents is expected for cell in (preexec.__closure__ or ()))
+
+
@_POSIX_ONLY
def test_python_sandboxed_uses_sandbox_preexec_and_safe_env(captured_popen, monkeypatch):
monkeypatch.setenv("HF_TOKEN", "secret-abc")
_python_exec("print(1)", None, 5, "t", disable_sandbox = False)
- assert captured_popen["kwargs"]["preexec_fn"] is tools._sandbox_preexec
+ assert _carries(captured_popen["kwargs"]["preexec_fn"], tools._sandbox_preexec)
assert "HF_TOKEN" not in captured_popen["kwargs"]["env"]
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index 44f96462701..e38bf52d0df 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -3050,6 +3050,29 @@ def test_gated_python_call_still_streams_its_arguments(monkeypatch):
assert events.index(provisional[0]) < events.index(gated[0])
[email protected]("verdict", ["allow", "deny"])
+def test_only_an_approved_call_is_marked_approved(monkeypatch, verdict):
+ first_stream = _streamed_structured_tool_call("python", {"code": "print(1)"}, "call_gated")
+ final_stream = [_sse({"content": "Done."}), _done()]
+ backend, _payloads = _backend_and_payloads(monkeypatch, [first_stream, final_stream])
+ seen: list = []
+ monkeypatch.setattr(
+ "core.inference.tools.execute_tool",
+ lambda name, arguments, **kwargs: seen.append(kwargs.get("host_access_approved")) or "OK",
+ )
+ monkeypatch.setattr("core.inference.llama_cpp.wait_tool_decision", lambda *_a, **_k: verdict)
+
+ _run_tool_loop(
+ backend,
+ [{"role": "user", "content": "run it"}],
+ [{"type": "function", "function": {"name": "python"}}],
+ confirm_tool_calls = True,
+ permission_mode = "ask",
+ )
+
+ assert seen == ([True] if verdict == "allow" else [])
+
+
def test_auto_mode_render_html_suppresses_provisional_card_under_confirm(monkeypatch):
"""render_html is no longer unconditionally safe (a networked canvas asks), so
with confirm_tool_calls set under permission_mode="auto" its early provisional
diff --git a/studio/backend/tests/test_permission_mode.py b/studio/backend/tests/test_permission_mode.py
index e11e01f10c9..66c4c29929b 100644
--- a/studio/backend/tests/test_permission_mode.py
+++ b/studio/backend/tests/test_permission_mode.py
@@ -2761,6 +2761,50 @@ def test_auto_mode_gates_high_risk_calls():
assert exec_fn.disable_sandbox_seen == [False], _diag(events, exec_fn)
+class _ApprovalRecordingExecuteTool(_FakeExecuteTool):
+ def __init__(self):
+ super().__init__()
+ self.approved_seen = []
+
+ def __call__(
+ self,
+ name,
+ arguments,
+ *,
+ host_access_approved = False,
+ **kwargs,
+ ):
+ self.approved_seen.append(host_access_approved)
+ return super().__call__(name, arguments, disable_sandbox = kwargs.get("disable_sandbox"))
+
+
+ "code, decisions, approved",
+ [
+ # Gated and allowed: the user saw the host path and let it through.
+ ('open(\\"/srv/data.csv\\").read()', ["allow"], [True]),
+ # Not gated in auto, so nobody approved anything.
+ ("print(1)", [], [False]),
+ ],
+)
+def test_the_approval_reaches_the_executor(code, decisions, approved):
+ exec_fn = _ApprovalRecordingExecuteTool()
+ session = f"{_SESSION}-{uuid.uuid4().hex}"
+ decision_iter = iter(decisions)
+ for ev in run_safetensors_tool_loop(
+ single_turn = _multi_turn([_tool_call("python", f'{{"code": "{code}"}}'), "final"]),
+ messages = [{"role": "user", "content": "hi"}],
+ tools = _DEFAULT_TOOLS,
+ execute_tool = exec_fn,
+ session_id = session,
+ confirm_tool_calls = True,
+ permission_mode = "auto",
+ ):
+ if ev["type"] == "tool_start" and ev.get("awaiting_confirmation"):
+ resolve_tool_decision(ev["approval_id"], next(decision_iter), session_id = session)
+ assert exec_fn.approved_seen == approved
+
+
def test_auto_mode_does_not_gate_ordinary_mutation():
# The core of "Approve for me": an ordinary in-workdir write is not high risk,
# so auto runs it without a prompt even though it is not read-only.
diff --git a/studio/backend/tests/test_sandbox_files_and_storage_roots.py b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
index 87bfd29a60e..f92d625c995 100644
--- a/studio/backend/tests/test_sandbox_files_and_storage_roots.py
+++ b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
@@ -1419,7 +1419,7 @@ def test_the_executor_leaves_nothing_in_the_sandbox(tmp_path, monkeypatch):
tools = _shared_setup_1(monkeypatch, tmp_path)
workdir = Path(tools.get_sandbox_workdir("__LOCALID_scratch"))
tools._python_exec("print('hi')", session_id = "__LOCALID_scratch")
- assert sorted(p.name for p in workdir.iterdir()) == [
+ assert sorted(p.name for p in workdir.iterdir() if p.name != ".cache") == [
tools._SANDBOX_MARKER,
tools._SANDBOX_TEMP_DIRNAME,
]
@@ -1920,7 +1920,8 @@ def test_a_user_python_file_is_never_executor_scratch(tmp_path, monkeypatch):
assert sorted(
p.name
for p in workdir.iterdir()
- if p.name not in tools._INTERNAL_SANDBOX_FILES and p.name != tools._SANDBOX_TEMP_DIRNAME
+ if p.name not in tools._INTERNAL_SANDBOX_FILES
+ and p.name not in (tools._SANDBOX_TEMP_DIRNAME, ".cache")
) == ["studio_exec_results.py"]
assert inference._sandbox_listing_names(str(workdir)) == ["studio_exec_results.py"]
# And a delete without the opt-in will not quietly take it.
@@ -2000,7 +2001,8 @@ def test_the_scratch_script_is_never_reported_as_a_file(tmp_path, monkeypatch):
assert sorted(
p.name
for p in workdir.iterdir()
- if p.name not in tools._INTERNAL_SANDBOX_FILES and p.name != tools._SANDBOX_TEMP_DIRNAME
+ if p.name not in tools._INTERNAL_SANDBOX_FILES
+ and p.name not in (tools._SANDBOX_TEMP_DIRNAME, ".cache")
) == ["studio_exec_results.py"]
assert json.loads(files) == [{"name": "studio_exec_results.py", "size": 5}]
diff --git a/studio/backend/tests/test_sandbox_install_remediation.py b/studio/backend/tests/test_sandbox_install_remediation.py
new file mode 100644
index 00000000000..f216b6a9792
--- /dev/null
+++ b/studio/backend/tests/test_sandbox_install_remediation.py
@@ -0,0 +1,78 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""The Linux remediation must be one copy-paste: the exact command for this host, never a promise."""
+
+from __future__ import annotations
+
+from pathlib import Path
+import re
+
+import pytest
+
+from core.inference import os_sandbox
+
+_INSTALL_SH = Path(__file__).resolve().parents[3] / "install.sh"
+
+
+def _which_only(monkeypatch, present):
+ monkeypatch.setattr(
+ os_sandbox.shutil, "which", lambda name: f"/usr/bin/{name}" if name in present else None
+ )
+
+
+ ("managers", "command"),
+ [
+ ({"apt-get"}, "sudo apt-get install -y bubblewrap"),
+ ({"apt-get", "dnf"}, "sudo apt-get install -y bubblewrap"),
+ ({"dnf"}, "sudo dnf install -y bubblewrap"),
+ ({"pacman"}, "sudo pacman -S --needed bubblewrap"),
+ ({"zypper"}, "sudo zypper install -y bubblewrap"),
+ ({"apk"}, "sudo apk add bubblewrap"),
+ ],
+)
+def test_missing_bwrap_names_the_command_for_this_package_manager(monkeypatch, managers, command):
+ _which_only(monkeypatch, managers)
+ monkeypatch.setattr(os_sandbox, "_linux_userns_blocked_by_apparmor", lambda: False)
+ remediation = os_sandbox.linux_unavailable_remediation()
+ assert f"`{command}`" in remediation
+ # Setup never installed bwrap for an ordinary user, so the text must not send them there.
+ assert "re-run Studio setup" not in remediation
+
+
+def test_missing_bwrap_on_ubuntu_with_userns_restriction_is_still_one_command(monkeypatch):
+ # Measured on 24.04: installing bubblewrap alone leaves it "setting up uid map: Permission denied".
+ _which_only(monkeypatch, {"apt-get"})
+ monkeypatch.setattr(os_sandbox, "_linux_userns_blocked_by_apparmor", lambda: True)
+ remediation = os_sandbox.linux_unavailable_remediation()
+ assert (
+ f"`sudo apt-get install -y bubblewrap && {os_sandbox._BWRAP_APPARMOR_FIX}`" in remediation
+ )
+
+
+def test_missing_bwrap_on_an_unknown_package_manager(monkeypatch):
+ _which_only(monkeypatch, set())
+ remediation = os_sandbox.linux_unavailable_remediation()
+ assert "install bubblewrap with your distribution's package manager" in remediation
+
+
+def test_apparmor_block_names_the_profile_ubuntu_ships(monkeypatch):
+ _which_only(monkeypatch, {"bwrap", "apt-get"})
+ monkeypatch.setattr(os_sandbox, "_linux_userns_blocked_by_apparmor", lambda: True)
+ remediation = os_sandbox.linux_unavailable_remediation()
+ # apparmor-profiles installs it under extra-profiles, disabled; it is not in /etc/apparmor.d.
+ assert (
+ "/usr/share/apparmor/extra-profiles/bwrap-userns-restrict /etc/apparmor.d/" in remediation
+ )
+ assert "apparmor_parser -r /etc/apparmor.d/bwrap-userns-restrict" in remediation
+ assert "re-run Studio setup" not in remediation
+
+
+def test_installer_and_backend_give_the_same_commands():
+ text = _INSTALL_SH.read_text(encoding = "utf-8")
+ fix = re.search(r'^_BWRAP_APPARMOR_FIX="([^"]+)"$', text, re.MULTILINE)
+ assert fix and fix.group(1) == os_sandbox._BWRAP_APPARMOR_FIX
+ body = text[text.index("_bwrap_install_command() {") :]
+ body = body[: body.index("\n}\n")]
+ shell = re.findall(r'command -v (\S+) >/dev/null 2>&1; then echo "([^"]+)"', body)
+ assert shell == list(os_sandbox._BWRAP_INSTALL_COMMANDS)
diff --git a/studio/backend/tests/test_sandbox_linux.py b/studio/backend/tests/test_sandbox_linux.py
new file mode 100644
index 00000000000..d410f294ceb
--- /dev/null
+++ b/studio/backend/tests/test_sandbox_linux.py
@@ -0,0 +1,2289 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""What the Linux sandbox argv and its seccomp program actually say."""
+
+from __future__ import annotations
+
+import ast
+import ctypes
+import errno
+import inspect
+import json
+import os
+import platform
+import shutil
+import socket
+import stat
+import struct
+import sys
+import sysconfig
+import tempfile
+import threading
+import time
+
+import pytest
+
+if sys.platform != "linux":
+ pytest.skip("the bubblewrap backend is Linux only", allow_module_level = True)
+
+from core.inference import ( # noqa: E402
+ os_sandbox,
+ sandbox_landlock,
+ sandbox_linux,
+ sandbox_seccomp,
+)
+from core.inference.os_sandbox import ( # noqa: E402
+ SandboxUnavailableError,
+ ToolLaunchPlan,
+ WorkdirUnsafeError,
+) # noqa: E402
+
+
+def _plan(
+ workdir,
+ argv = ("/bin/true",),
+ **kwargs,
+):
+ return ToolLaunchPlan(argv = argv, workdir = str(workdir), env = {"PATH": "/usr/bin"}, **kwargs)
+
+
+def prepared(tmp_path):
+ if sandbox_linux.shutil.which("bwrap") is None:
+ pytest.skip("bubblewrap is not installed on this host")
+ launch = sandbox_linux.prepare(_plan(tmp_path))
+ yield launch
+ launch.cleanup()
+
+
+def _pairs(argv, flag):
+ return [
+ (argv[index + 1], argv[index + 2])
+ for index, token in enumerate(argv)
+ if token == flag and index + 2 < len(argv)
+ ]
+
+
+def test_the_launch_runs_bwrap_and_ends_with_the_payload_after_a_bare_separator(prepared):
+ assert os.path.basename(prepared.argv[0]) == "bwrap"
+ separator = prepared.argv.index("--")
+ assert prepared.argv[separator + 1 :] == ("/bin/true",)
+ assert prepared.argv.count("--") == 1
+
+
+def test_the_network_namespace_is_deliberately_left_alone(prepared):
+ assert "--unshare-net" not in prepared.argv
+ assert "--unshare-all" not in prepared.argv
+
+
+def test_every_namespace_except_the_network_one_is_unshared(prepared):
+ for option in (
+ "--unshare-user",
+ "--unshare-pid",
+ "--unshare-ipc",
+ "--unshare-uts",
+ "--unshare-cgroup",
+ ):
+ assert option in prepared.argv
+
+
+def test_the_session_dies_with_studio_and_detaches_from_the_terminal(prepared):
+ assert "--die-with-parent" in prepared.argv
+ assert "--new-session" in prepared.argv
+
+
+def test_capabilities_are_dropped_and_the_filter_arrives_as_an_inherited_descriptor(prepared):
+ argv = prepared.argv
+ assert argv[argv.index("--cap-drop") + 1] == "ALL"
+ fd = int(argv[argv.index("--seccomp") + 1])
+ assert prepared.pass_fds == (fd,)
+ assert [handle.fileno() for handle in prepared.owned_files] == [fd]
+ assert os.lseek(fd, 0, os.SEEK_CUR) == 0
+
+
+def test_identity_is_synthesised_rather_than_bound_from_the_host(prepared):
+ binds = {destination: source for source, destination in _pairs(prepared.argv, "--ro-bind")}
+ passwd, group = binds["/etc/passwd"], binds["/etc/group"]
+ assert passwd != "/etc/passwd" and group != "/etc/group"
+ assert prepared.cleanup_paths == [os.path.dirname(passwd)]
+ assert os.stat(os.path.dirname(passwd)).st_mode & 0o777 == 0o700
+ with open(passwd, encoding = "utf-8") as stream:
+ entries = stream.read().splitlines()
+ assert len(entries) == 1 and entries[0].split(":")[2] == str(os.getuid())
+
+
+def test_the_writable_workdir_bind_lands_after_the_root_goes_read_only(prepared, tmp_path):
+ argv = prepared.argv
+ workdir = os.path.realpath(tmp_path)
+ remount = argv.index("--remount-ro")
+ assert argv[remount + 1] == "/"
+ assert argv.index("--dir", 0, remount) < remount
+ assert (workdir, workdir) in _pairs(argv[remount:], "--bind")
+ assert argv[argv.index("--chdir") + 1] == workdir
+
+
+def test_both_spellings_of_a_symlinked_workdir_get_a_mount_point(tmp_path):
+ real = tmp_path / "real"
+ real.mkdir()
+ link = tmp_path / "link"
+ link.symlink_to(real)
+
+ launch = sandbox_linux.prepare(
+ ToolLaunchPlan(
+ argv = (sys.executable, "-c", "pass"),
+ workdir = str(link),
+ env = {"PATH": "/usr/bin:/bin"},
+ )
+ )
+ try:
+ argv = launch.argv
+ remount = argv.index("--remount-ro")
+ made = [argv[i + 1] for i, token in enumerate(argv[:remount]) if token == "--dir"]
+ assert str(link) in made, "the caller's spelling has no mount point"
+ assert os.path.realpath(link) in made, "the canonical spelling has no mount point"
+ bound = _pairs(argv[remount:], "--bind")
+ assert (os.path.realpath(link), str(link)) in bound
+ finally:
+ launch.cleanup()
+
+
+def test_the_private_tmpfs_replaces_the_shared_directories(prepared):
+ argv = prepared.argv
+ remount = argv.index("--remount-ro")
+ tmpfs = [argv[i + 1] for i, token in enumerate(argv) if token == "--tmpfs"]
+ assert tmpfs[:2] == ["/dev/shm", "/tmp"]
+ assert argv.index("--tmpfs") > remount
+
+
+def test_no_private_key_directory_enters_the_jail_at_all(prepared):
+ sources = [source for source, _ in _pairs(prepared.argv, "--ro-bind-try")]
+ assert "/etc/ssl/certs" in sources
+ assert "/etc/ssl" not in sources and "/etc/pki" not in sources
+ secret = "/etc/ssl/private"
+ assert os.path.isdir(secret), "no private-key directory here, so this proves nothing"
+ for source, _ in (*_pairs(prepared.argv, "--ro-bind-try"), *_pairs(prepared.argv, "--ro-bind")):
+ assert not sandbox_linux._within(secret, source), source
+
+
+def test_pip_gets_a_writable_target_inside_the_workdir(prepared):
+ argv = prepared.argv
+ packages = os.path.join(prepared.workdir, sandbox_linux.SESSION_PACKAGES_RELPATH)
+ assert argv[argv.index("PIP_TARGET") + 1] == packages
+ pythonpath = argv[argv.index("PYTHONPATH") + 1].split(os.pathsep)
+ assert packages in pythonpath
+ assert pythonpath[-1] == packages
+
+
+def test_system_directories_are_bound_whole_and_never_file_by_file(prepared):
+ sources = [source for source, _ in _pairs(prepared.argv, "--ro-bind-try")]
+ assert "/usr/lib" in sources
+ named = {
+ *sandbox_linux._ETC_FILES,
+ *sandbox_linux._ETC_FILES_IF_TRUSTED,
+ *sandbox_linux._NETWORK_FILES,
+ }
+ identity_dir = prepared.cleanup_paths[0]
+ for flag in ("--bind", "--ro-bind", "--ro-bind-try"):
+ for source, _ in _pairs(prepared.argv, flag):
+ if os.path.isdir(source):
+ continue
+ if source in named or os.path.dirname(source) == identity_dir:
+ continue
+ assert os.path.basename(source) == "pyvenv.cfg", source
+
+
+def test_the_interpreter_contributes_only_a_handful_of_read_only_binds(prepared):
+ runtime = [
+ source
+ for source, destination in _pairs(prepared.argv, "--ro-bind")
+ if source == destination
+ ]
+ assert 0 < len(runtime) < 40, runtime
+ system_roots = tuple(path for path in sandbox_linux._SYSTEM_ROOTS if os.path.isdir(path))
+ for path in runtime:
+ assert not any(sandbox_linux._within(path, root) for root in system_roots)
+
+
+def test_nothing_binds_or_creates_the_filesystem_root(prepared):
+ for flag in ("--bind", "--ro-bind", "--ro-bind-try"):
+ for source, destination in _pairs(prepared.argv, flag):
+ assert source != "/" and destination != "/"
+ directories = [
+ prepared.argv[index + 1] for index, token in enumerate(prepared.argv) if token == "--dir"
+ ]
+ assert "/" not in directories
+
+
+def test_a_launch_with_no_command_is_refused_rather_than_handed_to_bwrap(tmp_path):
+ with pytest.raises(SandboxUnavailableError, match = "needs a command"):
+ sandbox_linux.prepare(_plan(tmp_path, argv = ()))
+
+
+def test_a_path_bwrap_from_a_writable_location_is_never_executed(tmp_path, monkeypatch):
+ planted = tmp_path / "bwrap"
+ planted.write_text("#!/bin/sh\nexit 0\n", encoding = "utf-8")
+ planted.chmod(0o777)
+ monkeypatch.setattr(sandbox_linux.shutil, "which", lambda _name: str(planted))
+
+ with pytest.raises(SandboxUnavailableError, match = "trusted system installation"):
+ sandbox_linux.prepare(_plan(tmp_path))
+
+
+def test_the_workdir_is_the_only_writable_bind(prepared, tmp_path):
+ workdir = os.path.realpath(tmp_path)
+ assert _pairs(prepared.argv, "--bind") == [(workdir, workdir)]
+
+
+def test_the_model_cache_shares_its_data_subdirectories_and_nothing_else(tmp_path, monkeypatch):
+ cache = tmp_path / "hostcache"
+ for name in ("hub", "datasets", "modules", "xet", "assets"):
+ (cache / name).mkdir(parents = True)
+ (cache / "token").write_text("hf_A_REAL_LOOKING_TOKEN")
+ (cache / "stored_tokens").write_text("{}")
+ _share_cache(monkeypatch, cache)
+
+ launch = sandbox_linux.prepare(_plan(tmp_path))
+ try:
+ workdir = os.path.realpath(tmp_path)
+ inner = os.path.join(workdir, ".cache", "huggingface")
+ shared = _pairs(launch.argv, "--bind-try")
+ assert sorted(shared) == sorted(
+ (os.path.join(str(cache), name), os.path.join(inner, name))
+ for name in ("hub", "datasets", "xet", "assets")
+ )
+ assert not any("modules" in destination for _, destination in shared)
+ assert launch.argv[launch.argv.index("HF_HOME") + 1] == inner
+ for credential in ("token", "stored_tokens"):
+ host_path = os.path.join(str(cache), credential)
+ assert not any(host_path in token for token in launch.argv), credential
+ finally:
+ launch.cleanup()
+
+
+def test_the_cache_mount_points_are_made_here_and_left(tmp_path, cache):
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+
+ launch = sandbox_linux.prepare(_plan(workdir))
+ launch.cleanup()
+ assert (workdir / ".cache" / "huggingface" / "hub").is_dir()
+ second = sandbox_linux.prepare(_plan(workdir))
+ second.cleanup()
+ assert (workdir / ".cache" / "huggingface" / "hub").is_dir()
+
+
+def test_a_cache_directory_the_tool_call_wrote_is_left_alone(tmp_path, cache):
+ workdir = tmp_path / "session"
+ (workdir / ".cache" / "huggingface").mkdir(parents = True)
+ (workdir / ".cache" / "notes.txt").write_text("the user's")
+
+ launch = sandbox_linux.prepare(_plan(workdir))
+ launch.cleanup()
+ assert (workdir / ".cache" / "notes.txt").read_text() == "the user's"
+
+
+def test_the_model_cache_bind_is_absent_when_the_host_has_no_cache(tmp_path, monkeypatch):
+ monkeypatch.setattr(sandbox_linux, "_model_cache_binds", lambda workdir: {})
+ launch = sandbox_linux.prepare(_plan(tmp_path))
+ try:
+ assert "HF_HOME" not in launch.argv
+ assert [
+ p for p in _pairs(launch.argv, "--bind") if p[0] != os.path.realpath(tmp_path)
+ ] == []
+ finally:
+ launch.cleanup()
+
+
+def test_the_inner_home_and_tmpdir_are_set_by_bwrap_not_by_the_caller_environment(prepared):
+ argv = prepared.argv
+ assert argv[argv.index("HOME") + 1] == prepared.workdir
+ assert argv[argv.index("TMPDIR") + 1] == "/tmp"
+ assert prepared.env == {"PATH": "/usr/bin"}
+
+
+def test_a_tmpdir_inside_the_workdir_survives_into_the_jail(tmp_path):
+ scratch = tmp_path / "unsloth-tmp"
+ scratch.mkdir()
+ plan = ToolLaunchPlan(
+ argv = ("/bin/true",),
+ workdir = str(tmp_path),
+ env = {"PATH": "/usr/bin", "TMPDIR": str(scratch)},
+ )
+ launch = sandbox_linux.prepare(plan)
+ try:
+ assert launch.argv[launch.argv.index("TMPDIR") + 1] == str(scratch)
+ finally:
+ launch.cleanup()
+
+
+def test_a_tmpdir_outside_the_workdir_is_replaced_by_the_private_tmpfs(tmp_path):
+ plan = ToolLaunchPlan(
+ argv = ("/bin/true",),
+ workdir = str(tmp_path),
+ env = {"PATH": "/usr/bin", "TMPDIR": "/var/tmp/somewhere-else"},
+ )
+ launch = sandbox_linux.prepare(plan)
+ try:
+ assert launch.argv[launch.argv.index("TMPDIR") + 1] == "/tmp"
+ finally:
+ launch.cleanup()
+
+
+def test_the_outer_setsid_preexec_is_preserved(tmp_path):
+ ran = []
+ launch = sandbox_linux.prepare(_plan(tmp_path, preexec_fn = lambda: ran.append("plan")))
+ try:
+ assert launch.preexec_fn is not None
+ launch.preexec_fn()
+ assert ran == ["plan"]
+ finally:
+ launch.cleanup()
+
+
+def test_the_plan_policy_fields_survive_preparation(tmp_path):
+ launch = sandbox_linux.prepare(_plan(tmp_path, timeout_seconds = 42, terminate_descendants = False))
+ try:
+ assert launch.timeout_seconds == 42
+ assert launch.terminate_descendants is False
+ assert launch.backend == sandbox_linux.BACKEND_NAME
+ finally:
+ launch.cleanup()
+
+
+def test_cleanup_releases_the_descriptor_and_the_private_identity_directory(tmp_path):
+ launch = sandbox_linux.prepare(_plan(tmp_path))
+ identity_dir = launch.cleanup_paths[0]
+ handle = launch.owned_files[0]
+ launch.cleanup()
+ assert handle.closed
+ assert not os.path.exists(identity_dir)
+ assert launch.cleanup_diagnostics == []
+
+
+def test_the_backend_declares_the_two_things_it_does_not_confine():
+ assert "unrestricted_network" in sandbox_linux.LIMITATIONS
+ assert "model_cache_writable" in sandbox_linux.LIMITATIONS
+ assert isinstance(sandbox_linux.LIMITATIONS, tuple)
+ assert sandbox_linux.BACKEND_NAME and sandbox_linux.PROFILE_ID
+
+
+def test_a_unix_socket_under_the_workdir_is_refused():
+ workdir = tempfile.mkdtemp(prefix = "sbx-")
+ listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ try:
+ listener.bind(os.path.join(workdir, "s"))
+ with pytest.raises(SandboxUnavailableError, match = "device or IPC node"):
+ sandbox_linux._validate_workdir(workdir)
+ finally:
+ listener.close()
+ shutil.rmtree(workdir, ignore_errors = True)
+
+
+def test_a_fifo_under_the_workdir_is_refused(tmp_path):
+ os.mkfifo(str(tmp_path / "pipe"))
+ with pytest.raises(SandboxUnavailableError, match = "device or IPC node"):
+ sandbox_linux._validate_workdir(str(tmp_path))
+
+
+def test_a_file_hard_linked_from_outside_the_workdir_is_refused(tmp_path):
+ outside, workdir = tmp_path / "outside", tmp_path / "session"
+ outside.mkdir()
+ workdir.mkdir()
+ (outside / "secret").write_text("x")
+ os.link(str(outside / "secret"), str(workdir / "innocent"))
+ with pytest.raises(SandboxUnavailableError, match = "hard-linked from outside"):
+ sandbox_linux._validate_workdir(str(workdir))
+
+
+def test_a_hard_link_wholly_inside_the_workdir_is_allowed(tmp_path):
+ (tmp_path / "a").write_text("x")
+ os.link(str(tmp_path / "a"), str(tmp_path / "b"))
+ (tmp_path / "nested").mkdir()
+ os.link(str(tmp_path / "a"), str(tmp_path / "nested" / "c"))
+ assert sandbox_linux._validate_workdir(str(tmp_path)) == (os.path.realpath(tmp_path), ())
+
+
+def test_a_nested_host_mount_under_the_workdir_is_refused(tmp_path, monkeypatch):
+ nested = tmp_path / "mounted"
+ nested.mkdir()
+ real = os.path.ismount
+ monkeypatch.setattr(
+ os.path, "ismount", lambda path: os.path.samefile(path, nested) or real(path)
+ )
+ with pytest.raises(SandboxUnavailableError, match = "nested host mount"):
+ sandbox_linux._validate_workdir(str(tmp_path))
+
+
+def test_the_workdir_itself_being_a_mount_point_is_allowed(tmp_path, monkeypatch):
+ real = os.path.ismount
+ monkeypatch.setattr(
+ os.path, "ismount", lambda path: os.path.samefile(path, tmp_path) or real(path)
+ )
+ assert sandbox_linux._validate_workdir(str(tmp_path)) == (os.path.realpath(tmp_path), ())
+
+
+def test_a_workdir_too_large_to_check_still_launches_and_says_it_was_not_checked(
+ tmp_path, monkeypatch
+):
+ monkeypatch.setattr(os_sandbox, "WORKDIR_SCAN_ENTRIES", 2)
+ for name in ("a", "b", "c", "d"):
+ (tmp_path / name).write_text("")
+ resolved, limitations = sandbox_linux._validate_workdir(str(tmp_path))
+ assert resolved == os.path.realpath(tmp_path)
+ assert limitations == ("workdir_scan_incomplete",)
+
+
+def test_an_overrun_does_not_stop_a_real_finding_from_refusing(tmp_path, monkeypatch):
+ os.mkfifo(str(tmp_path / "channel"))
+ with pytest.raises(SandboxUnavailableError, match = "device or IPC node"):
+ sandbox_linux._validate_workdir(str(tmp_path))
+
+
+def test_an_incomplete_scan_reaches_the_execution_record(tmp_path, monkeypatch):
+ monkeypatch.setattr(os_sandbox, "WORKDIR_SCAN_ENTRIES", 2)
+ for name in ("a", "b", "c", "d"):
+ (tmp_path / name).write_text("")
+ prepared = sandbox_linux.prepare(
+ os_sandbox.ToolLaunchPlan(
+ argv = (sys.executable, "-c", "pass"),
+ workdir = str(tmp_path),
+ env = {},
+ requested_mode = "required",
+ )
+ )
+ try:
+ assert "workdir_scan_incomplete" in prepared.launch_limitations
+ finally:
+ prepared.cleanup()
+
+
+def test_a_workdir_that_is_not_a_directory_is_refused(tmp_path):
+ with pytest.raises(SandboxUnavailableError, match = "not a safe canonical directory"):
+ sandbox_linux._validate_workdir(str(tmp_path / "missing"))
+ with pytest.raises(SandboxUnavailableError, match = "not a safe canonical directory"):
+ sandbox_linux._validate_workdir("/")
+
+
+def test_a_symlinked_directory_under_the_workdir_is_not_followed(tmp_path):
+ (tmp_path / "escape").symlink_to("/dev")
+ assert sandbox_linux._validate_workdir(str(tmp_path)) == (os.path.realpath(tmp_path), ())
+
+
+def test_every_interpreter_path_this_python_imports_from_is_bound(prepared, tmp_path):
+ bound = [
+ source
+ for flag in ("--ro-bind", "--ro-bind-try", "--bind")
+ for source, _ in _pairs(prepared.argv, flag)
+ ]
+ prefixes = (sys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix)
+ paths = sysconfig.get_paths()
+ needed = {
+ paths[key] for key in ("stdlib", "platstdlib", "purelib", "platlib") if paths.get(key)
+ }
+ needed |= {
+ entry
+ for entry in sys.path
+ if entry and any(sandbox_linux._within(entry, os.path.join(p, "lib")) for p in prefixes)
+ }
+ for path in sorted(needed):
+ if not os.path.exists(path):
+ continue
+ assert any(sandbox_linux._within(path, root) for root in bound), path
+
+
+def test_a_venv_at_a_project_root_does_not_expose_the_project(tmp_path, monkeypatch):
+ project = tmp_path / "project"
+ (project / "lib").mkdir(parents = True)
+ (project / "bin").mkdir()
+ (project / "src").mkdir()
+ (project / ".env").write_text("TOKEN=secret")
+ for name in ("prefix", "exec_prefix"):
+ monkeypatch.setattr(sys, name, str(project))
+ roots = tuple(path for path in sandbox_linux._SYSTEM_ROOTS if os.path.isdir(path))
+ paths = sandbox_linux._runtime_read_paths(os.path.realpath(tmp_path / "wd"), roots)
+ assert os.path.realpath(project) not in paths
+ assert os.path.realpath(project / "lib") in paths
+ assert not any(sandbox_linux._within(str(project / "src"), path) for path in paths)
+
+
+def test_an_interpreter_path_resolving_to_the_filesystem_root_is_refused(tmp_path, monkeypatch):
+ (tmp_path / "lib").symlink_to("/")
+ monkeypatch.setattr(sys, "prefix", str(tmp_path))
+ with pytest.raises(SandboxUnavailableError, match = "filesystem root"):
+ sandbox_linux._runtime_read_paths(str(tmp_path / "wd"), ("/usr/lib",))
+
+
+def test_a_system_interpreter_adds_nothing_the_system_roots_do_not_already_cover(
+ tmp_path, monkeypatch
+):
+ monkeypatch.setattr(sys, "prefix", "/usr")
+ monkeypatch.setattr(sys, "base_prefix", "/usr")
+ roots = tuple(path for path in sandbox_linux._SYSTEM_ROOTS if os.path.isdir(path))
+ for path in sandbox_linux._runtime_read_paths(str(tmp_path), roots):
+ assert path not in ("/", "/usr", "/usr/local")
+
+
+def test_runtime_paths_inside_the_workdir_are_left_to_the_writable_bind(tmp_path, monkeypatch):
+ inner = tmp_path / "venv"
+ (inner / "lib").mkdir(parents = True)
+ monkeypatch.setattr(sys, "prefix", str(inner))
+ roots = tuple(path for path in sandbox_linux._SYSTEM_ROOTS if os.path.isdir(path))
+ paths = sandbox_linux._runtime_read_paths(os.path.realpath(tmp_path), roots)
+ assert os.path.realpath(inner / "lib") not in paths
+
+
+def test_the_probe_builds_its_launch_through_the_real_argv_builder(tmp_path):
+ if sandbox_linux.shutil.which("bwrap") is None:
+ pytest.skip("bubblewrap is not installed on this host")
+ launch = sandbox_linux.probe_argv(str(tmp_path), ("/bin/true", "-x"), {"PATH": "/usr/bin"})
+ try:
+ reference = sandbox_linux.prepare(_plan(tmp_path, argv = ("/bin/true", "-x")))
+ try:
+
+ def normalise(argv, launch):
+ fd = str(argv[argv.index("--seccomp") + 1])
+ identity = launch.cleanup_paths[0]
+ return tuple(item.replace(identity, "<identity>") for item in argv if item != fd)
+
+ assert normalise(launch.argv, launch) == normalise(reference.argv, reference)
+ finally:
+ reference.cleanup()
+ finally:
+ launch.cleanup()
+
+
+_AUDIT_ARCH = sandbox_seccomp._ABIS.get(platform.machine().lower(), (0,))[0]
+_KILL, _ALLOW = 0x80000000, 0x7FFF0000
+_EPERM, _ENOSYS = sandbox_seccomp._EPERM, sandbox_seccomp._ENOSYS
+
+if _AUDIT_ARCH == 0:
+ pytest.skip(f"no seccomp ABI for {platform.machine()}", allow_module_level = True)
+
+
+def _evaluate(
+ instructions,
+ *,
+ nr,
+ arch = _AUDIT_ARCH,
+ args = (0,) * 6,
+):
+ data = struct.pack("=IIQ6Q", nr, arch, 0, *args)
+ accumulator, counter = 0, 0
+ for _ in range(len(instructions) * 4):
+ code, jt, jf, k = instructions[counter]
+ counter += 1
+ if code == 0x20:
+ (accumulator,) = struct.unpack_from("=I", data, k)
+ elif code == 0x15:
+ counter += jt if accumulator == k else jf
+ elif code == 0x45:
+ counter += jt if accumulator & k else jf
+ elif code == 0x06:
+ return k
+ else:
+ raise AssertionError(f"unexpected BPF opcode {code:#x}")
+ raise AssertionError("the program ran off the end without returning")
+
+
+def _share_cache(monkeypatch, cache):
+ """Share every subdirectory of *cache* that exists, as the real resolver would."""
+ monkeypatch.setattr(
+ sandbox_linux,
+ "_model_cache_binds",
+ lambda workdir: {
+ name: str(cache / name)
+ for name in sandbox_linux._MODEL_CACHE_SUBDIRS
+ if (cache / name).is_dir()
+ },
+ )
+
+
+def cache(tmp_path, monkeypatch):
+ """A host cache with one populated subdirectory, shared into the jail."""
+ directory = tmp_path / "hostcache"
+ (directory / "hub").mkdir(parents = True)
+ _share_cache(monkeypatch, directory)
+ return directory
+
+
[email protected](params = [False, True], ids = ["userns_by_bwrap", "userns_by_seccomp"])
+def program(request):
+ return sandbox_seccomp.program(platform.machine(), block_userns = request.param)
+
+
+def _socket_nr():
+ return sandbox_seccomp._ABIS[platform.machine().lower()][1]
+
+
+def test_a_vsock_socket_is_denied_because_no_mount_namespace_can_hide_it(program):
+ assert _evaluate(program, nr = _socket_nr(), args = (40, 0, 0, 0, 0, 0)) == _EPERM
+
+
+def test_ordinary_sockets_stay_allowed_because_the_network_is_not_confined(program):
+ for family in (1, 2, 10):
+ assert _evaluate(program, nr = _socket_nr(), args = (family, 0, 0, 0, 0, 0)) == _ALLOW
+
+
+def test_a_vsock_socketpair_is_denied_too(program):
+ socketpair_nr = sandbox_seccomp._ABIS[platform.machine().lower()][2]
+ assert _evaluate(program, nr = socketpair_nr, args = (40, 0, 0, 0, 0, 0)) == _EPERM
+ assert _evaluate(program, nr = socketpair_nr, args = (1, 0, 0, 0, 0, 0)) == _ALLOW
+
+
+def test_io_uring_is_denied_on_all_three_entry_points(program):
+ for number in (425, 426, 427):
+ assert _evaluate(program, nr = number) == _EPERM
+
+
+def test_the_keyring_syscalls_are_denied(program):
+ for number in sandbox_seccomp._KEYRING_SYSCALLS[platform.machine().lower()]:
+ assert _evaluate(program, nr = number) == _EPERM
+
+
+def test_an_unrelated_syscall_is_allowed(program):
+ assert _evaluate(program, nr = 1) == _ALLOW
+
+
+def test_a_foreign_abi_is_killed_rather_than_evaluated(program):
+ assert _evaluate(program, nr = 1, arch = 0xDEADBEEF) == _KILL
+
+
[email protected](platform.machine().lower() not in ("x86_64", "amd64"), reason = "x32 is x86 only")
+def test_the_x32_syscall_table_is_killed(program):
+ assert _evaluate(program, nr = 1 | 0x40000000) == _KILL
+
+
+def test_nested_user_namespaces_are_refused_only_when_bwrap_cannot_do_it():
+ clone_nr, unshare_nr, clone3_nr = sandbox_seccomp._USERNS_SYSCALLS[platform.machine().lower()]
+ blocking = sandbox_seccomp.program(platform.machine(), block_userns = True)
+ assert _evaluate(blocking, nr = unshare_nr, args = (0x10000000, 0, 0, 0, 0, 0)) == _EPERM
+ for flags in (0x00000200, 0x00000400, 0x00040000):
+ assert _evaluate(blocking, nr = unshare_nr, args = (flags, 0, 0, 0, 0, 0)) == _ALLOW
+ assert _evaluate(blocking, nr = clone3_nr) == _ENOSYS
+ assert _evaluate(blocking, nr = clone_nr, args = (0x10000000, 0, 0, 0, 0, 0)) == _EPERM
+ assert _evaluate(blocking, nr = clone_nr, args = (0x00000100, 0, 0, 0, 0, 0)) == _ALLOW
+
+ permissive = sandbox_seccomp.program(platform.machine(), block_userns = False)
+ assert _evaluate(permissive, nr = unshare_nr, args = (0x10000000, 0, 0, 0, 0, 0)) == _ALLOW
+ assert _evaluate(permissive, nr = clone3_nr) == _ALLOW
+
+
+class _SockFilter(ctypes.Structure):
+ _fields_ = [
+ ("code", ctypes.c_ushort),
+ ("jt", ctypes.c_ubyte),
+ ("jf", ctypes.c_ubyte),
+ ("k", ctypes.c_uint32),
+ ]
+
+
+class _SockFprog(ctypes.Structure):
+ _fields_ = [("len", ctypes.c_ushort), ("filter", ctypes.POINTER(_SockFilter))]
+
+
+def _kernel_verdicts(block_userns):
+ """Each probe's errno from a fork child, 0 meaning allowed."""
+ clone3_nr, unshare_nr = 435, sandbox_seccomp._USERNS_SYSCALLS[platform.machine().lower()][1]
+ keyctl_nr = sandbox_seccomp._KEYRING_SYSCALLS[platform.machine().lower()][2]
+ read_fd, write_fd = os.pipe()
+ pid = os.fork()
+ if pid == 0: # pragma: no cover - this child never returns into pytest
+ os.close(read_fd)
+ try:
+ instructions = sandbox_seccomp.program(platform.machine(), block_userns = block_userns)
+ block = (_SockFilter * len(instructions))(
+ *(_SockFilter(*item) for item in instructions)
+ )
+ libc = ctypes.CDLL(None, use_errno = True)
+ libc.syscall.restype = ctypes.c_long
+ if libc.prctl(38, 1, 0, 0, 0) != 0:
+ os._exit(97)
+ fprog = _SockFprog(len(instructions), block)
+ if libc.prctl(22, 2, ctypes.byref(fprog), 0, 0) != 0:
+ os._exit(98)
+ verdicts = {}
+ for name, family in (("inet", socket.AF_INET), ("unix", socket.AF_UNIX), ("vsock", 40)):
+ try:
+ socket.socket(family, socket.SOCK_STREAM).close()
+ verdicts[name] = 0
+ except OSError as error:
+ verdicts[name] = error.errno
+ for name, number, argument in (
+ ("io_uring", 425, 0),
+ ("keyctl", keyctl_nr, 0),
+ ("clone3", clone3_nr, None),
+ ("unshare_userns", unshare_nr, 0x10000000),
+ ("unshare_fs", unshare_nr, 0x00000200),
+ ):
+ ctypes.set_errno(0)
+ result = libc.syscall(number, argument, 0, 0)
+ verdicts[name] = 0 if result >= 0 else ctypes.get_errno()
+ child = os.fork()
+ if child == 0:
+ os._exit(0)
+ verdicts["fork"] = os.waitpid(child, 0)[1]
+ os.write(write_fd, json.dumps(verdicts).encode())
+ os._exit(0)
+ except BaseException:
+ os._exit(99)
+ os.close(write_fd)
+ with os.fdopen(read_fd, "rb") as stream:
+ payload = stream.read()
+ status = os.waitpid(pid, 0)[1]
+ assert status == 0, f"the seccomp child exited with status {status:#x}"
+ return json.loads(payload)
+
+
+def test_the_kernel_loads_the_filter_and_denies_the_channels_it_names():
+ for block_userns in (False, True):
+ verdicts = _kernel_verdicts(block_userns)
+ assert verdicts["vsock"] == errno.EPERM
+ assert verdicts["io_uring"] == errno.EPERM
+ assert verdicts["keyctl"] == errno.EPERM
+ assert verdicts["inet"] == 0 and verdicts["unix"] == 0
+ assert verdicts["fork"] == 0
+
+
+def test_the_kernel_refuses_nested_user_namespaces_only_in_the_fallback_filter():
+ assert _kernel_verdicts(block_userns = True)["clone3"] == errno.ENOSYS
+ blocking = _kernel_verdicts(block_userns = True)
+ assert blocking["unshare_userns"] == errno.EPERM
+ assert blocking["unshare_fs"] == 0
+ assert _kernel_verdicts(block_userns = False)["clone3"] != errno.ENOSYS
+
+
+def test_an_unreviewed_architecture_is_refused_rather_than_left_unfiltered():
+ with pytest.raises(RuntimeError, match = "little-endian"):
+ sandbox_seccomp.program("riscv64")
+
+
+def test_the_filter_file_holds_exactly_the_program_and_is_rewound():
+ stream = sandbox_seccomp.filter_file(block_userns = True)
+ try:
+ assert stream.tell() == 0
+ payload = stream.read()
+ assert payload == sandbox_seccomp.program_bytes(block_userns = True)
+ assert len(payload) % 8 == 0
+ instructions = sandbox_seccomp.program(platform.machine(), block_userns = True)
+ assert len(payload) // 8 == len(instructions)
+ assert struct.unpack_from("=HBBI", payload, 0) == instructions[0]
+ finally:
+ stream.close()
+
+
+def test_a_runtime_path_symlinked_out_of_the_workdir_is_not_bound(tmp_path, monkeypatch):
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ secret = tmp_path / "secrets"
+ secret.mkdir()
+ (secret / "id_rsa").write_text("PRIVATE KEY")
+ venv = workdir / "venv"
+ venv.mkdir()
+ (venv / "lib").symlink_to(secret)
+ monkeypatch.setattr(sys, "prefix", str(venv))
+
+ paths = sandbox_linux._runtime_read_paths(str(workdir), ("/usr/lib",))
+ assert str(secret) not in paths
+ assert not any(sandbox_linux._within(str(secret), path) for path in paths)
+
+
+def test_a_symlinked_cache_ancestor_is_refused_rather_than_written_through(tmp_path, cache):
+ """Refused rather than unlinked: symlinking a cache leaf at another volume is a legitimate layout."""
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (workdir / ".cache").symlink_to(outside)
+
+ with pytest.raises(SandboxUnavailableError, match = "not a plain directory"):
+ sandbox_linux.prepare(_plan(workdir))
+ assert (workdir / ".cache").is_symlink()
+ assert sorted(entry.name for entry in outside.iterdir()) == []
+
+
+def test_the_probe_launch_sets_no_new_privs_like_a_real_one(tmp_path):
+ from core.inference import sandbox_probe
+
+ assert sandbox_probe._PR_SET_NO_NEW_PRIVS == 38
+ source = inspect.getsource(sandbox_probe._run_probe)
+ assert "preexec_fn = _no_new_privs" in source
+ assert not [
+ node
+ for node in ast.walk(ast.parse(inspect.getsource(sandbox_probe._no_new_privs)))
+ if isinstance(node, (ast.Import, ast.ImportFrom))
+ ]
+
+
+def test_the_pip_targets_script_directory_is_last_on_path(prepared):
+ argv = prepared.argv
+ entries = argv[argv.index("PATH") + 1].split(os.pathsep)
+ packages = os.path.join(prepared.workdir, sandbox_linux.SESSION_PACKAGES_RELPATH)
+ assert entries[-1] == os.path.join(packages, "bin")
+ assert "/usr/bin" in entries[:-1]
+
+
+def test_the_compiler_headers_a_source_build_needs_are_readable(prepared):
+ sources = [source for source, _ in _pairs(prepared.argv, "--ro-bind-try")]
+ assert "/usr/include" in sources
+ assert "/usr/local/include" in sources
+ include = sysconfig.get_paths().get("include")
+ if include and os.path.isdir(include):
+ bound = [source for source, _ in _pairs(prepared.argv, "--ro-bind")]
+ assert any(sandbox_linux._within(include, path) for path in (*sources, *bound)), include
+
+
+def test_a_runtime_prefix_contributes_its_git_helpers(tmp_path, monkeypatch):
+ prefix = tmp_path / "conda"
+ for name in ("bin", "libexec", "lib"):
+ (prefix / name).mkdir(parents = True)
+ monkeypatch.setattr(sys, "prefix", str(prefix))
+ paths = sandbox_linux._runtime_read_paths(str(tmp_path / "session"), ("/usr/lib",))
+ assert str(prefix / "libexec") in paths
+ assert str(prefix) not in paths
+
+
+def test_the_launch_pre_exec_scopes_abstract_sockets(tmp_path):
+ if not sandbox_landlock.abstract_scope_supported():
+ pytest.skip("this kernel predates the Landlock abstract-socket scope")
+ name = b"\0unsloth-abstract-probe-" + os.urandom(6).hex().encode()
+ listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ listener.bind(name)
+ listener.listen(1)
+ read_fd, write_fd = os.pipe()
+ try:
+ child = os.fork()
+ if child == 0: # pragma: no cover - runs in the forked child
+ try:
+ os.close(read_fd)
+ sandbox_landlock.with_abstract_scope(None)()
+ probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ probe.settimeout(2)
+ try:
+ probe.connect(name)
+ os.write(write_fd, b"connected")
+ except OSError as error:
+ os.write(write_fd, str(error.errno).encode())
+ finally:
+ os._exit(0)
+ os.close(write_fd)
+ write_fd = -1
+ with os.fdopen(read_fd, "rb") as stream:
+ verdict = stream.read()
+ read_fd = -1
+ os.waitpid(child, 0)
+ assert verdict == str(errno.EPERM).encode(), verdict
+ control = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ control.settimeout(2)
+ control.connect(name)
+ control.close()
+ finally:
+ for fd in (read_fd, write_fd):
+ if fd >= 0:
+ os.close(fd)
+ listener.close()
+
+
+def test_the_backend_says_so_when_the_kernel_cannot_scope_them(monkeypatch):
+ supported = sandbox_landlock.abstract_scope_supported()
+ assert ("host_abstract_sockets_reachable" in sandbox_linux.LIMITATIONS) is not supported
+
+
+def test_a_landlock_probe_child_that_never_answers_does_not_hang_the_server(monkeypatch):
+ if not sandbox_landlock._abi_reports_scope():
+ pytest.skip("no Landlock ABI 6 here, so the fork under test never happens")
+
+ def never_answers():
+ time.sleep(30)
+
+ monkeypatch.setattr(sandbox_landlock, "apply_abstract_scope", never_answers)
+ monkeypatch.setattr(sandbox_landlock, "_PROBE_TIMEOUT_SECONDS", 1.0)
+ sandbox_landlock.abstract_scope_supported.cache_clear()
+ try:
+ started = time.monotonic()
+ assert sandbox_landlock.abstract_scope_supported() is False
+ assert time.monotonic() - started < 10, "the deadline did not fire"
+ finally:
+ sandbox_landlock.abstract_scope_supported.cache_clear()
+
+
+def test_the_plan_pre_exec_still_runs_before_the_scope():
+ ran = []
+ composed = sandbox_landlock.with_abstract_scope(lambda: ran.append("plan"))
+ composed()
+ assert ran == ["plan"]
+
+
+def test_a_standalone_interpreter_in_the_workdir_is_re_bound_read_only(tmp_path, monkeypatch):
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ executable = workdir / "python"
+ executable.write_bytes(b"#!/bin/sh\nexit 0\n")
+ executable.chmod(0o755)
+ for attribute in ("prefix", "base_prefix", "exec_prefix", "base_exec_prefix"):
+ monkeypatch.setattr(sys, attribute, str(workdir))
+ monkeypatch.setattr(sys, "executable", str(executable))
+
+ assert sandbox_linux._runtime_paths_under(str(workdir)) == (str(executable),)
+ launch = sandbox_linux.prepare(_plan(workdir))
+ try:
+ argv = list(launch.argv)
+ read_only = [argv[i + 1] for i, item in enumerate(argv) if item == "--ro-bind"]
+ assert str(executable) in read_only, read_only
+ assert argv.index("--ro-bind", argv.index("--bind")) > argv.index("--bind")
+ finally:
+ launch.cleanup()
+
+
+def test_an_interpreter_in_a_home_directory_does_not_bind_the_home(tmp_path, monkeypatch):
+ home = tmp_path / "alice"
+ (home / ".ssh").mkdir(parents = True)
+ (home / ".ssh" / "id_rsa").write_text("SECRET", encoding = "utf-8")
+ executable = home / "python"
+ executable.write_bytes(b"#!/bin/sh\nexit 0\n")
+ executable.chmod(0o755)
+ monkeypatch.setattr(sys, "executable", str(executable))
+
+ paths = sandbox_linux._runtime_read_paths(str(tmp_path / "session"), ("/usr/lib",))
+ assert str(home) not in paths, paths
+ assert not any(_within_for_test(p, str(home / ".ssh")) for p in paths), paths
+ assert str(executable) in paths, paths
+
+
+def _within_for_test(path: str, root: str) -> bool:
+ return path == root or path.startswith(root.rstrip("/") + "/")
+
+
+def test_a_runtime_origin_is_excluded_under_the_workdir_alias_too(tmp_path, monkeypatch):
+ real = tmp_path / "real"
+ real.mkdir()
+ alias = tmp_path / "alias"
+ alias.symlink_to(real)
+ secret = tmp_path / "secrets"
+ secret.mkdir()
+ (secret / "id_rsa").write_text("SECRET", encoding = "utf-8")
+ venv = real / "venv"
+ (venv / "bin").mkdir(parents = True)
+ (venv / "lib").symlink_to(secret)
+ for attribute in ("prefix", "base_prefix", "exec_prefix", "base_exec_prefix"):
+ monkeypatch.setattr(sys, attribute, str(alias / "venv"))
+
+ paths = sandbox_linux._runtime_read_paths(os.path.realpath(real), ("/usr/lib",), str(alias))
+ assert not any(os.path.realpath(p) == str(secret) for p in paths), paths
+ launch = sandbox_linux.prepare(_plan(alias))
+ try:
+ argv = list(launch.argv)
+ bound = [
+ argv[i + 1] for i, item in enumerate(argv) if item in ("--ro-bind", "--ro-bind-try")
+ ]
+ assert not any(os.path.realpath(p) == str(secret) for p in bound), bound
+ finally:
+ launch.cleanup()
+
+
+def test_an_editable_source_inside_the_workdir_is_re_bound_read_only(tmp_path, monkeypatch):
+ workdir = tmp_path / "session"
+ package = workdir / "mypkg"
+ package.mkdir(parents = True)
+ (package / "__init__.py").write_text("", encoding = "utf-8")
+ monkeypatch.setattr(sandbox_linux, "editable_source_roots", lambda: (str(package),))
+
+ assert str(package) in sandbox_linux._runtime_paths_under(str(workdir))
+ assert str(package) not in sandbox_linux._runtime_read_paths(str(workdir), ("/usr/lib",))
+
+
+def test_the_interpreter_spelling_the_launch_execs_is_bound(tmp_path, monkeypatch):
+ target_bin = tmp_path / "opt" / "py" / "bin"
+ target_bin.mkdir(parents = True)
+ target = target_bin / "python3.13"
+ target.write_bytes(b"#!/bin/sh\nexit 0\n")
+ target.chmod(0o755)
+ user_bin = tmp_path / "home" / "bin"
+ user_bin.mkdir(parents = True)
+ link = user_bin / "python"
+ link.symlink_to(target)
+ monkeypatch.setattr(sys, "executable", str(link))
+ for attribute in ("prefix", "base_prefix", "exec_prefix", "base_exec_prefix"):
+ monkeypatch.setattr(sys, attribute, str(tmp_path / "opt" / "py"))
+
+ paths = sandbox_linux._runtime_read_paths(str(tmp_path / "session"), ("/usr/lib",))
+ assert str(link) in paths, paths
+ assert str(target) in paths or str(target_bin) in paths, paths
+ assert str(user_bin) not in paths, paths
+
+
+def test_a_wedged_cache_mount_drops_the_cache_instead_of_hanging_the_launch(tmp_path, monkeypatch):
+ cache = tmp_path / "hostcache"
+ (cache / "hub").mkdir(parents = True)
+ _share_cache_paths(monkeypatch, cache)
+
+ def wedged(path):
+ time.sleep(30)
+ raise AssertionError("the caller should not have waited for this")
+
+ monkeypatch.setattr(
+ sandbox_linux, "_inspect_cache_component", lambda name, path, witness = None: wedged(path)
+ )
+ monkeypatch.setattr(sandbox_linux, "_CACHE_INSPECT_SECONDS", 1.0)
+ started = time.monotonic()
+ binds = sandbox_linux._model_cache_binds(str(tmp_path / "session"))
+ assert time.monotonic() - started < 10, "the deadline did not fire"
+ assert binds == {}, binds
+
+
+def _share_cache_paths(monkeypatch, cache):
+ import types
+
+ class _Paths:
+ cache_home = str(cache)
+ hub_cache = str(cache / "hub")
+ xet_cache = str(cache / "xet")
+
+ module = types.ModuleType("utils.hf_cache_settings")
+ module.get_hf_cache_paths = lambda: _Paths()
+ monkeypatch.setitem(sys.modules, "utils.hf_cache_settings", module)
+
+
+def test_a_symlinked_runtime_entry_inside_the_workdir_is_protected_by_name(tmp_path, monkeypatch):
+ workdir = tmp_path / "session"
+ target = workdir / "real_pkg"
+ target.mkdir(parents = True)
+ (target / "__init__.py").write_text("", encoding = "utf-8")
+ entry = workdir / "mypkg"
+ entry.symlink_to(target)
+ monkeypatch.setattr(sandbox_linux, "editable_source_roots", lambda: (str(entry),))
+
+ protected = sandbox_linux._runtime_paths_under(str(workdir))
+ assert str(entry) in protected, protected
+ assert str(target) in protected, protected
+
+
+def test_a_wedged_cache_path_is_not_re_scanned_by_every_later_launch(tmp_path, monkeypatch):
+ cache = tmp_path / "hostcache"
+ (cache / "hub").mkdir(parents = True)
+ _share_cache_paths(monkeypatch, cache)
+ started: list[str] = []
+
+ def wedged(
+ name,
+ path,
+ witness = None,
+ ):
+ started.append(path)
+ time.sleep(30)
+
+ monkeypatch.setattr(sandbox_linux, "_inspect_cache_component", wedged)
+ monkeypatch.setattr(sandbox_linux, "_CACHE_INSPECT_SECONDS", 0.5)
+ monkeypatch.setattr(sandbox_linux, "_cache_scan_pending", {})
+ session = str(tmp_path / "session")
+ assert sandbox_linux._model_cache_binds(session) == {}
+ first = len(started)
+ assert first > 0
+ assert sandbox_linux._model_cache_binds(session) == {}
+ assert len(started) == first, "a second launch started another worker on the same path"
+
+
+def test_revalidating_a_cached_verdict_on_a_wedged_mount_is_bounded_too(monkeypatch, tmp_path):
+ """A memo hit re-stats every directory the walk saw, which blocks on a stalled NFS/FUSE cache just like the walk."""
+ component = tmp_path / "hub"
+ component.mkdir()
+ monkeypatch.setattr(sandbox_linux, "_cache_scan_pending", {})
+ sandbox_linux.reset_cache_verdicts()
+ assert sandbox_linux._cache_hazard_within_deadline("hub", str(component)) is None
+
+ release = threading.Event()
+ monkeypatch.setattr(
+ sandbox_linux, "directory_witness_matches", lambda witness: release.wait(30)
+ )
+ monkeypatch.setattr(sandbox_linux, "_CACHE_INSPECT_SECONDS", 0.5)
+ start = time.monotonic()
+ try:
+ hazard = sandbox_linux._cache_hazard_within_deadline("hub", str(component))
+ finally:
+ release.set()
+
+ assert time.monotonic() - start < 10
+ assert hazard is not None and "wedged" in hazard, hazard
+
+
+def test_a_runtime_entry_whose_target_leaves_the_workdir_gets_no_rule(tmp_path, monkeypatch):
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ private = tmp_path / "private"
+ private.mkdir()
+ (private / "id_rsa").write_text("SECRET", encoding = "utf-8")
+ (workdir / "venv").mkdir()
+ (workdir / "venv" / "lib").symlink_to(private)
+ monkeypatch.setattr(sys, "prefix", str(workdir / "venv"))
+ monkeypatch.setattr(sys, "exec_prefix", str(workdir / "venv"))
+
+ protected = sandbox_linux._runtime_paths_under(str(workdir))
+ assert str(workdir / "venv" / "lib") not in protected, protected
+ assert not any(os.path.realpath(p) == str(private) for p in protected), protected
+
+
+def test_an_interpreter_symlinked_out_of_the_workdir_fails_the_call(tmp_path, monkeypatch):
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ outside = tmp_path / "elsewhere"
+ outside.mkdir()
+ real = outside / "python"
+ real.write_bytes(b"#!/bin/sh\nexit 0\n")
+ real.chmod(0o755)
+ link = workdir / "python"
+ link.symlink_to(real)
+ monkeypatch.setattr(sys, "executable", str(link))
+
+ with pytest.raises(WorkdirUnsafeError, match = "Python that runs Studio"):
+ sandbox_linux._runtime_paths_under(str(workdir))
+
+
+def test_concurrent_launches_start_one_cache_worker_and_never_raise(tmp_path, monkeypatch):
+ cache = tmp_path / "hostcache"
+ (cache / "hub").mkdir(parents = True)
+ _share_cache_paths(monkeypatch, cache)
+ started: list[str] = []
+ gate = threading.Event()
+
+ def wedged(
+ name,
+ path,
+ witness = None,
+ ):
+ started.append(path)
+ gate.wait(30)
+
+ monkeypatch.setattr(sandbox_linux, "_inspect_cache_component", wedged)
+ monkeypatch.setattr(sandbox_linux, "_CACHE_INSPECT_SECONDS", 0.5)
+ monkeypatch.setattr(sandbox_linux, "_cache_scan_pending", {})
+ session = str(tmp_path / "session")
+ errors: list[BaseException] = []
+
+ def launch() -> None:
+ try:
+ sandbox_linux._model_cache_binds(session)
+ except BaseException as exc: # noqa: BLE001 - the point of the test
+ errors.append(exc)
+
+ threads = [threading.Thread(target = launch) for _ in range(8)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(60)
+ gate.set()
+ assert not errors, errors
+ assert started, "the inspection never ran"
+ assert len(started) == len(set(started)), f"a path was scanned twice: {sorted(started)}"
+
+
+def test_a_runtime_prefix_contributes_its_certificate_store(tmp_path, monkeypatch):
+ prefix = tmp_path / "conda"
+ for name in ("bin", "ssl", "lib"):
+ (prefix / name).mkdir(parents = True)
+ monkeypatch.setattr(sys, "prefix", str(prefix))
+ paths = sandbox_linux._runtime_read_paths(str(tmp_path / "session"), ("/usr/lib",))
+ assert str(prefix / "ssl") in paths
+
+
+def test_a_workdir_reached_through_a_symlink_is_bound_at_the_spelling_the_caller_used(tmp_path):
+ real = tmp_path / "real"
+ real.mkdir()
+ link = tmp_path / "link"
+ link.symlink_to(real)
+ launch = sandbox_linux.prepare(_plan(link))
+ try:
+ binds = _pairs(launch.argv, "--bind")
+ assert (str(real), str(link)) in binds
+ assert (str(real), str(real)) in binds
+ assert launch.argv[launch.argv.index("--chdir") + 1] == str(link)
+ assert launch.argv[launch.argv.index("HOME") + 1] == str(link)
+ finally:
+ launch.cleanup()
+
+
+def test_a_cache_leaf_left_behind_as_a_file_is_refused_at_preparation(tmp_path, cache):
+ workdir = tmp_path / "session"
+ (workdir / ".cache" / "huggingface").mkdir(parents = True)
+ (workdir / ".cache" / "huggingface" / "hub").write_text("not a directory")
+
+ with pytest.raises(SandboxUnavailableError, match = "not a plain directory"):
+ sandbox_linux.prepare(_plan(workdir))
+ assert (workdir / ".cache" / "huggingface" / "hub").read_text() == "not a directory"
+
+
+ os.geteuid() == 0,
+ reason = "root reads and writes regardless of the mode bits, so the premise is void",
+)
+def test_an_unreadable_directory_is_refused(tmp_path):
+ """A mode-000 directory hides a link out from the scan, and the process that owns it can chmod it back."""
+ locked = tmp_path / "locked"
+ locked.mkdir()
+ (locked / "inside").write_text("x")
+ locked.chmod(0o000)
+ try:
+ with pytest.raises(SandboxUnavailableError, match = "cannot be fully inspected"):
+ sandbox_linux._validate_workdir(str(tmp_path))
+ finally:
+ locked.chmod(0o700)
+
+
+def test_the_cache_studio_actually_uses_is_the_one_shared(tmp_path, monkeypatch):
+ """HF_HUB_CACHE=/mnt/models is NOT /mnt/models/hub, so each component is bound where it actually is."""
+ hub = tmp_path / "mnt" / "models"
+ xet = tmp_path / "fast" / "xet"
+ home = tmp_path / "cachehome"
+ for path in (hub, xet, home / "datasets", home / "assets"):
+ path.mkdir(parents = True)
+ import utils.hf_cache_settings as cache_settings
+
+ monkeypatch.setattr(
+ cache_settings,
+ "get_hf_cache_paths",
+ lambda: cache_settings.HuggingFaceCachePaths(
+ cache_home = home, hub_cache = hub, xet_cache = xet, source = "studio"
+ ),
+ )
+ binds = sandbox_linux._model_cache_binds(str(tmp_path / "session"))
+ assert binds["hub"] == str(hub)
+ assert binds["xet"] == str(xet)
+ assert binds["datasets"] == str(home / "datasets")
+ assert "hub" not in sandbox_linux._model_cache_binds(str(hub.parent))
+
+
+def _real_cache(monkeypatch, home):
+ """Point the settings layer at *home* and let the REAL _model_cache_binds run."""
+ import types
+
+ paths = types.SimpleNamespace(cache_home = home, hub_cache = home / "hub", xet_cache = home / "xet")
+ module = types.ModuleType("utils.hf_cache_settings")
+ module.get_hf_cache_paths = lambda: paths
+ monkeypatch.setitem(sys.modules, "utils.hf_cache_settings", module)
+
+
+def test_a_cache_component_holding_an_ipc_node_is_not_shared(tmp_path, monkeypatch):
+ host = tmp_path / "hostcache"
+ (host / "hub").mkdir(parents = True)
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ monkeypatch.chdir(host / "hub")
+ sock.bind("leftover.sock")
+ try:
+ _real_cache(monkeypatch, host)
+ assert "hub" not in sandbox_linux._model_cache_binds(str(tmp_path / "session"))
+ finally:
+ sock.close()
+
+
+def test_a_cache_component_holding_an_external_hard_link_is_not_shared(tmp_path, monkeypatch):
+ """Same inode under two names, one of them outside the cache."""
+ host = tmp_path / "hostcache"
+ (host / "hub").mkdir(parents = True)
+ outside = tmp_path / "private.txt"
+ outside.write_text("secret")
+ os.link(outside, host / "hub" / "innocent.bin")
+ _real_cache(monkeypatch, host)
+ assert "hub" not in sandbox_linux._model_cache_binds(str(tmp_path / "session"))
+
+
+def test_a_clean_cache_component_is_still_shared(tmp_path, monkeypatch):
+ """The negative control: the check above must not simply drop everything."""
+ host = tmp_path / "hostcache"
+ (host / "hub" / "models--x").mkdir(parents = True)
+ (host / "hub" / "models--x" / "weights.bin").write_text("w")
+ _real_cache(monkeypatch, host)
+ assert sandbox_linux._model_cache_binds(str(tmp_path / "session"))["hub"] == str(host / "hub")
+
+
+def test_a_hazardous_cache_drops_the_component_rather_than_failing_the_launch(
+ tmp_path, monkeypatch
+):
+ host = tmp_path / "hostcache"
+ (host / "hub").mkdir(parents = True)
+ os.mkfifo(host / "hub" / "pipe")
+ _real_cache(monkeypatch, host)
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ launch = sandbox_linux.prepare(_plan(workdir))
+ try:
+ assert "HF_HOME" not in launch.argv
+ finally:
+ launch.cleanup()
+
+
+def test_a_trusted_system_gitconfig_is_bound_and_an_untrusted_one_is_not(tmp_path, monkeypatch):
+ good = tmp_path / "gitconfig"
+ good.write_text("[http]\n")
+ link = tmp_path / "linked"
+ link.symlink_to(good)
+ assert sandbox_linux._trusted_system_file(str(link)) is False, "a symlink is followed"
+ assert sandbox_linux._trusted_system_file(str(tmp_path / "absent")) is False
+ os.chmod(good, 0o666)
+ assert sandbox_linux._trusted_system_file(str(good)) is False, "world-writable accepted"
+
+
+def test_a_runtime_under_the_workdir_is_re_bound_read_only(tmp_path, monkeypatch):
+ workdir = tmp_path / "session"
+ venv = workdir / "venv"
+ (venv / "lib").mkdir(parents = True)
+ (venv / "bin").mkdir()
+ monkeypatch.setattr(sys, "prefix", str(venv))
+ monkeypatch.setattr(sys, "exec_prefix", str(venv))
+
+ launch = sandbox_linux.prepare(_plan(workdir))
+ try:
+ argv = launch.argv
+ writable = argv.index("--bind")
+ ro_after = [
+ source
+ for index, source in enumerate(argv)
+ if index > writable and argv[index - 1] == "--ro-bind"
+ ]
+ assert str(venv / "lib") in ro_after, "the runtime stayed writable"
+ assert str(venv / "bin") in ro_after
+ finally:
+ launch.cleanup()
+
+
+def test_a_runtime_symlinked_out_of_the_workdir_is_not_re_bound(tmp_path, monkeypatch):
+ """The negative control for the rule above."""
+ workdir = tmp_path / "session"
+ (workdir / "venv").mkdir(parents = True)
+ secret = tmp_path / "home" / ".ssh"
+ secret.mkdir(parents = True)
+ (workdir / "venv" / "lib").symlink_to(secret)
+ monkeypatch.setattr(sys, "prefix", str(workdir / "venv"))
+
+ launch = sandbox_linux.prepare(_plan(workdir))
+ try:
+ for flag in ("--bind", "--ro-bind", "--ro-bind-try"):
+ for source, _ in _pairs(launch.argv, flag):
+ assert not sandbox_linux._within(str(secret), source), source
+ finally:
+ launch.cleanup()
+
+
+def test_a_nested_bind_mount_in_the_cache_is_caught_by_the_mount_table(tmp_path, monkeypatch):
+ host = tmp_path / "hostcache"
+ (host / "hub" / "nested").mkdir(parents = True)
+ _real_cache(monkeypatch, host)
+ monkeypatch.setattr(
+ sandbox_linux, "_host_mount_points", lambda: (str(host / "hub" / "nested"),)
+ )
+ assert "hub" not in sandbox_linux._model_cache_binds(str(tmp_path / "session"))
+
+
+def test_a_nested_bind_mount_is_caught_through_a_symlinked_cache(tmp_path, monkeypatch):
+ """The mount table lists canonical paths, so a cache reached through a symlinked ~/.cache must be compared in its resolved form."""
+ real = tmp_path / "volume" / "huggingface"
+ (real / "hub" / "nested").mkdir(parents = True)
+ (tmp_path / "cache-link").symlink_to(tmp_path / "volume")
+ _real_cache(monkeypatch, tmp_path / "cache-link" / "huggingface")
+ monkeypatch.setattr(
+ sandbox_linux, "_host_mount_points", lambda: (str(real / "hub" / "nested"),)
+ )
+ assert "hub" not in sandbox_linux._model_cache_binds(str(tmp_path / "session"))
+
+
+def _fake_editable(
+ tmp_path,
+ monkeypatch,
+ source: str,
+ top_level: str | None = None,
+):
+ """A dist-info recording an editable install, the way an installer writes it."""
+ site_dir = tmp_path / "sitepkgs"
+ info = site_dir / "demo-1.0.dist-info"
+ info.mkdir(parents = True)
+ (info / "METADATA").write_text("Name: demo\nVersion: 1.0\n", encoding = "utf-8")
+ (info / "RECORD").write_text("", encoding = "utf-8")
+ if top_level is not None:
+ (info / "top_level.txt").write_text(top_level + "\n", encoding = "utf-8")
+ (info / "direct_url.json").write_text(
+ json.dumps({"url": f"file://{source}", "dir_info": {"editable": True}}),
+ encoding = "utf-8",
+ )
+ monkeypatch.syspath_prepend(str(site_dir))
+ os_sandbox.editable_source_roots.cache_clear()
+ return site_dir
+
+
+def test_an_editable_installs_source_root_is_readable(tmp_path, monkeypatch):
+ source = tmp_path / "checkout"
+ package = source / "demo"
+ package.mkdir(parents = True)
+ (package / "__init__.py").write_text("", encoding = "utf-8")
+ (source / ".env").write_text("AWS_SECRET_ACCESS_KEY=real\n", encoding = "utf-8")
+ (source / "fixtures").mkdir()
+ _fake_editable(tmp_path, monkeypatch, str(source))
+ try:
+ granted = os_sandbox.editable_source_roots()
+ assert str(package) in granted, granted
+ assert str(source) not in granted, granted
+ assert not any("fixtures" in path or ".env" in path for path in granted), granted
+ roots = tuple(p for p in sandbox_linux._SYSTEM_ROOTS if os.path.isdir(p))
+ read = sandbox_linux._runtime_read_paths(str(tmp_path / "wd"), roots)
+ assert str(package) in read
+ assert str(source) not in read
+ finally:
+ os_sandbox.editable_source_roots.cache_clear()
+
+
+def test_a_guessed_editable_import_root_gives_up_what_it_cannot_confirm(tmp_path, monkeypatch):
+ source = tmp_path / "checkout"
+ package = source / "demo"
+ package.mkdir(parents = True)
+ (package / "__init__.py").write_text("", encoding = "utf-8")
+ (source / "deploy.py").write_text("AWS_SECRET_ACCESS_KEY = 'real'\n", encoding = "utf-8")
+ (source / "conftest.py").write_text("", encoding = "utf-8")
+ tests_pkg = source / "tests"
+ tests_pkg.mkdir()
+ (tests_pkg / "__init__.py").write_text("", encoding = "utf-8")
+ (tests_pkg / "fixtures").mkdir()
+ (tests_pkg / "fixtures" / "id_rsa").write_text("-----BEGIN-----", encoding = "utf-8")
+ _fake_editable(tmp_path, monkeypatch, str(source), top_level = "demo")
+ try:
+ granted = os_sandbox.editable_source_roots()
+ assert granted == (str(package),), granted
+ finally:
+ os_sandbox.editable_source_roots.cache_clear()
+
+
+def test_a_declared_package_symlinked_out_of_the_checkout_is_refused(tmp_path, monkeypatch):
+ source = tmp_path / "checkout"
+ source.mkdir()
+ private = tmp_path / "private"
+ private.mkdir()
+ (private / "id_rsa").write_text("SECRET", encoding = "utf-8")
+ (private / "__init__.py").write_text("", encoding = "utf-8")
+ (source / "demo").symlink_to(private)
+ _fake_editable(tmp_path, monkeypatch, str(source), top_level = "demo")
+ try:
+ granted = os_sandbox.editable_source_roots()
+ assert granted == (), granted
+ finally:
+ os_sandbox.editable_source_roots.cache_clear()
+
+
+def test_an_editable_root_at_the_filesystem_root_is_refused(tmp_path, monkeypatch):
+ """The negative control."""
+ _fake_editable(tmp_path, monkeypatch, "/usr")
+ try:
+ assert os_sandbox.editable_source_roots() == ()
+ finally:
+ os_sandbox.editable_source_roots.cache_clear()
+
+
+def test_a_runtime_under_a_symlinked_workdir_is_read_only_through_both_spellings(
+ tmp_path, monkeypatch
+):
+ real = tmp_path / "real"
+ venv = real / "venv"
+ (venv / "lib").mkdir(parents = True)
+ (venv / "bin").mkdir()
+ alias = tmp_path / "alias"
+ alias.symlink_to(real)
+ monkeypatch.setattr(sys, "prefix", str(venv))
+ monkeypatch.setattr(sys, "exec_prefix", str(venv))
+
+ launch = sandbox_linux.prepare(_plan(alias))
+ try:
+ argv = list(launch.argv)
+ binds = [i for i, item in enumerate(argv) if item == "--bind"]
+ writable = [argv[i + 2] for i in binds]
+ assert str(alias) in writable and str(real) in writable, writable
+ last_bind = max(binds)
+ for leg in ("lib", "bin"):
+ for spelling in (real / "venv" / leg, alias / "venv" / leg):
+ landed = [
+ i
+ for i in range(len(argv))
+ if argv[i] == "--ro-bind" and argv[i + 2] == str(spelling)
+ ]
+ assert landed, f"{spelling} is not re-bound read-only"
+ assert min(landed) > last_bind, f"{spelling} is bound before the last --bind"
+ finally:
+ launch.cleanup()
+
+
+def test_a_runtime_is_protected_when_sys_prefix_carries_the_workdir_alias(tmp_path, monkeypatch):
+ real = tmp_path / "real"
+ (real / "venv" / "lib").mkdir(parents = True)
+ (real / "venv" / "bin").mkdir()
+ alias = tmp_path / "alias"
+ alias.symlink_to(real)
+ monkeypatch.setattr(sys, "prefix", str(alias / "venv"))
+ monkeypatch.setattr(sys, "exec_prefix", str(alias / "venv"))
+
+ under = sandbox_linux._runtime_paths_under(str(real))
+ assert str(real / "venv" / "lib") in under, under
+ assert str(real / "venv" / "bin") in under, under
+
+ launch = sandbox_linux.prepare(_plan(alias))
+ try:
+ argv = list(launch.argv)
+ last_bind = max(i for i, item in enumerate(argv) if item == "--bind")
+ for leg in ("lib", "bin"):
+ for spelling in (real / "venv" / leg, alias / "venv" / leg):
+ landed = [
+ i
+ for i in range(len(argv))
+ if argv[i] == "--ro-bind" and argv[i + 2] == str(spelling)
+ ]
+ assert landed and max(landed) > last_bind, f"{spelling} unprotected"
+ finally:
+ launch.cleanup()
+
+
+def test_an_editable_namespace_package_is_granted_without_an_init(tmp_path, monkeypatch):
+ source = tmp_path / "checkout"
+ namespace = source / "acme"
+ (namespace / "widget").mkdir(parents = True)
+ (namespace / "widget" / "__init__.py").write_text("", encoding = "utf-8")
+ (source / ".env").write_text("AWS_SECRET_ACCESS_KEY=real\n", encoding = "utf-8")
+ (source / "fixtures").mkdir()
+ _fake_editable(tmp_path, monkeypatch, str(source), top_level = "acme")
+ try:
+ granted = os_sandbox.editable_source_roots()
+ assert str(namespace) in granted, granted
+ assert not any("fixtures" in path or ".env" in path for path in granted), granted
+ assert str(source) not in granted, granted
+ finally:
+ os_sandbox.editable_source_roots.cache_clear()
+
+
+def test_the_cache_verdict_is_memoized_between_launches(tmp_path, monkeypatch):
+ """The walk is O(entries) and was re-paid on every launch."""
+ calls = []
+ real = sandbox_linux._inspect_cache_component
+ monkeypatch.setattr(
+ sandbox_linux,
+ "_inspect_cache_component",
+ lambda name, path, witness = None: (calls.append(path), real(name, path, witness))[1],
+ )
+ sandbox_linux.reset_cache_verdicts()
+ component = tmp_path / "hub"
+ component.mkdir()
+ (component / "a.bin").write_text("")
+
+ first = sandbox_linux._cache_hazard_within_deadline("hub", str(component))
+ walked_once = len(calls)
+ second = sandbox_linux._cache_hazard_within_deadline("hub", str(component))
+
+ assert second == first
+ assert len(calls) == walked_once, "the second launch re-walked the cache"
+
+
+def test_a_changed_cache_is_re_inspected_rather_than_trusted(tmp_path, monkeypatch):
+ """The memo key is the component root's identity and mtime, so a change made through the root must invalidate it."""
+ calls = []
+ real = sandbox_linux._inspect_cache_component
+ monkeypatch.setattr(
+ sandbox_linux,
+ "_inspect_cache_component",
+ lambda name, path, witness = None: (calls.append(path), real(name, path, witness))[1],
+ )
+ sandbox_linux.reset_cache_verdicts()
+ component = tmp_path / "hub"
+ component.mkdir()
+ sandbox_linux._cache_hazard_within_deadline("hub", str(component))
+ before = len(calls)
+
+ os.utime(component, (0, 0))
+ (component / "models--org--new").mkdir()
+ sandbox_linux._cache_hazard_within_deadline("hub", str(component))
+
+ assert len(calls) > before, "a changed cache reused its old verdict"
+
+
+def test_a_failed_launch_drops_every_cache_verdict(tmp_path, monkeypatch):
+ """tools.py calls this when a launch dies, for the same reason it drops the capability probe: a failed launch is the one signal that something the planner believed about this host has changed."""
+ calls = []
+ real = sandbox_linux._inspect_cache_component
+ monkeypatch.setattr(
+ sandbox_linux,
+ "_inspect_cache_component",
+ lambda name, path, witness = None: (calls.append(path), real(name, path, witness))[1],
+ )
+ sandbox_linux.reset_cache_verdicts()
+ component = tmp_path / "hub"
+ component.mkdir()
+ sandbox_linux._cache_hazard_within_deadline("hub", str(component))
+ before = len(calls)
+
+ sandbox_linux.reset_cache_verdicts()
+ sandbox_linux._cache_hazard_within_deadline("hub", str(component))
+
+ assert len(calls) > before, "reset_cache_verdicts did not invalidate the memo"
+
+
+def test_the_studio_state_directory_is_never_a_system_bind(monkeypatch, tmp_path):
+ """/opt is a system root and the Docker layout puts Studio's state in it."""
+ from core.inference import sandbox_linux
+
+ opt = tmp_path / "opt"
+ state = opt / "unsloth-studio"
+ (state / "auth").mkdir(parents = True)
+ (state / "auth" / "auth.db").write_text("secret")
+ toolchain = opt / "some-toolchain"
+ toolchain.mkdir()
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(state))
+
+ kept = sandbox_linux._without_studio_state((str(opt),))
+
+ assert str(state) not in kept
+ assert not any(
+ sandbox_linux._within(str(state), path) for path in kept
+ ), "a bind source still contains the Studio auth database"
+ assert str(toolchain) in kept, "unrelated /opt software stopped being readable"
+
+
+def test_a_system_root_without_studio_state_is_still_bound_whole(monkeypatch, tmp_path):
+ """The descent must only happen where it is needed, or every launch pays a listdir of /usr and binds hundreds of paths."""
+ from core.inference import sandbox_linux
+
+ opt = tmp_path / "opt"
+ (opt / "some-toolchain").mkdir(parents = True)
+ elsewhere = tmp_path / "home" / "studio"
+ elsewhere.mkdir(parents = True)
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(elsewhere))
+
+ assert sandbox_linux._without_studio_state((str(opt),)) == (str(opt),)
+
+
+def test_a_deeply_nested_studio_state_root_is_refused_not_restored(monkeypatch, tmp_path):
+ """The descent is bounded, and the bound must fail CLOSED."""
+ from core.inference import sandbox_linux
+
+ opt = tmp_path / "opt"
+ state = opt / "a" / "b" / "c" / "d" / "studio"
+ (state / "auth").mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(state))
+
+ kept = sandbox_linux._without_studio_state((str(opt),), depth = 0)
+
+ assert kept == (), "an ancestor of the Studio auth database was bound anyway"
+
+
+def test_a_symlinked_sibling_is_not_promoted_to_a_bind_source(monkeypatch, tmp_path):
+ """Splitting a system root must not mount what the whole-root bind did not."""
+ from core.inference import sandbox_linux
+
+ opt = tmp_path / "opt"
+ state = opt / "unsloth-studio"
+ (state / "auth").mkdir(parents = True)
+ private = tmp_path / "home" / "operator" / "private"
+ private.mkdir(parents = True)
+ (opt / "private").symlink_to(private)
+ (opt / "toolchain").mkdir()
+ (opt / "inside-link").symlink_to(opt / "toolchain")
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(state))
+
+ kept = sandbox_linux._without_studio_state((str(opt),))
+
+ assert str(opt / "private") not in kept, "a symlink out of the root became a bind source"
+ assert str(opt / "toolchain") in kept
+ assert str(opt / "inside-link") in kept
+
+
+def test_a_cache_holding_studio_state_is_not_shared_writable(monkeypatch, tmp_path):
+ """HF_HUB_CACHE at or above the Studio root would bind auth/auth.db in WRITABLE, and the hazard scan would not object: an ordinary file is not a host channel."""
+ from core.inference import sandbox_linux
+
+ state = tmp_path / "studio"
+ (state / "auth").mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(state))
+
+ assert sandbox_linux._holds_studio_state(str(state)) is True
+ assert (
+ sandbox_linux._holds_studio_state(str(tmp_path)) is True
+ ), "an ancestor of the Studio root was not recognised"
+ assert sandbox_linux._holds_studio_state(str(tmp_path / "elsewhere")) is False
+
+
+def test_the_cache_bind_itself_drops_a_component_holding_studio_state(monkeypatch, tmp_path):
+ """Through _model_cache_binds, not just the predicate: the guard is only worth anything if the bind list is what changes."""
+ import types
+
+ from core.inference import sandbox_linux
+
+ state = tmp_path / "studio"
+ (state / "auth").mkdir(parents = True)
+ elsewhere = tmp_path / "models"
+ for name in ("xet", "datasets", "assets"):
+ (elsewhere / name).mkdir(parents = True, exist_ok = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(state))
+
+ settings = types.ModuleType("utils.hf_cache_settings")
+ settings.get_hf_cache_paths = lambda: types.SimpleNamespace(
+ cache_home = str(elsewhere),
+ hub_cache = str(state),
+ xet_cache = str(elsewhere / "xet"),
+ )
+ monkeypatch.setitem(sys.modules, "utils.hf_cache_settings", settings)
+ monkeypatch.setattr(sandbox_linux, "_cache_hazard_within_deadline", lambda name, path: None)
+
+ binds = sandbox_linux._model_cache_binds(str(tmp_path / "work"))
+
+ assert "hub" not in binds, "the Studio root was shared into the sandbox as the hub cache"
+ assert binds.get("xet") == str(elsewhere / "xet")
+
+
+def test_a_cache_configured_as_a_home_directory_is_not_shared(monkeypatch, tmp_path):
+ """HF_HUB_CACHE pointed at a home is a misconfiguration; the consequence is not."""
+ import types
+
+ from core.inference import sandbox_linux
+
+ home = tmp_path / "home" / "alice"
+ (home / ".ssh").mkdir(parents = True)
+ (home / ".ssh" / "id_ed25519").write_text("private")
+ models = tmp_path / "models"
+ for name in ("xet", "datasets", "assets"):
+ (models / name).mkdir(parents = True, exist_ok = True)
+
+ monkeypatch.setenv("HOME", str(home))
+ settings = types.ModuleType("utils.hf_cache_settings")
+ settings.get_hf_cache_paths = lambda: types.SimpleNamespace(
+ cache_home = str(models),
+ hub_cache = str(home),
+ xet_cache = str(models / "xet"),
+ )
+ monkeypatch.setitem(sys.modules, "utils.hf_cache_settings", settings)
+ monkeypatch.setattr(sandbox_linux, "_cache_hazard_within_deadline", lambda name, path: None)
+
+ binds = sandbox_linux._model_cache_binds(str(tmp_path / "work"))
+
+ assert "hub" not in binds, "the user's home was shared into the sandbox writable"
+ assert binds.get("xet") == str(models / "xet"), "an ordinary cache stopped working"
+
+
+def test_a_filesystem_root_is_never_a_cache(monkeypatch, tmp_path):
+ """Cheap, and the worst case of the same mistake."""
+ from core.inference import sandbox_linux
+
+ monkeypatch.setenv("HOME", str(tmp_path / "somewhere-else"))
+
+ assert sandbox_linux._too_broad_for_a_cache("/") is True
+ assert sandbox_linux._too_broad_for_a_cache("/home") is True
+ assert sandbox_linux._too_broad_for_a_cache(str(tmp_path / "models" / "hub")) is False
+
+
+def _stub_capable_backend(monkeypatch, limitations):
+ """An available capability and a backend that builds, so the test is about prepare_tool_launch's decision rather than about this host's bwrap."""
+ from core.inference import os_sandbox, sandbox_linux
+
+ capability = os_sandbox.SandboxCapability(
+ backend = "stub",
+ available = True,
+ reason = "stub",
+ environment = "linux",
+ protection_state = "qualified",
+ profile_id = "stub",
+ limitations = (),
+ )
+ monkeypatch.setattr(os_sandbox, "capability_snapshot", lambda *a, **k: capability)
+
+ def build(plan):
+ return os_sandbox.PreparedSandboxLaunch(
+ argv = plan.argv,
+ workdir = plan.workdir,
+ env = dict(plan.env),
+ preexec_fn = None,
+ backend = "stub",
+ launch_limitations = limitations,
+ )
+
+ monkeypatch.setattr(sandbox_linux, "prepare", build)
+
+
+def test_required_refuses_a_workdir_it_could_not_finish_checking(monkeypatch, tmp_path):
+ """`auto` degrades here on purpose, and `required` must not."""
+ from core.inference import os_sandbox
+
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ for i in range(8):
+ (workdir / f"f{i}").write_text("")
+
+ monkeypatch.setattr(os_sandbox, "WORKDIR_SCAN_ENTRIES", 3)
+
+ limitations = os_sandbox.scan_workdir_for_host_channels(str(workdir))
+ assert limitations == (
+ os_sandbox.WORKDIR_SCAN_INCOMPLETE,
+ ), "the budget did not trip, so this test proves nothing"
+ _stub_capable_backend(monkeypatch, limitations)
+
+ plan = os_sandbox.ToolLaunchPlan(
+ argv = ("/bin/true",),
+ workdir = str(workdir),
+ env = {},
+ requested_mode = "required",
+ timeout_seconds = 10,
+ )
+
+ with pytest.raises(os_sandbox.WorkdirUnsafeError, match = "too large to check"):
+ os_sandbox.prepare_tool_launch(plan)
+
+
+def test_auto_still_launches_on_the_same_workdir(monkeypatch, tmp_path):
+ """The other half of the same decision: the brick fix must survive."""
+ from core.inference import os_sandbox
+
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ for i in range(8):
+ (workdir / f"f{i}").write_text("")
+
+ monkeypatch.setattr(os_sandbox, "WORKDIR_SCAN_ENTRIES", 3)
+ _stub_capable_backend(monkeypatch, (os_sandbox.WORKDIR_SCAN_INCOMPLETE,))
+
+ plan = os_sandbox.ToolLaunchPlan(
+ argv = ("/bin/true",),
+ workdir = str(workdir),
+ env = {},
+ requested_mode = "auto",
+ timeout_seconds = 10,
+ )
+
+ prepared = os_sandbox.prepare_tool_launch(plan)
+ try:
+ assert prepared.execution_record is not None
+ assert os_sandbox.WORKDIR_SCAN_INCOMPLETE in prepared.execution_record.limitations
+ finally:
+ prepared.cleanup()
+
+
+def test_a_registered_model_folder_is_bound_read_only(monkeypatch, tmp_path):
+ """The same disagreement on Linux: silent at the approval gate, absent from the binds, so the read fails inside the jail."""
+ from core.inference import os_sandbox
+
+ library = tmp_path / "library" / "models"
+ library.mkdir(parents = True)
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ monkeypatch.setattr(os_sandbox, "model_library_roots", lambda: (str(library),))
+
+ from core.inference import sandbox_linux
+
+ if sandbox_linux.shutil.which("bwrap") is None:
+ pytest.skip("bubblewrap is not installed on this host")
+ monkeypatch.setattr(sandbox_linux, "model_library_roots", lambda: (str(library),))
+
+ launch = sandbox_linux.prepare(_plan(workdir))
+ try:
+ pairs = _pairs(launch.argv, "--ro-bind-try")
+ finally:
+ launch.cleanup()
+
+ assert (str(library), str(library)) in pairs, "the registered model folder was not bound"
+
+
+def test_a_model_folder_that_is_a_system_directory_is_refused(monkeypatch):
+ """A registered folder that is really /etc or a home is a misconfiguration, and binding it would undo the rest of the profile."""
+ from core.inference import os_sandbox, tool_path_approval
+
+ monkeypatch.setattr(tool_path_approval, "_scan_folder_roots", lambda: ("/etc", "/"))
+ monkeypatch.setattr(
+ "utils.paths.storage_roots.well_known_model_dirs",
+ lambda: (os.path.expanduser("~"),),
+ raising = False,
+ )
+
+ assert os_sandbox.model_library_roots() == ()
+
+
+def test_a_model_folder_that_is_a_credential_directory_is_refused(monkeypatch, tmp_path):
+ """OLLAMA_MODELS=~/.ssh would otherwise grant the keys the approval gate still asks about."""
+ from core.inference import os_sandbox, tool_path_approval
+
+ keys = tmp_path / ".ssh"
+ models = tmp_path / "models"
+ keys.mkdir()
+ models.mkdir()
+ monkeypatch.setattr(tool_path_approval, "_scan_folder_roots", lambda: (str(keys),))
+ monkeypatch.setattr(
+ "utils.paths.storage_roots.well_known_model_dirs",
+ lambda: (str(models),),
+ raising = False,
+ )
+
+ assert os_sandbox.model_library_roots() == (os.path.realpath(models),)
+
+
+def _bind_unix_socket(path):
+ """Create a bound AF_UNIX socket at *path*."""
+ import socket
+
+ here = os.getcwd()
+ os.chdir(os.path.dirname(path))
+ try:
+ listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ try:
+ listener.bind(os.path.basename(path))
+ finally:
+ listener.close()
+ finally:
+ os.chdir(here)
+
+
+def test_a_stale_tool_socket_does_not_brick_the_session(tmp_path):
+ """A crashed tool's leftover listener must not end the chat."""
+ from core.inference import os_sandbox
+
+ workdir = tmp_path / "work"
+ scratch = workdir / os_sandbox.TOOL_TEMP_DIRNAME / "pymp-abc"
+ scratch.mkdir(parents = True)
+ os.chmod(scratch.parent, 0o700)
+ _bind_unix_socket(str(scratch / "listener-0"))
+ assert (scratch / "listener-0").exists(), "the stale socket was not created"
+
+ assert os_sandbox.scan_workdir_for_host_channels(str(workdir)) == ()
+ assert not (scratch / "listener-0").exists(), "the stale socket was left in place"
+
+
+def test_a_socket_outside_the_scratch_directory_still_fails_the_call(tmp_path):
+ """The sweep is an exemption for one Studio-owned directory, not a way past the check: a socket anywhere else in the workdir is still fatal."""
+ from core.inference import os_sandbox
+
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ _bind_unix_socket(str(workdir / "planted"))
+
+ with pytest.raises(os_sandbox.WorkdirUnsafeError, match = "device or IPC node"):
+ os_sandbox.scan_workdir_for_host_channels(str(workdir))
+
+
+def test_a_scratch_entry_that_cannot_be_removed_still_fails_the_call(tmp_path):
+ """Fails closed: what the sweep could not unlink is still a finding."""
+ from core.inference import os_sandbox
+
+ if os.geteuid() == 0:
+ pytest.skip("root ignores the directory permissions this test relies on")
+
+ workdir = tmp_path / "work"
+ scratch = workdir / os_sandbox.TOOL_TEMP_DIRNAME
+ held = scratch / "held"
+ held.mkdir(parents = True)
+ os.chmod(scratch, 0o700)
+ _bind_unix_socket(str(held / "listener-0"))
+ os.chmod(held, 0o500)
+ try:
+ with pytest.raises(os_sandbox.WorkdirUnsafeError, match = "device or IPC node"):
+ os_sandbox.scan_workdir_for_host_channels(str(workdir))
+ finally:
+ os.chmod(held, 0o700)
+
+
+def test_concurrent_launches_share_one_workdir_scan(monkeypatch, tmp_path):
+ """A second launch used to see the first one's walk in flight and report the workdir unchecked, which required refuses."""
+ import threading
+ import time
+
+ from core.inference import os_sandbox
+
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ walks = []
+
+ def slow(
+ root,
+ max_entries,
+ seconds,
+ witness = None,
+ ):
+ walks.append(root)
+ time.sleep(0.5)
+ return None
+
+ monkeypatch.setattr(os_sandbox, "_host_channel_hazard", slow)
+ results = []
+ callers = [
+ threading.Thread(
+ target = lambda: results.append(os_sandbox.scan_workdir_for_host_channels(str(workdir)))
+ )
+ for _ in range(3)
+ ]
+ for caller in callers:
+ caller.start()
+ for caller in callers:
+ caller.join(20)
+
+ assert results == [(), (), ()], results
+ assert len(walks) == 1, "each launch walked the workdir again"
+
+
+def test_a_workdir_scan_that_blocks_is_given_up_on_rather_than_waited_out(monkeypatch, tmp_path):
+ """The budget is checked between entries, which is only a deadline while the walk is running."""
+ import threading
+ import time
+
+ from core.inference import os_sandbox
+
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ released = threading.Event()
+
+ def wedged(root, max_entries, seconds):
+ released.wait(8)
+ return None
+
+ monkeypatch.setattr(os_sandbox, "_host_channel_hazard", wedged)
+ monkeypatch.setattr(os_sandbox, "WORKDIR_SCAN_SECONDS", 0.3)
+
+ started = time.monotonic()
+ try:
+ limitations = os_sandbox.scan_workdir_for_host_channels(str(workdir))
+ waited = time.monotonic() - started
+ finally:
+ released.set()
+
+ assert limitations == (os_sandbox.WORKDIR_SCAN_INCOMPLETE,)
+ assert waited < 5, f"the caller waited {waited:.1f}s on a wedged scan"
+
+
+def test_a_windows_drive_root_is_not_a_model_library():
+ """`C:\\` is not os.sep, so the filesystem-root check missed it and a folder registered as the whole system drive was granted read access."""
+ import ntpath
+ import posixpath
+
+ from core.inference import os_sandbox
+
+ assert os_sandbox._is_filesystem_root("C:\\", ntpath)
+ assert os_sandbox._is_filesystem_root("\\\\server\\share\\", ntpath)
+ assert not os_sandbox._is_filesystem_root("C:\\Models", ntpath)
+ assert os_sandbox._is_filesystem_root("/", posixpath)
+ assert not os_sandbox._is_filesystem_root("/models", posixpath)
+
+
+def test_a_windows_system_directory_is_not_a_model_library(monkeypatch, tmp_path):
+ """The Windows system directories are not fixed paths, so they are read from the environment rather than spelled in a POSIX-only table."""
+ from core.inference import os_sandbox, tool_path_approval
+
+ windows = tmp_path / "Windows"
+ windows.mkdir()
+ monkeypatch.setenv("SystemRoot", str(windows))
+ monkeypatch.setattr(tool_path_approval, "_scan_folder_roots", lambda: (str(windows),))
+ monkeypatch.setattr(
+ "utils.paths.storage_roots.well_known_model_dirs",
+ lambda: (),
+ raising = False,
+ )
+
+ assert os_sandbox.model_library_roots() == ()
+
+
+def test_the_directory_holding_every_home_is_not_a_model_library(monkeypatch, tmp_path):
+ """/home and /Users were listed literally; the Windows equivalent is C:\\Users under whichever drive Windows was installed on."""
+ from core.inference import os_sandbox, tool_path_approval
+
+ homes = tmp_path / "homes"
+ (homes / "someone").mkdir(parents = True)
+ monkeypatch.setenv("HOME", str(homes / "someone"))
+ monkeypatch.setattr(tool_path_approval, "_scan_folder_roots", lambda: (str(homes),))
+ monkeypatch.setattr(
+ "utils.paths.storage_roots.well_known_model_dirs",
+ lambda: (),
+ raising = False,
+ )
+
+ assert os_sandbox.model_library_roots() == ()
+
+
+def test_a_live_listener_in_the_scratch_directory_is_not_removed(tmp_path):
+ """Two tool calls can share the scratch directory, so "left behind" has to be proved: a listener the other call is still using must survive."""
+ import socket
+
+ from core.inference import os_sandbox
+
+ workdir = tmp_path / "work"
+ scratch = workdir / os_sandbox.TOOL_TEMP_DIRNAME
+ scratch.mkdir(parents = True)
+ os.chmod(scratch, 0o700)
+
+ here = os.getcwd()
+ os.chdir(scratch)
+ listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ try:
+ listener.bind("listener-0")
+ listener.listen(1)
+ os.chdir(here)
+ assert os_sandbox.clear_stale_tool_ipc(str(workdir)) == ()
+ assert (scratch / "listener-0").exists(), "a live listener was unlinked"
+ finally:
+ os.chdir(here)
+ listener.close()
+
+
+def test_a_scratch_directory_studio_did_not_create_is_left_alone(tmp_path):
+ """_sandbox_temp_dir adopts an existing unsloth-tmp rather than failing, so a project that already had one must not have its own endpoints swept."""
+ from core.inference import os_sandbox
+
+ workdir = tmp_path / "work"
+ scratch = workdir / os_sandbox.TOOL_TEMP_DIRNAME
+ scratch.mkdir(parents = True)
+ os.chmod(scratch, 0o755)
+ _bind_unix_socket(str(scratch / "theirs"))
+
+ assert os_sandbox.clear_stale_tool_ipc(str(workdir)) == ()
+ assert (scratch / "theirs").exists(), "a directory Studio did not create was swept"
+
+
+def test_a_dormant_fifo_is_never_swept(tmp_path):
+ """A FIFO with no reader is at rest, not abandoned: it is meant to outlive the processes at its ends, and 0700 plus ownership is evidence of who made the directory rather than proof."""
+ from core.inference import os_sandbox
+
+ workdir = tmp_path / "work"
+ scratch = workdir / os_sandbox.TOOL_TEMP_DIRNAME
+ scratch.mkdir(parents = True)
+ os.chmod(scratch, 0o700)
+ os.mkfifo(scratch / "theirs", 0o600)
+
+ assert os_sandbox.clear_stale_tool_ipc(str(workdir)) == ()
+ assert (scratch / "theirs").exists(), "an idle named pipe was deleted"
+ with pytest.raises(os_sandbox.WorkdirUnsafeError, match = "device or IPC node"):
+ os_sandbox.scan_workdir_for_host_channels(str(workdir))
+
+
+def test_the_stale_ipc_sweep_runs_inside_the_scan_budget(monkeypatch, tmp_path):
+ """The sweep walks the same workdir, so it can block on the same wedged mount."""
+ import threading
+ import time
+
+ from core.inference import os_sandbox
+
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ released = threading.Event()
+
+ def wedged_sweep(_workdir, _deadline = None):
+ released.wait(8)
+ return ()
+
+ monkeypatch.setattr(os_sandbox, "clear_stale_tool_ipc", wedged_sweep)
+ monkeypatch.setattr(os_sandbox, "WORKDIR_SCAN_SECONDS", 0.3)
+
+ started = time.monotonic()
+ try:
+ limitations = os_sandbox.scan_workdir_for_host_channels(str(workdir))
+ waited = time.monotonic() - started
+ finally:
+ released.set()
+
+ assert limitations == (os_sandbox.WORKDIR_SCAN_INCOMPLETE,)
+ assert waited < 5, f"the caller waited {waited:.1f}s on a wedged sweep"
+
+
+def test_the_sweep_stops_at_its_deadline(tmp_path):
+ """Past the deadline it leaves the rest for the walk to refuse rather than spending the call's time on a directory it may never finish."""
+ import time
+
+ from core.inference import os_sandbox
+
+ workdir = tmp_path / "work"
+ scratch = workdir / os_sandbox.TOOL_TEMP_DIRNAME
+ scratch.mkdir(parents = True)
+ os.chmod(scratch, 0o700)
+ _bind_unix_socket(str(scratch / "listener-0"))
+
+ assert os_sandbox.clear_stale_tool_ipc(str(workdir), time.monotonic() - 1) == ()
+ assert (scratch / "listener-0").exists()
+ assert os_sandbox.clear_stale_tool_ipc(str(workdir)) == (str(scratch / "listener-0"),)
+
+
+def test_a_channel_planted_deep_inside_a_cached_component_invalidates_its_verdict(
+ monkeypatch, tmp_path
+):
+ """The memo made the walk cheap and made invalidation wrong: a socket created inside an existing nested directory leaves the component root's mtime alone, so a clean verdict could be reused over exactly the channel the scan exists to reject."""
+ from core.inference import sandbox_linux
+
+ cache = tmp_path / "hostcache"
+ nested = cache / "hub" / "models--org--name" / "snapshots" / "abc"
+ nested.mkdir(parents = True)
+ (nested / "config.json").write_text("{}")
+ _share_cache_paths(monkeypatch, cache)
+ sandbox_linux.reset_cache_verdicts()
+
+ session = str(tmp_path / "session")
+ assert "hub" in sandbox_linux._model_cache_binds(session), "the clean cache was not shared"
+
+ _bind_unix_socket(str(nested / "planted"))
+ binds = sandbox_linux._model_cache_binds(session)
+
+ assert "hub" not in binds, "a cached verdict was reused over a newly planted socket"
+
+
+def test_an_unchanged_cache_is_not_walked_again(monkeypatch, tmp_path):
+ """The other half: revalidation has to stay cheaper than the walk it replaces, or the memo is pointless."""
+ from core.inference import sandbox_linux
+
+ cache = tmp_path / "hostcache"
+ (cache / "hub" / "models--org--name").mkdir(parents = True)
+ (cache / "hub" / "models--org--name" / "config.json").write_text("{}")
+ _share_cache_paths(monkeypatch, cache)
+ sandbox_linux.reset_cache_verdicts()
+
+ session = str(tmp_path / "session")
+ assert "hub" in sandbox_linux._model_cache_binds(session)
+
+ walks: list[str] = []
+ real = sandbox_linux._inspect_cache_component
+
+ def counted(
+ name,
+ path,
+ witness = None,
+ ):
+ walks.append(path)
+ return real(name, path, witness)
+
+ monkeypatch.setattr(sandbox_linux, "_inspect_cache_component", counted)
+ assert "hub" in sandbox_linux._model_cache_binds(session)
+ assert walks == [], f"the unchanged cache was walked again: {walks}"
+
+
+def test_a_bwrap_planted_on_path_is_refused_before_it_runs(monkeypatch, tmp_path):
+ """bwrap runs on the host before any isolation exists, so a user-writable one must never be executed."""
+ planted = tmp_path / "bin"
+ planted.mkdir()
+ marker = tmp_path / "ran"
+ fake = planted / "bwrap"
+ fake.write_text(f"#!/bin/sh\ntouch {marker}\n", encoding = "utf-8")
+ fake.chmod(0o755)
+ monkeypatch.setenv("PATH", f"{planted}{os.pathsep}{os.environ.get('PATH', '')}")
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ plan = os_sandbox.ToolLaunchPlan(
+ argv = (sys.executable, "-c", "pass"),
+ workdir = str(workdir),
+ env = {"PATH": os.environ["PATH"]},
+ execution_kind = "python",
+ timeout_seconds = 5,
+ )
+
+ with pytest.raises(os_sandbox.SandboxUnavailableError, match = "trusted system installation"):
+ sandbox_linux.prepare(plan)
+ assert not marker.exists(), "the planted bwrap was executed"
+
+
+def test_studio_state_inside_a_runtime_path_is_carved_out(monkeypatch, tmp_path):
+ """A runtime root bound whole would hand over a Studio home that lives inside it, auth.db included."""
+ lib = tmp_path / "venv" / "lib"
+ state = lib / "studio-state"
+ (state / "auth").mkdir(parents = True)
+ (lib / "python3.12").mkdir()
+ managed = tmp_path / "home" / "studio" / "venv"
+ managed.mkdir(parents = True)
+ monkeypatch.setattr(
+ sandbox_linux, "studio_state_roots", lambda: (str(state), str(tmp_path / "home" / "studio"))
+ )
+
+ kept = sandbox_linux._without_state_inside((str(lib), str(managed)))
+
+ assert str(lib) not in kept
+ assert str(state) not in kept
+ assert str(lib / "python3.12") in kept
+ assert str(managed) in kept, "the managed venv inside the Studio home must stay readable"
diff --git a/studio/backend/tests/test_sandbox_macos.py b/studio/backend/tests/test_sandbox_macos.py
new file mode 100644
index 00000000000..abf202a542e
--- /dev/null
+++ b/studio/backend/tests/test_sandbox_macos.py
@@ -0,0 +1,929 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for the macOS Seatbelt profile generator, asserting on the profile TEXT."""
+
+from __future__ import annotations
+
+import os
+import re
+import shlex
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+if sys.platform == "win32":
+ pytest.skip("the Seatbelt profile generator is POSIX only", allow_module_level = True)
+
+from core.inference import sandbox_macos as backend
+from core.inference.os_sandbox import (
+ SandboxUnavailableError,
+ ToolLaunchPlan,
+ WorkdirUnsafeError,
+)
+
+_WORKDIR = "/tmp/unsloth-session-abc123"
+_PRIVATE_TMP = "/tmp/us-seatbelt-xyz789"
+_READ_PREFIX = '(allow file-read* file-test-existence (literal "/") '
+_OPTIONAL_PREFIX = '(allow file-read* file-test-existence (literal "/etc/gitconfig")'
+_WRITE_PREFIX = "(allow file-write* (literal "
+
+
+def profile(monkeypatch) -> str:
+ real_exists, real_isdir = os.path.exists, os.path.isdir
+ named = {_WORKDIR, _PRIVATE_TMP}
+ monkeypatch.setattr(os.path, "exists", lambda path: path in named or real_exists(path))
+ monkeypatch.setattr(os.path, "isdir", lambda path: path in named or real_isdir(path))
+ return backend.build_profile(workdir = _WORKDIR, private_tmp = _PRIVATE_TMP, runtime_paths = ())
+
+
+def launchable(monkeypatch):
+ """Only the availability gate is stubbed; everything else runs for real."""
+ monkeypatch.setattr(backend, "available", lambda: (True, "stubbed for this test"))
+
+
+def _rule(profile: str, prefix: str) -> str:
+ matches = [line for line in profile.splitlines() if line.startswith(prefix)]
+ assert len(matches) == 1, f"expected exactly one rule starting {prefix!r}, got {len(matches)}"
+ return matches[0]
+
+
+def _subpaths(rule: str) -> set[str]:
+ return set(re.findall(r'\(subpath "([^"]+)"\)', rule))
+
+
+def _literals(rule: str) -> set[str]:
+ return set(re.findall(r'\(literal "([^"]+)"\)', rule))
+
+
+def test_module_imports_and_exports_the_backend_contract():
+ assert backend.BACKEND_NAME == "macos-seatbelt"
+ assert isinstance(backend.PROFILE_ID, str) and backend.PROFILE_ID
+ assert isinstance(backend.LIMITATIONS, tuple)
+ assert all(isinstance(item, str) for item in backend.LIMITATIONS)
+ assert "unrestricted_network" in backend.LIMITATIONS
+ assert callable(backend.prepare)
+
+
+def test_profile_is_deny_default(profile):
+ lines = profile.splitlines()
+ assert lines[0] == "(version 1)"
+ assert lines[1] == "(deny default)"
+ assert "(allow default)" not in profile
+
+
+def test_every_rule_is_a_balanced_s_expression(profile):
+ depth = 0
+ in_string = False
+ for index, char in enumerate(profile):
+ if in_string:
+ if char == "\\":
+ continue
+ if char == '"':
+ in_string = False
+ continue
+ if char == '"':
+ in_string = True
+ elif char == "(":
+ depth += 1
+ elif char == ")":
+ depth -= 1
+ assert depth >= 0, f"unbalanced ) at offset {index}"
+ assert depth == 0, f"{depth} unclosed ( in the profile"
+ assert not in_string, "the profile ends inside a quoted string"
+ for line in profile.splitlines():
+ assert line == "" or line.startswith("(") or line.startswith(" ("), line
+
+
+def test_login_keychain_mach_service_is_absent(profile):
+ """com.apple.SecurityServer would make the login Keychain readable through Security.framework."""
+ assert "com.apple.SecurityServer" not in profile
+ assert "com.apple.SecurityServer" not in backend._MACH_SERVICES
+ assert 'com.apple.trustd"' in profile
+ assert 'com.apple.ocspd"' in profile
+ assert '(literal "/usr/bin/security")' in _rule(profile, "(deny process-exec ")
+
+
+def test_denied_executables_are_denied_after_the_exec_allowance(profile):
+ """Seatbelt is last-match-wins, so the deny has to come after the allow."""
+ lines = profile.splitlines()
+ deny_index = next(
+ index for index, line in enumerate(lines) if line.startswith("(deny process-exec ")
+ )
+ assert lines.index("(allow process-exec)") < deny_index
+ denied = _literals(_rule(profile, "(deny process-exec "))
+ for path in backend._DENIED_EXECUTABLES:
+ assert path in denied, f"{path} is no longer exec-denied"
+
+
+def test_both_private_spellings_are_emitted_for_the_workdir(profile):
+ for rule in (_rule(profile, _READ_PREFIX), _rule(profile, _WRITE_PREFIX)):
+ for path in (_WORKDIR, f"/private{_WORKDIR}"):
+ assert f'(literal "{path}")' in rule
+ assert f'(subpath "{path}")' in rule
+
+
+def test_a_non_ascii_workdir_reaches_the_profile_unescaped(monkeypatch):
+ workdir = "/tmp/unsloth-session-caf\u00e9"
+ private_tmp = "/tmp/us-seatbelt-\u00fcber"
+ real_exists, real_isdir = os.path.exists, os.path.isdir
+ named = {workdir, private_tmp}
+ monkeypatch.setattr(os.path, "exists", lambda path: path in named or real_exists(path))
+ monkeypatch.setattr(os.path, "isdir", lambda path: path in named or real_isdir(path))
+ text = backend.build_profile(workdir = workdir, private_tmp = private_tmp, runtime_paths = ())
+ assert "\\u00" not in text
+ for path in (workdir, private_tmp):
+ assert f'(subpath "{path}")' in _rule(text, _WRITE_PREFIX)
+
+
+def test_optional_literals_are_allowed_even_though_they_do_not_exist(profile):
+ literals = _literals(_rule(profile, _OPTIONAL_PREFIX))
+ for path in backend._OPTIONAL_READ_LITERALS:
+ assert path in literals, f"{path} lost its unconditional read allowance"
+ assert {"/private/etc/gitconfig", "/private/etc/gitattributes"} <= literals
+ absent = [path for path in backend._OPTIONAL_READ_LITERALS if not os.path.exists(path)]
+ assert absent, "no optional literal is absent here, so this test proved nothing"
+
+
+def test_optional_read_literals_never_follow_a_symlink(tmp_path):
+ """Read literals must not resolve: an /etc/gitconfig symlinked at ~/dotfiles would put a home path in the read set."""
+ target = tmp_path / "secret"
+ target.write_text("")
+ link = tmp_path / "link"
+ link.symlink_to(target)
+ unresolved = backend._literal_filters((str(link),), resolve = False)
+ assert f'(literal "{link}")' in unresolved
+ assert not any(str(target) in filter_ for filter_ in unresolved), unresolved
+ assert f'(literal "{target}")' in backend._literal_filters((str(link),))
+
+
+def test_ancestor_metadata_rules_are_emitted(profile):
+ metadata_rule = _rule(profile, "(allow file-read-metadata ")
+ metadata = _literals(metadata_rule)
+ assert "/" in metadata
+ for ancestor in (
+ "/tmp",
+ "/private/tmp",
+ "/private",
+ "/etc",
+ "/private/etc",
+ "/usr/local/etc",
+ "/var/run",
+ "/private/var/run",
+ ):
+ assert ancestor in metadata, f"{ancestor} has no file-read-metadata rule"
+ assert not _subpaths(metadata_rule)
+
+
+def test_workdir_and_private_tmp_are_the_only_writable_subpaths(profile):
+ writable = _subpaths(_rule(profile, _WRITE_PREFIX))
+ assert writable == {_WORKDIR, f"/private{_WORKDIR}", _PRIVATE_TMP, f"/private{_PRIVATE_TMP}"}
+ for forbidden in ("/", "/usr", "/tmp", "/private/tmp", str(Path.home())):
+ assert forbidden not in writable
+ assert not _subpaths(_rule(profile, "(allow file-read* file-test-existence file-write-data "))
+
+
+def test_no_read_root_reaches_the_users_home(profile):
+ """Asserted against the tables, not the profile text: the read roots are existence-filtered and mostly vanish on a non-macOS host."""
+ home = str(Path.home())
+ assert f'(subpath "{home}")' not in profile
+ assert "/Users/" not in profile
+ tables = (
+ backend._READ_ROOTS
+ + backend._TLS_TRUST_PATHS
+ + backend._OPTIONAL_READ_ROOTS
+ + backend._OPTIONAL_READ_LITERALS
+ )
+ for path in tables:
+ assert not path.startswith("/Users/"), path
+ assert "~" not in path, path
+ assert "/System/Library/Keychains" in backend._TLS_TRUST_PATHS
+ assert not any("Library/Keychains" in path and path.startswith(home) for path in tables)
+
+
+def test_ip_egress_is_unrestricted_but_unix_sockets_are_not(profile):
+ lines = profile.splitlines()
+ for rule in ("(allow system-socket)", "(allow network-inbound)"):
+ assert rule in lines
+ assert "(allow network-outbound)" not in lines
+ assert "(allow network-bind)" not in lines
+ assert '(allow network-outbound (remote ip "*:*"))' in lines
+ assert '(allow network-bind (local ip "*:*"))' in lines
+ assert "localhost" not in profile
+ assert "proxy" not in profile.lower()
+ for root in (_PRIVATE_TMP, _WORKDIR):
+ for path in (root, f"/private{root}"):
+ assert f'(allow network-outbound (remote unix-socket (subpath "{path}")))' in lines
+ assert f'(allow network-bind (local unix-socket (subpath "{path}")))' in lines
+ assert '(allow network-outbound (literal "/private/var/run/mDNSResponder")' in profile
+ assert "(allow network-outbound (remote unix-socket (literal " in profile
+ for path in ("/var/run/mDNSResponder", "/private/var/run/mDNSResponder"):
+ assert f'(allow network-outbound (remote unix-socket (literal "{path}")))' in lines
+ assert '(literal "/var/run/mDNSResponder")' in profile
+ assert "docker.sock" not in profile
+
+
+def test_process_substitution_descriptors_are_readable(profile):
+ """bash process substitution hands the child /dev/fd/63, so narrowing the rule to 0, 1 and 2 fails a command that works everywhere else."""
+ assert '(allow file-read* (regex #"^/dev/fd/[0-9]+$"))' in profile
+ assert '(allow file-write* (regex #"^/dev/fd/[0-9]+$"))' in profile
+
+
+def test_pip_gets_a_writable_target_inside_the_workdir():
+ env = backend._sandbox_environment(
+ {"PATH": "/usr/bin", "PYTHONPATH": "/shim"}, _WORKDIR, _PRIVATE_TMP
+ )
+ packages = f"{_WORKDIR}/{backend.SESSION_PACKAGES_RELPATH}"
+ assert env["PIP_TARGET"] == packages
+ assert env["PYTHONPATH"].split(os.pathsep) == ["/shim", packages]
+
+
+def test_openmp_can_write_its_registration_segment(profile):
+ kmp = next(
+ block for block in profile.split("(allow ipc-posix-shm") if "__KMP_REGISTERED_LIB_" in block
+ )
+ assert "ipc-posix-shm-write-data" in kmp, kmp
+
+
+def test_sysctl_and_shm_rules_survive(profile):
+ sysctl = _rule(profile, "(allow sysctl-read ")
+ for name in ("hw.ncpu", "hw.memsize", "kern.osproductversion"):
+ assert f'(sysctl-name "{name}")' in sysctl
+ assert "(allow ipc-posix-sem)" in profile
+ assert "^/torch_[0-9]+_[0-9]+_[0-9]+$" in profile
+
+
+def test_runtime_read_paths_cover_the_interpreter_and_the_site_shim():
+ paths = backend.runtime_read_paths()
+ shim = os.path.normpath(os.path.join(os.path.dirname(backend.__file__), "sandbox_site"))
+ assert shim in paths
+ assert "/" not in paths and "/usr" not in paths
+ for prefix in (sys.prefix, sys.exec_prefix, sys.base_prefix, sys.base_exec_prefix):
+ for name in ("bin", "lib"):
+ member = os.path.join(prefix, name)
+ if not os.path.isdir(member):
+ continue
+ assert any(backend._within(member, root) for root in paths), member
+ dynload = os.path.join(
+ sys.base_exec_prefix,
+ "lib",
+ f"python{sys.version_info.major}." f"{sys.version_info.minor}",
+ "lib-dynload",
+ )
+ if os.path.isdir(dynload):
+ assert any(backend._within(dynload, root) for root in paths), dynload
+
+
+def test_a_venv_at_a_project_root_does_not_put_the_project_in_the_read_set(monkeypatch, tmp_path):
+ project = tmp_path / "project"
+ (project / "bin").mkdir(parents = True)
+ (project / "lib").mkdir()
+ (project / ".git").mkdir()
+ (project / ".env").write_text("OPENAI_API_KEY=sk-real")
+ (project / "pyvenv.cfg").write_text("home = /usr/bin\n")
+ for name in ("prefix", "base_prefix", "exec_prefix", "base_exec_prefix"):
+ monkeypatch.setattr(sys, name, str(project))
+
+ paths = backend.runtime_read_paths()
+ assert str(project) not in paths
+ assert not any(backend._within(str(project / ".env"), root) for root in paths)
+ assert not any(backend._within(str(project / ".git"), root) for root in paths)
+ assert str(project / "bin") in paths
+ assert str(project / "lib") in paths
+
+
+def test_prepare_wraps_argv_and_preserves_the_preexec(tmp_path, launchable):
+ """The preexec is tools.py's os.setsid(); losing it strands the process group."""
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+
+ def preexec() -> None:
+ return None
+
+ plan = ToolLaunchPlan(
+ argv = ("/bin/echo", "hello"),
+ workdir = str(workdir),
+ env = {"PATH": "/usr/bin", "DYLD_INSERT_LIBRARIES": "/evil.dylib", "KEEP": "1"},
+ preexec_fn = preexec,
+ timeout_seconds = 30,
+ )
+ prepared = backend.prepare(plan)
+ private_tmp = prepared.cleanup_paths[0]
+ try:
+ assert prepared.argv[0] == backend.SANDBOX_EXEC
+ assert prepared.argv[1] == "-p"
+ assert prepared.argv[2].startswith("(version 1)\n(deny default)")
+ assert prepared.argv[3] == "--"
+ assert prepared.argv[4:] == ("/bin/echo", "hello")
+ assert prepared.preexec_fn is preexec
+ assert prepared.backend == backend.BACKEND_NAME
+ assert prepared.timeout_seconds == 30
+ assert prepared.env["HOME"] == str(workdir)
+ assert prepared.env["KEEP"] == "1"
+ assert "DYLD_INSERT_LIBRARIES" not in prepared.env
+ assert len(prepared.cleanup_paths) == 1
+ assert prepared.env["TMPDIR"] == private_tmp
+ assert os.path.isdir(private_tmp)
+ writable = _subpaths(_rule(prepared.argv[2], _WRITE_PREFIX))
+ assert str(workdir) in writable and private_tmp in writable
+ finally:
+ prepared.cleanup()
+ assert not os.path.exists(private_tmp)
+
+
+def test_prepare_refuses_a_workdir_that_does_not_exist(tmp_path, launchable):
+ plan = ToolLaunchPlan(argv = ("/bin/echo",), workdir = str(tmp_path / "missing"), env = {})
+ with pytest.raises(SandboxUnavailableError, match = "does not exist"):
+ backend.prepare(plan)
+
+
+def test_prepare_refuses_the_filesystem_root_as_a_workdir(launchable):
+ plan = ToolLaunchPlan(argv = ("/bin/echo",), workdir = "/", env = {})
+ with pytest.raises(SandboxUnavailableError, match = "filesystem root"):
+ backend.prepare(plan)
+
+
+def test_prepare_refuses_when_the_launcher_is_missing(tmp_path):
+ """No stub here: argv[0] must never become a sandbox-exec that is not there."""
+ if os.path.exists(backend.SANDBOX_EXEC):
+ pytest.skip("this host has a real /usr/bin/sandbox-exec, so the gate cannot be observed")
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ plan = ToolLaunchPlan(argv = ("/bin/echo",), workdir = str(workdir), env = {})
+ with pytest.raises(SandboxUnavailableError, match = "Seatbelt launcher"):
+ backend.prepare(plan)
+
+
+def test_a_rule_that_lost_every_filter_raises_instead_of_granting_everything():
+ with pytest.raises(SandboxUnavailableError, match = "unconditionally"):
+ backend._rule("allow file-write*", [])
+ with pytest.raises(SandboxUnavailableError, match = "unconditionally"):
+ backend._rule("deny process-exec", [])
+ rendered = backend._rule("allow file-write*", ['(literal "/x")'])
+ assert rendered == '(allow file-write* (literal "/x"))'
+ with pytest.raises(SandboxUnavailableError, match = "unconditionally"):
+ backend.build_profile(
+ workdir = "/tmp/does-not-exist-workdir",
+ private_tmp = "/tmp/does-not-exist-tmp",
+ runtime_paths = (),
+ )
+
+
+def test_paths_must_be_absolute_and_free_of_newlines():
+ with pytest.raises(SandboxUnavailableError):
+ backend._validated("relative/path")
+ with pytest.raises(SandboxUnavailableError):
+ backend._validated("/tmp/with\nnewline")
+ with pytest.raises(SandboxUnavailableError):
+ backend._validated("/tmp/with\0nul")
+
+
+def test_available_never_raises_on_a_host_without_the_launcher():
+ ok, reason = backend.available()
+ assert isinstance(ok, bool) and isinstance(reason, str) and reason
+ if not os.path.exists(backend.SANDBOX_EXEC):
+ assert ok is False
+ assert backend.SANDBOX_EXEC in reason
+
+
+_darwin_only = pytest.mark.skipif(
+ sys.platform != "darwin" or not os.path.exists(backend.SANDBOX_EXEC),
+ reason = "needs a real macOS host: only a Darwin kernel can compile or enforce an SBPL profile",
+)
+
+
+@_darwin_only
+def test_profile_compiles_under_sandbox_exec(tmp_path):
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ plan = ToolLaunchPlan(argv = ("/usr/bin/true",), workdir = str(workdir), env = {})
+ prepared = backend.prepare(plan)
+ try:
+ result = subprocess.run(
+ prepared.argv, capture_output = True, text = True, timeout = 60, check = False
+ )
+ assert result.returncode == 0, result.stderr
+ finally:
+ prepared.cleanup()
+
+
+@_darwin_only
+def test_home_is_unreadable_inside_the_sandbox(tmp_path):
+ """The file is created and proven readable on the host first: a read that fails for an unrelated reason proves nothing."""
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ canary = Path(os.path.expanduser("~")) / ".unsloth-seatbelt-canary"
+ canary.write_text("UNSLOTH_CANARY_HOME_READABLE", encoding = "utf-8")
+ try:
+ argv = ("/bin/sh", "-c", f"cat {shlex.quote(str(canary))}")
+ host = subprocess.run(argv, capture_output = True, text = True, timeout = 60, check = False)
+ assert host.returncode == 0 and "UNSLOTH_CANARY_HOME_READABLE" in host.stdout, (
+ "the canary is not readable even outside the sandbox, so the negative "
+ f"control below would prove nothing: {host.stderr}"
+ )
+
+ prepared = backend.prepare(
+ ToolLaunchPlan(argv = argv, workdir = str(workdir), env = {"PATH": "/usr/bin:/bin"})
+ )
+ try:
+ result = subprocess.run(
+ prepared.argv, capture_output = True, text = True, timeout = 60, check = False
+ )
+ assert result.returncode != 0
+ assert "UNSLOTH_CANARY_HOME_READABLE" not in result.stdout
+ finally:
+ prepared.cleanup()
+ finally:
+ canary.unlink(missing_ok = True)
+
+
+def test_a_runtime_path_symlinked_out_of_the_workdir_is_not_readable(monkeypatch, tmp_path):
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ secret = tmp_path / "secrets"
+ secret.mkdir()
+ (secret / "id_rsa").write_text("PRIVATE KEY")
+ venv = workdir / "venv"
+ (venv / "bin").mkdir(parents = True)
+ (venv / "lib").symlink_to(secret)
+ for name in ("prefix", "base_prefix", "exec_prefix", "base_exec_prefix"):
+ monkeypatch.setattr(sys, name, str(venv))
+
+ paths = backend.runtime_read_paths(str(workdir))
+ assert str(secret) not in paths
+ assert not any(backend._within(str(secret), path) for path in paths)
+ assert str(secret) in backend.runtime_read_paths()
+
+
+def test_pip_console_scripts_are_reachable_and_never_shadow_a_system_command():
+ env = backend._sandbox_environment(
+ {"PATH": "/usr/bin:/bin", "PYTHONPATH": "/shim"}, _WORKDIR, _PRIVATE_TMP
+ )
+ packages = f"{_WORKDIR}/{backend.SESSION_PACKAGES_RELPATH}"
+ assert env["PATH"].split(os.pathsep) == ["/usr/bin", "/bin", f"{packages}/bin"]
+
+
+def test_the_semaphore_namespace_is_named_rather_than_narrowed(profile):
+ assert "(allow ipc-posix-sem)" in profile
+ assert "posix_semaphore_namespace_shared" in backend.LIMITATIONS
+
+
+def test_host_process_metadata_is_named_rather_than_withheld(profile):
+ sysctl = _rule(profile, "(allow sysctl-read ")
+ assert '(sysctl-name-prefix "kern.proc.pid.")' in sysctl
+ assert "host_process_metadata_readable" in backend.LIMITATIONS
+ assert "(allow process-info* (target same-sandbox))" in profile
+
+
+def test_a_framework_build_gets_its_dyld_image(monkeypatch, tmp_path):
+ prefix = tmp_path / "Python.framework" / "Versions" / "3.13"
+ (prefix / "bin").mkdir(parents = True)
+ (prefix / "lib").mkdir()
+ (prefix / "Python").write_bytes(b"\xcf\xfa\xed\xfe")
+ for name in ("prefix", "base_prefix", "exec_prefix", "base_exec_prefix"):
+ monkeypatch.setattr(sys, name, str(prefix))
+ paths = backend.runtime_read_paths()
+ assert str(prefix / "Python") in paths
+ assert str(prefix) not in paths
+
+
+def test_a_runtime_under_the_workdir_is_denied_write_after_the_allowance(tmp_path, monkeypatch):
+ workdir = tmp_path / "session"
+ venv = workdir / "venv"
+ (venv / "lib").mkdir(parents = True)
+ (venv / "bin").mkdir()
+ monkeypatch.setattr(sys, "prefix", str(venv))
+ monkeypatch.setattr(sys, "exec_prefix", str(venv))
+
+ profile = backend.build_profile(workdir = str(workdir), private_tmp = "/tmp/pt", runtime_paths = ())
+ lines = profile.splitlines()
+ allow = next(i for i, line in enumerate(lines) if line.startswith("(allow file-write* "))
+ deny = next(i for i, line in enumerate(lines) if line.startswith("(deny file-write* "))
+ assert deny > allow, "a deny before the allowance is overridden by it"
+ denied = _subpaths(lines[deny]) | _literals(lines[deny])
+ assert str(venv / "lib") in denied
+ assert str(venv / "bin") in denied
+
+
+def test_no_write_denial_is_emitted_when_the_runtime_is_outside_the_workdir(tmp_path, monkeypatch):
+ """The negative control: the rule above must not fire for an ordinary layout, where denying anything under the workdir would take away the one writable place."""
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ monkeypatch.setattr(sys, "prefix", "/usr")
+ monkeypatch.setattr(sys, "exec_prefix", "/usr")
+ profile = backend.build_profile(workdir = str(workdir), private_tmp = "/tmp/pt", runtime_paths = ())
+ assert not any(line.startswith("(deny file-write* ") for line in profile.splitlines())
+
+
+def test_the_openssl_directory_is_granted_by_component_not_whole(profile):
+ for spelling in ("/etc/ssl", "/private/etc/ssl"):
+ for line in profile.splitlines():
+ if line.startswith("(allow file-read-metadata"):
+ continue
+ assert f'(subpath "{spelling}")' not in line, line
+ assert f'(literal "{spelling}")' not in line, line
+ assert "/private/etc/ssl" not in backend._TLS_TRUST_PATHS
+ for component in ("cert.pem", "certs", "openssl.cnf"):
+ assert f"/private/etc/ssl/{component}" in backend._TLS_TRUST_PATHS
+
+
+ os.geteuid() == 0,
+ reason = "root reads and writes regardless of the mode bits, so the premise is void",
+)
+def test_a_toolchain_directory_the_user_can_write_is_not_trusted(tmp_path):
+ mine = tmp_path / "FakeXcode.app" / "Contents" / "Developer"
+ mine.mkdir(parents = True)
+ assert backend._trusted_system_dir(str(mine)) is False
+ assert backend._trusted_system_dir(str(tmp_path / "absent")) is False
+ missing_file = tmp_path / "Developer"
+ missing_file.write_text("", encoding = "utf-8")
+ assert backend._trusted_system_dir(str(missing_file)) is False
+ assert backend._trusted_system_dir("/usr") is True
+
+
+ os.geteuid() == 0,
+ reason = "root reads and writes regardless of the mode bits, so the premise is void",
+)
+def test_the_developer_dir_variable_never_reaches_xcode_select(monkeypatch, tmp_path):
+ mine = tmp_path / "Developer"
+ mine.mkdir()
+ monkeypatch.setenv("DEVELOPER_DIR", str(mine))
+ monkeypatch.setattr(backend.sys, "platform", "darwin")
+ monkeypatch.setattr(backend.os.path, "exists", lambda path: True)
+ seen: dict = {}
+
+ def fake_run(argv, **kwargs):
+ seen.update(kwargs)
+ return subprocess.CompletedProcess(argv, 0, stdout = str(mine), stderr = "")
+
+ monkeypatch.setattr(backend.subprocess, "run", fake_run)
+ monkeypatch.setattr(backend, "_developer_paths_cache", None)
+ try:
+ assert backend._developer_paths() == ()
+ finally:
+ backend._developer_paths_cache = None
+ assert "DEVELOPER_DIR" not in seen["env"]
+
+
+def _profile_for(workdir, monkeypatch, prefix):
+ monkeypatch.setattr(sys, "prefix", str(prefix))
+ monkeypatch.setattr(sys, "exec_prefix", str(prefix))
+ return backend.build_profile(workdir = str(workdir), private_tmp = _PRIVATE_TMP, runtime_paths = ())
+
+
+def test_a_runtime_under_a_symlinked_workdir_is_denied_through_both_spellings(
+ tmp_path, monkeypatch
+):
+ real = tmp_path / "real"
+ venv = real / "venv"
+ (venv / "lib").mkdir(parents = True)
+ (venv / "bin").mkdir()
+ alias = tmp_path / "alias"
+ alias.symlink_to(real)
+
+ profile = _profile_for(alias, monkeypatch, venv)
+ under = backend.runtime_paths_under(str(alias))
+ for spelling in (real / "venv" / "lib", alias / "venv" / "lib"):
+ assert str(spelling) in under, under
+ deny = _rule(profile, "(deny file-write* ")
+ for spelling in (real / "venv" / "lib", alias / "venv" / "lib"):
+ assert f'(subpath "{spelling}")' in deny, deny
+ lines = profile.splitlines()
+ assert lines.index(_rule(profile, _WRITE_PREFIX)) < lines.index(deny)
+
+
+def test_the_framework_python_image_is_denied_when_the_prefix_is_under_the_workdir(
+ tmp_path, monkeypatch
+):
+ workdir = tmp_path / "session"
+ prefix = workdir / "Python.framework" / "Versions" / "3.12"
+ (prefix / "lib").mkdir(parents = True)
+ image = prefix / "Python"
+ image.write_bytes(b"\xcf\xfa\xed\xfe")
+
+ deny = _rule(_profile_for(workdir, monkeypatch, prefix), "(deny file-write* ")
+ assert str(image) in backend.runtime_paths_under(str(workdir))
+ assert f'(literal "{image}")' in deny, deny
+
+
+def test_an_optional_search_root_that_resolves_out_of_its_prefix_is_dropped(monkeypatch):
+ home = os.path.expanduser("~")
+ real = os.path.realpath
+
+ def resolves_home(path):
+ return home if path == "/usr/local/bin" else real(path)
+
+ monkeypatch.setattr(os.path, "realpath", resolves_home)
+ kept = backend._contained_optional_roots()
+ assert "/usr/local/bin" not in kept
+ assert "/opt/homebrew/bin" in kept and "/usr/local/lib" in kept
+ named = {"/usr/local/bin", _WORKDIR, _PRIVATE_TMP}
+ real_isdir, real_exists = os.path.isdir, os.path.exists
+ monkeypatch.setattr(os.path, "isdir", lambda path: path in named or real_isdir(path))
+ monkeypatch.setattr(os.path, "exists", lambda path: path in named or real_exists(path))
+ profile = backend.build_profile(workdir = _WORKDIR, private_tmp = _PRIVATE_TMP, runtime_paths = ())
+ assert f'(subpath "{home}")' not in profile
+
+
+def test_an_editable_checkout_is_listable_but_not_readable(tmp_path, monkeypatch):
+ checkout = tmp_path / "checkout"
+ package = checkout / "demo"
+ package.mkdir(parents = True)
+ (package / "__init__.py").write_text("", encoding = "utf-8")
+ (checkout / ".env").write_text("AWS_SECRET_ACCESS_KEY=real\n", encoding = "utf-8")
+ monkeypatch.setattr(backend, "editable_source_roots", lambda: (str(package),))
+ monkeypatch.setattr(backend, "editable_import_roots", lambda: (str(checkout),))
+
+ named = {_WORKDIR, _PRIVATE_TMP}
+ real_isdir, real_exists = os.path.isdir, os.path.exists
+ monkeypatch.setattr(os.path, "isdir", lambda path: path in named or real_isdir(path))
+ monkeypatch.setattr(os.path, "exists", lambda path: path in named or real_exists(path))
+ profile = backend.build_profile(
+ workdir = _WORKDIR,
+ private_tmp = _PRIVATE_TMP,
+ runtime_paths = (str(package),),
+ )
+ assert f'(literal "{checkout}")' in profile
+ assert f'(subpath "{checkout}")' not in profile
+ assert f'(subpath "{package}")' in profile
+
+
+def test_a_standalone_interpreter_in_the_workdir_is_denied_writes(tmp_path, monkeypatch):
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ executable = workdir / "python"
+ executable.write_bytes(b"#!/bin/sh\nexit 0\n")
+ executable.chmod(0o755)
+ for attribute in ("prefix", "base_prefix", "exec_prefix", "base_exec_prefix"):
+ monkeypatch.setattr(sys, attribute, str(workdir))
+ monkeypatch.setattr(sys, "executable", str(executable))
+
+ paths = backend.runtime_paths_under(str(workdir))
+ assert str(executable) in paths
+ assert all(os.path.samefile(path, executable) for path in paths)
+ profile = backend.build_profile(
+ workdir = str(workdir), private_tmp = str(tmp_path / "tmp"), runtime_paths = ()
+ )
+ deny = _rule(profile, "(deny file-write* ")
+ assert f'(literal "{executable}")' in deny, deny
+
+
+def test_a_workdir_this_backend_cannot_name_fails_the_call_rather_than_de_isolating_it(
+ tmp_path, launchable
+):
+ with pytest.raises(WorkdirUnsafeError):
+ backend.prepare(
+ ToolLaunchPlan(argv = ("/usr/bin/true",), workdir = "/tmp/session-\udcff", env = {})
+ )
+
+
+def test_an_interpreter_in_a_home_directory_does_not_grant_the_home(tmp_path, monkeypatch):
+ home = tmp_path / "alice"
+ (home / ".ssh").mkdir(parents = True)
+ executable = home / "python"
+ executable.write_bytes(b"#!/bin/sh\nexit 0\n")
+ executable.chmod(0o755)
+ monkeypatch.setattr(sys, "executable", str(executable))
+ paths = backend.runtime_read_paths(str(tmp_path / "session"))
+ assert str(home) not in paths, paths
+ assert str(executable) in paths, paths
+
+
+def test_a_runtime_origin_is_excluded_under_either_workdir_spelling(tmp_path, monkeypatch):
+ real = tmp_path / "real"
+ real.mkdir()
+ alias = tmp_path / "alias"
+ alias.symlink_to(real)
+ secret = tmp_path / "secret"
+ secret.mkdir()
+ (secret / "id_rsa").write_text("SECRET", encoding = "utf-8")
+ venv = real / "venv"
+ (venv / "bin").mkdir(parents = True)
+ (venv / "lib").symlink_to(secret)
+ for attribute in ("prefix", "base_prefix", "exec_prefix", "base_exec_prefix"):
+ monkeypatch.setattr(sys, attribute, str(real / "venv"))
+
+ paths = backend.runtime_read_paths(str(alias))
+ assert not any(os.path.realpath(p) == str(secret) for p in paths), paths
+
+
+def test_an_interpreter_symlinked_out_of_the_workdir_fails_the_call(tmp_path, monkeypatch):
+ """The Linux twin's guard, on this backend."""
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ outside = tmp_path / "elsewhere"
+ outside.mkdir()
+ real = outside / "python"
+ real.write_bytes(b"#!/bin/sh\nexit 0\n")
+ real.chmod(0o755)
+ link = workdir / "python"
+ link.symlink_to(real)
+ monkeypatch.setattr(sys, "executable", str(link))
+
+ with pytest.raises(WorkdirUnsafeError, match = "Python that runs Studio"):
+ backend.runtime_paths_under(str(workdir))
+
+
+def test_a_path_with_a_control_byte_is_refused(tmp_path):
+ for control in ("\x0c", "\x01", "\x7f"):
+ with pytest.raises(SandboxUnavailableError, match = "control characters"):
+ backend._validated(f"/tmp/session{control}x")
+ assert backend._validated("/tmp/session-café") == "/tmp/session-café"
+
+
+def test_an_editable_source_inside_the_workdir_is_denied_writes(tmp_path, monkeypatch):
+ workdir = tmp_path / "session"
+ package = workdir / "mypkg"
+ package.mkdir(parents = True)
+ (package / "__init__.py").write_text("", encoding = "utf-8")
+ monkeypatch.setattr(backend, "editable_source_roots", lambda: (str(package),))
+ assert str(package) in backend.runtime_paths_under(str(workdir))
+
+
+def test_a_runtime_is_denied_when_sys_prefix_carries_the_workdir_alias(tmp_path, monkeypatch):
+ real = tmp_path / "real"
+ (real / "venv" / "lib").mkdir(parents = True)
+ alias = tmp_path / "alias"
+ alias.symlink_to(real)
+ profile = _profile_for(alias, monkeypatch, alias / "venv")
+ deny = _rule(profile, "(deny file-write* ")
+ for spelling in (real / "venv" / "lib", alias / "venv" / "lib"):
+ assert f'(subpath "{spelling}")' in deny, deny
+
+
+def test_a_path_that_cannot_be_encoded_is_refused_rather_than_carried():
+ with pytest.raises(SandboxUnavailableError, match = "encodable as UTF-8"):
+ backend._validated("/tmp/session-\udcff")
+ assert backend._validated("/tmp/session-café") == "/tmp/session-café"
+ assert "\\u00" not in backend._sbpl_string("/tmp/session-café")
+
+
+def test_studio_state_under_an_optional_read_root_is_denied(monkeypatch, tmp_path):
+ """A Homebrew-prefixed Studio home is inside a recursive read root."""
+ from core.inference import sandbox_macos
+
+ state = tmp_path / "Cellar" / "unsloth-studio"
+ (state / "auth").mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(state))
+
+ rules = sandbox_macos._studio_state_rules((), (), str(tmp_path / "work"), str(tmp_path / "tmp"))
+
+ assert rules, "no rule was emitted for a Studio home inside a read root"
+ assert rules[0].startswith("(deny file-read-data")
+ assert str(state) in rules[0]
+
+
+def test_a_studio_home_that_does_not_exist_yet_is_still_denied(monkeypatch, tmp_path):
+ """Measured on macos-15/26: with no Studio home the probe raised 'no paths survived' and never isolated."""
+ from core.inference import sandbox_macos
+
+ state = tmp_path / "not-created-yet" / "studio"
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(state))
+
+ rules = sandbox_macos._studio_state_rules((), (), str(tmp_path / "work"), str(tmp_path / "tmp"))
+
+ assert rules and rules[0].startswith("(deny file-read-data")
+ assert f'(subpath "{state}")' in rules[0]
+
+
+def test_the_runtime_inside_a_custom_studio_home_is_restored(monkeypatch, tmp_path):
+ """A blanket deny would break a custom-home install: the managed venv lives under the Studio root, so the interpreter itself would stop being readable."""
+ from core.inference import sandbox_macos
+
+ state = tmp_path / "studio"
+ venv = state / "unsloth_studio" / "lib"
+ venv.mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(state))
+
+ rules = sandbox_macos._studio_state_rules(
+ (str(venv),), (), str(tmp_path / "work"), str(tmp_path / "tmp")
+ )
+
+ assert len(rules) == 2, "the runtime under the Studio home was not restored"
+ assert rules[1].startswith("(allow file-read*")
+ assert str(venv) in rules[1]
+
+
+def test_the_studio_state_deny_keeps_path_traversal_working(monkeypatch, tmp_path):
+ """The workdir lives under the Studio root on a default install."""
+ from core.inference import sandbox_macos
+
+ state = tmp_path / "studio"
+ (state / "auth").mkdir(parents = True)
+ workdir = state / "sandbox" / "_default"
+ workdir.mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(state))
+
+ rules = sandbox_macos._studio_state_rules((), (), str(workdir), str(tmp_path / "tmp"))
+
+ assert rules[0].startswith("(deny file-read-data"), rules[0][:60]
+ assert "file-read-metadata" not in rules[0]
+ assert "file-test-existence" not in rules[0]
+ assert "file-read-data" in rules[0]
+ assert str(state) in rules[0]
+
+
+def test_the_workdir_under_the_studio_home_is_restored_for_the_operation_the_deny_names(
+ monkeypatch, tmp_path
+):
+ """Measured on macos-15: a later (allow file-read* ...) loses to (deny file-read-data ...), so every Python call in the default workdir failed with Operation not permitted."""
+ from core.inference import sandbox_macos
+
+ state = tmp_path / "studio"
+ workdir = state / "sandbox" / "_default"
+ workdir.mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(state))
+
+ deny, restore = sandbox_macos._studio_state_rules((), (), str(workdir), str(tmp_path / "tmp"))
+
+ denied = deny[1:].split(" (", 1)[0].split()[1:]
+ restored = restore[1:].split(" (", 1)[0].split()[1:]
+ assert restore.startswith("(allow ")
+ assert set(denied) <= set(restored), (denied, restored)
+ assert str(workdir) in restore
+
+
+def test_a_registered_model_folder_is_readable(monkeypatch, tmp_path):
+ """The approval gate treats registered model folders as read-silent, so a read from one never prompts."""
+ from core.inference import os_sandbox, sandbox_macos
+
+ library = tmp_path / "models"
+ library.mkdir()
+ monkeypatch.setattr(sandbox_macos, "model_library_roots", lambda: (str(library),))
+ monkeypatch.setattr(os_sandbox, "model_library_roots", lambda: (str(library),))
+
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ private_tmp = tmp_path / "tmp"
+ private_tmp.mkdir()
+
+ profile = sandbox_macos.build_profile(
+ workdir = str(workdir),
+ private_tmp = str(private_tmp),
+ runtime_paths = (),
+ )
+
+ assert str(library) in profile
+
+
+@_darwin_only
+def test_a_hard_link_to_a_readable_file_cannot_be_created_in_the_workdir(tmp_path, monkeypatch):
+ """The workdir is writable and the model folders are readable, both on one volume."""
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ library = tmp_path / "library"
+ library.mkdir()
+ external = library / "weights.bin"
+ external.write_text("UNSLOTH_EXTERNAL_INODE", encoding = "utf-8")
+ monkeypatch.setattr(backend, "model_library_roots", lambda: (str(library),))
+
+ control = workdir / "host-alias"
+ os.link(external, control)
+ assert control.stat().st_ino == external.stat().st_ino, (
+ "the host could not hard-link across these two paths, so the negative "
+ "control below would prove nothing"
+ )
+ control.unlink()
+
+ argv = ("/bin/ln", str(external), str(workdir / "alias"))
+ prepared = backend.prepare(
+ ToolLaunchPlan(argv = argv, workdir = str(workdir), env = {"PATH": "/usr/bin:/bin"})
+ )
+ try:
+ result = subprocess.run(
+ prepared.argv, capture_output = True, text = True, timeout = 60, check = False
+ )
+ finally:
+ prepared.cleanup()
+
+ assert result.returncode != 0, (
+ "a hard link to a readable file outside the workdir was created inside it, "
+ "so a tool can write to that file through the alias"
+ )
+ assert not (workdir / "alias").exists()
+
+
+def test_a_workdir_spelled_differently_from_the_studio_home_is_still_readable(
+ monkeypatch, tmp_path
+):
+ """The deny rules are emitted in every spelling a path has, so the restore list has to be built the same way."""
+ real_home = tmp_path / "private" / "studio-home"
+ workdir = real_home / "sandbox" / "_default"
+ workdir.mkdir(parents = True)
+ (tmp_path / "alias").symlink_to(tmp_path / "private")
+ aliased_home = tmp_path / "alias" / "studio-home"
+
+ monkeypatch.setattr(backend, "studio_state_roots", lambda: (str(aliased_home),))
+
+ rules = backend._studio_state_rules((), (), str(workdir.resolve()), "")
+
+ assert rules, "the state deny was not emitted, so this test proves nothing"
+ restored = [rule for rule in rules if rule.startswith("(allow")]
+ assert restored, "the workdir under the Studio home was never restored"
+ assert any(str(workdir.resolve()) in rule for rule in restored)
diff --git a/studio/backend/tests/test_sandbox_probe.py b/studio/backend/tests/test_sandbox_probe.py
new file mode 100644
index 00000000000..edc0eda2a85
--- /dev/null
+++ b/studio/backend/tests/test_sandbox_probe.py
@@ -0,0 +1,559 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""What the live probe is allowed to conclude, and from what."""
+
+from __future__ import annotations
+
+import inspect
+import os
+import pathlib
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+import pytest
+
+if sys.platform == "win32":
+ pytest.skip("the live probe is POSIX only", allow_module_level = True)
+
+from core.inference import os_sandbox, sandbox_landlock, sandbox_probe
+from core.inference.os_sandbox import PreparedSandboxLaunch, ToolLaunchPlan
+
+
[email protected](autouse = True)
+def _clean_probe_cache():
+ sandbox_probe.reset_probe_cache()
+ yield
+ sandbox_probe.reset_probe_cache()
+
+
+class _Backend:
+ """A stand-in exporting exactly the three names ``os_sandbox`` reads."""
+
+ PROFILE_ID = "test-profile"
+ LIMITATIONS = ()
+
+ def __init__(self, name, prepare):
+ self.BACKEND_NAME = name
+ self._prepare = prepare
+ self.prepared = []
+ self.calls = 0
+
+ def prepare(self, plan):
+ self.calls += 1
+ prepared = self._prepare(plan)
+ self.prepared.append(prepared)
+ return prepared
+
+
+def _passthrough(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:
+ return PreparedSandboxLaunch(
+ argv = plan.argv,
+ workdir = plan.workdir,
+ env = plan.env,
+ preexec_fn = plan.preexec_fn,
+ backend = "passthrough",
+ )
+
+
+_CONFINE_WRAPPER = """import builtins, os, sys
+WORK = os.path.realpath({workdir!r})
+# Both spellings, because on macOS the probe base is under /tmp, which is a
+# symlink to /private/tmp. With RESOLVE off the guard compares the path AS
+# WRITTEN, so resolving only one side made the double refuse its own workdir and
+# the probe stopped before it reached the symlink leg it exists to exercise.
+WORK_AS_GIVEN = os.path.abspath({workdir!r})
+LEAK_WRITES = {leak_writes!r}
+RESOLVE = {resolve!r}
+_host_open = builtins.open
+
+
+def _confined(file, *args, **kwargs):
+ # A stand-in for a filesystem namespace. RESOLVE picks whether the boundary
+ # is drawn on the resolved TARGET (what a real mount namespace does) or on
+ # the spelling of the path, which is the mistake the escape symlink catches.
+ try:
+ target = os.path.realpath(file) if RESOLVE else os.fspath(file)
+ except (TypeError, ValueError):
+ target = None
+ outside = isinstance(target, str) and not any(
+ target == root or target.startswith(root + os.sep)
+ for root in (WORK, WORK_AS_GIVEN)
+ )
+ if outside:
+ mode = args[0] if args else kwargs.get("mode", "r")
+ writing = "r" not in mode or "+" in mode
+ system_root = target == os.path.realpath(sys.executable)
+ # LEAK_WRITES models a backend that confines reads and protects the
+ # system root but lets an ordinary write through: every control the
+ # sandboxed process can evaluate comes out right, and the host still
+ # ends up with the file.
+ if not (LEAK_WRITES and writing and not system_root):
+ raise PermissionError(13, "confined to the workdir")
+ return _host_open(file, *args, **kwargs)
+
+
+builtins.open = _confined
+exec(compile({payload!r}, "<probe-payload>", "exec"), {{"__name__": "__main__"}})
+"""
+
+
+def _wrap(
+ plan: ToolLaunchPlan,
+ name: str,
+ *,
+ resolve = True,
+ leak_writes = False,
+):
+ """A builtins.open guard, not a kernel namespace."""
+ wrapper = _CONFINE_WRAPPER.format(
+ workdir = plan.workdir,
+ payload = plan.argv[-1],
+ resolve = resolve,
+ leak_writes = leak_writes,
+ )
+ return PreparedSandboxLaunch(
+ argv = plan.argv[:-1] + (wrapper,),
+ workdir = plan.workdir,
+ env = plan.env,
+ preexec_fn = sandbox_landlock.with_abstract_scope(plan.preexec_fn),
+ backend = name,
+ )
+
+
+def _confining(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:
+ return _wrap(plan, "confining")
+
+
+def _spelling_only(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:
+ return _wrap(plan, "spelling-only", resolve = False)
+
+
+def _leaking_writes(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:
+ return _wrap(plan, "leaky", leak_writes = True)
+
+
+def test_a_backend_that_confines_nothing_is_not_available():
+ backend = _Backend("passthrough", _passthrough)
+ available, reason = sandbox_probe.probe(backend)
+ assert available is False
+ assert "read the host sentinel" in reason, reason
+
+
+def test_a_backend_that_really_confines_is_available():
+ backend = _Backend("confining", _confining)
+ available, reason = sandbox_probe.probe(backend)
+ assert available is True, reason
+ assert "confining" in reason
+
+
+def test_the_symlink_leg_is_judged_on_the_target_not_the_path():
+ """A spelling-only guard passes the sentinel leg and fails here, so the two legs are not redundant."""
+ available, reason = sandbox_probe.probe(_Backend("spelling-only", _spelling_only))
+ assert available is False
+ assert "symlink" in reason, reason
+
+
+def test_a_write_that_reaches_the_host_fails_the_probe():
+ """This backend passes every control the sandboxed process can evaluate and still lands a write on the host, which only the host can see."""
+ available, reason = sandbox_probe.probe(_Backend("leaky", _leaking_writes))
+ assert available is False
+ assert "wrote through to the host" in reason, reason
+
+
+def test_the_escape_check_is_made_before_the_scratch_root_is_removed():
+ text = inspect.getsource(sandbox_probe._run_probe)
+ assert text.index("_host_saw_the_write") < text.index("shutil.rmtree")
+
+
+def test_the_positive_controls_run_before_anything_is_concluded(monkeypatch):
+ backend = _Backend("confining", _confining)
+ seen = []
+
+ def broken(workdir, sentinel, outside, env):
+ seen.append(sentinel)
+ return "the host itself could not read the probe sentinel (simulated)"
+
+ monkeypatch.setattr(sandbox_probe, "_host_positive_controls", broken)
+ available, reason = sandbox_probe.probe(backend)
+ assert available is False
+ assert "the host itself could not read" in reason
+ assert backend.calls == 0
+ assert seen
+
+
+def test_the_host_control_really_reads_the_sentinel_it_was_given(tmp_path):
+ work = tmp_path / "work"
+ work.mkdir()
+ env = {"PATH": os.environ.get("PATH", ""), "HOME": str(work), "TMPDIR": str(work)}
+ missing = str(tmp_path / "absent.txt")
+ assert "could not read" in sandbox_probe._host_positive_controls(
+ str(work), missing, str(tmp_path / "out.txt"), env
+ )
+ sentinel = tmp_path / "sentinel.txt"
+ sentinel.write_text("not the token", encoding = "utf-8")
+ assert "did not contain" in sandbox_probe._host_positive_controls(
+ str(work), str(sentinel), str(tmp_path / "out.txt"), env
+ )
+
+
+def test_a_host_that_fails_the_positive_half_is_not_blamed_on_the_backend():
+ backend = _Backend("confining", _confining)
+ real = sandbox_probe._host_payload
+ sandbox_probe._host_payload = lambda workdir: "raise SystemExit(7)"
+ try:
+ available, reason = sandbox_probe.probe(backend)
+ finally:
+ sandbox_probe._host_payload = real
+ assert available is False
+ assert reason.startswith("the host itself could not pass"), reason
+ assert backend.calls == 0
+
+
+def test_the_scratch_root_fits_an_af_unix_address():
+ base = sandbox_probe._probe_base()
+ try:
+ assert len(base) + len("/work/tmp") + 32 < 108, base
+ finally:
+ import shutil as _shutil
+ _shutil.rmtree(base, ignore_errors = True)
+
+
+def test_a_backend_that_cannot_prepare_is_unavailable_not_an_exception():
+ def explode(plan):
+ raise RuntimeError("no user namespaces here")
+
+ available, reason = sandbox_probe.probe(_Backend("exploding", explode))
+ assert available is False
+ assert "no user namespaces here" in reason
+
+
+def test_a_missing_backend_module_is_unavailable_not_an_exception():
+ class Absent:
+ pass
+
+ available, reason = sandbox_probe.probe(Absent())
+ assert available is False
+ assert reason
+
+
+def test_a_wedged_backend_times_out_instead_of_hanging(monkeypatch):
+ monkeypatch.setattr(sandbox_probe, "PROBE_TIMEOUT_SECONDS", 1.0)
+
+ def sleeper(plan):
+ return PreparedSandboxLaunch(
+ argv = (sys.executable, "-I", "-S", "-c", "import time; time.sleep(120)"),
+ workdir = plan.workdir,
+ env = plan.env,
+ preexec_fn = None,
+ backend = "wedged",
+ )
+
+ available, reason = sandbox_probe.probe(_Backend("wedged", sleeper))
+ assert available is False
+ assert "timed out" in reason
+
+
+def test_a_backend_that_only_prints_the_token_is_not_believed():
+ def liar(plan):
+ return PreparedSandboxLaunch(
+ argv = (sys.executable, "-I", "-S", "-c", f"print({sandbox_probe.PROBE_TOKEN!r})"),
+ workdir = plan.workdir,
+ env = plan.env,
+ preexec_fn = None,
+ backend = "liar",
+ )
+
+ backend = _Backend("liar", liar)
+ sandbox_probe.probe(backend)
+ handed_over = backend.prepared and True
+ assert handed_over
+
+
+def test_the_payload_handed_to_the_backend_carries_every_control():
+ backend = _Backend("passthrough", _passthrough)
+ sandbox_probe.probe(backend)
+ payload = backend.prepared[0].argv[-1]
+ for control in (
+ "read the host sentinel",
+ "followed a workdir symlink to the host sentinel",
+ sandbox_probe._OUTSIDE_WRITE_TOKEN,
+ "socketpair",
+ "DupFd",
+ "a python child could not run",
+ sandbox_probe.PROBE_TOKEN,
+ ):
+ assert control in payload, control
+ if os.access(sys.executable, os.W_OK):
+ assert "opened the interpreter for writing" in payload
+
+
+def test_the_launch_is_built_by_the_backend_not_by_the_probe():
+ backend = _Backend("confining", _confining)
+ sandbox_probe.probe(backend)
+ assert backend.calls == 1
+ plan = None
+
+ def capture(p):
+ nonlocal plan
+ plan = p
+ return _confining(p)
+
+ sandbox_probe.probe(_Backend("capture", capture))
+ assert isinstance(plan, ToolLaunchPlan)
+ assert plan.execution_kind == "python"
+ assert plan.env["HOME"] == plan.workdir
+ assert plan.env["TMPDIR"].startswith(plan.workdir + os.sep)
+
+
+def test_everything_the_probe_owns_is_released():
+ released = []
+
+ def prepare(plan):
+ prepared = _confining(plan)
+ prepared.cleanup_callbacks.append(lambda: released.append("backend"))
+ return prepared
+
+ backend = _Backend("confining", prepare)
+ available, reason = sandbox_probe.probe(backend)
+ assert available is True, reason
+ assert released == ["backend"]
+ assert not os.path.exists(backend.prepared[0].workdir)
+
+
+def test_cleanup_still_happens_when_the_launch_fails():
+ released = []
+
+ def prepare(plan):
+ prepared = _passthrough(plan)
+ prepared.cleanup_callbacks.append(lambda: released.append("backend"))
+ return prepared
+
+ backend = _Backend("passthrough", prepare)
+ assert sandbox_probe.probe(backend)[0] is False
+ assert released == ["backend"]
+ assert not os.path.exists(backend.prepared[0].workdir)
+
+
+def test_the_verdict_is_cached_so_a_tool_call_does_not_re_probe():
+ backend = _Backend("confining", _confining)
+ first = sandbox_probe.probe(backend)
+ second = sandbox_probe.probe(backend)
+ assert first == second
+ assert backend.calls == 1
+
+
+def test_force_re_probes():
+ backend = _Backend("confining", _confining)
+ sandbox_probe.probe(backend)
+ sandbox_probe.probe(backend, force = True)
+ assert backend.calls == 2
+
+
+def test_the_cache_is_keyed_on_the_backend_as_well_as_the_runtime():
+ confining = _Backend("confining", _confining)
+ passthrough = _Backend("passthrough", _passthrough)
+ assert sandbox_probe.probe(confining)[0] is True
+ assert sandbox_probe.probe(passthrough)[0] is False
+
+
+def test_linux_runtime_identity_includes_the_verified_bwrap(monkeypatch):
+ from core.inference import sandbox_linux
+
+ monkeypatch.setattr(os_sandbox.sys, "platform", "linux")
+ identity = ["/usr/bin/bwrap:first"]
+ monkeypatch.setattr(sandbox_linux, "bwrap_identity", lambda: identity[0])
+ first = os_sandbox._runtime_identity()
+
+ identity[0] = "/usr/bin/bwrap:replacement"
+ assert os_sandbox._runtime_identity() != first
+
+
+def test_an_expired_verdict_is_re_probed(monkeypatch):
+ """Set before the first probe: the expiry is stamped when the verdict is stored."""
+ monkeypatch.setattr(sandbox_probe, "_CACHE_TTL_SECONDS", 0.0)
+ backend = _Backend("confining", _confining)
+ sandbox_probe.probe(backend)
+ sandbox_probe.probe(backend)
+ assert backend.calls == 2
+
+
+def test_the_cache_cannot_grow_without_bound():
+ for index in range(sandbox_probe._CACHE_MAX_ENTRIES * 3):
+ sandbox_probe.probe(_Backend(f"passthrough-{index}", _passthrough))
+ assert len(sandbox_probe._cache) <= sandbox_probe._CACHE_MAX_ENTRIES
+
+
+def test_this_host_reports_unavailable_with_something_actionable():
+ if sys.platform != "linux":
+ pytest.skip("the AppArmor condition is Linux only")
+ capability = os_sandbox.capability_snapshot(force = True)
+ if capability.available:
+ pytest.skip("this host can build a real sandbox, so there is no fallback to check")
+ assert capability.backend == "none"
+ assert capability.limitations == ("no_os_isolation",)
+ assert capability.remediation
+ blocked = (
+ subprocess.run(
+ ["unshare", "--user", "--map-root-user", "true"],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.DEVNULL,
+ ).returncode
+ != 0
+ )
+ if blocked and os.path.exists("/proc/sys/kernel/apparmor_restrict_unprivileged_userns"):
+ assert "apparmor_restrict_unprivileged_userns" in capability.remediation
+
+
+def test_the_abstract_socket_control_is_paired_like_every_other(monkeypatch):
+ from core.inference import sandbox_landlock, sandbox_probe
+
+ monkeypatch.setattr(sandbox_landlock, "abstract_scope_supported", lambda: False)
+ assert sandbox_probe._abstract_control() == (None, None)
+
+ monkeypatch.setattr(sandbox_landlock, "abstract_scope_supported", lambda: True)
+ if sys.platform != "linux":
+ assert sandbox_probe._abstract_control() == (None, None)
+ return
+ name, listener = sandbox_probe._abstract_control()
+ try:
+ assert name is not None and name.startswith(b"\0unsloth-probe-")
+ assert listener is not None
+ finally:
+ if listener is not None:
+ listener.close()
+
+
+def test_the_payload_requires_the_abstract_socket_to_be_out_of_reach():
+ from core.inference import sandbox_probe
+
+ with_scope = sandbox_probe._payload(
+ "/work", "/sentinel", "/escape", "/outside", False, b"\0host-socket"
+ )
+ assert "connected to a host abstract unix socket" in with_scope
+ assert "AF_UNIX" in with_scope
+ without = sandbox_probe._payload("/work", "/sentinel", "/escape", "/outside", False, None)
+ assert "abstract" not in without
+
+
+def test_the_symlink_leg_survives_a_probe_base_reached_through_a_symlink(monkeypatch):
+ root = "/tmp" if os.path.isdir("/tmp") else tempfile.gettempdir()
+ holder = tempfile.mkdtemp(prefix = "us-sym-", dir = root)
+ real = pathlib.Path(holder) / "r"
+ real.mkdir()
+ alias = pathlib.Path(holder) / "a"
+ alias.symlink_to(real)
+ real_mkdtemp = sandbox_probe.tempfile.mkdtemp
+
+ def through_the_symlink(prefix = None, dir = None):
+ made = real_mkdtemp(prefix = prefix, dir = str(alias))
+ return made.replace(str(real), str(alias))
+
+ monkeypatch.setattr(sandbox_probe.tempfile, "mkdtemp", through_the_symlink)
+ try:
+ assert str(alias.resolve()) != str(alias)
+ available, reason = sandbox_probe.probe(_Backend("spelling-only", _spelling_only))
+ assert available is False
+ assert "symlink" in reason, reason
+ available, reason = sandbox_probe.probe(_Backend("confining", _confining))
+ assert available is True, reason
+ finally:
+ shutil.rmtree(holder, ignore_errors = True)
+
+
+def test_the_landlock_helper_imports_where_it_will_never_be_used():
+ source = pathlib.Path(sandbox_landlock.__file__).read_text(encoding = "utf-8")
+ guard = re.search(r"except \(([^)]*)\):[^\n]*\n(?:\s*#[^\n]*\n)*\s*_libc = None", source)
+ assert guard, "the CDLL(None) import guard moved; this test no longer checks it"
+ assert "TypeError" in guard.group(1), guard.group(1)
+ real = sandbox_landlock._libc
+ sandbox_landlock._libc = None
+ sandbox_landlock.abstract_scope_supported.cache_clear()
+ try:
+ assert sandbox_landlock.abstract_scope_supported() is False
+ sandbox_landlock.apply_abstract_scope()
+ sandbox_landlock.with_abstract_scope(None)()
+ finally:
+ sandbox_landlock._libc = real
+ sandbox_landlock.abstract_scope_supported.cache_clear()
+
+
+def test_a_cached_verdict_outlives_the_old_sixty_second_window(monkeypatch, tmp_path):
+ """The TTL was 60s, so an idle chat paid the cold probe again on its next message: a call 70s after the last one cost 1.24s against 0.040s unsandboxed."""
+ from core.inference import sandbox_probe
+
+ assert sandbox_probe._CACHE_TTL_SECONDS >= 600, (
+ "the probe TTL is back under 10 minutes; an idle chat pays the cold "
+ "probe again on its next message"
+ )
+
+ calls = []
+
+ class Backend:
+ BACKEND_NAME = "ttl-probe"
+
+ @staticmethod
+ def prepare(plan):
+ calls.append(plan)
+ raise AssertionError("the probe should not have re-run inside the TTL")
+
+ sandbox_probe.reset_probe_cache()
+ clock = {"now": 1000.0}
+ monkeypatch.setattr(sandbox_probe.time, "monotonic", lambda: clock["now"])
+
+ from core.inference import os_sandbox as _os_sandbox
+
+ key = (Backend.BACKEND_NAME, _os_sandbox._runtime_identity())
+ sandbox_probe._cache[key] = (
+ clock["now"] + sandbox_probe._CACHE_TTL_SECONDS,
+ True,
+ "seeded",
+ )
+
+ clock["now"] += 70.0
+ available, reason = sandbox_probe.probe(Backend)
+ assert (available, reason) == (True, "seeded")
+ assert calls == [], "the probe re-ran 70s later, which is the cost this fixed"
+
+
+def test_an_unavailable_verdict_is_not_cached_for_the_long_window(monkeypatch, tmp_path):
+ """A user who installs bubblewrap must not wait 15 minutes for it to count."""
+ from core.inference import os_sandbox as _os_sandbox
+ from core.inference import sandbox_probe
+
+ assert (
+ sandbox_probe._CACHE_TTL_UNAVAILABLE_SECONDS <= 120
+ ), "an unavailable verdict is cached long enough to outlive the user's own remediation"
+
+ probes = []
+
+ class Backend:
+ BACKEND_NAME = "unavailable-probe"
+
+ @staticmethod
+ def prepare(plan):
+ probes.append(plan)
+ raise RuntimeError("bubblewrap is not installed")
+
+ sandbox_probe.reset_probe_cache()
+ clock = {"now": 5000.0}
+ monkeypatch.setattr(sandbox_probe.time, "monotonic", lambda: clock["now"])
+
+ available, _ = sandbox_probe.probe(Backend)
+ assert available is False
+ assert len(probes) == 1
+
+ clock["now"] += 30.0
+ sandbox_probe.probe(Backend)
+ assert len(probes) == 1, "an unavailable verdict should still be cached briefly"
+
+ clock["now"] += 100.0
+ sandbox_probe.probe(Backend)
+ assert len(probes) == 2, (
+ "the host was never re-examined, so installing bubblewrap does not "
+ "take effect until the long TTL expires"
+ )
diff --git a/studio/backend/tests/test_studio_tool_loop.py b/studio/backend/tests/test_studio_tool_loop.py
index 014d664d1d7..f80f8cf5da2 100644
--- a/studio/backend/tests/test_studio_tool_loop.py
+++ b/studio/backend/tests/test_studio_tool_loop.py
@@ -613,6 +613,24 @@ def test_sandbox_stays_on_by_default(executed):
_run(transport, tools = [PY])
assert executed[0]["disable_sandbox"] is False
+ # Nobody approved it, so the executor keeps the jail even for a host path.
+ assert "host_access_approved" not in executed[0]
+
+
[email protected]("verdict", ["allow", "deny"])
+def test_only_an_approved_call_is_marked_approved(executed, monkeypatch, verdict):
+ monkeypatch.setattr(loop_mod, "begin_tool_decision", lambda session, approval: object())
+ monkeypatch.setattr(
+ loop_mod, "wait_tool_decision", lambda slot, approval, cancel_event = None: verdict
+ )
+ monkeypatch.setattr(loop_mod, "abort_tool_decision", lambda slot, approval: None)
+ monkeypatch.setattr(loop_mod, "new_approval_id", lambda: "ap1")
+ _run(_shared_setup_1(), tools = [PY], permission_mode = "auto", confirm_calls = True)
+
+ if verdict == "allow":
+ assert executed[0]["host_access_approved"] is True
+ else:
+ assert executed == []
# ── Forced tool choice ────────────────────────────────────────────
diff --git a/studio/backend/tests/test_tool_output_streaming.py b/studio/backend/tests/test_tool_output_streaming.py
index 9f3605f82c1..84420d6ecdb 100644
--- a/studio/backend/tests/test_tool_output_streaming.py
+++ b/studio/backend/tests/test_tool_output_streaming.py
@@ -87,6 +87,16 @@ def _gated_grandchild_sh(gate: Path, sentinel: Path) -> str:
return f"while [ ! -f '{gate}' ]; do sleep {_GATE_POLL_S}; done; touch '{sentinel}'"
+def _os_isolated_tools() -> bool:
+ """Whether PID-namespace teardown reaps descendants when the leader exits."""
+ from core.inference import os_sandbox
+
+ capability = os_sandbox.capability_snapshot()
+ return capability.available and (
+ "detached_processes_die_with_the_call" in capability.limitations
+ )
+
+
def _assert_grandchild_was_killed(gate: Path, sentinel: Path) -> None:
"""Open the gate, then require the sentinel to stay absent for the whole window."""
gate.write_text("go")
@@ -625,6 +635,10 @@ def test_bash_exec_invalid_utf8_identical_with_streaming():
assert "".join(chunks) == "ok�bad\n"
+ _os_isolated_tools(),
+ reason = "a PID namespace kills the background job with the leader; see below",
+)
def test_bash_exec_unlimited_timeout_waits_for_grandchild_output():
# A background grandchild holds the pipe open past the shell's exit and writes
# ~7s later. With timeout=None the drain must wait for EOF like
@@ -637,6 +651,23 @@ def test_bash_exec_unlimited_timeout_waits_for_grandchild_output():
assert "late-grandchild-output" in "".join(chunks)
+ not _os_isolated_tools(), reason = "no PID namespace here, so nothing reaps the job"
+)
+def test_bash_exec_unlimited_timeout_does_not_wait_for_a_job_the_namespace_reaps():
+ from core.inference import tools as tools_module
+
+ command = "( sleep 7; echo late-grandchild-output ) & echo parent-done"
+ started = time.monotonic()
+ result = _bash_exec(command, timeout = None, output_callback = lambda _t: None)
+ elapsed = time.monotonic() - started
+ assert "parent-done" in result
+ if tools_module._last_tool_execution_record.os_isolation:
+ assert elapsed < 5
+ else:
+ assert "late-grandchild-output" in result
+
+
def test_bash_exec_finite_timeout_kills_grandchild_holding_stdout(tmp_path):
# A backgrounded grandchild holds the pipe open past the finite timeout, then
# would write a sentinel. The parent shell has already exited, so killing only
@@ -646,7 +677,8 @@ def test_bash_exec_finite_timeout_kills_grandchild_holding_stdout(tmp_path):
gate = tmp_path / "gate"
command = f"( {_gated_grandchild_sh(gate, sentinel)} ) & echo parent-done"
result = _bash_exec(command, timeout = 1, output_callback = lambda _t: None)
- assert "timed out" in result
+ if not _os_isolated_tools():
+ assert "timed out" in result
_assert_grandchild_was_killed(gate, sentinel)
@@ -660,7 +692,8 @@ def test_bash_exec_nonstreaming_timeout_kills_grandchild(tmp_path):
gate = tmp_path / "gate"
command = f"( {_gated_grandchild_sh(gate, sentinel)} ) & echo parent-done"
result = _bash_exec(command, timeout = 1) # no output_callback -> communicate path
- assert "timed out" in result
+ if not _os_isolated_tools():
+ assert "timed out" in result
_assert_grandchild_was_killed(gate, sentinel)
@@ -1309,7 +1342,8 @@ def test_bash_exec_nonstreaming_cancel_kills_grandchild_after_leader_exit(tmp_pa
finally:
timer.cancel()
assert time.monotonic() - started < 2.5
- assert result == "Execution cancelled."
+ if not _os_isolated_tools():
+ assert result == "Execution cancelled."
_assert_grandchild_was_killed(gate, sentinel)
@@ -1331,5 +1365,6 @@ def test_python_exec_nonstreaming_cancel_kills_grandchild_after_leader_exit(tmp_
finally:
timer.cancel()
assert time.monotonic() - started < 2.5
- assert result == "Execution cancelled."
+ if not _os_isolated_tools():
+ assert result == "Execution cancelled."
_assert_grandchild_was_killed(gate, sentinel)
diff --git a/studio/backend/tests/test_tool_sandbox_wiring.py b/studio/backend/tests/test_tool_sandbox_wiring.py
new file mode 100644
index 00000000000..0f9c2eab4ae
--- /dev/null
+++ b/studio/backend/tests/test_tool_sandbox_wiring.py
@@ -0,0 +1,828 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The two tool launches, now routed through the OS-isolation planner."""
+
+from __future__ import annotations
+
+import ast
+import errno
+import importlib
+import inspect
+import os
+import shutil
+import socket
+import subprocess
+import sys
+import textwrap
+import time
+
+import pytest
+
+from core.inference import os_sandbox, tools
+from core.inference.os_sandbox import (
+ PreparedSandboxLaunch,
+ SandboxUnavailableError,
+ ToolLaunchPlan,
+)
+
+_SESSION = "__LOCALID_sandbox_wiring"
+
+
+def test_execute_tool_keeps_every_parameter_it_had_in_the_same_order():
+ parameters = inspect.signature(tools.execute_tool).parameters
+ positional = [
+ name
+ for name, parameter in parameters.items()
+ if parameter.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
+ ]
+ assert positional == [
+ "name",
+ "arguments",
+ "cancel_event",
+ "timeout",
+ "session_id",
+ "thread_id",
+ "rag_scope",
+ "disable_sandbox",
+ "output_callback",
+ "website_policy",
+ "conversation_branch",
+ "conversation_budget_tokens",
+ "conversation_token_counter",
+ "context_tokens",
+ "search_images",
+ "result_budget_tokens",
+ ]
+ assert parameters["tool_execution_mode"].kind is inspect.Parameter.KEYWORD_ONLY
+ assert parameters["tool_execution_mode"].default == "auto"
+
+
[email protected]("function", [tools._python_exec, tools._bash_exec])
+def test_the_executors_take_the_mode_keyword_only_and_default_it(function):
+ parameters = inspect.signature(function).parameters
+ assert parameters["tool_execution_mode"].kind is inspect.Parameter.KEYWORD_ONLY
+ assert parameters["tool_execution_mode"].default == "auto"
+ positional = [
+ name
+ for name, parameter in parameters.items()
+ if parameter.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
+ ]
+ assert positional[:5] == [
+ positional[0],
+ "cancel_event",
+ "timeout",
+ "session_id",
+ "disable_sandbox",
+ ]
+
+
+def test_a_caller_that_passes_nothing_new_behaves_as_auto():
+ tools._last_tool_execution_record = None
+ assert "2" in tools._python_exec("print(1 + 1)", None, 60, _SESSION)
+ assert tools._last_tool_execution_record.requested_mode == "auto"
+
+
+def test_disable_sandbox_still_means_full_access():
+ tools._last_tool_execution_record = None
+ assert "7" in tools._python_exec("print(7)", None, 60, _SESSION, disable_sandbox = True)
+ record = tools._last_tool_execution_record
+ assert record.requested_mode == "full"
+ assert record.effective_mode == "full"
+ assert record.limitations == ("security_restrictions_disabled",)
+
+
+def test_full_access_is_not_turned_into_a_refusal_by_a_stale_required():
+ tools._last_tool_execution_record = None
+ out = tools._python_exec(
+ "print(11)", None, 60, _SESSION, disable_sandbox = True, tool_execution_mode = "required"
+ )
+ assert "11" in out
+ assert tools._last_tool_execution_record.effective_mode == "full"
+
+
+def _fallback_host() -> bool:
+ return not os_sandbox.capability_snapshot().available
+
+
+ not _fallback_host(), reason = "this host can isolate, so there is no fallback to observe"
+)
+class TestAutoFallsBackOnAHostThatCannotIsolate:
+ def test_the_capability_is_unavailable_with_an_actionable_remediation(self):
+ capability = os_sandbox.capability_snapshot()
+ assert capability.available is False
+ assert capability.remediation
+ if sys.platform == "linux" and os.path.exists(
+ "/proc/sys/kernel/apparmor_restrict_unprivileged_userns"
+ ):
+ blocked = (
+ subprocess.run(
+ ["unshare", "--user", "--map-root-user", "true"],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.DEVNULL,
+ ).returncode
+ != 0
+ )
+ if blocked:
+ assert "apparmor_restrict_unprivileged_userns" in capability.remediation
+ assert "bwrap-userns-restrict" in capability.remediation
+
+ @pytest.mark.parametrize(
+ "run,expected",
+ [
+ (lambda: tools._python_exec("print(6 * 7)", None, 60, _SESSION), "42"),
+ (lambda: tools._bash_exec("echo 42", None, 60, _SESSION), "42"),
+ ],
+ ids = ["python", "terminal"],
+ )
+ def test_auto_refuses_nothing(self, run, expected):
+ tools._last_tool_execution_record = None
+ assert expected in run()
+ record = tools._last_tool_execution_record
+ assert record.requested_mode == "auto"
+ assert record.effective_mode == "software_safeguards"
+ assert record.os_isolation is False
+ assert "process_guard" in record.retained_safeguards
+ assert "no_os_isolation" in record.limitations
+ assert record.network_policy == "unrestricted"
+
+ def test_required_refuses_and_runs_nothing(self):
+ out = tools._python_exec(
+ "print('SHOULD_NOT_RUN')", None, 60, _SESSION, tool_execution_mode = "required"
+ )
+ assert "SHOULD_NOT_RUN" not in out
+ assert "OS_ISOLATION_UNAVAILABLE" in out
+ assert os_sandbox.capability_snapshot().remediation.split(".")[0] in out
+
+ def test_required_raises_out_of_the_planner_itself(self):
+ plan = ToolLaunchPlan(
+ argv = (sys.executable, "-c", "pass"),
+ workdir = os.getcwd(),
+ env = {},
+ requested_mode = "required",
+ )
+ with pytest.raises(SandboxUnavailableError) as excinfo:
+ os_sandbox.prepare_tool_launch(plan)
+ assert excinfo.value.remediation
+
+ def test_terminal_required_refuses_too(self):
+ out = tools._bash_exec(
+ "echo SHOULD_NOT_RUN", None, 60, _SESSION, tool_execution_mode = "required"
+ )
+ assert "SHOULD_NOT_RUN" not in out
+ assert "OS_ISOLATION_UNAVAILABLE" in out
+
+
+def test_an_unknown_mode_is_reported_rather_than_silently_downgraded():
+ out = tools._python_exec(
+ "print('SHOULD_NOT_RUN')", None, 60, _SESSION, tool_execution_mode = "nonsense"
+ )
+ assert "SHOULD_NOT_RUN" not in out
+ assert "nonsense" in out
+
+
+ sys.platform == "win32", reason = "pre-exec and pass_fds are POSIX; Windows keeps today's path"
+)
+def test_the_process_unsloth_holds_still_lands_in_its_own_session():
+ """Asserted about the OUTER process: under bubblewrap the payload is not a session leader, so asking it about its own sid only passes on a fallback."""
+ tools._python_exec("pass", None, 60, _SESSION)
+ tools._bash_exec("true", None, 60, _SESSION)
+
+ seen = []
+ real = subprocess.Popen
+
+ def capture(argv, **kwargs):
+ seen.append((argv, kwargs.get("preexec_fn")))
+ return real(argv, **kwargs)
+
+ subprocess.Popen = capture
+ try:
+ assert "5" in tools._python_exec("print(2 + 3)", None, 60, _SESSION)
+ assert "6" in tools._bash_exec("echo 6", None, 60, _SESSION)
+ finally:
+ subprocess.Popen = real
+ launches = [preexec for _, preexec in seen if preexec is not None]
+ bookkeeping = [argv for argv, preexec in seen if preexec is None]
+ assert len(launches) == 2, [argv for argv, _ in seen]
+ assert all(tuple(argv)[:1] == ("ps",) for argv in bookkeeping), bookkeeping
+ seen = launches
+ for preexec in seen:
+ read_fd, write_fd = os.pipe()
+ child = os.fork()
+ if child == 0: # pragma: no cover - runs in the forked child
+ try:
+ os.close(read_fd)
+ preexec()
+ os.write(write_fd, b"1" if os.getsid(0) == os.getpid() else b"0")
+ finally:
+ os._exit(0)
+ os.close(write_fd)
+ with os.fdopen(read_fd, "rb") as stream:
+ leads_its_session = stream.read()
+ os.waitpid(child, 0)
+ assert leads_its_session == b"1"
+
+
+def test_a_timeout_kills_the_tool_and_leaves_the_server_running():
+ start = time.monotonic()
+ out = tools._python_exec("import time; time.sleep(120)", None, 5, _SESSION)
+ assert "timed out" in out.lower(), out
+ assert time.monotonic() - start < 60
+ assert "9" in tools._python_exec("print(4 + 5)", None, 60, _SESSION)
+
+
+ sys.platform == "win32", reason = "pre-exec and pass_fds are POSIX; Windows keeps today's path"
+)
+def test_the_plan_carries_the_pre_exec_the_kill_paths_depend_on():
+ seen = []
+ real = os_sandbox.prepare_tool_launch
+
+ def capture(plan):
+ seen.append(plan)
+ return real(plan)
+
+ os_sandbox.prepare_tool_launch = capture
+ try:
+ tools._python_exec("print(1)", None, 60, _SESSION)
+ tools._bash_exec("echo 1", None, 60, _SESSION)
+ tools._python_exec("print(1)", None, 60, _SESSION, disable_sandbox = True)
+ finally:
+ os_sandbox.prepare_tool_launch = real
+ assert [plan.preexec_fn for plan in seen] == [
+ tools._sandbox_preexec,
+ tools._sandbox_preexec,
+ tools._bypass_preexec,
+ ]
+ assert [plan.execution_kind for plan in seen] == ["python", "terminal", "python"]
+
+
+def test_sandbox_preexec_runs_no_imports_after_the_fork():
+ for function in (tools._sandbox_preexec, tools._bypass_preexec):
+ tree = ast.parse(textwrap.dedent(inspect.getsource(function)))
+ offenders = [
+ node for node in ast.walk(tree) if isinstance(node, (ast.Import, ast.ImportFrom))
+ ]
+ assert not offenders, f"{function.__name__} imports after the fork"
+
+
[email protected]("disable_sandbox", [False, True], ids = ["sandboxed", "full"])
+def test_the_environment_the_shim_depends_on_survives(disable_sandbox):
+ workdir = tools._get_workdir(_SESSION)
+ out = tools._python_exec(
+ "import os\n"
+ "print('PYTHONPATH', os.environ.get('PYTHONPATH'))\n"
+ "print('HOME', os.environ.get('HOME'))\n"
+ "print('TMPDIR', os.environ.get('TMPDIR'))\n",
+ None,
+ 60,
+ _SESSION,
+ disable_sandbox = disable_sandbox,
+ )
+ lines = dict(line.split(" ", 1) for line in out.splitlines() if " " in line)
+ assert tools._SANDBOX_SITE_DIR in lines["PYTHONPATH"]
+ assert lines["HOME"] == workdir
+ assert lines["TMPDIR"].startswith(workdir)
+
+
+def test_the_path_remap_shim_still_heals_an_invented_absolute_path():
+ result = tools._python_exec(
+ "open('/mnt/data/wiring_probe.csv', 'w').write('a,b\\n')", None, 60, _SESSION
+ )
+ assert "Error" not in result
+ assert os.path.exists(os.path.join(tools._get_workdir(_SESSION), "wiring_probe.csv"))
+
+
+class _Recorder:
+ def __init__(self):
+ self.cleaned = 0
+ self.spawn_kwargs = None
+
+
+def _echoing_prepare(recorder, **overrides):
+ def prepare(plan):
+ prepared = PreparedSandboxLaunch(
+ argv = plan.argv,
+ workdir = plan.workdir,
+ env = plan.env,
+ preexec_fn = plan.preexec_fn,
+ backend = "test-double",
+ **overrides,
+ )
+ prepared.cleanup_callbacks.append(
+ lambda: setattr(recorder, "cleaned", recorder.cleaned + 1)
+ )
+ return prepared
+
+ return prepare
+
+
+ "run",
+ [
+ lambda: tools._python_exec("print(1)", None, 60, _SESSION),
+ lambda: tools._bash_exec("echo 1", None, 60, _SESSION),
+ ],
+ ids = ["python", "terminal"],
+)
+def test_the_launch_is_released_when_the_process_finishes(monkeypatch, run):
+ recorder = _Recorder()
+ monkeypatch.setattr(os_sandbox, "prepare_tool_launch", _echoing_prepare(recorder))
+ run()
+ assert recorder.cleaned == 1
+
+
+def test_the_launch_is_released_when_the_spawn_raises(monkeypatch):
+ recorder = _Recorder()
+ monkeypatch.setattr(os_sandbox, "prepare_tool_launch", _echoing_prepare(recorder))
+
+ def explode(prepared, **kwargs):
+ raise OSError("no fork for you")
+
+ monkeypatch.setattr(os_sandbox, "spawn_prepared_launch", explode)
+ assert "no fork for you" in tools._python_exec("print(1)", None, 60, _SESSION)
+ assert recorder.cleaned == 1
+
+
+def test_the_launch_is_released_when_required_refuses(monkeypatch):
+ def refuse(plan):
+ raise SandboxUnavailableError("OS_ISOLATION_UNAVAILABLE: nope", remediation = "install it")
+
+ monkeypatch.setattr(os_sandbox, "prepare_tool_launch", refuse)
+ out = tools._python_exec("print(1)", None, 60, _SESSION, tool_execution_mode = "required")
+ assert "install it" in out
+
+
+ sys.platform == "win32", reason = "pre-exec and pass_fds are POSIX; Windows keeps today's path"
+)
+def test_pass_fds_and_owned_files_reach_the_spawn(monkeypatch):
+ read_fd, write_fd = os.pipe()
+ holder = os.fdopen(write_fd, "wb")
+ recorder = _Recorder()
+ monkeypatch.setattr(
+ os_sandbox,
+ "prepare_tool_launch",
+ _echoing_prepare(recorder, pass_fds = (read_fd,)),
+ )
+
+ real_spawn = os_sandbox.spawn_prepared_launch
+
+ def capture(prepared, **kwargs):
+ prepared.owned_files.append(holder)
+ recorder.spawn_kwargs = dict(kwargs)
+ return real_spawn(prepared, **kwargs)
+
+ monkeypatch.setattr(os_sandbox, "spawn_prepared_launch", capture)
+ try:
+ out = tools._python_exec(
+ f"import os; os.fstat({read_fd}); print('INHERITED')", None, 60, _SESSION
+ )
+ finally:
+ os.close(read_fd)
+ assert "INHERITED" in out, out
+ assert recorder.spawn_kwargs["pass_fds"] == (read_fd,)
+ assert recorder.spawn_kwargs["cwd"] == tools._get_workdir(_SESSION)
+ assert recorder.spawn_kwargs["close_fds"] is True
+ assert recorder.cleaned == 1
+ assert holder.closed
+
+
+def test_auto_still_runs_when_the_planner_itself_breaks(monkeypatch):
+ def explode(plan):
+ raise ImportError("no module named sandbox_linux")
+
+ monkeypatch.setattr(os_sandbox, "prepare_tool_launch", explode)
+ tools._last_tool_execution_record = None
+ assert "5" in tools._python_exec("print(5)", None, 60, _SESSION)
+ record = tools._last_tool_execution_record
+ assert record.effective_mode == "software_safeguards"
+ assert "sandbox_planner_error" in record.limitations
+
+
+def test_full_access_keeps_its_own_label_even_when_the_planner_breaks(monkeypatch):
+ def explode(plan):
+ raise RuntimeError("planner down")
+
+ monkeypatch.setattr(os_sandbox, "prepare_tool_launch", explode)
+ tools._last_tool_execution_record = None
+ assert "9" in tools._python_exec("print(9)", None, 60, _SESSION, disable_sandbox = True)
+ record = tools._last_tool_execution_record
+ assert record.effective_mode == "full"
+ assert "security_restrictions_disabled" in record.limitations
+ assert "command_and_code_analysis" not in record.retained_safeguards
+
+
+ sys.platform == "win32", reason = "pre-exec and pass_fds are POSIX; Windows keeps today's path"
+)
+def test_a_backend_that_drops_the_pre_exec_has_it_put_back(monkeypatch):
+ def forgetful(plan):
+ return PreparedSandboxLaunch(
+ argv = plan.argv,
+ workdir = plan.workdir,
+ env = plan.env,
+ preexec_fn = None,
+ backend = "forgetful",
+ )
+
+ monkeypatch.setattr(os_sandbox, "prepare_tool_launch", forgetful)
+ out = tools._python_exec(
+ "import os; print('SID_MATCHES', os.getsid(0) == os.getpid())", None, 60, _SESSION
+ )
+ assert "SID_MATCHES True" in out, out
+
+
+def test_required_still_refuses_when_the_planner_itself_breaks(monkeypatch):
+ def explode(plan):
+ raise ImportError("no module named sandbox_linux")
+
+ monkeypatch.setattr(os_sandbox, "prepare_tool_launch", explode)
+ out = tools._python_exec(
+ "print('SHOULD_NOT_RUN')", None, 60, _SESSION, tool_execution_mode = "required"
+ )
+ assert "SHOULD_NOT_RUN" not in out
+ assert "OS_ISOLATION_UNAVAILABLE" in out
+
+
[email protected]("platform", ["win32", "cygwin", "aix"])
+def test_a_platform_with_no_backend_gets_exactly_the_plan_it_handed_in(monkeypatch, platform):
+ monkeypatch.setattr(sys, "platform", platform)
+
+ def marker():
+ return None
+
+ env = {"PATH": "/usr/bin"}
+ plan = ToolLaunchPlan(
+ argv = ("prog", "arg"),
+ workdir = "/work",
+ env = env,
+ preexec_fn = marker,
+ requested_mode = "auto",
+ timeout_seconds = 300,
+ )
+ prepared = os_sandbox.prepare_tool_launch(plan)
+ assert prepared.argv == plan.argv
+ assert prepared.env is env
+ assert prepared.preexec_fn is marker
+ assert prepared.workdir == "/work"
+ assert prepared.pass_fds == ()
+ assert prepared.close_fds is True
+ assert prepared.execution_record.effective_mode == "software_safeguards"
+ assert prepared.execution_record.os_isolation is False
+
+
+def test_a_platform_with_no_backend_still_refuses_in_required(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "win32")
+ with pytest.raises(SandboxUnavailableError):
+ os_sandbox.prepare_tool_launch(
+ ToolLaunchPlan(argv = ("prog",), workdir = "/work", env = {}, requested_mode = "required")
+ )
+
+
+def test_the_tool_descriptions_are_untouched_by_this_change():
+ note = tools._build_sandbox_paths_note()
+ assert "isolation" not in note.lower()
+ full = tools._to_full_access(
+ "Execute Python code in a sandbox and return stdout/stderr." + note, "python"
+ )
+ assert "in a sandbox" not in full
+ assert "sandbox is disabled" in full
+
+
+def _declining_backend(
+ monkeypatch,
+ reason: str,
+ unsafe: bool = True,
+) -> None:
+ """*unsafe* picks WHICH refusal; the two are told apart by type."""
+ error = os_sandbox.WorkdirUnsafeError if unsafe else SandboxUnavailableError
+
+ def decline(plan):
+ raise error(reason)
+
+ monkeypatch.setattr(os_sandbox, "prepare_tool_launch", decline)
+
+
+def test_an_unsafe_workdir_fails_the_call_rather_than_de_isolating_it(monkeypatch):
+ _declining_backend(monkeypatch, "the session workdir contains a device node")
+ tools._last_tool_execution_record = None
+ out = tools._python_exec("print('SHOULD_NOT_RUN')", None, 60, _SESSION)
+ assert "SHOULD_NOT_RUN" not in out
+ assert "device node" in out
+ assert tools._last_tool_execution_record is None
+
+
+def test_required_still_refuses_when_the_backend_declines_this_launch(monkeypatch):
+ _declining_backend(monkeypatch, "the session workdir contains a device node")
+ out = tools._python_exec(
+ "print('SHOULD_NOT_RUN')", None, 60, _SESSION, tool_execution_mode = "required"
+ )
+ assert "SHOULD_NOT_RUN" not in out
+ assert "device node" in out
+
+
[email protected](sys.platform == "win32", reason = "the workdir scan is POSIX only")
+def test_tool_code_cannot_switch_the_boundary_off_for_the_next_call(monkeypatch):
+ if not os_sandbox.capability_snapshot().available:
+ pytest.skip("this host cannot isolate, so there is no boundary to switch off")
+ workdir = tools._get_workdir(_SESSION)
+ planted = os.path.join(workdir, "planted.sock")
+ holder = socket.socket(socket.AF_UNIX)
+ monkeypatch.chdir(workdir)
+ holder.bind("planted.sock")
+ try:
+ tools._last_tool_execution_record = None
+ out = tools._python_exec("print('SHOULD_NOT_RUN')", None, 60, _SESSION)
+ assert "SHOULD_NOT_RUN" not in out
+ assert "device or IPC node" in out
+ assert tools._last_tool_execution_record is None
+ finally:
+ holder.close()
+ os.unlink(planted)
+ assert "42" in tools._python_exec("print(6 * 7)", None, 60, _SESSION)
+ assert tools._last_tool_execution_record.os_isolation is True
+
+
+ "function,payload",
+ [(tools._python_exec, "print('SHOULD_NOT_RUN')"), (tools._bash_exec, "echo SHOULD_NOT_RUN")],
+ ids = ["python", "terminal"],
+)
+def test_full_is_not_requestable_through_the_mode(function, payload):
+ tools._last_tool_execution_record = None
+ out = function(payload, None, 60, _SESSION, tool_execution_mode = "full")
+ assert "SHOULD_NOT_RUN" not in out
+ assert "TOOL_EXECUTION_MODE_INVALID" in out
+ assert "disable_sandbox" in out
+ assert tools._last_tool_execution_record is None
+
+
+def test_disable_sandbox_is_still_the_way_to_full_access():
+ tools._last_tool_execution_record = None
+ assert "7" in tools._python_exec(
+ "print(7)", None, 60, _SESSION, disable_sandbox = True, tool_execution_mode = "full"
+ )
+ assert tools._last_tool_execution_record.effective_mode == "full"
+
+
+ "run",
+ [
+ lambda: tools._python_exec(
+ "import sys; print('IN', repr(sys.stdin.read()))", None, 60, _SESSION
+ ),
+ lambda: tools._bash_exec("printf 'IN %s\\n' \"$(cat)\"", None, 60, _SESSION),
+ ],
+ ids = ["python", "terminal"],
+)
+def test_a_tool_call_cannot_read_the_servers_stdin(run):
+ read_fd, write_fd = os.pipe()
+ os.write(write_fd, b"OPERATOR SECRET\n")
+ os.close(write_fd)
+ saved = os.dup(0)
+ try:
+ os.dup2(read_fd, 0)
+ out = run()
+ finally:
+ os.dup2(saved, 0)
+ os.close(saved)
+ os.close(read_fd)
+ assert "OPERATOR SECRET" not in out
+ assert "IN" in out
+
+
+def test_the_fallback_never_claims_a_descendant_sweep_it_does_not_perform():
+ limitations = os_sandbox._software_only_limitations()
+ if sys.platform == "win32":
+ assert "detached_descendant_cleanup_unverified" not in limitations
+ else:
+ assert "detached_descendant_cleanup_unverified" in limitations
+ assert not hasattr(os_sandbox, "descendant_sweep_supported")
+
+
+def test_a_backend_that_has_just_stopped_being_available_still_falls_back(monkeypatch):
+ _declining_backend(
+ monkeypatch, "bubblewrap (bwrap) is not installed on this host", unsafe = False
+ )
+ tools._last_tool_execution_record = None
+ assert "42" in tools._python_exec("print(6 * 7)", None, 60, _SESSION)
+ record = tools._last_tool_execution_record
+ assert record.os_isolation is False
+ assert "sandbox_became_unavailable" in record.limitations
+
+
+def test_a_backend_that_fails_at_launch_drops_the_cached_verdict(monkeypatch):
+ reset = []
+ monkeypatch.setattr(
+ "core.inference.sandbox_probe.reset_probe_cache", lambda: reset.append(True)
+ )
+ prepared = PreparedSandboxLaunch(
+ argv = ("bwrap",), workdir = "/work", env = {}, preexec_fn = None, backend = "bubblewrap"
+ )
+ tools._forget_sandbox_capability_if_the_backend_failed(
+ prepared, "Exit code 1:\nbwrap: setting up uid map: Permission denied\n"
+ )
+ assert reset == [True]
+
+ tools._forget_sandbox_capability_if_the_backend_failed(
+ prepared, "Exit code 1:\nTraceback (most recent call last):\n"
+ )
+ prepared.backend = "software-safeguards"
+ tools._forget_sandbox_capability_if_the_backend_failed(
+ prepared, "Exit code 1:\nbwrap: setting up uid map: Permission denied\n"
+ )
+ assert reset == [True]
+
+
+def test_a_planner_os_error_refuses_rather_than_running_unisolated(monkeypatch):
+ backend = importlib.import_module(
+ "core.inference.sandbox_linux"
+ if sys.platform == "linux"
+ else "core.inference.sandbox_macos"
+ )
+
+ def full_disk(plan):
+ raise OSError(errno.ENOSPC, "No space left on device")
+
+ monkeypatch.setattr(
+ os_sandbox,
+ "capability_snapshot",
+ lambda **kwargs: os_sandbox.SandboxCapability(
+ backend = backend.BACKEND_NAME,
+ available = True,
+ reason = "probe passed",
+ profile_id = backend.PROFILE_ID,
+ ),
+ )
+ monkeypatch.setattr(backend, "prepare", full_disk)
+ tools._last_tool_execution_record = None
+ out = tools._python_exec("print('SHOULD_NOT_RUN')", None, 60, _SESSION)
+ assert "SHOULD_NOT_RUN" not in out
+ assert tools._last_tool_execution_record is None
+
+
+def test_an_unisolated_launch_cannot_be_hooked_by_a_planted_usercustomize(tmp_path):
+ workdir = tmp_path / "session"
+ (workdir / os_sandbox.SESSION_PACKAGES_RELPATH).mkdir(parents = True)
+ env = tools._with_session_packages({"PATH": "/usr/bin"}, str(workdir))
+ assert env["PYTHONNOUSERSITE"] == "1"
+
+
+def test_the_shipped_sitecustomize_is_found_before_the_session_packages(tmp_path):
+ workdir = tmp_path / "session"
+ (workdir / os_sandbox.SESSION_PACKAGES_RELPATH).mkdir(parents = True)
+ env = tools._with_session_packages({"PYTHONPATH": tools._SANDBOX_SITE_DIR}, str(workdir))
+ entries = env["PYTHONPATH"].split(os.pathsep)
+ assert entries.index(tools._SANDBOX_SITE_DIR) < entries.index(
+ str(workdir / os_sandbox.SESSION_PACKAGES_RELPATH)
+ )
+
+
[email protected](("os_name", "scripts"), [("nt", "Scripts"), ("posix", "bin")])
+def test_session_package_commands_stay_on_path(monkeypatch, tmp_path, os_name, scripts):
+ """pip --target writes console scripts to Scripts on Windows, so bin alone lost them there."""
+ workdir = tmp_path / "session"
+ packages = workdir / os_sandbox.SESSION_PACKAGES_RELPATH
+ packages.mkdir(parents = True)
+ monkeypatch.setattr(os_sandbox.os, "name", os_name)
+ env = os_sandbox.with_session_packages({"PATH": "/usr/bin"}, str(workdir))
+ assert env["PATH"].split(os.pathsep) == ["/usr/bin", str(packages / scripts)]
+
+
+def test_a_seatbelt_launch_failure_also_drops_the_cached_verdict(monkeypatch):
+ """A rejected Seatbelt profile is reported as `sandbox-exec:`, not `bwrap:`."""
+ reset = []
+ monkeypatch.setattr(
+ "core.inference.sandbox_probe.reset_probe_cache", lambda: reset.append(True)
+ )
+ prepared = PreparedSandboxLaunch(
+ argv = ("/usr/bin/sandbox-exec",),
+ workdir = "/work",
+ env = {},
+ preexec_fn = None,
+ backend = "macos-seatbelt",
+ )
+
+ tools._forget_sandbox_capability_if_the_backend_failed(
+ prepared, "Exit code 1:\nsandbox-exec: sandbox_apply: Operation not permitted\n"
+ )
+ assert reset == [True]
+
+ tools._forget_sandbox_capability_if_the_backend_failed(
+ prepared, "Exit code 1:\nTraceback (most recent call last):\n"
+ )
+ assert reset == [True]
+
+
+def test_an_unknown_execution_mode_is_refused_whatever_the_account(monkeypatch):
+ """A managed account's confinement is the outer launch contract and skips the planner, which was the only place the mode was checked."""
+ import pytest
+
+ with pytest.raises(os_sandbox.SandboxUnavailableError) as refusal:
+ tools._requested_execution_mode("nonsense", False)
+
+ assert "TOOL_EXECUTION_MODE_INVALID" in str(refusal.value)
+ assert tools._requested_execution_mode("auto", False) == "auto"
+ assert tools._requested_execution_mode("required", False) == "required"
+ assert tools._requested_execution_mode("auto", True) == "full"
+
+
+def test_the_unconfined_placeholder_is_not_treated_as_a_boundary():
+ """`unconfined-by-owner` records that the owner ALLOWED unconfined tools on a host that cannot confine them."""
+ from core.inference.tool_confinement import Confinement
+
+ assert Confinement(mechanism = "unconfined-by-owner").confines is False
+ assert Confinement(mechanism = "landlock", preexec = lambda: None).confines is True
+ assert Confinement(mechanism = "sandbox-exec", wrapper = ("sandbox-exec",)).confines is True
+
+
+def test_a_managed_account_without_confinement_still_refuses_required(monkeypatch):
+ """The whole point of `required`: no boundary means no execution."""
+ from core.inference.tool_confinement import Confinement
+
+ monkeypatch.setattr(
+ tools,
+ "_account_confinement",
+ lambda: Confinement(mechanism = "unconfined-by-owner"),
+ )
+ _declining_backend(
+ monkeypatch, "bubblewrap (bwrap) is not installed on this host", unsafe = False
+ )
+
+ result = tools._python_exec("print(1)", None, 60, _SESSION, tool_execution_mode = "required")
+
+ assert "1" not in result.splitlines()[:1], f"the call ran unisolated: {result!r}"
+ assert "Execution error" in result or "OS_ISOLATION_UNAVAILABLE" in result
+
+
+ "run",
+ [
+ lambda **kw: tools._python_exec(
+ "import os\nprint('ran', os.path.exists('/srv/pr-approved/data.csv'))",
+ None,
+ 60,
+ _SESSION,
+ **kw,
+ ),
+ lambda **kw: tools._bash_exec(
+ "ls /srv/pr-approved/data.csv; echo ran", None, 60, _SESSION, **kw
+ ),
+ ],
+ ids = ["python", "terminal"],
+)
+ "approved, mode, jailed",
+ [
+ (True, "auto", False),
+ (False, "auto", True),
+ (True, "required", True),
+ ],
+)
+def test_an_approved_host_path_call_runs_as_it_does_without_the_jail(
+ monkeypatch, run, approved, mode, jailed
+):
+ planned: list = []
+
+ def prepare(plan):
+ planned.append(plan)
+ return _echoing_prepare(_Recorder())(plan)
+
+ monkeypatch.setattr(os_sandbox, "prepare_tool_launch", prepare)
+ tools._last_tool_execution_record = None
+ out = run(host_access_approved = approved, tool_execution_mode = mode)
+ assert "ran" in out
+ assert bool(planned) is jailed
+ if not jailed:
+ record = tools._last_tool_execution_record
+ assert record.effective_mode == "software_safeguards"
+ assert "user_approved_host_access" in record.limitations
+
+
+def test_an_approval_does_not_lift_the_jail_for_a_call_that_needs_no_host_path(monkeypatch):
+ planned: list = []
+
+ def prepare(plan):
+ planned.append(plan)
+ return _echoing_prepare(_Recorder())(plan)
+
+ monkeypatch.setattr(os_sandbox, "prepare_tool_launch", prepare)
+ assert "3" in tools._python_exec("print(1 + 2)", None, 60, _SESSION, host_access_approved = True)
+ assert len(planned) == 1
+
+
+ "command",
+ [
+ "cat /srv/private/report.txt",
+ "cat $'/srv/private/report.txt'",
+ "cat $'/srv/private/rep\\x6frt.txt'",
+ ],
+)
+def test_an_approved_ansi_c_quoted_host_path_is_recognised(command):
+ """The approval classifier decodes $'...' and prompts; the reach check must agree, or the approved call stays jailed."""
+ assert tools._reaches_host_paths("terminal", command)
diff --git a/tests/sh/test_linux_tool_sandbox.sh b/tests/sh/test_linux_tool_sandbox.sh
new file mode 100755
index 00000000000..77014d191dc
--- /dev/null
+++ b/tests/sh/test_linux_tool_sandbox.sh
@@ -0,0 +1,137 @@
+#!/bin/bash
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+#
+# Guards the Linux tool-sandbox step in install.sh: bubblewrap is optional, so it is installed
+# only when that needs no elevation, and otherwise the one command that enables it is printed.
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+INSTALL_SH="$SCRIPT_DIR/../../install.sh"
+PASS=0
+FAIL=0
+
+assert_contains() {
+ if echo "$2" | grep -qF "$3"; then
+ echo " PASS: $1"; PASS=$((PASS + 1))
+ else
+ echo " FAIL: $1 (expected to find '$3')"
+ echo "$2" | sed 's/^/ | /'; FAIL=$((FAIL + 1))
+ fi
+}
+
+assert_not_contains() {
+ if echo "$2" | grep -qF "$3"; then
+ echo " FAIL: $1 (found '$3' but should not)"; FAIL=$((FAIL + 1))
+ else
+ echo " PASS: $1"; PASS=$((PASS + 1))
+ fi
+}
+
+_FN_FILE=$(mktemp)
+grep '^_BWRAP_APPARMOR_FIX=' "$INSTALL_SH" > "$_FN_FILE"
+sed -n '/^_bwrap_install_command()/,/^}/p' "$INSTALL_SH" >> "$_FN_FILE"
+sed -n '/^_check_linux_tool_sandbox()/,/^}/p' "$INSTALL_SH" >> "$_FN_FILE"
+if ! grep -q '_check_linux_tool_sandbox()' "$_FN_FILE"; then
+ echo "FAIL: could not extract _check_linux_tool_sandbox from install.sh"
+ exit 1
+fi
+
+_BIN=$(mktemp -d)
+_SYSCTL=$(mktemp)
+_HARNESS=$(mktemp)
+cat > "$_HARNESS" <<HARNESS
+C_WARN=''; C_ERR=''; C_OK=''; C_DIM=''; C_RST=''
+step() { echo "STEP \$1 \$2"; }
+substep() { echo "SUBSTEP \$1"; }
+# Stands in for a root apt: creates bwrap when APT_WORKS=1, as an unprivileged apt-get would not.
+_smart_apt_install() {
+ echo "APT_CALLED: \$* optional=\${_SMART_APT_OPTIONAL:-false}"
+ if [ "\${APT_WORKS:-0}" = 1 ]; then printf '#!/bin/sh\nexit 0\n' > "$_BIN/bwrap"; /bin/chmod +x "$_BIN/bwrap"; fi
+ return 2
+}
+HARNESS
+
+_mk() { printf '#!/bin/sh\n%s\n' "$2" > "$_BIN/$1"; chmod +x "$_BIN/$1"; }
+_SH="${BASH:-/bin/bash}"
+
+_run() {
+ ( PATH="$_BIN"; export PATH
+ "$_SH" -c "_BW_USERNS_SYSCTL='$_SYSCTL'; APT_WORKS=${1:-0}; . '$_HARNESS'; . '$_FN_FILE'; _check_linux_tool_sandbox; echo \"RC=\$?\"" 2>&1 )
+}
+
+echo "=== apt host, installer already root: bubblewrap is installed, optionally ==="
+rm -f "$_BIN"/*; : > "$_SYSCTL"
+_mk apt-get 'exit 0'
+_out="$(_run 1)"
+assert_contains "asks apt for bubblewrap" "$_out" "APT_CALLED: bubblewrap"
+assert_contains "never as a required package" "$_out" "optional=true"
+assert_contains "then reports the sandbox works" "$_out" "bubblewrap works"
+assert_contains "never fails the install" "$_out" "RC=0"
+
+echo "=== apt host, ordinary user: no prompt, the exact command is printed ==="
+rm -f "$_BIN"/*
+_mk apt-get 'exit 0'
+_out="$(_run 0)"
+assert_contains "warns about software safeguards" "$_out" "bubblewrap not installed"
+assert_contains "names the apt command" "$_out" "sudo apt-get install -y bubblewrap"
+assert_contains "never fails the install" "$_out" "RC=0"
+
+echo "=== apt host with the Ubuntu 23.10+ userns restriction: still one command ==="
+rm -f "$_BIN"/*
+_mk apt-get 'exit 0'
+echo 1 > "$_SYSCTL"
+_out="$(_run 0)"
+assert_contains "installs bwrap and loads its profile" "$_out" "install -y bubblewrap && sudo apt-get install -y apparmor-profiles"
+: > "$_SYSCTL"
+
+echo "=== dnf host: no apt call, the dnf command is printed ==="
+rm -f "$_BIN"/*
+_mk dnf 'exit 0'
+_out="$(_run 0)"
+assert_not_contains "does not reach for apt" "$_out" "APT_CALLED"
+assert_contains "names the dnf command" "$_out" "sudo dnf install -y bubblewrap"
+
+echo "=== pacman host ==="
+rm -f "$_BIN"/*
+_mk pacman 'exit 0'
+_out="$(_run 0)"
+assert_contains "names the pacman command" "$_out" "sudo pacman -S --needed bubblewrap"
+
+echo "=== unknown package manager ==="
+rm -f "$_BIN"/*
+_out="$(_run 0)"
+assert_contains "falls back to generic advice" "$_out" "install bubblewrap with your package manager"
+
+echo "=== bubblewrap present and working: nothing to install ==="
+rm -f "$_BIN"/*
+_mk apt-get 'exit 0'
+_mk bwrap 'exit 0'
+_out="$(_run 0)"
+assert_not_contains "no apt call" "$_out" "APT_CALLED"
+assert_contains "reports it works" "$_out" "bubblewrap works"
+
+echo "=== bubblewrap present, AppArmor restricts user namespaces ==="
+rm -f "$_BIN"/*
+_mk bwrap 'echo "bwrap: setting up uid map: Permission denied" >&2; exit 1'
+echo 1 > "$_SYSCTL"
+_out="$(_run 0)"
+assert_contains "names AppArmor" "$_out" "AppArmor blocks bubblewrap"
+assert_contains "gives Ubuntu's own profile" "$_out" "extra-profiles/bwrap-userns-restrict /etc/apparmor.d/"
+assert_contains "and loads it" "$_out" "apparmor_parser -r /etc/apparmor.d/bwrap-userns-restrict"
+assert_contains "never fails the install" "$_out" "RC=0"
+
+echo "=== bubblewrap present, blocked without AppArmor (a container) ==="
+: > "$_SYSCTL"
+_out="$(_run 0)"
+assert_contains "says why" "$_out" "cannot create a sandbox here"
+assert_not_contains "does not blame AppArmor" "$_out" "AppArmor blocks"
+
+echo "=== the Linux branch runs the step without letting it fail the install ==="
+_case="$(sed -n '/^case "\$OS" in/,/^esac/p' "$INSTALL_SH")"
+assert_contains "called after the deps gate" "$_case" "_check_linux_tool_sandbox || true"
+
+rm -rf "$_BIN" "$_FN_FILE" "$_HARNESS" "$_SYSCTL"
+echo ""
+echo "=== $PASS passed, $FAIL failed ==="
+[ "$FAIL" -eq 0 ]