165 lines
6.5 KiB
Python
165 lines
6.5 KiB
Python
"""Sandbox Manager for managing workspace files and selecting the active isolation backend."""
|
|
|
|
import logging
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
from typing import Optional
|
|
|
|
from extensions.sandbox.base import BaseSandboxBackend, ExecutionResult
|
|
from extensions.sandbox.bwrap_backend import BubblewrapBackend
|
|
from extensions.sandbox.docker_backend import DockerBackend
|
|
from extensions.sandbox.process_backend import ProcessBackend
|
|
from homeagent.config import get_settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class SandboxManager:
|
|
"""Manages the isolated workspace and executes code/commands via the selected sandbox backend."""
|
|
|
|
def __init__(self) -> None:
|
|
self.settings = get_settings()
|
|
self.workspace_dir: Path = self.settings.DATA_DIR / "sandbox_workspace"
|
|
self.workspace_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
self._bwrap = BubblewrapBackend()
|
|
self._docker = DockerBackend()
|
|
self._process = ProcessBackend()
|
|
self._active_backend: Optional[BaseSandboxBackend] = None
|
|
|
|
def get_backend(self) -> BaseSandboxBackend:
|
|
if self._active_backend is not None:
|
|
return self._active_backend
|
|
|
|
choice = self.settings.SANDBOX_BACKEND.lower()
|
|
|
|
if choice == "bwrap":
|
|
if self._bwrap.is_available():
|
|
self._active_backend = self._bwrap
|
|
logger.info("Sandbox using Bubblewrap (bwrap) backend.")
|
|
return self._active_backend
|
|
logger.warning("Configured backend 'bwrap' unavailable, falling back to process.")
|
|
|
|
elif choice == "docker":
|
|
if self._docker.is_available():
|
|
self._active_backend = self._docker
|
|
logger.info("Sandbox using Docker backend.")
|
|
return self._active_backend
|
|
logger.warning("Configured backend 'docker' unavailable, falling back to process.")
|
|
|
|
elif choice == "process":
|
|
self._active_backend = self._process
|
|
logger.info("Sandbox using Process backend.")
|
|
return self._active_backend
|
|
|
|
# Auto detection: bwrap -> docker -> process
|
|
if self._bwrap.is_available():
|
|
self._active_backend = self._bwrap
|
|
logger.info("Sandbox auto-selected Bubblewrap (bwrap) backend.")
|
|
elif self._docker.is_available():
|
|
self._active_backend = self._docker
|
|
logger.info("Sandbox auto-selected Docker backend.")
|
|
else:
|
|
self._active_backend = self._process
|
|
logger.info("Sandbox auto-selected Process backend.")
|
|
|
|
return self._active_backend
|
|
|
|
def get_backend_name(self) -> str:
|
|
backend = self.get_backend()
|
|
if isinstance(backend, BubblewrapBackend):
|
|
return "Bubblewrap (bwrap, Linux Namespaces)"
|
|
if isinstance(backend, DockerBackend):
|
|
return "Docker Container"
|
|
return "Process Sandbox (Resource Limits)"
|
|
|
|
def _resolve_safe_path(self, filename: str) -> Path:
|
|
"""Resolve path inside workspace and prevent directory traversal outside workspace."""
|
|
clean_name = filename.strip().lstrip("/\\")
|
|
target_path = (self.workspace_dir / clean_name).resolve()
|
|
workspace_resolved = self.workspace_dir.resolve()
|
|
|
|
if not str(target_path).startswith(str(workspace_resolved)):
|
|
raise ValueError(f"Access denied: path '{filename}' points outside the sandbox workspace.")
|
|
return target_path
|
|
|
|
def write_file(self, filename: str, content: str) -> Path:
|
|
"""Safely write a file to the sandbox workspace."""
|
|
path = self._resolve_safe_path(filename)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(content, encoding="utf-8")
|
|
return path
|
|
|
|
def read_file(self, filename: str, max_chars: int = 8000) -> str:
|
|
"""Safely read a file from the sandbox workspace."""
|
|
path = self._resolve_safe_path(filename)
|
|
if not path.exists() or not path.is_file():
|
|
raise FileNotFoundError(f"File '{filename}' does not exist in sandbox workspace.")
|
|
|
|
content = path.read_text(encoding="utf-8", errors="replace")
|
|
if len(content) > max_chars:
|
|
content = content[:max_chars] + f"\n\n... [Файл обрезан, показано первые {max_chars} символов]"
|
|
return content
|
|
|
|
def clean_workspace(self) -> None:
|
|
"""Remove all files inside sandbox workspace."""
|
|
if self.workspace_dir.exists():
|
|
for item in self.workspace_dir.iterdir():
|
|
try:
|
|
if item.is_dir():
|
|
shutil.rmtree(item)
|
|
else:
|
|
item.unlink()
|
|
except Exception as e:
|
|
logger.warning("Could not delete workspace item %s: %s", item, e)
|
|
|
|
async def run_code(
|
|
self,
|
|
code: str,
|
|
language: str = "python",
|
|
timeout: Optional[int] = None,
|
|
) -> ExecutionResult:
|
|
"""Execute code in the isolated sandbox."""
|
|
lang = language.lower().strip()
|
|
effective_timeout = timeout or self.settings.SANDBOX_TIMEOUT_SECONDS
|
|
backend = self.get_backend()
|
|
|
|
if lang in ("python", "py", "python3"):
|
|
script_path = self.write_file("main.py", code)
|
|
cmd = ["python3", "main.py"]
|
|
elif lang in ("bash", "sh"):
|
|
script_path = self.write_file("script.sh", code)
|
|
cmd = ["bash", "script.sh"]
|
|
elif lang in ("javascript", "js", "node"):
|
|
script_path = self.write_file("index.js", code)
|
|
cmd = ["node", "index.js"]
|
|
else:
|
|
raise ValueError(
|
|
f"Unsupported language '{language}'. Supported languages: 'python', 'bash', 'javascript'."
|
|
)
|
|
|
|
return await backend.execute(
|
|
cmd=cmd,
|
|
workspace_dir=self.workspace_dir,
|
|
timeout=effective_timeout,
|
|
allow_network=self.settings.SANDBOX_ALLOW_NETWORK,
|
|
)
|
|
|
|
async def run_command(
|
|
self,
|
|
command: str,
|
|
timeout: Optional[int] = None,
|
|
) -> ExecutionResult:
|
|
"""Execute a shell command inside the isolated sandbox."""
|
|
effective_timeout = timeout or self.settings.SANDBOX_TIMEOUT_SECONDS
|
|
backend = self.get_backend()
|
|
cmd = ["bash", "-c", command]
|
|
|
|
return await backend.execute(
|
|
cmd=cmd,
|
|
workspace_dir=self.workspace_dir,
|
|
timeout=effective_timeout,
|
|
allow_network=self.settings.SANDBOX_ALLOW_NETWORK,
|
|
)
|