DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(runtime): tolerate bwrap loopback denial on modern Linux (#1516)
Frank_zhu7e55583107e5
diff --git a/deeptutor/services/sandbox/backends.py b/deeptutor/services/sandbox/backends.pyindex 86b9f1a26..cf598a2d1 100644--- a/deeptutor/services/sandbox/backends.py+++ b/deeptutor/services/sandbox/backends.py@@ -19,6 +19,7 @@ from __future__ import annotationsimport asynciofrom contextlib import suppressimport locale+import loggingimport osfrom pathlib import Pathimport shutil@@ -33,6 +34,8 @@ from deeptutor.services.sandbox.spec import (IsolationLevel,)+logger = logging.getLogger(__name__)+class SandboxBackend:"""Abstract execution backend."""@@ -136,6 +139,21 @@ class RunnerSidecarBackend(SandboxBackend):return False, f"runner unreachable: {type(exc).__name__}"+_LOOPBACK_DENIED_MARKER = "bwrap: loopback: Failed RTM_NEWADDR"+++def _is_bwrap_loopback_denied(result: ExecResult) -> bool:+ """Return True when bubblewrap aborted while configuring sandbox loopback.++ Ubuntu 24.04+ can deny ``RTM_NEWADDR`` inside an unprivileged netns+ (``kernel.apparmor_restrict_unprivileged_userns``). That failure is+ specific to loopback setup, not to the inner command.+ """+ if result.error or result.timed_out or result.exit_code == 0:+ return False+ return _LOOPBACK_DENIED_MARKER in (result.stderr or "")++class BwrapBackend(SandboxBackend):"""Bubblewrap mount-namespace isolation (Linux only)."""@@ -152,6 +170,7 @@ class BwrapBackend(SandboxBackend):inherit_virtualenv: bool = True,) -> None:self._bwrap = bwrap_path+ self._share_net = Falsedetected_prefix, uses_external_runtime = _active_python_prefix(inherit=inherit_virtualenv)if venv_path is not None:candidate = Path(venv_path).resolve()@@ -199,6 +218,9 @@ class BwrapBackend(SandboxBackend):self._bwrap,"--die-with-parent","--unshare-all",+ # Keep mount/PID isolation when the kernel denies loopback setup+ # inside a new netns (Ubuntu 24.04+ AppArmor userns restrictions).+ *(("--share-net",) if self._share_net else ()),"--new-session","--proc","/proc",@@ -247,8 +269,7 @@ class BwrapBackend(SandboxBackend):argv += ["/bin/sh", "-c", request.command]return argv- async def exec(self, request: ExecRequest) -> ExecResult:- argv = self._build_argv(request)+ async def _run_bwrap(self, argv: list[str], request: ExecRequest) -> ExecResult:try:process = await asyncio.create_subprocess_exec(*argv,@@ -264,15 +285,33 @@ class BwrapBackend(SandboxBackend):request.limits.max_output_chars,)+ async def exec(self, request: ExecRequest) -> ExecResult:+ result = await self._run_bwrap(self._build_argv(request), request)+ if not self._share_net and _is_bwrap_loopback_denied(result):+ logger.warning(+ "bwrap loopback setup denied (%s); retrying with --share-net",+ (result.stderr or "").strip() or f"exit {result.exit_code}",+ )+ self._share_net = True+ result = await self._run_bwrap(self._build_argv(request), request)+ return result+async def health(self) -> tuple[bool, str]:if shutil.which(self._bwrap) is None:return False, "bwrap not installed"# bwrap needs unprivileged user namespaces; a default-seccomp Docker# container blocks them, so confirm a trivial sandbox actually runs.+ # A non-zero exit with empty ``error`` still means the sandbox cannot+ # run (Ubuntu 24.04 loopback RTM_NEWADDR denial is the usual case).probe = ExecRequest(command="true")result = await self.exec(probe)- if result.error:- return False, result.error+ if result.error or result.exit_code != 0 or result.timed_out:+ detail = (+ result.error+ or (result.stderr.strip() if result.stderr else "")+ or f"bwrap probe exited with code {result.exit_code}"+ )+ return False, detailreturn True, "bwrap functional"diff --git a/deeptutor/services/sandbox/service.py b/deeptutor/services/sandbox/service.pyindex 5d1b020b5..946499839 100644--- a/deeptutor/services/sandbox/service.py+++ b/deeptutor/services/sandbox/service.py@@ -18,7 +18,11 @@ import asyncioimport loggingfrom deeptutor.services.i18n import t-from deeptutor.services.sandbox.backends import SandboxBackend+from deeptutor.services.sandbox.backends import (+ BwrapBackend,+ RestrictedSubprocessBackend,+ SandboxBackend,+)from deeptutor.services.sandbox.config import SandboxSettings, build_backendfrom deeptutor.services.sandbox.quota import QuotaExceeded, UserExecQuotafrom deeptutor.services.sandbox.spec import ExecRequest, ExecResult, IsolationLevel@@ -60,8 +64,38 @@ class SandboxService:type(self._backend).__name__,self._health_detail,)+ await self._try_subprocess_fallback()return bool(self._healthy)+ async def _try_subprocess_fallback(self) -> None:+ """Fall back to restricted subprocess when bwrap cannot run.++ Honours ``sandbox_allow_subprocess``. A down runner sidecar is left+ failed — the main process must not start executing untrusted shell.+ """+ if not self._settings.allow_subprocess:+ return+ if not isinstance(self._backend, BwrapBackend):+ return+ fallback = RestrictedSubprocessBackend()+ try:+ healthy, detail = await fallback.health()+ except Exception as exc:+ logger.warning("subprocess fallback health check failed: %s", exc)+ return+ if not healthy:+ logger.warning("subprocess fallback unhealthy: %s", detail)+ return+ logger.info(+ "sandbox backend %s failed (%s); falling back to %s",+ type(self._backend).__name__,+ self._health_detail,+ type(fallback).__name__,+ )+ self._backend = fallback+ self._healthy = True+ self._health_detail = "fallback subprocess functional"+async def isolation_level(self) -> IsolationLevel:"""Effective isolation level (OFF when no healthy backend)."""if not await self._ensure_healthy() or self._backend is None:diff --git a/tests/services/sandbox/test_sandbox.py b/tests/services/sandbox/test_sandbox.pyindex 6189fd278..946689416 100644--- a/tests/services/sandbox/test_sandbox.py+++ b/tests/services/sandbox/test_sandbox.py@@ -12,6 +12,7 @@ import pytestfrom deeptutor.services.sandbox.backends import (BwrapBackend,RestrictedSubprocessBackend,+ RunnerSidecarBackend,_decode_process_output,)from deeptutor.services.sandbox.config import SandboxSettings, build_backend@@ -327,6 +328,108 @@ async def test_service_runs_with_subprocess() -> None:assert "sandboxed" in result.stdout+_LOOPBACK_STDERR = "bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted\n"+++async def test_bwrap_health_treats_loopback_denial_as_unhealthy(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A bwrap probe that exits 1 with empty ``error`` is not healthy (#1516)."""+ backend = BwrapBackend()+ monkeypatch.setattr(+ "deeptutor.services.sandbox.backends.shutil.which",+ lambda _name: "/usr/bin/bwrap",+ )++ async def fake_exec(_request: ExecRequest) -> ExecResult:+ return ExecResult(stderr=_LOOPBACK_STDERR, exit_code=1)++ monkeypatch.setattr(backend, "exec", fake_exec)++ healthy, detail = await backend.health()+ assert healthy is False+ assert "RTM_NEWADDR" in detail+ assert "Operation not permitted" in detail+++async def test_bwrap_retries_with_shared_net_after_loopback_denial() -> None:+ """Ubuntu 24.04 can deny loopback setup; keep mount isolation via --share-net."""+ backend = BwrapBackend()+ calls: list[list[str]] = []++ async def fake_run(argv: list[str], _request: ExecRequest) -> ExecResult:+ calls.append(list(argv))+ if "--share-net" not in argv:+ return ExecResult(stderr=_LOOPBACK_STDERR, exit_code=1)+ return ExecResult(stdout="ok\n", exit_code=0)++ backend._run_bwrap = fake_run # type: ignore[method-assign]++ result = await backend.exec(ExecRequest(command="true"))++ assert result.exit_code == 0+ assert result.stdout.strip() == "ok"+ assert len(calls) == 2+ assert "--unshare-all" in calls[0] and "--share-net" not in calls[0]+ assert "--share-net" in calls[1]+ # Later execs must not pay the failed loopback spawn again.+ second = await backend.exec(ExecRequest(command="true"))+ assert second.exit_code == 0+ assert len(calls) == 3+ assert "--share-net" in calls[2]+++async def test_service_falls_back_to_subprocess_when_bwrap_unhealthy() -> None:+ """``sandbox_allow_subprocess`` must recover partner/file exec when bwrap cannot run."""+ svc = SandboxService(SandboxSettings(allow_subprocess=True))++ class UnhealthyBwrap(BwrapBackend):+ async def health(self) -> tuple[bool, str]:+ return False, _LOOPBACK_STDERR.strip()++ svc._backend = UnhealthyBwrap()++ assert await svc.isolation_level() is IsolationLevel.APPLICATION+ assert isinstance(svc._backend, RestrictedSubprocessBackend)+ result = await svc.run(ExecRequest(command="echo recovered"), user_id="u1")+ assert "recovered" in result.stdout+++async def test_service_surfaces_bwrap_failure_when_subprocess_disallowed() -> None:+ svc = SandboxService(SandboxSettings(allow_subprocess=False))++ class UnhealthyBwrap(BwrapBackend):+ async def health(self) -> tuple[bool, str]:+ return False, _LOOPBACK_STDERR.strip()++ svc._backend = UnhealthyBwrap()++ assert await svc.isolation_level() is IsolationLevel.OFF+ assert isinstance(svc._backend, UnhealthyBwrap)+ result = await svc.run(ExecRequest(command="echo hi"), user_id="u1")+ assert not result.ok+ assert "RTM_NEWADDR" in result.error+++async def test_service_does_not_fallback_from_unhealthy_runner() -> None:+ """A down runner sidecar must not start executing untrusted shell in-process."""+ svc = SandboxService(SandboxSettings(allow_subprocess=True))++ class UnhealthyRunner(RunnerSidecarBackend):+ async def health(self) -> tuple[bool, str]:+ return False, "runner unreachable"++ svc._backend = UnhealthyRunner("http://sandbox-runner:8900")++ assert await svc.isolation_level() is IsolationLevel.OFF+ assert isinstance(svc._backend, UnhealthyRunner)++@pytest.mark.asyncioasync def test_quota_rate_limit() -> None:quota = UserExecQuota(max_concurrent=5, max_per_minute=2)