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: let the Linux tool sandbox use bubblewrap on NixOS and in FHS launchers (#13768)

oobabooga6ac0e2189606
diff --git a/studio/backend/core/inference/os_sandbox.py b/studio/backend/core/inference/os_sandbox.py
index 63fed4a0ef9..ba2216477af 100644
--- a/studio/backend/core/inference/os_sandbox.py
+++ b/studio/backend/core/inference/os_sandbox.py
@@ -787,7 +787,22 @@ def bwrap_install_command() -> str | None:
def linux_unavailable_remediation() -> str:
- missing = [name for name in _LINUX_REQUIRED_BINARIES if shutil.which(name) is None]
+ from . import sandbox_linux
+
+ try:
+ sandbox_linux._trusted_bwrap_path()
+ except sandbox_linux.BwrapUntrustedError as exc:
+ # Installing another copy would be refused the same way; say what to change instead.
+ if exc.pinned or exc.hidden_root:
+ return f"{exc}. {_FALLBACK_NOTE}"
+ except SandboxUnavailableError:
+ pass
+ # A pinned bwrap need not be on PATH.
+ missing = (
+ []
+ if os.environ.get(sandbox_linux.BWRAP_PATH_ENV)
+ else [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.
diff --git a/studio/backend/core/inference/sandbox_linux.py b/studio/backend/core/inference/sandbox_linux.py
index f63e4a9164c..b18fc484091 100644
--- a/studio/backend/core/inference/sandbox_linux.py
+++ b/studio/backend/core/inference/sandbox_linux.py
@@ -81,40 +81,117 @@ _SYSTEM_ROOTS = (
)
-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)
+# Pins bubblewrap for packagers and FHS-style launchers; the executable itself is still checked.
+BWRAP_PATH_ENV = "UNSLOTH_BWRAP_PATH"
+
+
+class BwrapUntrustedError(SandboxUnavailableError):
+ """bwrap exists but is refused; `pinned` or `hidden_root` means installing another copy would not help."""
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ pinned: bool = False,
+ hidden_root: bool = False,
+ ) -> None:
+ super().__init__(message)
+ self.pinned = pinned
+ self.hidden_root = hidden_root
+
+
+def _unmapped_uid() -> int | None:
+ """The overflow uid when a user namespace hides host owners (root shows as it), else None."""
+ try:
+ with open("/proc/self/uid_map", encoding = "utf-8") as f:
+ ranges = [
+ tuple(map(int, line.split())) for line in f.read().splitlines() if line.strip()
+ ]
+ with open("/proc/sys/kernel/overflowuid", encoding = "utf-8") as f:
+ overflow = int(f.read())
+ except (OSError, ValueError):
+ return None
+ # A mapped overflow uid is a real user (rootless containers map 65534), not hidden root.
+ if any(len(r) != 3 or r[0] <= overflow < r[0] + r[2] for r in ranges):
+ return None
+ # Unmapped itself, Studio's own files would show as this uid too.
+ return None if os.geteuid() == overflow else overflow
+
+
+def _executable_refusal(resolved: str, owners: tuple[int, ...]) -> str | None:
+ """Why the file at `resolved` could be modified by someone outside `owners`, or None."""
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)
+ except OSError as exc:
+ return str(exc)
+ if (
+ not stat.S_ISREG(executable.st_mode)
+ or executable.st_uid not in owners
+ or executable.st_mode & (stat.S_IWGRP | stat.S_IWOTH)
+ or not os.access(resolved, os.X_OK)
+ ):
+ return "the executable is not root-owned, executable, and non-writable"
+ return None
+
+
+def _ancestor_refusal(resolved: str) -> str | None:
+ """Why a directory above `resolved` would let a non-root user replace it, or None."""
+ parent = os.path.dirname(resolved)
+ try:
while True:
directory = os.stat(parent, follow_symlinks = False)
+ # Sticky (/nix/store is root:nixbld 1775): other writers cannot rename or delete root's entries.
+ shared = directory.st_mode & (stat.S_IWGRP | stat.S_IWOTH)
if (
not stat.S_ISDIR(directory.st_mode)
or directory.st_uid != 0
- or directory.st_mode & (stat.S_IWGRP | stat.S_IWOTH)
+ or (shared and not directory.st_mode & stat.S_ISVTX)
):
- raise OSError(f"its directory is replaceable: {parent}")
+ return f"its directory is replaceable: {parent}"
ancestor = os.path.dirname(parent)
if ancestor == parent:
- break
+ return None
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
+ return str(exc)
+
+
+def _trusted_bwrap_path() -> str:
+ """Resolve bubblewrap to a system-owned executable that the Studio user cannot replace."""
+ pinned = os.environ.get(BWRAP_PATH_ENV, "")
+ if pinned and not os.path.isabs(pinned):
+ raise BwrapUntrustedError(
+ f"{BWRAP_PATH_ENV} must be an absolute path: {pinned}", pinned = True
+ )
+ candidate = pinned or shutil.which("bwrap")
+ if candidate is None:
+ raise SandboxUnavailableError("bubblewrap (bwrap) is not installed on this host")
+ resolved = os.path.realpath(candidate)
+ overflow = _unmapped_uid()
+ vouched = (0,) if overflow is None else (0, overflow)
+ if pinned:
+ # The pin vouches for the path: in an FHS env even / is a tmpfs owned by the Studio user.
+ detail = _executable_refusal(resolved, vouched)
+ if detail is None:
+ return resolved
+ raise BwrapUntrustedError(
+ f"{BWRAP_PATH_ENV} names a bubblewrap Unsloth will not run ({resolved}: {detail})",
+ pinned = True,
+ )
+ detail = _executable_refusal(resolved, (0,)) or _ancestor_refusal(resolved)
+ if detail is None:
+ return resolved
+ if overflow is not None and _executable_refusal(resolved, vouched) is None:
+ raise BwrapUntrustedError(
+ "Studio runs in a user namespace (an AppImage or nixpkgs FHS wrapper, Flatpak or a "
+ f"rootless container) where Unsloth cannot confirm that {resolved} is system-owned "
+ f"({detail}). If it is the system bubblewrap, set {BWRAP_PATH_ENV}={candidate}",
+ hidden_root = True,
+ )
+ raise BwrapUntrustedError(
+ "bubblewrap must come from a trusted system installation; install it with the "
+ f"distribution package manager ({resolved}: {detail})"
+ )
def bwrap_identity() -> str:
@@ -171,6 +248,8 @@ _MODEL_CACHE_RELPATH = os.path.join(".cache", "huggingface")
_MODEL_CACHE_SUBDIRS = ("hub", "datasets", "xet", "assets")
# NixOS keeps glibc here, so a store interpreter cannot link without it.
_NIX_STORE = "/nix/store"
+# The NixOS system PATH (and nix-ld's loader) resolve through this link into the store.
+_NIXOS_CURRENT_SYSTEM = "/run/current-system"
def _trusted_system_file(path: str) -> bool:
@@ -360,20 +439,34 @@ def proc_mount_refused(stderr: str) -> bool:
return bool(_PROC_MOUNT_REFUSED.search(stderr or ""))
-def _preflight(bwrap: str, proc: tuple[str, ...]) -> "subprocess.CompletedProcess | None":
- """The launch's namespaces, /proc and system binds in its order, running only `true`."""
- # NixOS has no FHS `true`: run the store file itself, with the store bound as launches bind it.
+def _system_true() -> str | None:
+ """The host's `true`, resolved: in the store on NixOS and in FHS envs built from it."""
found = next(
(
p
- for p in ("/usr/bin/true", "/bin/true", "/run/current-system/sw/bin/true")
+ for p in ("/usr/bin/true", "/bin/true", f"{_NIXOS_CURRENT_SYSTEM}/sw/bin/true")
if os.path.isfile(p)
),
None,
)
- if found is None:
+ return None if found is None else os.path.realpath(found)
+
+
+def _nixos_current_system() -> str | None:
+ """Where /run/current-system points, when it is a NixOS link into the store."""
+ try:
+ target = os.readlink(_NIXOS_CURRENT_SYSTEM)
+ except OSError:
+ return None
+ return target if _within(target, _NIX_STORE) else None
+
+
+def _preflight(bwrap: str, proc: tuple[str, ...]) -> "subprocess.CompletedProcess | None":
+ """The launch's namespaces, /proc and system binds in its order, running only `true`."""
+ # NixOS has no FHS `true`: run the store file itself, with the store bound as launches bind it.
+ true = _system_true()
+ if true is None:
return None
- true = os.path.realpath(found)
argv = [bwrap, "--unshare-user", "--unshare-pid", *proc, "--dev", "/dev"]
roots = _SYSTEM_ROOTS + ((_NIX_STORE,) if _within(true, _NIX_STORE) else ())
for root in roots:
@@ -837,9 +930,18 @@ def prepare(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:
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):
+ # FHS envs (the AppImage and nixpkgs wrappers) link their system files into the store too.
+ current_system = None
+ if os.path.isdir(_NIX_STORE) and any(
+ path is not None and _within(path, _NIX_STORE)
+ for path in (os.path.realpath(sys.executable), _system_true())
+ ):
system_roots += (_NIX_STORE,)
+ current_system = _nixos_current_system()
runtime_paths = _without_state_inside(_runtime_read_paths(workdir, system_roots, inner))
+ if current_system:
+ # Reached through the link below; binding them would make /run/current-system a directory.
+ runtime_paths = tuple(p for p in runtime_paths if not _within(p, _NIXOS_CURRENT_SYSTEM))
silent_roots = tuple(
root
for root in model_library_roots()
@@ -903,6 +1005,8 @@ def prepare(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:
for path in runtime_paths:
if path not in tmp_runtime_paths:
argv += ["--ro-bind", path, path]
+ if current_system:
+ argv += ["--symlink", current_system, _NIXOS_CURRENT_SYSTEM]
# Mount points for both spellings must exist before / goes read-only.
argv += ["--dir", workdir]
if inner != workdir:
diff --git a/studio/backend/core/inference/sandbox_setup_plan.py b/studio/backend/core/inference/sandbox_setup_plan.py
index 03b005dbee8..c1f3f22a616 100644
--- a/studio/backend/core/inference/sandbox_setup_plan.py
+++ b/studio/backend/core/inference/sandbox_setup_plan.py
@@ -270,12 +270,16 @@ def _linux_elevation() -> tuple[str | None, str | None]:
def _bwrap_state() -> str:
- """As the launcher sees it: "trusted", "missing", or "shadowed" (PATH finds an untrusted copy first)."""
+ """As the launcher sees it: "trusted", "missing", "shadowed" (PATH finds an untrusted copy first),
+ or "refused" (a pinned or namespace-hidden copy, which installing would not change)."""
from . import sandbox_linux
try:
sandbox_linux._trusted_bwrap_path()
return "trusted"
+ except sandbox_linux.BwrapUntrustedError as exc:
+ if exc.pinned or exc.hidden_root:
+ return "refused"
except Exception: # noqa: BLE001 - any refusal means the launcher will not run it
pass
if shutil.which("bwrap") is None or trusted_system_binary("bwrap") is None:
@@ -289,6 +293,8 @@ def _linux_plan() -> SetupPlan:
reason = os_sandbox.linux_unavailable_remediation()
manager = _package_manager()
state = _bwrap_state()
+ if state == "refused":
+ return SetupPlan(platform = sys.platform, reason = reason)
if state == "shadowed":
# Installing changes nothing: the system copy is there, PATH just finds another one first.
return SetupPlan(
diff --git a/studio/backend/tests/test_sandbox_install_remediation.py b/studio/backend/tests/test_sandbox_install_remediation.py
index f216b6a9792..844962449b4 100644
--- a/studio/backend/tests/test_sandbox_install_remediation.py
+++ b/studio/backend/tests/test_sandbox_install_remediation.py
@@ -9,7 +9,7 @@ import re
import pytest
-from core.inference import os_sandbox
+from core.inference import os_sandbox, sandbox_linux
_INSTALL_SH = Path(__file__).resolve().parents[3] / "install.sh"
@@ -76,3 +76,11 @@ def test_installer_and_backend_give_the_same_commands():
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)
+
+
+def test_a_pinned_bwrap_off_path_is_not_reported_missing(monkeypatch):
+ _which_only(monkeypatch, {"apt-get"})
+ monkeypatch.setenv(sandbox_linux.BWRAP_PATH_ENV, "/opt/bubblewrap/bin/bwrap")
+ monkeypatch.setattr(sandbox_linux, "_trusted_bwrap_path", lambda: "/opt/bubblewrap/bin/bwrap")
+ monkeypatch.setattr(os_sandbox, "_linux_userns_blocked_by_apparmor", lambda: False)
+ assert "not installed" not in os_sandbox.linux_unavailable_remediation()
diff --git a/studio/backend/tests/test_sandbox_linux.py b/studio/backend/tests/test_sandbox_linux.py
index 6d2cb6f0d19..2dbc38ed9a9 100644
--- a/studio/backend/tests/test_sandbox_linux.py
+++ b/studio/backend/tests/test_sandbox_linux.py
@@ -9,6 +9,7 @@ import ast
import ctypes
import errno
import inspect
+import io
import json
import os
import platform
@@ -359,6 +360,150 @@ def test_a_path_bwrap_from_a_writable_location_is_never_executed(tmp_path, monke
sandbox_linux.prepare(_plan(tmp_path))
+_NIX_BWRAP = "/nix/store/abc-bubblewrap/bin/bwrap"
+_OVERFLOW = 65534
+
+
+def _fake_tree(
+ monkeypatch,
+ entries,
+ *,
+ found = _NIX_BWRAP,
+ overflow = None,
+):
+ """Point the trust check at `found` over `entries` ({path: (mode, uid)}), in a namespace if `overflow`."""
+ real_stat, real_access = os.stat, os.access
+
+ def fake_stat(path, *args, **kwargs):
+ if os.fspath(path) not in entries:
+ return real_stat(path, *args, **kwargs)
+ mode, uid = entries[os.fspath(path)]
+ return os.stat_result((mode, 1, 1, 1, uid, 0, 0, 0, 0, 0))
+
+ monkeypatch.setattr(sandbox_linux.shutil, "which", lambda _name: found)
+ monkeypatch.setattr(sandbox_linux.os.path, "realpath", lambda path, **_kw: path)
+ monkeypatch.setattr(sandbox_linux.os, "stat", fake_stat)
+ monkeypatch.setattr(
+ sandbox_linux.os, "access", lambda path, mode: path in entries or real_access(path, mode)
+ )
+ monkeypatch.setattr(sandbox_linux, "_unmapped_uid", lambda: overflow)
+ monkeypatch.delenv(sandbox_linux.BWRAP_PATH_ENV, raising = False)
+
+
+def _nix_tree(
+ store_mode = stat.S_ISVTX | 0o775,
+ owner = 0,
+ store_owner = 0,
+):
+ return {
+ "/": (stat.S_IFDIR | 0o755, owner),
+ "/nix": (stat.S_IFDIR | 0o755, owner),
+ "/nix/store": (stat.S_IFDIR | store_mode, store_owner),
+ "/nix/store/abc-bubblewrap": (stat.S_IFDIR | 0o555, owner),
+ "/nix/store/abc-bubblewrap/bin": (stat.S_IFDIR | 0o555, owner),
+ _NIX_BWRAP: (stat.S_IFREG | 0o555, owner),
+ }
+
+
+def test_a_nix_store_bwrap_is_trusted(monkeypatch):
+ # /nix/store is root:nixbld 1775: the sticky bit stops build users from replacing root's entries.
+ _fake_tree(monkeypatch, _nix_tree())
+ assert sandbox_linux._trusted_bwrap_path() == _NIX_BWRAP
+
+
+ "store_mode, store_owner",
+ [(0o775, 0), (0o777, 0), (stat.S_ISVTX | 0o777, 1000)],
+ ids = ["group-writable", "world-writable", "sticky-but-user-owned"],
+)
+def test_a_replaceable_store_is_still_refused(monkeypatch, store_mode, store_owner):
+ _fake_tree(monkeypatch, _nix_tree(store_mode, store_owner = store_owner))
+ with pytest.raises(sandbox_linux.BwrapUntrustedError, match = "replaceable: /nix/store\\)"):
+ sandbox_linux._trusted_bwrap_path()
+
+
+def _fhs_tree():
+ """An FHS env (appimageTools, nixpkgs wrappers): / is the user's tmpfs, host files show as the overflow uid."""
+ tree = _nix_tree(owner = _OVERFLOW, store_owner = _OVERFLOW)
+ tree["/"] = (stat.S_IFDIR | 0o755, 1000)
+ return tree
+
+
+def test_a_namespace_hidden_owner_names_the_pin_instead_of_an_install(monkeypatch):
+ _fake_tree(monkeypatch, _fhs_tree(), found = "/usr/bin/bwrap", overflow = _OVERFLOW)
+ monkeypatch.setattr(sandbox_linux.os.path, "realpath", lambda _path, **_kw: _NIX_BWRAP)
+ with pytest.raises(sandbox_linux.BwrapUntrustedError) as refused:
+ sandbox_linux._trusted_bwrap_path()
+ assert refused.value.hidden_root and not refused.value.pinned
+ # The stable PATH spelling, not the store path a rebuild would change.
+ assert f"{sandbox_linux.BWRAP_PATH_ENV}=/usr/bin/bwrap" in str(refused.value)
+ assert "package manager" not in str(refused.value)
+
+
+def test_a_pin_vouches_for_the_path_and_the_namespace_overflow_owner(monkeypatch):
+ _fake_tree(monkeypatch, _fhs_tree(), found = None, overflow = _OVERFLOW)
+ monkeypatch.setenv(sandbox_linux.BWRAP_PATH_ENV, _NIX_BWRAP)
+ assert sandbox_linux._trusted_bwrap_path() == _NIX_BWRAP
+
+
+ "owner, overflow",
+ [(_OVERFLOW, None), (1000, _OVERFLOW)],
+ ids = ["real-nobody-outside-a-namespace", "user-owned-in-a-namespace"],
+)
+def test_a_pin_is_still_held_to_the_ownership_checks(monkeypatch, owner, overflow):
+ tree = _nix_tree()
+ tree[_NIX_BWRAP] = (stat.S_IFREG | 0o555, owner)
+ _fake_tree(monkeypatch, tree, overflow = overflow)
+ monkeypatch.setenv(sandbox_linux.BWRAP_PATH_ENV, _NIX_BWRAP)
+ with pytest.raises(
+ sandbox_linux.BwrapUntrustedError, match = sandbox_linux.BWRAP_PATH_ENV
+ ) as refused:
+ sandbox_linux._trusted_bwrap_path()
+ assert refused.value.pinned
+
+
+def test_a_relative_pin_is_refused(monkeypatch):
+ _fake_tree(monkeypatch, _nix_tree())
+ monkeypatch.setenv(sandbox_linux.BWRAP_PATH_ENV, "bin/bwrap")
+ with pytest.raises(sandbox_linux.BwrapUntrustedError, match = "must be an absolute path"):
+ sandbox_linux._trusted_bwrap_path()
+
+
+ "uid_map, euid, expected",
+ [
+ (" 0 0 4294967295\n", 1000, None),
+ (" 1000 1000 1\n", 1000, _OVERFLOW),
+ (" 0 1000 1\n", 0, _OVERFLOW),
+ ("", _OVERFLOW, None),
+ (" 0 1000 1\n 1 100000 65536\n", 0, None),
+ (" 0 0 100000\n", 1000, None),
+ ],
+ ids = [
+ "initial-namespace",
+ "current-user-mapped",
+ "mapped-to-root",
+ "unmapped-itself",
+ "rootless-subuid-range-maps-it",
+ "partial-identity-map-covers-it",
+ ],
+)
+def test_the_overflow_uid_counts_only_inside_a_namespace(monkeypatch, uid_map, euid, expected):
+ files = {"/proc/self/uid_map": uid_map, "/proc/sys/kernel/overflowuid": f"{_OVERFLOW}\n"}
+ real_open = open
+ monkeypatch.setattr(
+ sandbox_linux,
+ "open",
+ lambda path, *a, **kw: io.StringIO(files[path])
+ if path in files
+ else real_open(path, *a, **kw),
+ raising = False,
+ )
+ monkeypatch.setattr(sandbox_linux.os, "geteuid", lambda: euid)
+ assert sandbox_linux._unmapped_uid() == expected
+
+
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)]
@@ -2624,6 +2769,36 @@ def test_the_two_proc_layouts_never_share_a_profile_or_a_cached_verdict(monkeypa
assert seen[False][2] != seen[True][2]
[email protected]("linked", [True, False], ids = ["fhs-or-nixos", "plain-host"])
+def test_a_launch_binds_the_store_when_system_files_link_into_it(tmp_path, monkeypatch, linked):
+ if sandbox_linux.shutil.which("bwrap") is None:
+ pytest.skip("bubblewrap is not installed on this host")
+ # The interpreter is not a store path, as with Studio's own Python inside an FHS env.
+ nix_true = "/nix/store/abc-coreutils/bin/true" if linked else "/usr/bin/true"
+ real_isdir = os.path.isdir
+ monkeypatch.setattr(sandbox_linux, "_system_true", lambda: nix_true)
+ monkeypatch.setattr(os.path, "isdir", lambda p: p == sandbox_linux._NIX_STORE or real_isdir(p))
+ monkeypatch.setattr(
+ sandbox_linux, "_nixos_current_system", lambda: "/nix/store/xyz-nixos-system"
+ )
+ # A NixOS interpreter's spelling: binding it would turn /run/current-system into a directory.
+ nixos_python = "/run/current-system/sw/bin/python3"
+ real_runtime = sandbox_linux._runtime_read_paths
+ monkeypatch.setattr(
+ sandbox_linux,
+ "_runtime_read_paths",
+ lambda *a, **kw: (*real_runtime(*a, **kw), nixos_python),
+ )
+ launch = sandbox_linux.prepare(_plan(tmp_path))
+ try:
+ assert (("/nix/store", "/nix/store") in _pairs(launch.argv, "--ro-bind-try")) is linked
+ symlinks = _pairs(launch.argv, "--symlink")
+ assert (("/nix/store/xyz-nixos-system", "/run/current-system") in symlinks) is linked
+ assert ((nixos_python, nixos_python) in _pairs(launch.argv, "--ro-bind")) is not linked
+ finally:
+ launch.cleanup()
+
+
def test_the_preflight_runs_a_nix_store_true_with_the_store_bound(monkeypatch):
nix_true = "/nix/store/abc-coreutils/bin/true"
real_isfile, real_isdir, real_realpath = os.path.isfile, os.path.isdir, os.path.realpath
diff --git a/studio/backend/tests/test_sandbox_setup_plan.py b/studio/backend/tests/test_sandbox_setup_plan.py
index 172e00d6fb0..c29618e7906 100644
--- a/studio/backend/tests/test_sandbox_setup_plan.py
+++ b/studio/backend/tests/test_sandbox_setup_plan.py
@@ -12,6 +12,8 @@ import pytest
from core.inference import os_sandbox, sandbox_setup_plan as plan_mod
from utils import client_ip
+_REAL_BWRAP_STATE = plan_mod._bwrap_state
+
@pytest.fixture(autouse = True)
def _fresh():
@@ -176,6 +178,27 @@ def test_bwrap_state_follows_the_launchers_trust_check(monkeypatch, tmp_path):
assert plan_mod._bwrap_state() == "shadowed"
[email protected]("pinned", [False, True], ids = ["namespace-hidden", "pinned"])
+def test_a_refused_bwrap_installing_cannot_fix_gets_no_install(linux, monkeypatch, pinned):
+ from core.inference import sandbox_linux
+
+ linux["tool"]("apt-get", "bwrap")
+ monkeypatch.setattr(plan_mod, "_bwrap_state", _REAL_BWRAP_STATE)
+
+ def refuse():
+ raise sandbox_linux.BwrapUntrustedError(
+ f"set {sandbox_linux.BWRAP_PATH_ENV}=/usr/bin/bwrap",
+ pinned = pinned,
+ hidden_root = not pinned,
+ )
+
+ monkeypatch.setattr(sandbox_linux, "_trusted_bwrap_path", refuse)
+ plan = plan_mod.detect(False)
+ assert plan.action is None and plan.manual_command == ""
+ assert sandbox_linux.BWRAP_PATH_ENV in plan.reason
+ assert "not installed" not in plan.reason
+
+
def test_an_unblocked_host_with_bwrap_needs_nothing(linux):
linux["tool"]("apt-get", "bwrap")
linux["restricted"] = True