Coverage for src/governed_harness/runtime/sandbox.py: 99%
147 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""Write confinement of agent-provider processes (``runtime.agentSandbox: enforce``).
3The harness's own file handling is contained to the workspace by ``contained_path``; an agent
4CLI launched as a command provider is a separate process with the user's permissions and is not.
5Under ``enforce`` the provider command is wrapped so that the operating system denies every file
6write outside the workspace, the resolved ``$TMPDIR`` and the declared write paths. Reads,
7network access and process execution stay allowed: an agent needs to read the system, reach its
8model API and run tools.
10* macOS: ``/usr/bin/sandbox-exec -p <profile>`` with a Seatbelt profile that allows everything
11 and then denies ``file-write*`` except on the allowed paths.
12* Linux: ``bwrap`` (bubblewrap) with the root file system bound read-only and each allowed path
13 bound writable.
14* Anything else, or a host without the tool: no confinement exists, and the caller must block
15 instead of running the agent unconfined (:class:`SandboxUnavailable`).
16"""
18from __future__ import annotations
20import glob
21import json
22import os
23import platform
24import re
25import shutil
26import tempfile
27from collections.abc import Sequence
28from dataclasses import dataclass, field
29from pathlib import Path
30from typing import Literal
32from governed_harness.evidence.hashing import sha256_bytes
34SANDBOX_EXEC = "/usr/bin/sandbox-exec"
36SandboxMechanism = Literal["sandbox-exec", "bwrap"]
37PathMatch = Literal["subpath", "prefix"]
39# Device files a confined process may still write: the null and zero devices, its own standard
40# streams and descriptors, terminals (an interactive agent or a pty-backed tool) and the DTrace
41# helper that Node.js opens for writing at start-up.
42_DEVICE_LITERALS = (
43 "/dev/null",
44 "/dev/zero",
45 "/dev/stdout",
46 "/dev/stderr",
47 "/dev/ptmx",
48 "/dev/dtracehelper",
49)
50_DEVICE_PATTERNS = ("^/dev/fd/", "^/dev/tty")
52_SBPL_REGEX_SPECIALS = re.compile(r"([.^$*+?()\[\]{}|\\])")
55class SandboxUnavailable(RuntimeError):
56 """``enforce`` was requested and this host offers no confinement mechanism."""
59@dataclass(frozen=True)
60class SandboxHost:
61 """What the sandbox needs to know about the host; injectable so tests choose the platform."""
63 system: str
64 home: Path
65 temp_dir: Path
66 sandbox_exec: str | None = None
67 bwrap: str | None = None
69 @classmethod
70 def detect(cls) -> SandboxHost:
71 system = platform.system()
72 return cls(
73 system=system,
74 home=Path.home(),
75 temp_dir=Path(tempfile.gettempdir()),
76 sandbox_exec=SANDBOX_EXEC
77 if system == "Darwin" and os.access(SANDBOX_EXEC, os.X_OK)
78 else None,
79 bwrap=shutil.which("bwrap") if system == "Linux" else None,
80 )
83@dataclass(frozen=True)
84class SandboxPath:
85 path: str
86 match: PathMatch
87 source: str
90@dataclass(frozen=True)
91class SandboxPlan:
92 """The confinement applied to one provider invocation, recorded as evidence."""
94 mechanism: SandboxMechanism
95 system: str
96 prefix: tuple[str, ...]
97 """argv placed before the provider command."""
98 profile: str
99 """The Seatbelt profile, or the bwrap arguments as a JSON array."""
100 profile_digest: str
101 allowed_paths: tuple[SandboxPath, ...]
102 skipped_paths: tuple[SandboxPath, ...] = field(default=())
103 protected_paths: tuple[str, ...] = field(default=())
104 """Paths inside the workspace the agent may read but not write
105 (``governance.protectExcludedPaths``: ``.harness`` and ``.git``)."""
106 network_denied: bool = False
107 """Outbound network access is denied (``runtime.allowNetwork: false`` under
108 ``governance.applyNetworkPolicy``)."""
110 def evidence(self) -> dict[str, object]:
111 record: dict[str, object] = {
112 "mode": "enforce",
113 "mechanism": self.mechanism,
114 "platform": self.system,
115 "executable": self.prefix[0],
116 "profileDigest": self.profile_digest,
117 "profile": self.profile,
118 "allowedPaths": [_path_record(item) for item in self.allowed_paths],
119 "skippedPaths": [_path_record(item) for item in self.skipped_paths],
120 }
121 if self.protected_paths:
122 record["protectedPaths"] = list(self.protected_paths)
123 if self.network_denied:
124 record["network"] = "denied"
125 return record
128def _path_record(item: SandboxPath) -> dict[str, str]:
129 return {"path": item.path, "match": item.match, "source": item.source}
132def resolve_write_paths(
133 workspace: Path, configured: Sequence[str], host: SandboxHost
134) -> tuple[SandboxPath, ...]:
135 """The workspace, the resolved temporary directory and each configured path, with ``~``
136 expanded and symbolic links resolved (on macOS ``/tmp`` is ``/private/tmp``, ``/var`` is
137 ``/private/var``): the kernel checks the resolved path."""
138 resolved: list[SandboxPath] = [
139 SandboxPath(_real(workspace), "subpath", "workspace"),
140 SandboxPath(_real(host.temp_dir), "subpath", "tempdir"),
141 ]
142 for entry in configured:
143 expanded = str(host.home) + entry[1:] if entry.startswith("~") else entry
144 if expanded.endswith("*"):
145 stem = Path(expanded[:-1])
146 resolved.append(SandboxPath(str(Path(_real(stem.parent)) / stem.name), "prefix", entry))
147 else:
148 resolved.append(SandboxPath(_real(Path(expanded)), "subpath", entry))
149 unique: dict[tuple[str, str], SandboxPath] = {}
150 for item in resolved:
151 unique.setdefault((item.path, item.match), item)
152 return tuple(unique.values())
155def _real(path: Path) -> str:
156 return os.path.realpath(path)
159def build_sandbox(
160 workspace: Path,
161 configured: Sequence[str],
162 host: SandboxHost,
163 protected: Sequence[Path] = (),
164 *,
165 allow_network: bool = True,
166) -> SandboxPlan:
167 """The confinement for one provider invocation. ``protected`` paths (inside the
168 workspace) stay readable but are not writable, whatever the allowed paths say."""
169 paths = resolve_write_paths(workspace, configured, host)
170 denied = tuple(dict.fromkeys(_real(path) for path in protected))
171 if host.system == "Darwin" and host.sandbox_exec:
172 profile = seatbelt_profile(paths, denied, allow_network=allow_network)
173 return SandboxPlan(
174 mechanism="sandbox-exec",
175 system=host.system,
176 prefix=(host.sandbox_exec, "-p", profile),
177 profile=profile,
178 profile_digest=sha256_bytes(profile.encode("utf-8")),
179 allowed_paths=paths,
180 protected_paths=denied,
181 network_denied=not allow_network,
182 )
183 if host.system == "Linux" and host.bwrap:
184 arguments, allowed, skipped = bwrap_arguments(paths, denied, allow_network=allow_network)
185 profile = json.dumps(arguments)
186 return SandboxPlan(
187 mechanism="bwrap",
188 system=host.system,
189 prefix=(host.bwrap, *arguments, "--"),
190 profile=profile,
191 profile_digest=sha256_bytes(profile.encode("utf-8")),
192 allowed_paths=allowed,
193 skipped_paths=skipped,
194 protected_paths=tuple(path for path in denied if Path(path).exists()),
195 network_denied=not allow_network,
196 )
197 if host.system == "Darwin":
198 reason = f"{SANDBOX_EXEC} is not available"
199 elif host.system == "Linux":
200 reason = "bwrap (bubblewrap) is not installed"
201 else:
202 reason = f"no agent sandbox mechanism is supported on {host.system or 'this platform'}"
203 raise SandboxUnavailable(reason)
206def _sbpl_string(value: str) -> str:
207 return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
210def seatbelt_profile(
211 paths: Sequence[SandboxPath], protected: Sequence[str] = (), *, allow_network: bool = True
212) -> str:
213 """Allow everything, deny every file write, then allow writes below the allowed paths and,
214 last, deny them again below the protected paths.
216 In a Seatbelt profile the last matching rule wins, so the ``allow`` re-opens only the listed
217 paths and the final ``deny`` closes the protected ones inside them."""
218 rules = []
219 for item in paths:
220 if item.match == "subpath":
221 rules.append(f"(subpath {_sbpl_string(item.path)})")
222 else:
223 escaped = _SBPL_REGEX_SPECIALS.sub(r"\\\1", item.path)
224 rules.append(f'(regex #"^{escaped}")')
225 rules.extend(f"(literal {_sbpl_string(device)})" for device in _DEVICE_LITERALS)
226 rules.extend(f'(regex #"{pattern}")' for pattern in _DEVICE_PATTERNS)
227 body = "\n ".join(rules)
228 profile = f"(version 1)\n(allow default)\n(deny file-write*)\n(allow file-write*\n {body})\n"
229 if protected:
230 denied = "\n ".join(f"(subpath {_sbpl_string(path)})" for path in protected)
231 profile += f"(deny file-write*\n {denied})\n"
232 if not allow_network:
233 # Outbound IP connections; local (Unix-domain) sockets stay allowed.
234 profile += '(deny network-outbound (remote ip "*:*"))\n'
235 return profile
238def bwrap_arguments(
239 paths: Sequence[SandboxPath],
240 protected: Sequence[str] = (),
241 *,
242 allow_network: bool = True,
243) -> tuple[list[str], tuple[SandboxPath, ...], tuple[SandboxPath, ...]]:
244 """Bind the root read-only, keep /dev, bind each existing allowed path writable and then
245 bind each existing protected path read-only again (a later mount covers an earlier one).
247 A bind mount needs an existing source, so a path that does not exist is skipped (and
248 recorded); a prefix pattern binds each existing file that matches it."""
249 arguments = ["--ro-bind", "/", "/", "--dev-bind", "/dev", "/dev", "--die-with-parent"]
250 allowed: list[SandboxPath] = []
251 skipped: list[SandboxPath] = []
252 for item in paths:
253 if item.match == "prefix":
254 matches = sorted(glob.glob(glob.escape(item.path) + "*"))
255 if not matches: 255 ↛ 256line 255 didn't jump to line 256 because the condition on line 255 was never true
256 skipped.append(item)
257 for match in matches:
258 arguments.extend(("--bind", match, match))
259 allowed.append(SandboxPath(match, "subpath", item.source))
260 elif Path(item.path).exists():
261 arguments.extend(("--bind", item.path, item.path))
262 allowed.append(item)
263 else:
264 skipped.append(item)
265 for path in protected:
266 if Path(path).exists():
267 arguments.extend(("--ro-bind", path, path))
268 if not allow_network:
269 arguments.append("--unshare-net")
270 return arguments, tuple(allowed), tuple(skipped)
273_DENIAL_MARKERS = re.compile(
274 r"operation not permitted|read-only file system|sandbox|deny\(\d+\) file-write", re.IGNORECASE
275)
276_QUOTED_PATH = re.compile(r"""['"`](/[^'"`\n]+)['"`]""")
277_PATH_BEFORE_DENIAL = re.compile(
278 r"(/[^\s:'\"`]+):\s*(?:operation not permitted|read-only file system)", re.IGNORECASE
279)
280_PATH_AFTER_DENY = re.compile(r"deny\(\d+\) file-write[\w-]* (/\S+)")
283def denied_writes(stderr: bytes) -> tuple[bool, tuple[str, ...]]:
284 """Whether the provider's standard error reports a denied write, and the paths it names.
286 Python (``[Errno 1] Operation not permitted: '/path'``), Node.js (``EPERM: operation not
287 permitted, open '/path'``) and GNU tools under bwrap (``cannot touch '/path': Read-only file
288 system``) quote the path; shells write ``sh: /path: Operation not permitted`` and the
289 Seatbelt log ``deny(1) file-write-create /path``."""
290 text = stderr.decode("utf-8", errors="replace")
291 found = False
292 paths: dict[str, None] = {}
293 for line in text.splitlines():
294 if not _DENIAL_MARKERS.search(line):
295 continue
296 found = True
297 candidates = (
298 _QUOTED_PATH.findall(line)
299 or _PATH_BEFORE_DENIAL.findall(line)
300 or _PATH_AFTER_DENY.findall(line)
301 )
302 for candidate in candidates:
303 paths.setdefault(candidate, None)
304 return found, tuple(paths)