Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: expose active virtualenv inside bwrap (#887)

Bingxi Zhao076508516620
diff --git a/deeptutor/services/sandbox/backends.py b/deeptutor/services/sandbox/backends.py
index d8f553808..a434a2fc0 100644
--- a/deeptutor/services/sandbox/backends.py
+++ b/deeptutor/services/sandbox/backends.py
@@ -21,6 +21,7 @@ from contextlib import suppress
import os
from pathlib import Path
import shutil
+import sys
import httpx
@@ -115,9 +116,56 @@ class BwrapBackend(SandboxBackend):
level = IsolationLevel.SYSTEM
_RO_SYSTEM_DIRS = ("/usr", "/usr/local", "/bin", "/lib", "/lib64", "/etc", "/sbin")
-
- def __init__(self, bwrap_path: str = "bwrap") -> None:
+ _DEFAULT_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
+
+ def __init__(
+ self,
+ bwrap_path: str = "bwrap",
+ *,
+ venv_path: str | Path | None = None,
+ inherit_virtualenv: bool = True,
+ ) -> None:
self._bwrap = bwrap_path
+ detected_virtualenv = (
+ venv_path is None and inherit_virtualenv and sys.prefix != sys.base_prefix
+ )
+ if venv_path is not None:
+ candidate = Path(venv_path).resolve()
+ elif detected_virtualenv:
+ candidate = Path(sys.prefix).resolve()
+ else:
+ candidate = None
+ self._venv_path = candidate if candidate is not None and candidate.is_dir() else None
+ self._python_runtime_mounts = (
+ self._detect_python_runtime_mounts() if self._venv_path and detected_virtualenv else ()
+ )
+
+ @classmethod
+ def _detect_python_runtime_mounts(cls) -> tuple[tuple[Path, Path], ...]:
+ """Return narrowly scoped base-Python mounts needed by managed venvs."""
+ candidates: list[tuple[Path, Path]] = []
+ for prefix in {sys.base_prefix, sys.base_exec_prefix}:
+ path = Path(prefix)
+ candidates.append((path.resolve(), path.absolute()))
+
+ base_executable = Path(getattr(sys, "_base_executable", sys.executable))
+ runtime_root = base_executable.parent.parent
+ candidates.append((runtime_root.resolve(), runtime_root.absolute()))
+
+ system_roots = tuple(Path(path).resolve() for path in cls._RO_SYSTEM_DIRS)
+ home = Path.home().resolve()
+ mounts: list[tuple[Path, Path]] = []
+ for source, destination in candidates:
+ if not source.is_dir() or source == Path("/") or source == home:
+ continue
+ if len(source.parts) < 3:
+ continue
+ if any(destination == root or root in destination.parents for root in system_roots):
+ continue
+ binding = (source, destination)
+ if binding not in mounts:
+ mounts.append(binding)
+ return tuple(mounts)
def _build_argv(self, request: ExecRequest) -> list[str]:
argv = [
@@ -138,9 +186,32 @@ class BwrapBackend(SandboxBackend):
for mount in request.mounts:
flag = "--ro-bind" if mount.read_only else "--bind"
argv += [flag, mount.host_path, mount.sandbox_path]
+ # uv-managed venvs can link their interpreter to a versioned runtime
+ # outside /usr. Mount only those concrete runtime roots, never their
+ # shared manager/home parent. Both the resolved and alias destinations
+ # may be needed because venv shebangs preserve the alias path.
+ for source, destination in self._python_runtime_mounts:
+ argv += ["--ro-bind", str(source), str(destination)]
+ # Mount only the environment itself, never its workspace or home-dir
+ # parent. Keeping the original absolute path preserves venv shebangs
+ # and direct sys.executable argv while the later mount order ensures a
+ # writable request mount cannot make the environment writable.
+ if self._venv_path is not None and self._venv_path.is_dir():
+ venv = str(self._venv_path)
+ argv += ["--ro-bind", venv, venv]
if request.workdir:
argv += ["--chdir", request.workdir]
- for key, value in request.env.items():
+ env = dict(request.env)
+ if self._venv_path is not None and self._venv_path.is_dir():
+ venv = str(self._venv_path)
+ venv_bin = str(self._venv_path / "bin")
+ base_path = env.get("PATH") or os.environ.get("PATH") or self._DEFAULT_PATH
+ path_entries = [part for part in base_path.split(os.pathsep) if part != venv_bin]
+ env["PATH"] = os.pathsep.join([venv_bin, *path_entries])
+ # The mounted environment is authoritative. A model-supplied env
+ # must not redirect Python tooling to an unmounted host path.
+ env["VIRTUAL_ENV"] = venv
+ for key, value in env.items():
argv += ["--setenv", key, value]
if request.argv:
# No shell in between: bwrap execs the vector directly.
diff --git a/tests/services/sandbox/test_sandbox.py b/tests/services/sandbox/test_sandbox.py
index b821a4b3a..30e9d425b 100644
--- a/tests/services/sandbox/test_sandbox.py
+++ b/tests/services/sandbox/test_sandbox.py
@@ -10,7 +10,13 @@ from deeptutor.services.sandbox.backends import BwrapBackend, RestrictedSubproce
from deeptutor.services.sandbox.config import SandboxSettings, build_backend
from deeptutor.services.sandbox.quota import QuotaExceeded, UserExecQuota
from deeptutor.services.sandbox.service import SandboxService
-from deeptutor.services.sandbox.spec import ExecRequest, ExecResult, IsolationLevel, ResourceLimits
+from deeptutor.services.sandbox.spec import (
+ ExecRequest,
+ ExecResult,
+ IsolationLevel,
+ Mount,
+ ResourceLimits,
+)
def test_backend_selection_runner_url() -> None:
@@ -61,6 +67,102 @@ def test_bwrap_binds_usr_local_when_available(tmp_path, monkeypatch: pytest.Monk
assert str(missing) not in argv
+def _bwrap_setenv(argv: list[str]) -> dict[str, str]:
+ return {
+ argv[index + 1]: argv[index + 2] for index, item in enumerate(argv) if item == "--setenv"
+ }
+
+
+def test_bwrap_mounts_only_the_active_virtualenv_read_only(tmp_path) -> None:
+ workspace = tmp_path / "workspace"
+ venv = workspace / ".venv"
+ (venv / "bin").mkdir(parents=True)
+
+ argv = BwrapBackend(venv_path=venv)._build_argv(
+ ExecRequest(
+ command="python -c 'import pptx'",
+ env={"PATH": "/custom/bin:/usr/bin", "VIRTUAL_ENV": "/untrusted"},
+ )
+ )
+ resolved_venv = str(venv.resolve())
+ ro_binds = [
+ tuple(argv[index + 1 : index + 3]) for index, item in enumerate(argv) if item == "--ro-bind"
+ ]
+ env = _bwrap_setenv(argv)
+
+ assert (resolved_venv, resolved_venv) in ro_binds
+ assert (str(workspace.resolve()), str(workspace.resolve())) not in ro_binds
+ assert env["VIRTUAL_ENV"] == resolved_venv
+ assert env["PATH"] == f"{resolved_venv}/bin:/custom/bin:/usr/bin"
+
+
+def test_bwrap_mounts_only_the_uv_python_runtime_roots(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ venv = tmp_path / "workspace" / ".venv"
+ (venv / "bin").mkdir(parents=True)
+ runtime = tmp_path / "uv" / "cpython-3.12.13-linux-x86_64"
+ runtime_alias = tmp_path / "uv" / "cpython-3.12-linux-x86_64"
+ (runtime / "bin").mkdir(parents=True)
+ (runtime / "lib").mkdir()
+ runtime_alias.symlink_to(runtime, target_is_directory=True)
+
+ monkeypatch.setattr("sys.prefix", str(venv))
+ monkeypatch.setattr("sys.base_prefix", str(runtime))
+ monkeypatch.setattr("sys.base_exec_prefix", str(runtime))
+ monkeypatch.setattr("sys._base_executable", str(runtime_alias / "bin" / "python3.12"))
+
+ argv = BwrapBackend()._build_argv(ExecRequest(command="python -V"))
+ ro_binds = [
+ tuple(argv[index + 1 : index + 3]) for index, item in enumerate(argv) if item == "--ro-bind"
+ ]
+
+ resolved_runtime = str(runtime.resolve())
+ assert (resolved_runtime, resolved_runtime) in ro_binds
+ assert (resolved_runtime, str(runtime_alias.absolute())) in ro_binds
+ assert (str(venv.resolve()), str(venv.resolve())) in ro_binds
+ assert (str((tmp_path / "uv").resolve()), str((tmp_path / "uv").resolve())) not in ro_binds
+ assert (str(tmp_path.resolve()), str(tmp_path.resolve())) not in ro_binds
+
+
+def test_bwrap_virtualenv_mount_overrides_a_writable_parent_mount(tmp_path) -> None:
+ workspace = tmp_path / "workspace"
+ venv = workspace / ".venv"
+ (venv / "bin").mkdir(parents=True)
+ resolved_workspace = str(workspace.resolve())
+ resolved_venv = str(venv.resolve())
+
+ argv = BwrapBackend(venv_path=venv)._build_argv(
+ ExecRequest(
+ command="true",
+ mounts=(Mount(resolved_workspace, resolved_workspace, read_only=False),),
+ )
+ )
+
+ writable_index = argv.index(resolved_workspace)
+ venv_index = argv.index(resolved_venv)
+ assert argv[writable_index - 1 : writable_index + 2] == [
+ "--bind",
+ resolved_workspace,
+ resolved_workspace,
+ ]
+ assert argv[venv_index - 1 : venv_index + 2] == [
+ "--ro-bind",
+ resolved_venv,
+ resolved_venv,
+ ]
+ assert venv_index > writable_index
+
+
+def test_bwrap_can_disable_virtualenv_inheritance() -> None:
+ argv = BwrapBackend(inherit_virtualenv=False)._build_argv(
+ ExecRequest(command="true", env={"PATH": "/custom/bin"})
+ )
+ env = _bwrap_setenv(argv)
+
+ assert env == {"PATH": "/custom/bin"}
+
+
@pytest.mark.asyncio
async def test_restricted_subprocess_runs() -> None:
backend = RestrictedSubprocessBackend()