zeph_tools/sandbox/mod.rs
1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! OS-level sandbox abstractions for subprocess tool execution.
5//!
6//! This module provides a portable [`Sandbox`] trait and platform-specific backends that
7//! restrict filesystem, network, and syscall access for shell commands spawned by
8//! `ShellExecutor`.
9//!
10//! # Scope (NFR-SB-1)
11//!
12//! The sandbox applies **only to subprocess executors** (`ShellExecutor`). In-process executors
13//! (`WebScrapeExecutor`, `FileExecutor`) do not spawn a child process and are therefore not
14//! subject to OS-level sandboxing. Application-layer controls (allowed hosts, path allowlists)
15//! govern those executors instead.
16//!
17//! # Platform support
18//!
19//! | Platform | Backend | Compiled |
20//! |----------|---------|----------|
21//! | macOS | `sandbox-exec` (Seatbelt) | always |
22//! | Linux + `sandbox` feature | `bwrap` + Landlock + seccomp | `#[cfg(all(target_os="linux", feature="sandbox"))]` |
23//! | Other | `NoopSandbox` (logs WARN) | always |
24//!
25//! # Example
26//!
27//! ```rust,no_run
28//! use zeph_tools::{build_sandbox, SandboxPolicy, SandboxProfile};
29//! use tokio::process::Command;
30//!
31//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
32//! let policy = SandboxPolicy {
33//! profile: SandboxProfile::Workspace,
34//! allow_read: vec![],
35//! allow_write: vec![std::env::current_dir()?],
36//! allow_network: false,
37//! allow_exec: vec![],
38//! env_inherit: vec![],
39//! denied_domains: vec![],
40//! };
41//! let sb = build_sandbox(false)?;
42//! let mut cmd = Command::new("bash");
43//! cmd.arg("-c").arg("echo hello");
44//! sb.wrap(&mut cmd, &policy)?;
45//! # Ok(())
46//! # }
47//! ```
48
49use std::path::PathBuf;
50
51use thiserror::Error;
52
53pub mod noop;
54
55#[cfg(target_os = "macos")]
56pub mod macos;
57
58#[cfg(all(target_os = "linux", feature = "sandbox"))]
59pub mod linux;
60
61pub use noop::NoopSandbox;
62
63#[cfg(target_os = "macos")]
64pub use macos::MacosSandbox;
65
66#[cfg(all(target_os = "linux", feature = "sandbox"))]
67pub use linux::LinuxSandbox;
68
69/// Declarative sandbox policy evaluated at command launch.
70///
71/// Applied *after* blocklist, `PolicyGate`, and `TrustGate` have accepted the call.
72/// The sandbox is the last hard boundary, not a replacement for application-level controls.
73#[derive(Debug, Clone)]
74pub struct SandboxPolicy {
75 /// The enforcement profile controlling which restrictions are active.
76 pub profile: SandboxProfile,
77 /// Paths granted read (and execute) access. Normalized to absolute paths at construction.
78 ///
79 /// Paths are resolved to their canonical (real) form by [`SandboxPolicy::canonicalized`]
80 /// before being applied. If a path is a symlink, the resolved target is used for the allow
81 /// rule. Deny rules for well-known secret paths are also generated for the canonical form,
82 /// so the allow override works correctly even when the denied path is a symlink.
83 pub allow_read: Vec<PathBuf>,
84 /// Paths granted read and write access. Normalized to absolute paths at construction.
85 pub allow_write: Vec<PathBuf>,
86 /// Whether unrestricted network egress is permitted.
87 pub allow_network: bool,
88 /// Additional executables or directories granted execute permission.
89 pub allow_exec: Vec<PathBuf>,
90 /// Environment variable names or prefixes that are inherited by the sandboxed child.
91 pub env_inherit: Vec<String>,
92 /// Hostname patterns (exact or `*.suffix`) denied network egress.
93 ///
94 /// Enforcement is per-backend:
95 /// - macOS Seatbelt: `(deny network* (remote host "<host>"))` after `(allow network*)`.
96 /// - Linux bwrap: `/etc/hosts` override resolving the name to `0.0.0.0` (best-effort).
97 /// - [`NoopSandbox`]: ignored (log WARN at construction if non-empty).
98 pub denied_domains: Vec<String>,
99}
100
101impl SandboxPolicy {
102 /// Canonicalize all path fields so that symlinks and `..` components cannot bypass
103 /// the policy. Paths that cannot be resolved (e.g., non-existent) are dropped and
104 /// logged at WARN level with the OS error — callers should ensure paths exist
105 /// before adding them to the policy.
106 #[must_use]
107 pub fn canonicalized(mut self) -> Self {
108 self.allow_read = canonicalize_paths(self.allow_read);
109 self.allow_write = canonicalize_paths(self.allow_write);
110 self.allow_exec = canonicalize_paths(self.allow_exec);
111 self
112 }
113}
114
115fn canonicalize_paths(paths: Vec<PathBuf>) -> Vec<PathBuf> {
116 paths
117 .into_iter()
118 .filter_map(|p| match std::fs::canonicalize(&p) {
119 Ok(canonical) => {
120 if canonical != p {
121 tracing::debug!(
122 "sandbox: resolved symlink {} → {}",
123 p.display(),
124 canonical.display()
125 );
126 }
127 Some(canonical)
128 }
129 Err(e) => {
130 tracing::warn!(
131 path = %p.display(),
132 error = %e,
133 "sandbox: allow-list path could not be canonicalized and was dropped from policy"
134 );
135 None
136 }
137 })
138 .collect()
139}
140
141impl Default for SandboxPolicy {
142 fn default() -> Self {
143 let cwd =
144 std::fs::canonicalize(std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
145 .unwrap_or_else(|_| PathBuf::from("/"));
146 Self {
147 profile: SandboxProfile::Workspace,
148 allow_read: vec![cwd.clone()],
149 allow_write: vec![cwd],
150 allow_network: false,
151 allow_exec: vec![],
152 env_inherit: vec![],
153 denied_domains: vec![],
154 }
155 }
156}
157
158pub(crate) use zeph_config::tools::SandboxProfile;
159
160/// Error returned when sandbox setup or policy application fails.
161#[derive(Debug, Error)]
162pub enum SandboxError {
163 /// The OS backend binary or kernel API is unavailable on this system.
164 #[error("sandbox backend unavailable: {reason}")]
165 Unavailable { reason: String },
166 /// The configured policy is not supported by the backend.
167 #[error("policy not supported by {backend}: {reason}")]
168 UnsupportedPolicy {
169 /// Backend name for diagnostics.
170 backend: &'static str,
171 /// Human-readable explanation.
172 reason: String,
173 },
174 /// I/O error during sandbox setup (e.g. temp file creation).
175 #[error("sandbox setup failed: {0}")]
176 Setup(#[from] std::io::Error),
177 /// Policy string generation failed.
178 #[error("policy generation failed: {0}")]
179 Policy(String),
180}
181
182/// Operating-system sandbox backend.
183///
184/// `wrap` is the sole entry point. Implementations rewrite a [`tokio::process::Command`]
185/// in place so that the next `.spawn()` launches inside the OS sandbox. Implementations
186/// must be fork-safe: state installed via the command builder must survive `fork()+exec()`.
187///
188/// # Contract for implementors
189///
190/// - Must not spawn the child themselves — only rewrite `cmd`.
191/// - Must not use `unsafe` code.
192/// - When the profile is [`SandboxProfile::Off`], `wrap` MUST be a no-op.
193pub trait Sandbox: Send + Sync + std::fmt::Debug {
194 /// Short identifier for logging and diagnostics (e.g., `"macos-seatbelt"`, `"linux-bwrap"`).
195 fn name(&self) -> &'static str;
196
197 /// Verify that `policy` is expressible on this backend.
198 ///
199 /// # Errors
200 ///
201 /// Returns [`SandboxError::UnsupportedPolicy`] when a required feature is missing.
202 fn supports(&self, policy: &SandboxPolicy) -> Result<(), SandboxError>;
203
204 /// Rewrite `cmd` to execute inside the OS sandbox described by `policy`.
205 ///
206 /// Called synchronously in the executor thread. Must not block on I/O for more than a few
207 /// milliseconds (temp file writes are acceptable; network calls are not).
208 ///
209 /// # Errors
210 ///
211 /// Returns [`SandboxError`] if wrapping fails (binary missing, profile generation error, etc.).
212 fn wrap(
213 &self,
214 cmd: &mut tokio::process::Command,
215 policy: &SandboxPolicy,
216 ) -> Result<(), SandboxError>;
217}
218
219/// Construct the best available [`Sandbox`] backend for the current platform.
220///
221/// Selection order:
222/// 1. macOS → `MacosSandbox`
223/// 2. Linux + `sandbox` feature → `LinuxSandbox`
224/// 3. Fallback → [`NoopSandbox`]
225///
226/// # Errors
227///
228/// Returns [`SandboxError::Unavailable`] when `strict = true` and the preferred backend
229/// is missing (e.g. `bwrap` not on `PATH`).
230pub fn build_sandbox(strict: bool) -> Result<Box<dyn Sandbox>, SandboxError> {
231 build_sandbox_with_policy(strict, false, false)
232}
233
234/// Construct the best available [`Sandbox`] backend with additional safety options.
235///
236/// Extends [`build_sandbox`] with:
237/// - `fail_if_unavailable`: when `true`, even a successful noop fallback is an error.
238/// Use this when `denied_domains` must be enforced and no effective sandbox exists.
239/// - `denied_domains_present`: when `true` and the noop backend is selected with
240/// `fail_if_unavailable = false`, emits a one-shot `WARN` that the deny list is unenforceable.
241///
242/// # Errors
243///
244/// - [`SandboxError::Unavailable`] when `strict = true` and the preferred backend binary is
245/// missing (same as [`build_sandbox`]).
246/// - [`SandboxError::Unavailable`] when `fail_if_unavailable = true` and noop would be selected.
247pub fn build_sandbox_with_policy(
248 strict: bool,
249 fail_if_unavailable: bool,
250 denied_domains_present: bool,
251) -> Result<Box<dyn Sandbox>, SandboxError> {
252 #[cfg(target_os = "macos")]
253 {
254 let _ = (strict, fail_if_unavailable, denied_domains_present);
255 Ok(Box::new(MacosSandbox::new()))
256 }
257
258 #[cfg(all(target_os = "linux", feature = "sandbox"))]
259 {
260 let _ = (fail_if_unavailable, denied_domains_present);
261 linux::LinuxSandbox::new(strict).map(|s| Box::new(s) as Box<dyn Sandbox>)
262 }
263
264 // Noop path: platform without an OS sandbox backend.
265 #[cfg(not(any(target_os = "macos", all(target_os = "linux", feature = "sandbox"))))]
266 {
267 if strict {
268 return Err(SandboxError::Unavailable {
269 reason: "OS sandbox not supported on this platform and strict=true".into(),
270 });
271 }
272 if fail_if_unavailable {
273 return Err(SandboxError::Unavailable {
274 reason: "noop backend selected but fail_if_unavailable=true; \
275 OS sandbox is required on this platform"
276 .into(),
277 });
278 }
279 if denied_domains_present {
280 tracing::warn!(
281 "sandbox.denied_domains is set but the OS sandbox is unavailable on this platform \
282 — denied domains cannot be enforced; set fail_if_unavailable=true to make this a \
283 startup error"
284 );
285 } else {
286 tracing::warn!(
287 "OS sandbox not supported on this platform — running without subprocess isolation"
288 );
289 }
290 Ok(Box::new(NoopSandbox))
291 }
292}
293
294#[cfg(test)]
295mod tests {
296 #[test]
297 #[cfg(not(any(target_os = "macos", all(target_os = "linux", feature = "sandbox"))))]
298 fn build_sandbox_strict_fails_when_unsupported() {
299 use super::{SandboxError, build_sandbox};
300 let err = build_sandbox(true).expect_err("strict must fail on unsupported platform");
301 assert!(matches!(err, SandboxError::Unavailable { .. }));
302 }
303
304 #[test]
305 #[cfg(not(any(target_os = "macos", all(target_os = "linux", feature = "sandbox"))))]
306 fn build_sandbox_nonstrict_falls_back_to_noop() {
307 use super::build_sandbox;
308 let sb = build_sandbox(false).expect("noop fallback ok");
309 assert_eq!(sb.name(), "noop");
310 }
311
312 #[test]
313 fn canonicalize_paths_drops_nonexistent_path() {
314 use super::{SandboxPolicy, SandboxProfile};
315 use std::path::PathBuf;
316
317 let policy = SandboxPolicy {
318 profile: SandboxProfile::Workspace,
319 allow_read: vec![PathBuf::from(
320 "/this/path/does/not/exist/zeph-test-sentinel",
321 )],
322 allow_write: vec![],
323 allow_network: false,
324 allow_exec: vec![],
325 env_inherit: vec![],
326 denied_domains: vec![],
327 }
328 .canonicalized();
329
330 assert!(
331 policy.allow_read.is_empty(),
332 "non-existent path must be dropped by canonicalized()"
333 );
334 }
335}