"""Process sandbox backend using resource limits and sanitized environment.""" import asyncio import logging import os from pathlib import Path import resource 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 ProcessBackend(BaseSandboxBackend): """Fallback sandbox running subprocess with resource limits and stripped environment.""" def __init__(self) -> None: self.settings = get_settings() def is_available(self) -> bool: return True async def execute( self, cmd: list[str], workspace_dir: Path, timeout: int, allow_network: bool = False, env: Optional[dict[str, str]] = None, ) -> ExecutionResult: workspace_dir.mkdir(parents=True, exist_ok=True) mem_bytes = self.settings.SANDBOX_MEMORY_LIMIT_MB * 1024 * 1024 def _setup_child_limits() -> None: # Set new process group so we can cleanly kill all children os.setsid() try: # Limit virtual memory resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, mem_bytes)) except Exception: pass try: # Limit CPU time resource.setrlimit(resource.RLIMIT_CPU, (timeout + 5, timeout + 5)) except Exception: pass try: # Limit max open files resource.setrlimit(resource.RLIMIT_NOFILE, (128, 128)) except Exception: pass # Completely sanitize environment: do NOT leak host variables or secrets (.env) safe_env = { "PATH": os.environ.get("PATH", "/usr/bin:/bin"), "LANG": "C.UTF-8", "LC_ALL": "C.UTF-8", "HOME": str(workspace_dir), "TMPDIR": str(workspace_dir), "PYTHONIOENCODING": "utf-8", } if env: safe_env.update(env) start_time = time.monotonic() try: proc = await asyncio.create_subprocess_exec( *cmd, cwd=str(workspace_dir), env=safe_env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, preexec_fn=_setup_child_limits, ) 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("Process sandbox timed out after %ds", 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 Process sandbox: %s", e) return ExecutionResult( stdout="", stderr=f"Process execution error: {type(e).__name__}: {str(e)}", exit_code=-1, duration_seconds=round(duration, 3), timed_out=False, )