9Execution Sandbox (Layer 4, outer wrapper) for the ``oct-mcp``
10six-layer pipeline. Provides environment sanitisation, working-directory
11pinning, timeout enforcement, and output-size limiting for subprocess
14Phase 5C adds pluggable OS-level sandbox *backends*:
16* :class:`NativeBackend` - existing behavior (subprocess + env
17 sanitization). Always available; default on Windows.
18* :class:`BubblewrapBackend` - Linux only. Wraps every command in
19 ``bwrap --unshare-net --die-with-parent``. Requires ``bwrap`` in PATH.
20* :class:`SandboxExecBackend` - macOS only. Prepends
21 ``sandbox-exec -p "(deny network*)(allow default)"``. Requires
22 ``sandbox-exec`` in PATH.
24Use :func:`make_sandbox_backend` to select the appropriate backend based
25on :class:`~oct.mcp.config.McpConfig`.
29- Strip sensitive environment variables before forking (``PYTHONPATH``,
30 common secret-named vars).
31- Pin the subprocess working directory to the validated project root.
32- Enforce per-tool timeouts and kill the process on expiry.
33- Cap combined stdout+stderr output to ``max_output_bytes``.
34- Never use ``shell=True``.
35- Return a :class:`SandboxResult` - never raise for subprocess errors.
41 L1 - errors: process launch failures, unexpected errors
42 L2 - lifecycle: process start, process end, backend selection
43 L3 - command details (argv)
44 L4 - deep trace: per-line output, env keys
48- ``shell=False`` is enforced unconditionally in all backends - no
49 caller path can override it.
50- :meth:`SandboxExecutor.run` never raises. Any ``OSError`` or
51 ``subprocess.SubprocessError`` is caught, logged at level 1, and
52 returned as a ``SandboxResult`` with a non-zero exit code.
53- The sanitised environment always preserves ``PATH``, ``HOME``,
54 ``LANG``, ``TERM``, ``USER``, ``USERNAME``, ``LOGNAME``,
55 ``VIRTUAL_ENV``, ``CONDA_DEFAULT_ENV``, and
56 ``OCT_MCP_SESSION_ID`` / ``OCT_MCP_REQUEST_ID`` correlation IDs.
57- :func:`make_sandbox_backend` never raises - it always returns a
58 usable backend (falls back to :class:`NativeBackend`).
62- oct.core.diagnostics (_dbg structured logger)
63- bwrap (not imported; the bubblewrap CLI that BubblewrapBackend wraps every command in on Linux)
66from __future__
import annotations
72from dataclasses
import dataclass
73from pathlib
import Path
74from typing
import Protocol, runtime_checkable
76from oct.core.diagnostics
import _dbg
86_SENSITIVE_ENV_EXACT: frozenset[str] = frozenset({
92_SENSITIVE_ENV_SUBSTRINGS: tuple[str, ...] = (
94 "password",
"passwd",
"pwd",
105_SAFE_ENV_KEYS: frozenset[str] = frozenset({
121 "OCT_MCP_SESSION_ID",
122 "OCT_MCP_REQUEST_ID",
135 """Build a sanitised environment for subprocess execution.
137 Starts from ``os.environ``, preserves :data:`_SAFE_ENV_KEYS`,
138 strips :data:`_SENSITIVE_ENV_EXACT` exact keys and anything whose
139 key contains a :data:`_SENSITIVE_ENV_SUBSTRINGS` token (case-
140 insensitive), and adds ``OCT_MCP_CWD`` so the subprocess knows
141 its sandboxed working directory.
145 A new ``dict[str, str]`` - never modifies ``os.environ``.
147 func =
"_sanitise_env"
148 clean: dict[str, str] = {}
150 for key, value
in os.environ.items():
151 key_upper = key.upper()
154 if key_upper
in {k.upper()
for k
in _SAFE_ENV_KEYS}:
159 if key_upper
in {k.upper()
for k
in _SENSITIVE_ENV_EXACT}:
160 _dbg(
"MCP", func, f
"stripped env key={key}", 4)
164 if any(sub
in key_upper.lower()
for sub
in _SENSITIVE_ENV_SUBSTRINGS):
165 _dbg(
"MCP", func, f
"stripped env key={key} (substring match)", 4)
171 clean[
"OCT_MCP_CWD"] = str(project_root)
183 """Result of a sandboxed subprocess execution.
188 The subprocess return code, or ``1`` on launch failure.
190 Captured standard output (possibly truncated).
192 Captured standard error (possibly truncated).
194 ``True`` if the process was killed due to timeout.
196 ``True`` if combined stdout+stderr exceeded ``max_output_bytes``.
198 Non-empty if the process could not be launched (e.g. not found
199 on PATH). Distinct from stderr - set on ``OSError``.
205 timed_out: bool =
False
206 output_truncated: bool =
False
207 error_message: str =
""
217 """Protocol for OS-level sandbox backends.
219 Each backend wraps the subprocess call with platform-specific
220 isolation (network namespace, resource limits, etc.). The backend
221 receives a sanitised environment and returns raw
222 ``(exit_code, stdout, stderr)`` - output capping and error handling
223 live in :class:`SandboxExecutor`.
232 memory_limit_bytes: int |
None,
233 ) -> tuple[int, str, str]:
234 """Run *cmd* and return ``(exit_code, stdout, stderr)``.
239 Command + arguments list. Must not use ``shell=True``.
241 Sanitised environment dict.
243 Working directory (validated project root).
245 Maximum wall-clock seconds.
247 Virtual memory ceiling in bytes, or ``None`` to skip.
248 Implementations on POSIX apply this via ``setrlimit``; on
249 Windows it is silently ignored.
260 """Subprocess-only backend - existing Phase 5A/5B behavior.
262 On POSIX, when *memory_limit_bytes* is non-None and non-zero,
263 applies ``resource.setrlimit(RLIMIT_AS, ...)`` via ``preexec_fn``
264 to limit virtual address space. On Windows the limit is silently
265 ignored (use Docker for Windows memory enforcement).
274 memory_limit_bytes: int |
None,
275 ) -> tuple[int, str, str]:
277 if memory_limit_bytes
and os.name !=
"nt":
278 limit = memory_limit_bytes
280 def _preexec() -> None:
283 resource.RLIMIT_AS, (limit, limit)
288 result = subprocess.run(
300 return result.returncode, result.stdout
or "", result.stderr
or ""
304 """Linux bubblewrap backend - network-isolated, die-with-parent.
306 Wraps every command in ``bwrap --unshare-net --die-with-parent``.
307 Requires ``bwrap`` to be available in PATH.
309 Network isolation is provided by ``--unshare-net``. The project
310 root is bind-mounted read-write; system paths are read-only.
313 def _bwrap_cmd(self, cmd: list[str], cwd: Path) -> list[str]:
314 """Build the full ``bwrap ... -- cmd`` invocation."""
318 for ro_path
in (
"/usr",
"/lib",
"/lib64",
"/bin",
"/sbin",
"/etc",
320 if Path(ro_path).exists():
321 bwrap += [
"--ro-bind", ro_path, ro_path]
328 "--bind", str(cwd), str(cwd),
344 memory_limit_bytes: int |
None,
345 ) -> tuple[int, str, str]:
347 result = subprocess.run(
358 return result.returncode, result.stdout
or "", result.stderr
or ""
362 """macOS ``sandbox-exec`` backend - network-denied policy.
364 Prepends ``sandbox-exec -p "<profile>"`` to every command.
365 Requires ``sandbox-exec`` to be available in PATH.
367 The policy denies all network access while allowing everything else
368 (file I/O, process creation, etc.) needed to run ``oct`` commands.
371 _PROFILE: str =
"(version 1)(deny network*)(allow default)"
374 """Return ``["sandbox-exec", "-p", PROFILE] + cmd``."""
375 return [
"sandbox-exec",
"-p", self.
_PROFILE] + cmd
383 memory_limit_bytes: int |
None,
384 ) -> tuple[int, str, str]:
386 result = subprocess.run(
397 return result.returncode, result.stdout
or "", result.stderr
or ""
406 """Select and return the best available :class:`SandboxBackend`.
411 A :class:`~oct.mcp.config.McpConfig` instance. Reads the
412 ``sandbox_backend`` field (``"auto"`` / ``"native"`` /
413 ``"bubblewrap"`` / ``"sandbox_exec"``) and ``memory_limit_mb``.
417 A concrete backend instance. On ``"auto"``, picks:
419 * :class:`BubblewrapBackend` on Linux when ``bwrap`` is in PATH.
420 * :class:`SandboxExecBackend` on macOS when ``sandbox-exec`` is in PATH.
421 * :class:`NativeBackend` otherwise (always safe).
423 When a *specific* backend is forced (e.g. ``"bubblewrap"``) but its
424 binary is not found, raises :exc:`RuntimeError`.
426 Never raises on ``"auto"`` or ``"native"`` - always returns a
429 func =
"make_sandbox_backend"
430 name: str = getattr(config,
"sandbox_backend",
"auto")
432 if name ==
"bubblewrap":
433 if not shutil.which(
"bwrap"):
435 "sandbox_backend='bubblewrap' requested but 'bwrap' was not "
436 "found in PATH. Install bubblewrap or set sandbox_backend='auto'."
438 _dbg(
"MCP", func,
"backend=BubblewrapBackend (forced)", 2)
441 if name ==
"sandbox_exec":
442 if not shutil.which(
"sandbox-exec"):
445 "sandbox_backend='sandbox_exec' requested but 'sandbox-exec' "
446 "was not found in PATH. This backend requires macOS."
448 _dbg(
"MCP", func,
"backend=SandboxExecBackend (forced)", 2)
452 if sys.platform ==
"linux" and shutil.which(
"bwrap"):
453 _dbg(
"MCP", func,
"backend=BubblewrapBackend (auto, Linux)", 2)
455 if sys.platform ==
"darwin" and shutil.which(
"sandbox-exec"):
456 _dbg(
"MCP", func,
"backend=SandboxExecBackend (auto, macOS)", 2)
460 _dbg(
"MCP", func,
"backend=NativeBackend", 2)
470 """Sandboxed subprocess runner for the MCP execution layer.
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
480 OS-level isolation backend. Defaults to :class:`NativeBackend`
481 when not supplied (Phase 5A/5B backward compatibility).
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.
490 backend: SandboxBackend |
None =
None,
491 memory_limit_mb: int = 0,
495 memory_limit_mb * 1024 * 1024
if memory_limit_mb > 0
else None
503 max_output_bytes: int = 1_048_576,
505 """Execute *cmd* in a sanitised environment under *cwd*.
510 The command and arguments to run. Must not contain shell
511 metacharacters - this is enforced by passing ``shell=False``
514 Working directory, pinned to the validated project root.
516 Maximum wall-clock seconds before the process is killed.
518 Combined stdout+stderr cap. When exceeded, output is
519 truncated and :attr:`SandboxResult.output_truncated` is set.
523 :class:`SandboxResult` - never raises.
525 func =
"SandboxExecutor.run"
526 _dbg(
"MCP", func, f
"cmd={cmd!r} cwd={cwd} timeout={timeout}s", 3)
541 combined_bytes = len(
542 (stdout + stderr).encode(
"utf-8", errors=
"replace")
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"
552 remaining = max_output_bytes - len(stdout_bytes)
554 stderr.encode(
"utf-8", errors=
"replace")[:remaining]
555 .decode(
"utf-8", errors=
"replace")
560 f
"output truncated combined_bytes={combined_bytes} "
561 f
"limit={max_output_bytes}",
567 f
"exit_code={exit_code} truncated={truncated}",
575 output_truncated=truncated,
578 except subprocess.TimeoutExpired:
579 _dbg(
"MCP", func, f
"SYSTEM_ERROR: timeout after {timeout}s cmd={cmd!r}", 1)
583 stderr=f
"Process timed out after {timeout} seconds.",
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)
595 except OSError
as exc:
596 msg = f
"Failed to launch subprocess: {exc}"
597 _dbg(
"MCP", func, f
"SYSTEM_ERROR: {msg}", 1)
tuple[int, str, str] run(self, list[str] cmd, dict[str, str] env, Path cwd, int timeout, int|None memory_limit_bytes)
list[str] _bwrap_cmd(self, list[str] cmd, Path cwd)
tuple[int, str, str] run(self, list[str] cmd, dict[str, str] env, Path cwd, int timeout, int|None memory_limit_bytes)
tuple[int, str, str] run(self, list[str] cmd, dict[str, str] env, Path cwd, int timeout, int|None memory_limit_bytes)
list[str] _sandboxed_cmd(self, list[str] cmd)
tuple[int, str, str] run(self, list[str] cmd, dict[str, str] env, Path cwd, int timeout, int|None memory_limit_bytes)
None __init__(self, SandboxBackend|None backend=None, int memory_limit_mb=0)
tuple _memory_limit_bytes
SandboxResult run(self, list[str] cmd, Path cwd, int timeout, int max_output_bytes=1_048_576)
SandboxBackend make_sandbox_backend(object config)
dict[str, str] _sanitise_env(Path project_root)