Option C Tools
Loading...
Searching...
No Matches
sandbox.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# oct/mcp/sandbox.py
4
5"""
6Purpose
7-------
8Execution Sandbox (Layer 4, outer wrapper) for the ``oct-mcp``
9six-layer pipeline. Provides environment sanitisation, working-directory
10pinning, timeout enforcement, and output-size limiting for subprocess
11execution.
12
13Phase 5C adds pluggable OS-level sandbox *backends*:
14
15* :class:`NativeBackend` — existing behavior (subprocess + env
16 sanitization). Always available; default on Windows.
17* :class:`BubblewrapBackend` — Linux only. Wraps every command in
18 ``bwrap --unshare-net --die-with-parent``. Requires ``bwrap`` in PATH.
19* :class:`SandboxExecBackend` — macOS only. Prepends
20 ``sandbox-exec -p "(deny network*)(allow default)"``. Requires
21 ``sandbox-exec`` in PATH.
22
23Use :func:`make_sandbox_backend` to select the appropriate backend based
24on :class:`~oct.mcp.config.McpConfig`.
25
26Responsibilities
27----------------
28- Strip sensitive environment variables before forking (``PYTHONPATH``,
29 common secret-named vars).
30- Pin the subprocess working directory to the validated project root.
31- Enforce per-tool timeouts and kill the process on expiry.
32- Cap combined stdout+stderr output to ``max_output_bytes``.
33- Never use ``shell=True``.
34- Return a :class:`SandboxResult` — never raise for subprocess errors.
35
36Diagnostics
37-----------
38Domain: MCP
39Levels:
40 L1 — errors: process launch failures, unexpected errors
41 L2 — lifecycle: process start, process end, backend selection
42 L3 — command details (argv)
43 L4 — deep trace: per-line output, env keys
44
45Contracts
46---------
47- ``shell=False`` is enforced unconditionally in all backends — no
48 caller path can override it.
49- :meth:`SandboxExecutor.run` never raises. Any ``OSError`` or
50 ``subprocess.SubprocessError`` is caught, logged at level 1, and
51 returned as a ``SandboxResult`` with a non-zero exit code.
52- The sanitised environment always preserves ``PATH``, ``HOME``,
53 ``LANG``, ``TERM``, ``USER``, ``USERNAME``, ``LOGNAME``,
54 ``VIRTUAL_ENV``, ``CONDA_DEFAULT_ENV``, and
55 ``OCT_MCP_SESSION_ID`` / ``OCT_MCP_REQUEST_ID`` correlation IDs.
56- :func:`make_sandbox_backend` never raises — it always returns a
57 usable backend (falls back to :class:`NativeBackend`).
58"""
59
60from __future__ import annotations
61
62import os
63import shutil
64import subprocess
65import sys
66from dataclasses import dataclass
67from pathlib import Path
68from typing import Protocol, runtime_checkable
69
70try:
71 from oc_diagnostics import _dbg as _real_dbg
72
73 def _dbg(*args, **kwargs) -> None:
74 _real_dbg(*args, **kwargs)
75except ImportError: # pragma: no cover
76 def _dbg(*args, **kwargs) -> None:
77 return None
78
79
80# ---------------------------------------------------------------------
81# Constants
82# ---------------------------------------------------------------------
83
84#: Environment variable keys (or key substrings, case-insensitive) that
85#: must be stripped before passing the environment to a subprocess.
86#: Full key names are exact-matched first; substrings are checked second.
87_SENSITIVE_ENV_EXACT: frozenset[str] = frozenset({
88 "PYTHONPATH",
89})
90
91#: Case-insensitive substrings. Any env key containing one of these
92#: tokens is stripped.
93_SENSITIVE_ENV_SUBSTRINGS: tuple[str, ...] = (
94 "api_key", "apikey",
95 "password", "passwd", "pwd",
96 "secret",
97 "token",
98 "credentials",
99 "private_key",
100 "auth",
101 "access_key",
102)
103
104#: Environment variable keys that are always preserved regardless of
105#: name-based filtering.
106_SAFE_ENV_KEYS: frozenset[str] = frozenset({
107 "PATH",
108 "HOME",
109 "LANG",
110 "LC_ALL",
111 "LC_CTYPE",
112 "TERM",
113 "COLORTERM",
114 "USER",
115 "USERNAME",
116 "LOGNAME",
117 "USERPROFILE", # Windows home directory
118 "SYSTEMROOT", # Windows system root
119 "VIRTUAL_ENV",
120 "CONDA_DEFAULT_ENV",
121 "CONDA_PREFIX",
122 "OCT_MCP_SESSION_ID",
123 "OCT_MCP_REQUEST_ID",
124 # Diagnostics env vars
125 "OCT_DBG_LEVEL",
126 "OCT_DBG_FILE",
127})
128
129
130# ---------------------------------------------------------------------
131# Environment sanitisation (shared by all backends)
132# ---------------------------------------------------------------------
133
134
135def _sanitise_env(project_root: Path) -> dict[str, str]:
136 """Build a sanitised environment for subprocess execution.
137
138 Starts from ``os.environ``, preserves :data:`_SAFE_ENV_KEYS`,
139 strips :data:`_SENSITIVE_ENV_EXACT` exact keys and anything whose
140 key contains a :data:`_SENSITIVE_ENV_SUBSTRINGS` token (case-
141 insensitive), and adds ``OCT_MCP_CWD`` so the subprocess knows
142 its sandboxed working directory.
143
144 Returns
145 -------
146 A new ``dict[str, str]`` — never modifies ``os.environ``.
147 """
148 func = "_sanitise_env"
149 clean: dict[str, str] = {}
150
151 for key, value in os.environ.items():
152 key_upper = key.upper()
153
154 # Always keep safe keys.
155 if key_upper in {k.upper() for k in _SAFE_ENV_KEYS}:
156 clean[key] = value
157 continue
158
159 # Strip exact sensitive keys.
160 if key_upper in {k.upper() for k in _SENSITIVE_ENV_EXACT}:
161 _dbg("MCP", func, f"stripped env key={key}", 4)
162 continue
163
164 # Strip substring-matched keys.
165 if any(sub in key_upper.lower() for sub in _SENSITIVE_ENV_SUBSTRINGS):
166 _dbg("MCP", func, f"stripped env key={key} (substring match)", 4)
167 continue
168
169 clean[key] = value
170
171 # Pin working directory as an env var for informational purposes.
172 clean["OCT_MCP_CWD"] = str(project_root)
173
174 return clean
175
176
177# ---------------------------------------------------------------------
178# Result type
179# ---------------------------------------------------------------------
180
181
182@dataclass
184 """Result of a sandboxed subprocess execution.
185
186 Attributes
187 ----------
188 exit_code
189 The subprocess return code, or ``1`` on launch failure.
190 stdout
191 Captured standard output (possibly truncated).
192 stderr
193 Captured standard error (possibly truncated).
194 timed_out
195 ``True`` if the process was killed due to timeout.
196 output_truncated
197 ``True`` if combined stdout+stderr exceeded ``max_output_bytes``.
198 error_message
199 Non-empty if the process could not be launched (e.g. not found
200 on PATH). Distinct from stderr — set on ``OSError``.
201 """
202
203 exit_code: int
204 stdout: str
205 stderr: str
206 timed_out: bool = False
207 output_truncated: bool = False
208 error_message: str = ""
209
210
211# ---------------------------------------------------------------------
212# Backend protocol
213# ---------------------------------------------------------------------
214
215
216@runtime_checkable
217class SandboxBackend(Protocol):
218 """Protocol for OS-level sandbox backends.
219
220 Each backend wraps the subprocess call with platform-specific
221 isolation (network namespace, resource limits, etc.). The backend
222 receives a sanitised environment and returns raw
223 ``(exit_code, stdout, stderr)`` — output capping and error handling
224 live in :class:`SandboxExecutor`.
225 """
226
227 def run(
228 self,
229 cmd: list[str],
230 env: dict[str, str],
231 cwd: Path,
232 timeout: int,
233 memory_limit_bytes: int | None,
234 ) -> tuple[int, str, str]:
235 """Run *cmd* and return ``(exit_code, stdout, stderr)``.
236
237 Parameters
238 ----------
239 cmd
240 Command + arguments list. Must not use ``shell=True``.
241 env
242 Sanitised environment dict.
243 cwd
244 Working directory (validated project root).
245 timeout
246 Maximum wall-clock seconds.
247 memory_limit_bytes
248 Virtual memory ceiling in bytes, or ``None`` to skip.
249 Implementations on POSIX apply this via ``setrlimit``; on
250 Windows it is silently ignored.
251 """
252 ...
253
254
255# ---------------------------------------------------------------------
256# Concrete backends
257# ---------------------------------------------------------------------
258
259
261 """Subprocess-only backend — existing Phase 5A/5B behavior.
262
263 On POSIX, when *memory_limit_bytes* is non-None and non-zero,
264 applies ``resource.setrlimit(RLIMIT_AS, ...)`` via ``preexec_fn``
265 to limit virtual address space. On Windows the limit is silently
266 ignored (use Docker for Windows memory enforcement).
267 """
268
269 def run(
270 self,
271 cmd: list[str],
272 env: dict[str, str],
273 cwd: Path,
274 timeout: int,
275 memory_limit_bytes: int | None,
276 ) -> tuple[int, str, str]:
277 preexec = None
278 if memory_limit_bytes and os.name != "nt":
279 limit = memory_limit_bytes
280
281 def _preexec() -> None:
282 import resource
283 resource.setrlimit(
284 resource.RLIMIT_AS, (limit, limit)
285 )
286
287 preexec = _preexec
288
289 result = subprocess.run(
290 cmd,
291 capture_output=True,
292 text=True,
293 encoding="utf-8",
294 errors="replace",
295 cwd=str(cwd),
296 env=env,
297 timeout=timeout,
298 shell=False, # NEVER shell=True
299 preexec_fn=preexec,
300 )
301 return result.returncode, result.stdout or "", result.stderr or ""
302
303
305 """Linux bubblewrap backend — network-isolated, die-with-parent.
306
307 Wraps every command in ``bwrap --unshare-net --die-with-parent``.
308 Requires ``bwrap`` to be available in PATH.
309
310 Network isolation is provided by ``--unshare-net``. The project
311 root is bind-mounted read-write; system paths are read-only.
312 """
313
314 def _bwrap_cmd(self, cmd: list[str], cwd: Path) -> list[str]:
315 """Build the full ``bwrap ... -- cmd`` invocation."""
316 bwrap = ["bwrap"]
317
318 # Read-only system mounts (common paths; skip missing ones silently).
319 for ro_path in ("/usr", "/lib", "/lib64", "/bin", "/sbin", "/etc",
320 "/run", "/opt"):
321 if Path(ro_path).exists():
322 bwrap += ["--ro-bind", ro_path, ro_path]
323
324 bwrap += [
325 "--proc", "/proc",
326 "--dev", "/dev",
327 "--tmpfs", "/tmp",
328 # Project root bind-mounted read-write.
329 "--bind", str(cwd), str(cwd),
330 "--chdir", str(cwd),
331 # Network isolation.
332 "--unshare-net",
333 # Kill sandbox when the parent exits.
334 "--die-with-parent",
335 "--",
336 ]
337 return bwrap + cmd
338
339 def run(
340 self,
341 cmd: list[str],
342 env: dict[str, str],
343 cwd: Path,
344 timeout: int,
345 memory_limit_bytes: int | None,
346 ) -> tuple[int, str, str]:
347 wrapped = self._bwrap_cmd(cmd, cwd)
348 result = subprocess.run(
349 wrapped,
350 capture_output=True,
351 text=True,
352 encoding="utf-8",
353 errors="replace",
354 cwd=str(cwd),
355 env=env,
356 timeout=timeout,
357 shell=False,
358 )
359 return result.returncode, result.stdout or "", result.stderr or ""
360
361
363 """macOS ``sandbox-exec`` backend — network-denied policy.
364
365 Prepends ``sandbox-exec -p "<profile>"`` to every command.
366 Requires ``sandbox-exec`` to be available in PATH.
367
368 The policy denies all network access while allowing everything else
369 (file I/O, process creation, etc.) needed to run ``oct`` commands.
370 """
371
372 _PROFILE: str = "(version 1)(deny network*)(allow default)"
373
374 def _sandboxed_cmd(self, cmd: list[str]) -> list[str]:
375 """Return ``["sandbox-exec", "-p", PROFILE] + cmd``."""
376 return ["sandbox-exec", "-p", self._PROFILE] + cmd
377
378 def run(
379 self,
380 cmd: list[str],
381 env: dict[str, str],
382 cwd: Path,
383 timeout: int,
384 memory_limit_bytes: int | None,
385 ) -> tuple[int, str, str]:
386 wrapped = self._sandboxed_cmd(cmd)
387 result = subprocess.run(
388 wrapped,
389 capture_output=True,
390 text=True,
391 encoding="utf-8",
392 errors="replace",
393 cwd=str(cwd),
394 env=env,
395 timeout=timeout,
396 shell=False,
397 )
398 return result.returncode, result.stdout or "", result.stderr or ""
399
400
401# ---------------------------------------------------------------------
402# Backend factory
403# ---------------------------------------------------------------------
404
405
406def make_sandbox_backend(config: object) -> SandboxBackend:
407 """Select and return the best available :class:`SandboxBackend`.
408
409 Parameters
410 ----------
411 config
412 A :class:`~oct.mcp.config.McpConfig` instance. Reads the
413 ``sandbox_backend`` field (``"auto"`` / ``"native"`` /
414 ``"bubblewrap"`` / ``"sandbox_exec"``) and ``memory_limit_mb``.
415
416 Returns
417 -------
418 A concrete backend instance. On ``"auto"``, picks:
419
420 * :class:`BubblewrapBackend` on Linux when ``bwrap`` is in PATH.
421 * :class:`SandboxExecBackend` on macOS when ``sandbox-exec`` is in PATH.
422 * :class:`NativeBackend` otherwise (always safe).
423
424 When a *specific* backend is forced (e.g. ``"bubblewrap"``) but its
425 binary is not found, raises :exc:`RuntimeError`.
426
427 Never raises on ``"auto"`` or ``"native"`` — always returns a
428 usable backend.
429 """
430 func = "make_sandbox_backend"
431 name: str = getattr(config, "sandbox_backend", "auto")
432
433 if name == "bubblewrap":
434 if not shutil.which("bwrap"):
435 raise RuntimeError(
436 "sandbox_backend='bubblewrap' requested but 'bwrap' was not "
437 "found in PATH. Install bubblewrap or set sandbox_backend='auto'."
438 )
439 _dbg("MCP", func, "backend=BubblewrapBackend (forced)", 2)
440 return BubblewrapBackend()
441
442 if name == "sandbox_exec":
443 if not shutil.which("sandbox-exec"):
444 raise RuntimeError(
445 "sandbox_backend='sandbox_exec' requested but 'sandbox-exec' "
446 "was not found in PATH. This backend requires macOS."
447 )
448 _dbg("MCP", func, "backend=SandboxExecBackend (forced)", 2)
449 return SandboxExecBackend()
450
451 if name == "auto":
452 if sys.platform == "linux" and shutil.which("bwrap"):
453 _dbg("MCP", func, "backend=BubblewrapBackend (auto, Linux)", 2)
454 return BubblewrapBackend()
455 if sys.platform == "darwin" and shutil.which("sandbox-exec"):
456 _dbg("MCP", func, "backend=SandboxExecBackend (auto, macOS)", 2)
457 return SandboxExecBackend()
458
459 # "native" or auto-fallback (e.g. Windows, or no bwrap/sandbox-exec found).
460 _dbg("MCP", func, "backend=NativeBackend", 2)
461 return NativeBackend()
462
463
464# ---------------------------------------------------------------------
465# Sandbox executor
466# ---------------------------------------------------------------------
467
468
470 """Sandboxed subprocess runner for the MCP execution layer.
471
472 Wraps a :class:`SandboxBackend` with environment sanitisation,
473 output capping, and error handling. A single :class:`SandboxExecutor`
474 instance may be reused across multiple tool calls within the same
475 server session.
476
477 Parameters
478 ----------
479 backend
480 OS-level isolation backend. Defaults to :class:`NativeBackend`
481 when not supplied (Phase 5A/5B backward compatibility).
482 memory_limit_mb
483 Per-subprocess virtual memory limit in megabytes. ``0`` means
484 no limit. Forwarded to the backend as bytes. POSIX only —
485 silently ignored on Windows.
486 """
487
489 self,
490 backend: SandboxBackend | None = None,
491 memory_limit_mb: int = 0,
492 ) -> None:
493 self._backend: SandboxBackend = backend if backend is not None else NativeBackend()
494 self._memory_limit_bytes: int | None = (
495 memory_limit_mb * 1024 * 1024 if memory_limit_mb > 0 else None
496 )
497
498 def run(
499 self,
500 cmd: list[str],
501 cwd: Path,
502 timeout: int,
503 max_output_bytes: int = 1_048_576,
504 ) -> SandboxResult:
505 """Execute *cmd* in a sanitised environment under *cwd*.
506
507 Parameters
508 ----------
509 cmd
510 The command and arguments to run. Must not contain shell
511 metacharacters — this is enforced by passing ``shell=False``
512 in every backend.
513 cwd
514 Working directory, pinned to the validated project root.
515 timeout
516 Maximum wall-clock seconds before the process is killed.
517 max_output_bytes
518 Combined stdout+stderr cap. When exceeded, output is
519 truncated and :attr:`SandboxResult.output_truncated` is set.
520
521 Returns
522 -------
523 :class:`SandboxResult` — never raises.
524 """
525 func = "SandboxExecutor.run"
526 _dbg("MCP", func, f"cmd={cmd!r} cwd={cwd} timeout={timeout}s", 3)
527
528 env = _sanitise_env(cwd)
529
530 try:
531 exit_code, stdout, stderr = self._backend.run(
532 cmd=cmd,
533 env=env,
534 cwd=cwd,
535 timeout=timeout,
536 memory_limit_bytes=self._memory_limit_bytes,
537 )
538 truncated = False
539
540 # Enforce combined output cap.
541 combined_bytes = len(
542 (stdout + stderr).encode("utf-8", errors="replace")
543 )
544 if combined_bytes > max_output_bytes:
545 stdout_bytes = stdout.encode("utf-8", errors="replace")
546 if len(stdout_bytes) > max_output_bytes:
547 stdout = stdout_bytes[:max_output_bytes].decode(
548 "utf-8", errors="replace"
549 )
550 stderr = ""
551 else:
552 remaining = max_output_bytes - len(stdout_bytes)
553 stderr = (
554 stderr.encode("utf-8", errors="replace")[:remaining]
555 .decode("utf-8", errors="replace")
556 )
557 truncated = True
558 _dbg(
559 "MCP", func,
560 f"output truncated combined_bytes={combined_bytes} "
561 f"limit={max_output_bytes}",
562 2,
563 )
564
565 _dbg(
566 "MCP", func,
567 f"exit_code={exit_code} truncated={truncated}",
568 2,
569 )
570 return SandboxResult(
571 exit_code=exit_code,
572 stdout=stdout,
573 stderr=stderr,
574 timed_out=False,
575 output_truncated=truncated,
576 )
577
578 except subprocess.TimeoutExpired:
579 _dbg("MCP", func, f"SYSTEM_ERROR: timeout after {timeout}s cmd={cmd!r}", 1)
580 return SandboxResult(
581 exit_code=1,
582 stdout="",
583 stderr=f"Process timed out after {timeout} seconds.",
584 timed_out=True,
585 )
586 except FileNotFoundError:
587 msg = f"Command not found: {cmd[0]!r}. Is 'oct' installed on PATH?"
588 _dbg("MCP", func, f"SYSTEM_ERROR: {msg}", 1)
589 return SandboxResult(
590 exit_code=1,
591 stdout="",
592 stderr=msg,
593 error_message=msg,
594 )
595 except OSError as exc:
596 msg = f"Failed to launch subprocess: {exc}"
597 _dbg("MCP", func, f"SYSTEM_ERROR: {msg}", 1)
598 return SandboxResult(
599 exit_code=1,
600 stdout="",
601 stderr=msg,
602 error_message=msg,
603 )
tuple[int, str, str] run(self, list[str] cmd, dict[str, str] env, Path cwd, int timeout, int|None memory_limit_bytes)
Definition sandbox.py:346
list[str] _bwrap_cmd(self, list[str] cmd, Path cwd)
Definition sandbox.py:314
tuple[int, str, str] run(self, list[str] cmd, dict[str, str] env, Path cwd, int timeout, int|None memory_limit_bytes)
Definition sandbox.py:276
tuple[int, str, str] run(self, list[str] cmd, dict[str, str] env, Path cwd, int timeout, int|None memory_limit_bytes)
Definition sandbox.py:234
list[str] _sandboxed_cmd(self, list[str] cmd)
Definition sandbox.py:374
tuple[int, str, str] run(self, list[str] cmd, dict[str, str] env, Path cwd, int timeout, int|None memory_limit_bytes)
Definition sandbox.py:385
None __init__(self, SandboxBackend|None backend=None, int memory_limit_mb=0)
Definition sandbox.py:492
SandboxResult run(self, list[str] cmd, Path cwd, int timeout, int max_output_bytes=1_048_576)
Definition sandbox.py:504
None _dbg(*args, **kwargs)
Definition sandbox.py:73
SandboxBackend make_sandbox_backend(object config)
Definition sandbox.py:406
dict[str, str] _sanitise_env(Path project_root)
Definition sandbox.py:135