Files
barsic/extensions/sandbox/bwrap_backend.py
T
2026-11-07 22:34:12 +03:00

136 lines
5.3 KiB
Python

"""Bubblewrap (bwrap) sandbox backend providing Linux namespace isolation."""
import asyncio
import logging
import os
from pathlib import Path
import shutil
import signal
import time
from typing import Optional
from extensions.sandbox.base import BaseSandboxBackend, ExecutionResult
from homeagent.config import get_settings
logger = logging.getLogger(__name__)
class BubblewrapBackend(BaseSandboxBackend):
"""Executes processes inside an unprivileged Bubblewrap container namespace."""
def __init__(self) -> None:
self.settings = get_settings()
self.bwrap_bin = shutil.which("bwrap")
def is_available(self) -> bool:
return bool(self.bwrap_bin and os.path.exists("/usr"))
async def execute(
self,
cmd: list[str],
workspace_dir: Path,
timeout: int,
allow_network: bool = False,
env: Optional[dict[str, str]] = None,
) -> ExecutionResult:
if not self.bwrap_bin:
raise RuntimeError("bwrap executable is not installed or not in PATH.")
workspace_dir.mkdir(parents=True, exist_ok=True)
mem_kb = self.settings.SANDBOX_MEMORY_LIMIT_MB * 1024
bwrap_args: list[str] = [
self.bwrap_bin,
"--ro-bind", "/usr", "/usr",
"--proc", "/proc",
"--dev", "/dev",
"--tmpfs", "/tmp",
"--bind", str(workspace_dir), "/workspace",
"--chdir", "/workspace",
"--die-with-parent",
"--setenv", "PATH", "/usr/bin:/bin",
"--setenv", "HOME", "/workspace",
"--setenv", "LANG", "C.UTF-8",
"--setenv", "LC_ALL", "C.UTF-8",
"--setenv", "PYTHONIOENCODING", "utf-8",
]
# Standard symlinks across modern Linux
if os.path.exists("/lib64"):
bwrap_args.extend(["--symlink", "usr/lib64", "/lib64"])
if os.path.exists("/lib"):
bwrap_args.extend(["--symlink", "usr/lib", "/lib"])
if os.path.exists("/bin"):
bwrap_args.extend(["--symlink", "usr/bin", "/bin"])
if os.path.exists("/sbin"):
bwrap_args.extend(["--symlink", "usr/bin", "/sbin"])
# Network isolation
if not allow_network:
bwrap_args.append("--unshare-all")
else:
bwrap_args.extend(["--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup"])
if os.path.exists("/etc/resolv.conf"):
bwrap_args.extend(["--ro-bind", "/etc/resolv.conf", "/etc/resolv.conf"])
if os.path.exists("/etc/ssl"):
bwrap_args.extend(["--ro-bind", "/etc/ssl", "/etc/ssl"])
if os.path.exists("/etc/ca-certificates"):
bwrap_args.extend(["--ro-bind", "/etc/ca-certificates", "/etc/ca-certificates"])
# Custom environment variables
if env:
for k, v in env.items():
bwrap_args.extend(["--setenv", k, v])
# Apply memory ulimit via bash wrapper
quoted_cmd = " ".join(f'"{c}"' if " " in c else c for c in cmd)
wrapped_script = f"ulimit -v {mem_kb} 2>/dev/null; exec {quoted_cmd}"
full_cmd = bwrap_args + ["bash", "-c", wrapped_script]
start_time = time.monotonic()
try:
proc = await asyncio.create_subprocess_exec(
*full_cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
preexec_fn=os.setsid,
)
try:
stdout_data, stderr_data = await asyncio.wait_for(
proc.communicate(),
timeout=float(timeout),
)
duration = time.monotonic() - start_time
return ExecutionResult(
stdout=stdout_data.decode("utf-8", errors="replace"),
stderr=stderr_data.decode("utf-8", errors="replace"),
exit_code=proc.returncode if proc.returncode is not None else -1,
duration_seconds=round(duration, 3),
timed_out=False,
)
except asyncio.TimeoutError:
duration = time.monotonic() - start_time
logger.warning("Sandbox process timed out after %ds, killing process group", timeout)
try:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
except ProcessLookupError:
pass
return ExecutionResult(
stdout="",
stderr=f"Ошибка: превышен максимальный таймаут выполнения ({timeout} сек). Процесс принудительно остановлен.",
exit_code=-1,
duration_seconds=round(duration, 3),
timed_out=True,
)
except Exception as e:
duration = time.monotonic() - start_time
logger.error("Failed to execute in Bubblewrap sandbox: %s", e)
return ExecutionResult(
stdout="",
stderr=f"Bubblewrap execution error: {type(e).__name__}: {str(e)}",
exit_code=-1,
duration_seconds=round(duration, 3),
timed_out=False,
)