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