Skip to main content

microclaw_engine/internal/tool_runtime/
local_sandbox.rs

1//! Local OS sandbox for shell commands (`sandbox.backend: local`).
2//!
3//! Commands run on the host, confined by the operating system instead of a
4//! container:
5//!
6//! - **Linux**: [bubblewrap](https://github.com/containers/bubblewrap)
7//!   (`bwrap`). The whole filesystem is mounted read-only, the workspace,
8//!   the temp directory and the writable roots are bound read-write,
9//!   credential directories are replaced by empty tmpfs mounts, and the
10//!   network namespace is unshared when network access is off.
11//! - **macOS**: Seatbelt (`sandbox-exec`) with a generated profile: reads
12//!   are allowed except for credential directories; writes only under the
13//!   workspace, the temp directories and the writable roots; network access
14//!   is denied when off.
15//!
16//! The process keeps the caller's user, environment and toolchains, so
17//! builds and tests behave as they do outside the sandbox. What it cannot do
18//! is change files outside the allowed roots, read SSH/cloud credentials, or
19//! (when network is off) reach the network.
20
21use std::path::{Path, PathBuf};
22use std::sync::OnceLock;
23
24use crate::internal::tool_runtime::command_runner::CommandSpec;
25
26/// The OS mechanism a [`LocalPolicy`] is enforced with.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum LocalSandboxKind {
29    Bubblewrap,
30    Seatbelt,
31    /// Linux fallback without bubblewrap: write confinement (and TCP
32    /// blocking on newer kernels) through Landlock; cannot hide directories.
33    Landlock,
34}
35
36impl LocalSandboxKind {
37    pub fn name(self) -> &'static str {
38        match self {
39            Self::Bubblewrap => "bubblewrap",
40            Self::Seatbelt => "seatbelt",
41            Self::Landlock => "landlock",
42        }
43    }
44
45    /// Whether this mechanism hides the credential directories.
46    pub fn hides_credentials(self) -> bool {
47        !matches!(self, Self::Landlock)
48    }
49}
50
51const SEATBELT: &str = "/usr/bin/sandbox-exec";
52
53/// Home-relative directories a sandboxed command can never read.
54const HIDDEN_HOME_DIRS: &[&str] = &[
55    ".ssh",
56    ".gnupg",
57    ".aws",
58    ".azure",
59    ".config/gcloud",
60    ".kube",
61    ".docker",
62    ".netrc",
63    ".git-credentials",
64    ".microclaw",
65    ".mccode",
66];
67
68/// Home-relative tool caches commands may write (package downloads, build
69/// caches), so builds and tests keep working.
70const DEFAULT_WRITABLE_HOME_DIRS: &[&str] = &[
71    ".cache",
72    ".cargo",
73    ".rustup",
74    ".npm",
75    ".pnpm-store",
76    ".yarn",
77    ".bun",
78    ".gradle",
79    ".m2",
80    "go",
81    "Library/Caches",
82];
83
84/// Which mechanism is available on this machine, probed once. On Linux the
85/// probe runs `bwrap` for real, because user namespaces can be disabled
86/// (some containers, hardened kernels); without it, Landlock is used when the
87/// kernel supports it. `MICROCLAW_LOCAL_SANDBOX=bubblewrap|landlock|none`
88/// overrides the choice.
89pub fn detect() -> Option<LocalSandboxKind> {
90    static DETECTED: OnceLock<Option<LocalSandboxKind>> = OnceLock::new();
91    *DETECTED.get_or_init(|| {
92        let forced = std::env::var("MICROCLAW_LOCAL_SANDBOX").ok();
93        match forced.as_deref().map(str::trim) {
94            Some("none") | Some("off") => return None,
95            Some("landlock") => {
96                return crate::internal::tool_runtime::landlock::abi()
97                    .map(|_| LocalSandboxKind::Landlock)
98            }
99            _ => {}
100        }
101        if cfg!(target_os = "macos") {
102            Path::new(SEATBELT)
103                .exists()
104                .then_some(LocalSandboxKind::Seatbelt)
105        } else if cfg!(target_os = "linux") {
106            let works = std::process::Command::new("bwrap")
107                .args([
108                    "--ro-bind",
109                    "/",
110                    "/",
111                    "--dev",
112                    "/dev",
113                    "--unshare-net",
114                    "--die-with-parent",
115                    "--",
116                    "true",
117                ])
118                .stdin(std::process::Stdio::null())
119                .stdout(std::process::Stdio::null())
120                .stderr(std::process::Stdio::null())
121                .status()
122                .is_ok_and(|s| s.success());
123            if works {
124                Some(LocalSandboxKind::Bubblewrap)
125            } else {
126                crate::internal::tool_runtime::landlock::abi().map(|_| LocalSandboxKind::Landlock)
127            }
128        } else {
129            None
130        }
131    })
132}
133
134/// What a sandboxed command may touch.
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct LocalPolicy {
137    /// Writable (the repository / chat working directory).
138    pub workspace: PathBuf,
139    /// Additional writable directories (existing ones only are applied).
140    pub writable_roots: Vec<PathBuf>,
141    /// Allow network access.
142    pub network: bool,
143    /// Directories that are hidden (unreadable).
144    pub hidden: Vec<PathBuf>,
145}
146
147fn canonical(path: &Path) -> Option<PathBuf> {
148    std::fs::canonicalize(path).ok()
149}
150
151fn home_dir() -> Option<PathBuf> {
152    std::env::var_os("HOME")
153        .filter(|h| !h.is_empty())
154        .map(PathBuf::from)
155}
156
157impl LocalPolicy {
158    /// The default policy for a workspace: write the workspace, the temp
159    /// directory and the usual tool caches; hide credential directories.
160    pub fn for_workspace(workspace: &Path, extra_writable: &[PathBuf], network: bool) -> Self {
161        let home = home_dir();
162        let mut writable_roots = vec![std::env::temp_dir()];
163        if cfg!(target_os = "macos") {
164            writable_roots.push(PathBuf::from("/private/tmp"));
165            writable_roots.push(PathBuf::from("/private/var/folders"));
166        } else {
167            writable_roots.push(PathBuf::from("/tmp"));
168        }
169        if let Some(home) = &home {
170            writable_roots.extend(DEFAULT_WRITABLE_HOME_DIRS.iter().map(|d| home.join(d)));
171        }
172        writable_roots.extend(extra_writable.iter().cloned());
173        let hidden = home
174            .map(|home| HIDDEN_HOME_DIRS.iter().map(|d| home.join(d)).collect())
175            .unwrap_or_default();
176        Self {
177            workspace: workspace.to_path_buf(),
178            writable_roots,
179            network,
180            hidden,
181        }
182    }
183
184    /// Canonical workspace and existing writable roots, deduplicated; hidden
185    /// paths that exist and do not contain the workspace.
186    fn resolved(&self) -> (PathBuf, Vec<PathBuf>, Vec<PathBuf>) {
187        let workspace = canonical(&self.workspace).unwrap_or_else(|| self.workspace.clone());
188        let mut writable: Vec<PathBuf> = Vec::new();
189        for root in &self.writable_roots {
190            let Some(root) = canonical(root) else {
191                continue;
192            };
193            if root == Path::new("/")
194                || writable.iter().any(|w| root.starts_with(w))
195                || root.starts_with(&workspace)
196            {
197                continue;
198            }
199            writable.retain(|w| !w.starts_with(&root));
200            writable.push(root);
201        }
202        let hidden = self
203            .hidden
204            .iter()
205            .filter_map(|p| canonical(p))
206            .filter(|p| !workspace.starts_with(p))
207            .collect();
208        (workspace, writable, hidden)
209    }
210}
211
212/// Wrap `spec` so it runs under `kind` with `policy`, starting in `cwd`.
213pub fn wrap(
214    kind: LocalSandboxKind,
215    policy: &LocalPolicy,
216    spec: &CommandSpec,
217    cwd: &Path,
218) -> CommandSpec {
219    match kind {
220        LocalSandboxKind::Bubblewrap => bubblewrap(policy, spec, cwd),
221        LocalSandboxKind::Seatbelt => seatbelt(policy, spec),
222        LocalSandboxKind::Landlock => landlock(policy, spec),
223    }
224}
225
226fn landlock(policy: &LocalPolicy, spec: &CommandSpec) -> CommandSpec {
227    let (workspace, writable, _) = policy.resolved();
228    let mut roots = writable;
229    roots.push(workspace);
230    match crate::internal::tool_runtime::landlock::Ruleset::new(&roots, policy.network) {
231        Ok(rules) => CommandSpec {
232            program: spec.program.clone(),
233            args: spec.args.clone(),
234            landlock: Some(std::sync::Arc::new(rules)),
235        },
236        // Never run unconfined when the sandbox was requested.
237        Err(e) => CommandSpec {
238            program: "/bin/sh".into(),
239            args: vec![
240                "-c".into(),
241                format!(
242                    "echo 'microclaw: could not set up the Landlock sandbox: {e}' >&2; exit 126"
243                ),
244            ],
245            landlock: None,
246        },
247    }
248}
249
250fn bubblewrap(policy: &LocalPolicy, spec: &CommandSpec, cwd: &Path) -> CommandSpec {
251    let (workspace, writable, hidden) = policy.resolved();
252    let path = |p: &Path| p.to_string_lossy().into_owned();
253    let mut args: Vec<String> = vec![
254        "--ro-bind".into(),
255        "/".into(),
256        "/".into(),
257        "--dev".into(),
258        "/dev".into(),
259        "--proc".into(),
260        "/proc".into(),
261    ];
262    for root in writable.iter().chain(std::iter::once(&workspace)) {
263        args.extend(["--bind".into(), path(root), path(root)]);
264    }
265    for dir in &hidden {
266        if dir.is_dir() {
267            args.extend(["--tmpfs".into(), path(dir)]);
268        } else {
269            args.extend(["--ro-bind".into(), "/dev/null".into(), path(dir)]);
270        }
271    }
272    if !policy.network {
273        args.push("--unshare-net".into());
274    }
275    args.extend([
276        "--die-with-parent".into(),
277        "--new-session".into(),
278        "--chdir".into(),
279        path(cwd),
280        "--".into(),
281        spec.program.clone(),
282    ]);
283    args.extend(spec.args.iter().cloned());
284    CommandSpec {
285        program: "bwrap".into(),
286        args,
287        landlock: None,
288    }
289}
290
291/// Quote a path for a Seatbelt profile string literal.
292fn sbpl_string(path: &Path) -> String {
293    let raw = path.to_string_lossy();
294    let mut out = String::with_capacity(raw.len() + 2);
295    out.push('"');
296    for c in raw.chars() {
297        match c {
298            '"' | '\\' => {
299                out.push('\\');
300                out.push(c);
301            }
302            _ => out.push(c),
303        }
304    }
305    out.push('"');
306    out
307}
308
309/// The Seatbelt profile for `policy` (later rules win in SBPL).
310pub fn seatbelt_profile(policy: &LocalPolicy) -> String {
311    let (workspace, writable, hidden) = policy.resolved();
312    let mut profile = String::from(
313        "(version 1)\n\
314         (deny default)\n\
315         (allow process-exec)\n\
316         (allow process-fork)\n\
317         (allow process-info*)\n\
318         (allow signal (target same-sandbox))\n\
319         (allow sysctl-read)\n\
320         (allow mach-lookup)\n\
321         (allow ipc-posix-shm*)\n\
322         (allow ipc-posix-sem)\n\
323         (allow iokit-open)\n\
324         (allow pseudo-tty)\n\
325         (allow file-ioctl)\n\
326         (allow file-read*)\n\
327         (allow file-write-data (literal \"/dev/null\") (literal \"/dev/zero\") (literal \"/dev/dtracehelper\") (regex #\"^/dev/tty\") (regex #\"^/dev/fd/\"))\n",
328    );
329    profile.push_str("(allow file-write*");
330    for root in writable.iter().chain(std::iter::once(&workspace)) {
331        profile.push_str(&format!(" (subpath {})", sbpl_string(root)));
332    }
333    profile.push_str(")\n");
334    if !hidden.is_empty() {
335        profile.push_str("(deny file-read* file-write*");
336        for dir in &hidden {
337            profile.push_str(&format!(" (subpath {})", sbpl_string(dir)));
338        }
339        profile.push_str(")\n");
340    }
341    if policy.network {
342        profile.push_str("(allow network*)\n(allow system-socket)\n");
343    } else {
344        profile.push_str("(allow network* (local unix))\n");
345    }
346    profile
347}
348
349fn seatbelt(policy: &LocalPolicy, spec: &CommandSpec) -> CommandSpec {
350    let mut args = vec![
351        "-p".to_string(),
352        seatbelt_profile(policy),
353        spec.program.clone(),
354    ];
355    args.extend(spec.args.iter().cloned());
356    CommandSpec {
357        program: SEATBELT.into(),
358        args,
359        landlock: None,
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366    use crate::internal::tool_runtime::command_runner::{build_command, shell_command};
367
368    fn policy(workspace: &Path, network: bool) -> LocalPolicy {
369        LocalPolicy {
370            workspace: workspace.to_path_buf(),
371            writable_roots: vec![std::env::temp_dir()],
372            network,
373            hidden: Vec::new(),
374        }
375    }
376
377    #[test]
378    fn bubblewrap_arguments_bind_the_workspace_and_drop_the_network() {
379        let dir = tempfile::tempdir().unwrap();
380        let ws = dir.path().join("ws");
381        let secret = dir.path().join("secret");
382        std::fs::create_dir_all(&ws).unwrap();
383        std::fs::create_dir_all(&secret).unwrap();
384        let mut p = policy(&ws, false);
385        p.hidden = vec![secret.clone(), dir.path().join("missing")];
386        let spec = bubblewrap(&p, &shell_command("ls"), &ws);
387        let args = spec.args.join(" ");
388        let ws = std::fs::canonicalize(&ws).unwrap();
389        let secret = std::fs::canonicalize(&secret).unwrap();
390        assert_eq!(spec.program, "bwrap");
391        assert!(args.starts_with("--ro-bind / /"), "{args}");
392        assert!(args.contains(&format!("--bind {} {}", ws.display(), ws.display())));
393        assert!(args.contains(&format!("--tmpfs {}", secret.display())));
394        assert!(!args.contains("missing"));
395        assert!(args.contains("--unshare-net"));
396        assert!(!bubblewrap(&policy(&ws, true), &shell_command("ls"), &ws)
397            .args
398            .contains(&"--unshare-net".to_string()));
399    }
400
401    #[test]
402    fn seatbelt_profile_limits_writes_and_hides_credentials() {
403        let dir = tempfile::tempdir().unwrap();
404        let ws = dir.path().join("ws \"q\"");
405        std::fs::create_dir_all(&ws).unwrap();
406        let secret = dir.path().join(".ssh");
407        std::fs::create_dir_all(&secret).unwrap();
408        let mut p = policy(&ws, false);
409        p.hidden = vec![secret];
410        let profile = seatbelt_profile(&p);
411        assert!(profile.contains("(deny default)"));
412        assert!(profile.contains("(allow file-write* "));
413        assert!(profile.contains("ws \\\"q\\\""), "{profile}");
414        assert!(profile.contains("(deny file-read* file-write* (subpath"));
415        assert!(profile.contains("(allow network* (local unix))"));
416        assert!(seatbelt_profile(&policy(&ws, true)).contains("(allow network*)\n"));
417    }
418
419    #[test]
420    fn hidden_paths_that_contain_the_workspace_are_kept_visible() {
421        let dir = tempfile::tempdir().unwrap();
422        let ws = dir.path().join("a/ws");
423        std::fs::create_dir_all(&ws).unwrap();
424        let mut p = policy(&ws, true);
425        p.hidden = vec![dir.path().join("a")];
426        let (_, _, hidden) = p.resolved();
427        assert!(hidden.is_empty());
428    }
429
430    #[cfg(target_os = "linux")]
431    #[tokio::test]
432    async fn landlock_wrapping_confines_writes() {
433        if crate::internal::tool_runtime::landlock::abi().is_none() {
434            eprintln!("Landlock unavailable; skipping");
435            return;
436        }
437        let base = tempfile::tempdir().unwrap();
438        let ws = base.path().join("ws");
439        let outside = base.path().join("outside");
440        std::fs::create_dir_all(&ws).unwrap();
441        std::fs::create_dir_all(&outside).unwrap();
442        let p = LocalPolicy {
443            workspace: ws.clone(),
444            writable_roots: Vec::new(),
445            network: true,
446            hidden: Vec::new(),
447        };
448        let script = format!(
449            "echo in > inside.txt; echo out > '{}/x.txt'; echo done",
450            outside.display()
451        );
452        let spec = wrap(LocalSandboxKind::Landlock, &p, &shell_command(&script), &ws);
453        let output = build_command(&spec, Some(&ws)).output().await.unwrap();
454        assert!(ws.join("inside.txt").exists());
455        assert!(!outside.join("x.txt").exists());
456        assert!(String::from_utf8_lossy(&output.stdout).contains("done"));
457    }
458
459    /// Runs only where the OS sandbox actually works (bwrap with user
460    /// namespaces, or macOS).
461    #[tokio::test]
462    async fn sandboxed_commands_can_write_the_workspace_only() {
463        let Some(kind) = detect() else {
464            eprintln!("no local sandbox on this machine; skipping");
465            return;
466        };
467        let base = tempfile::tempdir().unwrap();
468        let ws = base.path().join("ws");
469        let outside = base.path().join("outside");
470        let secret = base.path().join("secret");
471        for d in [&ws, &outside, &secret] {
472            std::fs::create_dir_all(d).unwrap();
473        }
474        std::fs::write(secret.join("key"), "hunter2").unwrap();
475        let p = LocalPolicy {
476            workspace: ws.clone(),
477            writable_roots: Vec::new(),
478            network: false,
479            hidden: vec![secret.clone()],
480        };
481        let run = |script: &str| {
482            let spec = wrap(kind, &p, &shell_command(script), &ws);
483            let mut cmd = build_command(&spec, Some(&ws));
484            async move { cmd.output().await.unwrap() }
485        };
486        let ok = run("echo inside > inside.txt && cat inside.txt").await;
487        assert!(
488            ok.status.success(),
489            "{}",
490            String::from_utf8_lossy(&ok.stderr)
491        );
492        assert_eq!(String::from_utf8_lossy(&ok.stdout).trim(), "inside");
493        assert!(ws.join("inside.txt").exists());
494
495        let denied = run(&format!("echo x > '{}/escape.txt'", outside.display())).await;
496        assert!(!denied.status.success());
497        assert!(!outside.join("escape.txt").exists());
498
499        let hidden = run(&format!("cat '{}/key'", secret.display())).await;
500        assert!(!String::from_utf8_lossy(&hidden.stdout).contains("hunter2"));
501    }
502}