Skip to main content

aidaemon_tools/
exec.rs

1//! Sandboxes for the `shell` tool.
2//!
3//! A sandbox decides *where and how contained* a command runs. It never
4//! decides *whether* it may run: approval is a policy concern and belongs in
5//! an [`aidaemon_core::Hook`].
6
7use std::path::{Path, PathBuf};
8use std::process::Stdio;
9use std::sync::atomic::{AtomicU64, Ordering};
10use std::sync::{Arc, Mutex, OnceLock};
11use std::time::{Duration, Instant};
12
13use async_trait::async_trait;
14use tokio::io::AsyncReadExt;
15use tokio::process::Command;
16
17use aidaemon_core::CancellationToken;
18
19use crate::util::HeadTail;
20
21/// Where `terminal` commands execute.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
23#[serde(rename_all = "lowercase")]
24pub enum TerminalConfinement {
25    /// Run commands directly on the host as the daemon's user, with the
26    /// host's environment, network, and credentials. The default: what a
27    /// person at the shell gets, so deploys, package managers, and
28    /// authenticated CLIs just work.
29    #[default]
30    Host,
31    /// Run every command inside the OS sandbox (seatbelt on macOS; on
32    /// Linux the Codex sandbox adapter when installed, else bubblewrap)
33    /// with deny-by-default filesystem and network policy scoped to the
34    /// task. Opt-in for advanced users who want blast-radius
35    /// containment; expect tools that rely on `$HOME` credentials or the
36    /// network to need explicit grants.
37    Sandbox,
38}
39
40impl std::fmt::Display for TerminalConfinement {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            Self::Host => write!(f, "host"),
44            Self::Sandbox => write!(f, "sandbox"),
45        }
46    }
47}
48
49/// One command to run.
50#[derive(Debug, Clone)]
51pub struct SandboxCommand {
52    /// Shell command line, run with `sh -c`.
53    pub command: String,
54    /// Working directory (absolute, inside `workspace_root`).
55    pub cwd: PathBuf,
56    /// Canonical workspace root; sandboxes make only this writable.
57    pub workspace_root: PathBuf,
58    /// The complete environment for the command (nothing else is inherited
59    /// by sandboxed or local children).
60    pub env: Vec<(String, String)>,
61    pub timeout: Duration,
62    /// Bytes of combined output kept (head + tail).
63    pub max_output_bytes: usize,
64    /// Whether the command may use the network (sandboxes only).
65    pub allow_network: bool,
66    /// Host paths the command must not read, on top of the backend's own
67    /// defaults ([`HOME_SECRET_PATHS`] for bubblewrap and seatbelt). Only
68    /// backends whose [`Sandbox::enforces_deny_read`] is true honour it;
69    /// the shell tool refuses to run a command with a deny list on any
70    /// other. Paths that do not exist are skipped. Under bubblewrap a denied directory appears empty and a
71    /// denied file reads as empty; under seatbelt reading either fails.
72    pub deny_read: Vec<PathBuf>,
73    /// Cancelled when the run is cancelled; the command is killed.
74    pub cancel: CancellationToken,
75}
76
77impl SandboxCommand {
78    /// A spec with defaults: 60 s timeout, 20 000 output bytes, no network.
79    pub fn new(command: impl Into<String>, workspace_root: impl Into<PathBuf>) -> Self {
80        let root = workspace_root.into();
81        Self {
82            command: command.into(),
83            cwd: root.clone(),
84            workspace_root: root,
85            env: Vec::new(),
86            timeout: Duration::from_secs(60),
87            max_output_bytes: 20_000,
88            allow_network: false,
89            deny_read: Vec::new(),
90            cancel: CancellationToken::new(),
91        }
92    }
93}
94
95/// What a command did.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct CommandOutput {
98    /// `None` when killed by a signal or timeout.
99    pub exit_code: Option<i32>,
100    /// Combined stdout and stderr, interleaved in arrival order, capped to
101    /// head + tail.
102    pub output: String,
103    pub output_bytes: usize,
104    pub truncated: bool,
105    pub timed_out: bool,
106    pub cancelled: bool,
107    pub duration: Duration,
108}
109
110/// The command could not be started (as opposed to starting and failing).
111#[derive(Debug, thiserror::Error)]
112pub enum ExecError {
113    #[error("execution backend `{0}` is not available on this machine")]
114    Unavailable(&'static str),
115    #[error("failed to start command: {0}")]
116    Spawn(#[from] std::io::Error),
117}
118
119pub type Result<T> = std::result::Result<T, ExecError>;
120
121/// Where commands run.
122#[async_trait]
123pub trait Sandbox: Send + Sync {
124    /// Short name recorded in receipts, for example `local` or `bubblewrap`.
125    fn name(&self) -> &'static str;
126    /// Whether this backend can run commands here.
127    fn is_available(&self) -> bool;
128    /// Whether the backend confines writes to the workspace.
129    fn is_contained(&self) -> bool;
130    /// Whether the backend keeps a command from reading the paths in
131    /// [`SandboxCommand::deny_read`]. Default `false`: a backend claims it
132    /// only when it enforces it, and callers refuse rather than pretend.
133    fn enforces_deny_read(&self) -> bool {
134        false
135    }
136    /// Whether the backend cuts the network when
137    /// [`SandboxCommand::allow_network`] is false. Default `false`, as for
138    /// [`Sandbox::enforces_deny_read`].
139    fn enforces_network_off(&self) -> bool {
140        false
141    }
142    async fn run(&self, cmd: &SandboxCommand) -> Result<CommandOutput>;
143}
144
145/// Spawn `command`, collect combined output with a bound, enforce the
146/// timeout and cancellation, and kill the process group on expiry.
147async fn run_process(
148    mut command: Command,
149    spec: &SandboxCommand,
150    clear_env: bool,
151) -> Result<CommandOutput> {
152    if clear_env {
153        command.env_clear();
154        command.envs(spec.env.iter().map(|(k, v)| (k, v)));
155    }
156    command
157        .stdin(Stdio::null())
158        .stdout(Stdio::piped())
159        .stderr(Stdio::piped())
160        .kill_on_drop(true);
161    #[cfg(unix)]
162    command.process_group(0);
163
164    let started = Instant::now();
165    let mut child = command.spawn()?;
166    let buffer = Arc::new(Mutex::new(HeadTail::new(spec.max_output_bytes)));
167
168    let mut pumps = Vec::new();
169    if let Some(stdout) = child.stdout.take() {
170        pumps.push(tokio::spawn(pump(stdout, buffer.clone())));
171    }
172    if let Some(stderr) = child.stderr.take() {
173        pumps.push(tokio::spawn(pump(stderr, buffer.clone())));
174    }
175
176    let mut timed_out = false;
177    let mut cancelled = false;
178    let status = tokio::select! {
179        status = child.wait() => Some(status?),
180        _ = tokio::time::sleep(spec.timeout) => { timed_out = true; None }
181        _ = spec.cancel.cancelled() => { cancelled = true; None }
182    };
183    if status.is_none() {
184        kill_tree(&mut child);
185        let _ = tokio::time::timeout(Duration::from_secs(2), child.wait()).await;
186    }
187    // Background grandchildren may hold the pipes open; give the readers a
188    // short grace period, then stop waiting.
189    let grace = Duration::from_millis(if status.is_some() { 1000 } else { 200 });
190    for pump in pumps {
191        let abort = pump.abort_handle();
192        if tokio::time::timeout(grace, pump).await.is_err() {
193            abort.abort();
194        }
195    }
196
197    let buf = buffer.lock().expect("output buffer poisoned");
198    Ok(CommandOutput {
199        exit_code: status.and_then(|s| s.code()),
200        output: buf.render(),
201        output_bytes: buf.total(),
202        truncated: buf.truncated(),
203        timed_out,
204        cancelled,
205        duration: started.elapsed(),
206    })
207}
208
209async fn pump(mut reader: impl tokio::io::AsyncRead + Unpin, buffer: Arc<Mutex<HeadTail>>) {
210    let mut chunk = [0u8; 8192];
211    loop {
212        match reader.read(&mut chunk).await {
213            Ok(0) | Err(_) => break,
214            Ok(n) => buffer
215                .lock()
216                .expect("output buffer poisoned")
217                .push(&chunk[..n]),
218        }
219    }
220}
221
222fn kill_tree(child: &mut tokio::process::Child) {
223    #[cfg(unix)]
224    if let Some(pid) = child.id() {
225        // The child leads its own process group; kill the whole group so
226        // pipelines and background jobs die too.
227        // SAFETY: kill(2) has no memory-safety preconditions.
228        unsafe {
229            libc::kill(-(pid as i32), libc::SIGKILL);
230        }
231    }
232    let _ = child.start_kill();
233}
234
235fn probe(program: &str, args: &[&str]) -> bool {
236    std::process::Command::new(program)
237        .args(args)
238        .stdin(Stdio::null())
239        .stdout(Stdio::null())
240        .stderr(Stdio::null())
241        .status()
242        .is_ok_and(|s| s.success())
243}
244
245// ------------------------------------------------------------ secret paths
246
247/// Credential locations under the home directory that the contained
248/// backends ([`BubblewrapSandbox`], [`SeatbeltSandbox`]) keep commands from
249/// reading by default: SSH keys, cloud and cluster credentials, GnuPG,
250/// registry logins, `.netrc` and git's stored credentials. Replace the
251/// list per backend with `default_deny_read(..)` (an empty list turns the
252/// defaults off).
253pub const HOME_SECRET_PATHS: &[&str] = &[
254    ".ssh",
255    ".aws",
256    ".gnupg",
257    ".config/gcloud",
258    ".kube",
259    ".docker/config.json",
260    ".netrc",
261    ".git-credentials",
262];
263
264/// [`HOME_SECRET_PATHS`] under `home`.
265pub fn home_secret_paths(home: &Path) -> Vec<PathBuf> {
266    HOME_SECRET_PATHS.iter().map(|rel| home.join(rel)).collect()
267}
268
269/// [`HOME_SECRET_PATHS`] under `$HOME` (empty when `HOME` is unset): the
270/// contained backends' default deny-read list.
271pub fn default_deny_read() -> Vec<PathBuf> {
272    std::env::var_os("HOME")
273        .filter(|home| !home.is_empty())
274        .map(|home| home_secret_paths(Path::new(&home)))
275        .unwrap_or_default()
276}
277
278/// The backend's defaults plus the command's own list. A default that
279/// contains the workspace is left out, so a workspace under, say, `~/.ssh`
280/// is not hidden from itself; a path the caller names is always kept.
281fn deny_list(defaults: &[PathBuf], cmd: &SandboxCommand) -> Vec<PathBuf> {
282    let root =
283        dunce::canonicalize(&cmd.workspace_root).unwrap_or_else(|_| cmd.workspace_root.clone());
284    let mut out: Vec<PathBuf> = existing_canonical(defaults)
285        .into_iter()
286        .filter(|path| !root.starts_with(path))
287        .collect();
288    for path in existing_canonical(&cmd.deny_read) {
289        if !out.contains(&path) {
290            out.push(path);
291        }
292    }
293    out
294}
295
296// -------------------------------------------------------------------- local
297
298/// Runs commands directly on the host with `sh -c`.
299///
300/// **No containment.** The command can read and write anything the current
301/// user can, and use the network. The environment is still reduced to the
302/// allowlist and the cwd is still confined to the workspace, but a command
303/// can `cd` anywhere. Use it only with trusted models or behind an approval
304/// hook.
305#[derive(Debug, Clone, Default)]
306pub struct LocalSandbox;
307
308#[async_trait]
309impl Sandbox for LocalSandbox {
310    fn name(&self) -> &'static str {
311        "local"
312    }
313
314    fn is_available(&self) -> bool {
315        crate::platform_shell::shell_available()
316    }
317
318    fn is_contained(&self) -> bool {
319        false
320    }
321
322    async fn run(&self, cmd: &SandboxCommand) -> Result<CommandOutput> {
323        let mut command = crate::platform_shell::shell_command(&cmd.command);
324        command.current_dir(&cmd.cwd);
325        run_process(command, cmd, true).await
326    }
327}
328
329// --------------------------------------------------------------- bubblewrap
330
331/// Linux sandbox using `bwrap`: the host filesystem is mounted read-only,
332/// the workspace read-write, `/tmp` is a private tmpfs, PID and (unless
333/// allowed) network namespaces are unshared, and the sandbox dies with its
334/// parent. The credential locations in [`HOME_SECRET_PATHS`] are hidden by
335/// default.
336#[derive(Debug, Clone)]
337pub struct BubblewrapSandbox {
338    program: String,
339    default_deny_read: Vec<PathBuf>,
340}
341
342impl Default for BubblewrapSandbox {
343    fn default() -> Self {
344        Self {
345            program: "bwrap".into(),
346            default_deny_read: default_deny_read(),
347        }
348    }
349}
350
351impl BubblewrapSandbox {
352    pub fn new() -> Self {
353        Self::default()
354    }
355
356    /// Replace the paths hidden from every command (default:
357    /// [`default_deny_read`]). An empty list hides nothing beyond each
358    /// command's own [`SandboxCommand::deny_read`].
359    pub fn default_deny_read(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
360        self.default_deny_read = paths.into_iter().collect();
361        self
362    }
363
364    /// The `bwrap` argument list for a spec (before `sh -c <command>`).
365    pub fn args(&self, cmd: &SandboxCommand) -> Vec<String> {
366        let ws = cmd.workspace_root.display().to_string();
367        let mut args: Vec<String> = [
368            "--ro-bind",
369            "/",
370            "/",
371            "--dev",
372            "/dev",
373            "--proc",
374            "/proc",
375            "--tmpfs",
376            "/tmp",
377        ]
378        .iter()
379        .map(|s| s.to_string())
380        .collect();
381        // After the tmpfs so a workspace under /tmp stays visible.
382        args.extend(["--bind".into(), ws.clone(), ws]);
383        // After the workspace so a denied path inside it is hidden too.
384        for path in deny_list(&self.default_deny_read, cmd) {
385            let path = path.display().to_string();
386            if Path::new(&path).is_dir() {
387                args.extend(["--tmpfs".into(), path]);
388            } else {
389                args.extend(["--ro-bind".into(), "/dev/null".into(), path]);
390            }
391        }
392        args.push("--unshare-pid".into());
393        if !cmd.allow_network {
394            args.push("--unshare-net".into());
395        }
396        args.extend([
397            "--die-with-parent".into(),
398            "--new-session".into(),
399            "--chdir".into(),
400            cmd.cwd.display().to_string(),
401            "--".into(),
402            "sh".into(),
403            "-c".into(),
404            cmd.command.clone(),
405        ]);
406        args
407    }
408}
409
410#[async_trait]
411impl Sandbox for BubblewrapSandbox {
412    fn name(&self) -> &'static str {
413        "bubblewrap"
414    }
415
416    fn is_available(&self) -> bool {
417        static AVAILABLE: OnceLock<bool> = OnceLock::new();
418        cfg!(target_os = "linux")
419            && *AVAILABLE.get_or_init(|| {
420                // Probe a real sandbox with the same mounts and namespaces
421                // `run` uses: bwrap may be installed while user namespaces
422                // are disabled (or restricted by AppArmor).
423                probe(
424                    &self.program,
425                    &[
426                        "--ro-bind",
427                        "/",
428                        "/",
429                        "--dev",
430                        "/dev",
431                        "--proc",
432                        "/proc",
433                        "--tmpfs",
434                        "/tmp",
435                        "--unshare-pid",
436                        "--unshare-net",
437                        "--die-with-parent",
438                        "--new-session",
439                        "true",
440                    ],
441                )
442            })
443    }
444
445    fn is_contained(&self) -> bool {
446        true
447    }
448
449    fn enforces_deny_read(&self) -> bool {
450        true
451    }
452
453    fn enforces_network_off(&self) -> bool {
454        true
455    }
456
457    async fn run(&self, cmd: &SandboxCommand) -> Result<CommandOutput> {
458        if !self.is_available() {
459            return Err(ExecError::Unavailable("bubblewrap"));
460        }
461        let mut command = Command::new(&self.program);
462        command.args(self.args(cmd));
463        run_process(command, cmd, true).await
464    }
465}
466
467/// What a task-scoped bubblewrap sandbox may touch: deny by default, unlike
468/// [`BubblewrapSandbox::args`] (which mounts the whole host read-only). The
469/// command sees the base system directories (the dynamic loader, `/usr`,
470/// `/bin`, `/lib`), a private `/dev`, `/proc` and `/tmp`, and exactly the
471/// listed paths: `read_paths` read-only, `write_paths` read-write. With
472/// `allow_network` it also sees the resolver and CA configuration it needs
473/// to use the network. Listed paths that do not exist are skipped.
474#[derive(Debug, Clone, Default, PartialEq, Eq)]
475pub struct BubblewrapScope {
476    /// Working directory inside the sandbox (absolute).
477    pub cwd: String,
478    pub read_paths: Vec<String>,
479    pub write_paths: Vec<String>,
480    pub allow_network: bool,
481}
482
483/// Base system paths every scoped command can read.
484const SCOPED_SYSTEM_READS: &[&str] = &[
485    "/usr",
486    "/bin",
487    "/sbin",
488    "/lib",
489    "/lib32",
490    "/lib64",
491    "/libx32",
492    "/etc/ld.so.cache",
493    "/etc/ld.so.conf",
494    "/etc/ld.so.conf.d",
495    "/etc/alternatives",
496];
497
498/// Extra configuration a networked scoped command reads (name resolution,
499/// TLS roots).
500const SCOPED_NETWORK_READS: &[&str] = &[
501    "/etc/resolv.conf",
502    "/etc/hosts",
503    "/etc/nsswitch.conf",
504    "/etc/gai.conf",
505    "/etc/ssl",
506    "/etc/ca-certificates",
507    "/etc/pki",
508];
509
510impl BubblewrapSandbox {
511    /// The `bwrap` argument list for a task-scoped command (see
512    /// [`BubblewrapScope`]), ending with `-- <command...>`. Listed paths are
513    /// mounted shallowest first, so a narrower grant inside a wider one
514    /// keeps its own access; a path listed both ways is writable.
515    pub fn scoped_args(scope: &BubblewrapScope, command: &[String]) -> Vec<String> {
516        let mut args: Vec<String> = Vec::new();
517        let system = SCOPED_SYSTEM_READS.iter().chain(if scope.allow_network {
518            SCOPED_NETWORK_READS.iter()
519        } else {
520            [].iter()
521        });
522        for path in system {
523            args.extend(["--ro-bind-try".into(), path.to_string(), path.to_string()]);
524        }
525        args.extend(
526            ["--dev", "/dev", "--proc", "/proc", "--tmpfs", "/tmp"]
527                .iter()
528                .map(|s| s.to_string()),
529        );
530        let mut mounts: Vec<(&str, bool)> = Vec::new();
531        for path in &scope.write_paths {
532            if !mounts.iter().any(|(p, _)| *p == path.as_str()) {
533                mounts.push((path.as_str(), true));
534            }
535        }
536        for path in &scope.read_paths {
537            if !mounts.iter().any(|(p, _)| *p == path.as_str()) {
538                mounts.push((path.as_str(), false));
539            }
540        }
541        // Stable: equal depths keep writes before reads, and paths keep
542        // their listed order.
543        mounts.sort_by_key(|(path, _)| Path::new(path).components().count());
544        for (path, writable) in mounts {
545            let flag = if writable {
546                "--bind-try"
547            } else {
548                "--ro-bind-try"
549            };
550            args.extend([flag.into(), path.to_string(), path.to_string()]);
551        }
552        args.push("--unshare-pid".into());
553        if !scope.allow_network {
554            args.push("--unshare-net".into());
555        }
556        args.extend([
557            "--die-with-parent".into(),
558            "--new-session".into(),
559            "--chdir".into(),
560            scope.cwd.clone(),
561            "--".into(),
562        ]);
563        args.extend(command.iter().cloned());
564        args
565    }
566}
567
568// ----------------------------------------------------------------- seatbelt
569
570/// macOS sandbox using `sandbox-exec` with a generated profile: everything
571/// is readable except the credential locations in [`HOME_SECRET_PATHS`]
572/// (by default) and each command's deny list, writes are allowed only under
573/// the workspace (plus the `/dev` null/tty nodes), and the network is
574/// denied unless allowed.
575#[derive(Debug, Clone)]
576pub struct SeatbeltSandbox {
577    default_deny_read: Vec<PathBuf>,
578}
579
580impl Default for SeatbeltSandbox {
581    fn default() -> Self {
582        Self {
583            default_deny_read: default_deny_read(),
584        }
585    }
586}
587
588/// The canonical form of each path that exists (sandboxes match real paths:
589/// `/tmp` is `/private/tmp` on macOS, and bwrap cannot mount over a missing
590/// path on a read-only root).
591fn existing_canonical(paths: &[PathBuf]) -> Vec<PathBuf> {
592    paths
593        .iter()
594        .filter_map(|p| dunce::canonicalize(p).ok())
595        .collect()
596}
597
598fn sbpl_string(path: &Path) -> String {
599    let raw = path.display().to_string();
600    format!("\"{}\"", raw.replace('\\', "\\\\").replace('"', "\\\""))
601}
602
603impl SeatbeltSandbox {
604    pub fn new() -> Self {
605        Self::default()
606    }
607
608    /// Replace the paths no command may read (default:
609    /// [`default_deny_read`]). An empty list denies nothing beyond each
610    /// command's own [`SandboxCommand::deny_read`].
611    pub fn default_deny_read(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
612        self.default_deny_read = paths.into_iter().collect();
613        self
614    }
615
616    /// The generated sandbox profile (SBPL) for a spec.
617    pub fn profile(&self, cmd: &SandboxCommand) -> String {
618        let mut profile = String::from("(version 1)\n(allow default)\n(deny file-write*)\n");
619        profile.push_str(&format!(
620            "(allow file-write* (subpath {}) (literal \"/dev/null\") (literal \"/dev/tty\") \
621             (literal \"/dev/zero\") (regex #\"^/dev/fd/\"))\n",
622            sbpl_string(&cmd.workspace_root)
623        ));
624        if !cmd.allow_network {
625            profile.push_str("(deny network*)\n");
626        }
627        for path in deny_list(&self.default_deny_read, cmd) {
628            profile.push_str(&format!(
629                "(deny file-read* file-write* (subpath {}))\n",
630                sbpl_string(&path)
631            ));
632        }
633        profile
634    }
635
636    pub fn args(&self, cmd: &SandboxCommand) -> Vec<String> {
637        vec![
638            "-p".into(),
639            self.profile(cmd),
640            "sh".into(),
641            "-c".into(),
642            cmd.command.clone(),
643        ]
644    }
645}
646
647#[async_trait]
648impl Sandbox for SeatbeltSandbox {
649    fn name(&self) -> &'static str {
650        "seatbelt"
651    }
652
653    fn is_available(&self) -> bool {
654        cfg!(target_os = "macos") && Path::new("/usr/bin/sandbox-exec").exists()
655    }
656
657    fn is_contained(&self) -> bool {
658        true
659    }
660
661    fn enforces_deny_read(&self) -> bool {
662        true
663    }
664
665    fn enforces_network_off(&self) -> bool {
666        true
667    }
668
669    async fn run(&self, cmd: &SandboxCommand) -> Result<CommandOutput> {
670        if !self.is_available() {
671            return Err(ExecError::Unavailable("seatbelt"));
672        }
673        let mut command = Command::new("/usr/bin/sandbox-exec");
674        command.args(self.args(cmd)).current_dir(&cmd.cwd);
675        run_process(command, cmd, true).await
676    }
677}
678
679// ------------------------------------------------------------------- docker
680
681/// Runs each command in a fresh container: the workspace is mounted at
682/// `/workspace`, `--network none` unless allowed, and the container is
683/// removed afterwards (and killed on timeout). No other host path is
684/// mounted, so host paths in [`SandboxCommand::deny_read`] are out of reach
685/// already; denied paths inside the workspace are covered by an empty
686/// mount. On Unix the container runs as
687/// the calling user so files it creates stay editable.
688///
689/// The `docker` CLI keeps the host environment (it needs `DOCKER_HOST`,
690/// config paths and so on); the command inside sees only the spec's env,
691/// minus `PATH` and `HOME`, which come from the image.
692#[derive(Debug, Clone)]
693pub struct DockerSandbox {
694    image: String,
695    program: String,
696}
697
698static CONTAINER_SEQ: AtomicU64 = AtomicU64::new(0);
699
700impl DockerSandbox {
701    pub fn new(image: impl Into<String>) -> Self {
702        Self {
703            image: image.into(),
704            program: "docker".into(),
705        }
706    }
707
708    pub fn image(&self) -> &str {
709        &self.image
710    }
711
712    /// The `docker` argument list for a spec and container name.
713    pub fn args(&self, cmd: &SandboxCommand, name: &str) -> Vec<String> {
714        let rel = cmd
715            .cwd
716            .strip_prefix(&cmd.workspace_root)
717            .unwrap_or(Path::new(""));
718        let workdir = Path::new("/workspace").join(rel);
719        let mut args: Vec<String> = vec![
720            "run".into(),
721            "--rm".into(),
722            "--init".into(),
723            "--name".into(),
724            name.into(),
725        ];
726        if !cmd.allow_network {
727            args.extend(["--network".into(), "none".into()]);
728        }
729        #[cfg(unix)]
730        {
731            // SAFETY: getuid/getgid cannot fail and touch no memory.
732            let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
733            args.extend(["--user".into(), format!("{uid}:{gid}")]);
734        }
735        args.extend([
736            "-v".into(),
737            format!("{}:/workspace", cmd.workspace_root.display()),
738            "-w".into(),
739            workdir.display().to_string(),
740        ]);
741        let root =
742            dunce::canonicalize(&cmd.workspace_root).unwrap_or_else(|_| cmd.workspace_root.clone());
743        for path in existing_canonical(&cmd.deny_read) {
744            let Ok(rel) = path.strip_prefix(&root) else {
745                continue; // not mounted at all
746            };
747            let inside = Path::new("/workspace").join(rel).display().to_string();
748            if path.is_dir() {
749                args.extend(["--tmpfs".into(), inside]);
750            } else {
751                args.extend(["-v".into(), format!("/dev/null:{inside}:ro")]);
752            }
753        }
754        for (key, value) in &cmd.env {
755            if key != "PATH" && key != "HOME" {
756                args.extend(["-e".into(), format!("{key}={value}")]);
757            }
758        }
759        args.extend([
760            self.image.clone(),
761            "sh".into(),
762            "-c".into(),
763            cmd.command.clone(),
764        ]);
765        args
766    }
767}
768
769#[async_trait]
770impl Sandbox for DockerSandbox {
771    fn name(&self) -> &'static str {
772        "docker"
773    }
774
775    fn is_available(&self) -> bool {
776        static AVAILABLE: OnceLock<bool> = OnceLock::new();
777        *AVAILABLE.get_or_init(|| probe(&self.program, &["info", "--format", "{{.ServerVersion}}"]))
778    }
779
780    fn is_contained(&self) -> bool {
781        true
782    }
783
784    fn enforces_deny_read(&self) -> bool {
785        true
786    }
787
788    fn enforces_network_off(&self) -> bool {
789        true
790    }
791
792    async fn run(&self, cmd: &SandboxCommand) -> Result<CommandOutput> {
793        if !self.is_available() {
794            return Err(ExecError::Unavailable("docker"));
795        }
796        let nanos = std::time::SystemTime::now()
797            .duration_since(std::time::UNIX_EPOCH)
798            .map(|d| d.subsec_nanos())
799            .unwrap_or_default();
800        let name = format!(
801            "aidaemon-{}-{}-{nanos}",
802            std::process::id(),
803            CONTAINER_SEQ.fetch_add(1, Ordering::Relaxed)
804        );
805        let mut command = Command::new(&self.program);
806        command.args(self.args(cmd, &name));
807        let out = run_process(command, cmd, false).await?;
808        if out.timed_out || out.cancelled {
809            let _ = Command::new(&self.program)
810                .args(["kill", &name])
811                .stdout(Stdio::null())
812                .stderr(Stdio::null())
813                .status()
814                .await;
815        }
816        Ok(out)
817    }
818}
819
820/// The backends the default shell can choose between.
821#[derive(Debug, Clone, Copy, PartialEq, Eq)]
822pub enum SandboxKind {
823    /// [`BubblewrapSandbox`] (Linux).
824    Bubblewrap,
825    /// [`SeatbeltSandbox`] (macOS).
826    Seatbelt,
827    /// [`LocalSandbox`]: no containment.
828    Local,
829}
830
831impl SandboxKind {
832    pub fn as_str(self) -> &'static str {
833        match self {
834            Self::Bubblewrap => "bubblewrap",
835            Self::Seatbelt => "seatbelt",
836            Self::Local => "local",
837        }
838    }
839
840    /// A new backend of this kind.
841    pub fn backend(self) -> Arc<dyn Sandbox> {
842        match self {
843            Self::Bubblewrap => Arc::new(BubblewrapSandbox::new()),
844            Self::Seatbelt => Arc::new(SeatbeltSandbox::new()),
845            Self::Local => Arc::new(LocalSandbox),
846        }
847    }
848}
849
850impl std::str::FromStr for SandboxKind {
851    type Err = String;
852
853    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
854        match value.trim().to_ascii_lowercase().as_str() {
855            "bubblewrap" | "bwrap" => Ok(Self::Bubblewrap),
856            "seatbelt" | "sandbox-exec" => Ok(Self::Seatbelt),
857            "local" | "host" | "none" => Ok(Self::Local),
858            other => Err(format!(
859                "unknown sandbox `{other}` (expected auto, bubblewrap, seatbelt or local)"
860            )),
861        }
862    }
863}
864
865/// Environment variable that overrides the default shell's backend:
866/// `auto` (or unset), `bubblewrap`, `seatbelt`, or `local` (no containment).
867pub const SANDBOX_ENV: &str = "AIDAEMON_SHELL_SANDBOX";
868
869/// The result of [`select_sandbox`].
870#[derive(Debug, Clone, Copy, PartialEq, Eq)]
871pub struct SandboxSelection {
872    pub kind: SandboxKind,
873    /// No contained backend was available, so commands run uncontained.
874    /// Never set for an explicit choice.
875    pub fell_back: bool,
876}
877
878/// Pick a backend. An explicit `preference` always wins (an unavailable one
879/// then fails each command with [`ExecError::Unavailable`] rather than
880/// running uncontained). Otherwise the first available of bubblewrap and
881/// seatbelt, else [`SandboxKind::Local`] with `fell_back` set. `available`
882/// is the probe, injectable for tests.
883pub fn select_sandbox(
884    preference: Option<SandboxKind>,
885    available: impl Fn(SandboxKind) -> bool,
886) -> SandboxSelection {
887    if let Some(kind) = preference {
888        return SandboxSelection {
889            kind,
890            fell_back: false,
891        };
892    }
893    for kind in [SandboxKind::Bubblewrap, SandboxKind::Seatbelt] {
894        if available(kind) {
895            return SandboxSelection {
896                kind,
897                fell_back: false,
898            };
899        }
900    }
901    SandboxSelection {
902        kind: SandboxKind::Local,
903        fell_back: true,
904    }
905}
906
907/// Read [`SANDBOX_ENV`]: `Ok(None)` for unset, empty or `auto`.
908pub fn sandbox_preference_from_env() -> std::result::Result<Option<SandboxKind>, String> {
909    match std::env::var(SANDBOX_ENV) {
910        Ok(value) if value.trim().is_empty() || value.trim().eq_ignore_ascii_case("auto") => {
911            Ok(None)
912        }
913        Ok(value) => value.parse().map(Some),
914        Err(_) => Ok(None),
915    }
916}
917
918fn is_kind_available(kind: SandboxKind) -> bool {
919    match kind {
920        SandboxKind::Bubblewrap => BubblewrapSandbox::new().is_available(),
921        SandboxKind::Seatbelt => SeatbeltSandbox::new().is_available(),
922        SandboxKind::Local => LocalSandbox.is_available(),
923    }
924}
925
926/// The default shell's backend: the one named by [`SANDBOX_ENV`], else the
927/// most contained one available here (bubblewrap on Linux, seatbelt on
928/// macOS), else [`LocalSandbox`] (uncontained) with a one-time warning.
929/// Docker is never picked automatically because it needs an image choice.
930pub fn best_available_sandbox() -> Arc<dyn Sandbox> {
931    static WARN_ENV: std::sync::Once = std::sync::Once::new();
932    static WARN_FALLBACK: std::sync::Once = std::sync::Once::new();
933    let preference = sandbox_preference_from_env().unwrap_or_else(|err| {
934        WARN_ENV.call_once(|| tracing::warn!("{SANDBOX_ENV}: {err}; choosing automatically"));
935        None
936    });
937    let selection = select_sandbox(preference, is_kind_available);
938    if selection.fell_back {
939        WARN_FALLBACK.call_once(|| {
940            tracing::warn!(
941                "no OS sandbox is available ({}); the shell tool runs commands \
942                 uncontained on the host. Install bubblewrap on Linux, or set \
943                 {SANDBOX_ENV}=local to choose this explicitly.",
944                if cfg!(target_os = "linux") {
945                    "bwrap is missing or user namespaces are disabled"
946                } else {
947                    "no supported sandbox on this platform"
948                }
949            )
950        });
951    }
952    selection.kind.backend()
953}
954
955#[cfg(test)]
956mod tests {
957    use super::*;
958
959    fn spec(root: &Path) -> SandboxCommand {
960        let mut s = SandboxCommand::new("echo hi", root);
961        s.cwd = root.join("sub");
962        s.env = vec![
963            ("PATH".into(), "/usr/bin:/bin".into()),
964            ("LANG".into(), "C".into()),
965        ];
966        s
967    }
968
969    #[test]
970    fn bubblewrap_args_confine_and_drop_network() {
971        let s = spec(Path::new("/tmp/ws"));
972        let args = BubblewrapSandbox::new().args(&s);
973        let joined = args.join(" ");
974        assert!(joined.starts_with(
975            "--ro-bind / / --dev /dev --proc /proc --tmpfs /tmp --bind /tmp/ws /tmp/ws"
976        ));
977        assert!(args.contains(&"--unshare-net".to_string()));
978        assert!(args.contains(&"--die-with-parent".to_string()));
979        assert!(joined.ends_with("--chdir /tmp/ws/sub -- sh -c echo hi"));
980        let mut open = s.clone();
981        open.allow_network = true;
982        assert!(
983            !BubblewrapSandbox::new()
984                .args(&open)
985                .contains(&"--unshare-net".to_string())
986        );
987    }
988
989    #[test]
990    fn bubblewrap_scoped_args_mount_only_the_listed_paths() {
991        let scope = BubblewrapScope {
992            cwd: "/work/repo".into(),
993            read_paths: vec!["/work/repo".into(), "/work/repo/src".into()],
994            write_paths: vec!["/work/repo/target".into(), "/work/repo".into()],
995            allow_network: false,
996        };
997        let command = vec!["/bin/sh".to_string(), "-c".into(), "make".into()];
998        let args = BubblewrapSandbox::scoped_args(&scope, &command);
999        let joined = args.join(" ");
1000        // Deny by default: never the whole host, and no network config.
1001        assert!(!joined.contains("--ro-bind / /"), "{joined}");
1002        assert!(!joined.contains("/etc/resolv.conf"), "{joined}");
1003        assert!(joined.contains("--ro-bind-try /usr /usr"));
1004        assert!(joined.contains("--dev /dev --proc /proc --tmpfs /tmp"));
1005        // Shallowest first; the repo is listed both ways and stays writable;
1006        // the narrower read-only `src` comes after it.
1007        let repo = joined.find("--bind-try /work/repo /work/repo").unwrap();
1008        let src = joined
1009            .find("--ro-bind-try /work/repo/src /work/repo/src")
1010            .unwrap();
1011        let target = joined
1012            .find("--bind-try /work/repo/target /work/repo/target")
1013            .unwrap();
1014        assert!(repo < src && repo < target, "{joined}");
1015        assert!(!joined.contains("--ro-bind-try /work/repo /work/repo"));
1016        // The private /tmp is mounted before any listed path under it.
1017        assert!(joined.find("--tmpfs /tmp").unwrap() < repo);
1018        assert!(args.contains(&"--unshare-net".to_string()));
1019        assert!(joined.ends_with("--chdir /work/repo -- /bin/sh -c make"));
1020    }
1021
1022    #[test]
1023    fn bubblewrap_scoped_args_with_network_read_the_resolver() {
1024        let scope = BubblewrapScope {
1025            cwd: "/".into(),
1026            allow_network: true,
1027            ..BubblewrapScope::default()
1028        };
1029        let args = BubblewrapSandbox::scoped_args(&scope, &["true".to_string()]);
1030        let joined = args.join(" ");
1031        assert!(!args.contains(&"--unshare-net".to_string()));
1032        assert!(joined.contains("--ro-bind-try /etc/resolv.conf /etc/resolv.conf"));
1033        assert!(joined.contains("--ro-bind-try /etc/ssl /etc/ssl"));
1034    }
1035
1036    #[test]
1037    fn bubblewrap_args_hide_denied_paths_after_the_workspace() {
1038        let ws = tempfile::tempdir().unwrap();
1039        let root = dunce::canonicalize(ws.path()).unwrap();
1040        std::fs::create_dir(root.join("secrets")).unwrap();
1041        std::fs::write(root.join("token"), "t").unwrap();
1042        let mut s = SandboxCommand::new("true", &root);
1043        s.deny_read = vec![
1044            root.join("secrets"),
1045            root.join("token"),
1046            root.join("missing"),
1047        ];
1048        let joined = BubblewrapSandbox::new().args(&s).join(" ");
1049        let ws_bind = format!("--bind {0} {0}", root.display());
1050        let dir = format!("--tmpfs {}", root.join("secrets").display());
1051        let file = format!("--ro-bind /dev/null {}", root.join("token").display());
1052        let at = |needle: &str| {
1053            joined
1054                .find(needle)
1055                .unwrap_or_else(|| panic!("{needle}: {joined}"))
1056        };
1057        assert!(at(&ws_bind) < at(&dir) && at(&ws_bind) < at(&file));
1058        assert!(!joined.contains("missing"), "{joined}");
1059    }
1060
1061    #[test]
1062    fn seatbelt_profile_denies_reads_of_denied_paths() {
1063        let ws = tempfile::tempdir().unwrap();
1064        let root = dunce::canonicalize(ws.path()).unwrap();
1065        let mut s = SandboxCommand::new("true", &root);
1066        s.deny_read = vec![root.clone(), root.join("missing")];
1067        let profile = SeatbeltSandbox::new().profile(&s);
1068        assert!(
1069            profile.contains(&format!(
1070                "(deny file-read* file-write* (subpath {}))",
1071                sbpl_string(&root)
1072            )),
1073            "{profile}"
1074        );
1075        assert!(!profile.contains("missing"));
1076    }
1077
1078    #[test]
1079    fn home_secrets_are_denied_by_default_after_the_workspace() {
1080        let home = tempfile::tempdir().unwrap();
1081        let home = dunce::canonicalize(home.path()).unwrap();
1082        std::fs::create_dir_all(home.join(".aws")).unwrap();
1083        std::fs::write(home.join(".netrc"), "machine x").unwrap();
1084        let ws = home.join("project");
1085        std::fs::create_dir(&ws).unwrap();
1086        let s = SandboxCommand::new("true", &ws);
1087
1088        let seatbelt = SeatbeltSandbox::new().default_deny_read(home_secret_paths(&home));
1089        let profile = seatbelt.profile(&s);
1090        for denied in [".aws", ".netrc"] {
1091            assert!(
1092                profile.contains(&format!(
1093                    "(deny file-read* file-write* (subpath {}))",
1094                    sbpl_string(&home.join(denied))
1095                )),
1096                "{profile}"
1097            );
1098        }
1099        assert!(!profile.contains(".ssh"), "missing paths are skipped");
1100        let none = SeatbeltSandbox::new().default_deny_read(Vec::new());
1101        assert!(!none.profile(&s).contains(".aws"));
1102
1103        let bwrap = BubblewrapSandbox::new().default_deny_read(home_secret_paths(&home));
1104        let joined = bwrap.args(&s).join(" ");
1105        let ws_bind = format!("--bind {0} {0}", ws.display());
1106        let aws = format!("--tmpfs {}", home.join(".aws").display());
1107        let netrc = format!("--ro-bind /dev/null {}", home.join(".netrc").display());
1108        let at = |needle: &str| {
1109            joined
1110                .find(needle)
1111                .unwrap_or_else(|| panic!("{needle}: {joined}"))
1112        };
1113        assert!(at(&ws_bind) < at(&aws) && at(&ws_bind) < at(&netrc));
1114
1115        // A workspace inside a default location is not hidden from itself.
1116        let inside = home.join(".aws/project");
1117        std::fs::create_dir(&inside).unwrap();
1118        let s = SandboxCommand::new("true", &inside);
1119        let joined = bwrap.args(&s).join(" ");
1120        assert!(!joined.contains(&aws), "{joined}");
1121        assert!(
1122            !seatbelt
1123                .profile(&s)
1124                .contains(&sbpl_string(&home.join(".aws")))
1125        );
1126
1127        // The real defaults cover the usual locations under $HOME.
1128        let defaults = default_deny_read();
1129        if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
1130            assert!(defaults.contains(&Path::new(&home).join(".ssh")));
1131            assert!(defaults.contains(&Path::new(&home).join(".aws")));
1132        }
1133    }
1134
1135    #[test]
1136    fn backends_say_what_they_enforce() {
1137        assert!(!LocalSandbox.enforces_deny_read());
1138        assert!(!LocalSandbox.enforces_network_off());
1139        for backend in [
1140            Arc::new(BubblewrapSandbox::new()) as Arc<dyn Sandbox>,
1141            Arc::new(SeatbeltSandbox::new()),
1142            Arc::new(DockerSandbox::new("alpine:3")),
1143        ] {
1144            assert!(backend.enforces_deny_read(), "{}", backend.name());
1145            assert!(backend.enforces_network_off(), "{}", backend.name());
1146        }
1147    }
1148
1149    #[test]
1150    fn explicit_choice_wins_even_when_unavailable() {
1151        for kind in [
1152            SandboxKind::Bubblewrap,
1153            SandboxKind::Seatbelt,
1154            SandboxKind::Local,
1155        ] {
1156            let chosen = select_sandbox(Some(kind), |_| false);
1157            assert_eq!(chosen.kind, kind);
1158            assert!(!chosen.fell_back);
1159        }
1160    }
1161
1162    #[test]
1163    fn automatic_choice_prefers_contained_backends() {
1164        let only = |k: SandboxKind| move |c: SandboxKind| c == k;
1165        let bwrap = select_sandbox(None, only(SandboxKind::Bubblewrap));
1166        assert_eq!(bwrap.kind, SandboxKind::Bubblewrap);
1167        assert!(!bwrap.fell_back);
1168        let seatbelt = select_sandbox(None, only(SandboxKind::Seatbelt));
1169        assert_eq!(seatbelt.kind, SandboxKind::Seatbelt);
1170        assert!(!seatbelt.fell_back);
1171        assert_eq!(select_sandbox(None, |_| true).kind, SandboxKind::Bubblewrap);
1172        // No OS sandbox: uncontained, and flagged so the caller warns.
1173        let none = select_sandbox(None, |_| false);
1174        assert_eq!(none.kind, SandboxKind::Local);
1175        assert!(none.fell_back);
1176        let local_only = select_sandbox(None, only(SandboxKind::Local));
1177        assert_eq!(local_only.kind, SandboxKind::Local);
1178        assert!(local_only.fell_back);
1179    }
1180
1181    #[test]
1182    fn sandbox_kind_parses_names_and_builds_backends() {
1183        assert_eq!("bwrap".parse(), Ok(SandboxKind::Bubblewrap));
1184        assert_eq!(" Bubblewrap ".parse(), Ok(SandboxKind::Bubblewrap));
1185        assert_eq!("seatbelt".parse(), Ok(SandboxKind::Seatbelt));
1186        assert_eq!("none".parse(), Ok(SandboxKind::Local));
1187        assert_eq!("host".parse(), Ok(SandboxKind::Local));
1188        assert!("docker".parse::<SandboxKind>().is_err());
1189        for kind in [
1190            SandboxKind::Bubblewrap,
1191            SandboxKind::Seatbelt,
1192            SandboxKind::Local,
1193        ] {
1194            assert_eq!(kind.backend().name(), kind.as_str());
1195        }
1196    }
1197
1198    #[test]
1199    fn the_platform_default_matches_the_probe() {
1200        if std::env::var_os(SANDBOX_ENV).is_some() {
1201            println!("skipping: {SANDBOX_ENV} is set");
1202            return;
1203        }
1204        let expected = select_sandbox(None, is_kind_available).kind;
1205        assert_eq!(best_available_sandbox().name(), expected.as_str());
1206        if cfg!(target_os = "macos") && SeatbeltSandbox::new().is_available() {
1207            assert_eq!(expected, SandboxKind::Seatbelt);
1208        }
1209    }
1210
1211    #[tokio::test]
1212    async fn seatbelt_blocks_reads_of_home_secrets_by_default() {
1213        if !SeatbeltSandbox::new().is_available() {
1214            println!("skipping: sandbox-exec is not available");
1215            return;
1216        }
1217        let home = tempfile::tempdir().unwrap();
1218        std::fs::create_dir(home.path().join(".aws")).unwrap();
1219        std::fs::write(home.path().join(".aws/credentials"), "synthetic-secret").unwrap();
1220        let backend = SeatbeltSandbox::new().default_deny_read(home_secret_paths(home.path()));
1221        let ws = tempfile::tempdir().unwrap();
1222        let root = dunce::canonicalize(ws.path()).unwrap();
1223        let cat = format!("cat {}/.aws/credentials", home.path().display());
1224        let mut s = SandboxCommand::new(cat.clone(), &root);
1225        s.env = vec![("PATH".into(), "/usr/bin:/bin".into())];
1226        let out = backend.run(&s).await.unwrap();
1227        assert_ne!(out.exit_code, Some(0), "{}", out.output);
1228        assert!(!out.output.contains("synthetic-secret"), "{}", out.output);
1229        // Readable without the defaults, so the denial is the sandbox's.
1230        let open = SeatbeltSandbox::new().default_deny_read(Vec::new());
1231        let out = open.run(&s).await.unwrap();
1232        assert!(out.output.contains("synthetic-secret"), "{}", out.output);
1233    }
1234
1235    #[tokio::test]
1236    async fn seatbelt_blocks_reads_of_denied_paths() {
1237        let backend = SeatbeltSandbox::new();
1238        if !backend.is_available() {
1239            println!("skipping: sandbox-exec is not available");
1240            return;
1241        }
1242        let ws = tempfile::tempdir().unwrap();
1243        let root = dunce::canonicalize(ws.path()).unwrap();
1244        let secrets = tempfile::tempdir().unwrap();
1245        std::fs::write(secrets.path().join("key"), "synthetic-secret").unwrap();
1246        let mut s = SandboxCommand::new(format!("cat {}/key", secrets.path().display()), &root);
1247        s.env = vec![("PATH".into(), "/usr/bin:/bin".into())];
1248        s.deny_read = vec![secrets.path().to_path_buf()];
1249        let out = backend.run(&s).await.unwrap();
1250        assert_ne!(out.exit_code, Some(0), "{}", out.output);
1251        assert!(!out.output.contains("synthetic-secret"), "{}", out.output);
1252    }
1253
1254    #[test]
1255    fn seatbelt_profile_limits_writes_and_network() {
1256        let s = spec(Path::new("/Users/alice/ws \"q\""));
1257        let profile = SeatbeltSandbox::new().profile(&s);
1258        assert!(profile.contains("(deny file-write*)"));
1259        assert!(
1260            profile.contains("(subpath \"/Users/alice/ws \\\"q\\\"\")"),
1261            "{profile}"
1262        );
1263        assert!(profile.contains("(deny network*)"));
1264        let mut open = s.clone();
1265        open.allow_network = true;
1266        assert!(!SeatbeltSandbox::new().profile(&open).contains("network"));
1267    }
1268
1269    #[test]
1270    fn docker_args_mount_workspace_without_network() {
1271        let s = spec(Path::new("/srv/ws"));
1272        let args = DockerSandbox::new("alpine:3").args(&s, "c1");
1273        let joined = args.join(" ");
1274        assert!(joined.contains("--network none"));
1275        assert!(joined.contains("-v /srv/ws:/workspace -w /workspace/sub"));
1276        assert!(joined.contains("-e LANG=C"));
1277        assert!(!joined.contains("PATH="));
1278        assert!(joined.ends_with("alpine:3 sh -c echo hi"));
1279    }
1280
1281    #[test]
1282    fn docker_args_cover_denied_paths_inside_the_workspace() {
1283        let ws = tempfile::tempdir().unwrap();
1284        let root = dunce::canonicalize(ws.path()).unwrap();
1285        std::fs::create_dir(root.join("private")).unwrap();
1286        std::fs::write(root.join("token"), "t").unwrap();
1287        let mut s = SandboxCommand::new("true", &root);
1288        s.deny_read = vec![root.join("private"), root.join("token"), "/etc".into()];
1289        let joined = DockerSandbox::new("alpine:3").args(&s, "c1").join(" ");
1290        assert!(joined.contains("--tmpfs /workspace/private"), "{joined}");
1291        assert!(
1292            joined.contains("-v /dev/null:/workspace/token:ro"),
1293            "{joined}"
1294        );
1295        assert!(
1296            !joined.contains("/etc"),
1297            "not mounted, nothing to cover: {joined}"
1298        );
1299    }
1300
1301    #[tokio::test]
1302    async fn bubblewrap_blocks_writes_outside_workspace() {
1303        let backend = BubblewrapSandbox::new();
1304        if !backend.is_available() {
1305            println!("skipping: bubblewrap is not available");
1306            return;
1307        }
1308        let ws = tempfile::tempdir().unwrap();
1309        let root = dunce::canonicalize(ws.path()).unwrap();
1310        let outside = tempfile::tempdir_in(std::env::var("HOME").unwrap_or("/".into()))
1311            .or_else(|_| tempfile::tempdir())
1312            .unwrap();
1313        let mut s = SandboxCommand::new(
1314            format!(
1315                "echo ok > inside.txt; echo bad > {}/x.txt; echo done",
1316                outside.path().display()
1317            ),
1318            &root,
1319        );
1320        s.env = vec![("PATH".into(), "/usr/bin:/bin".into())];
1321        let out = backend.run(&s).await.unwrap();
1322        assert!(root.join("inside.txt").exists(), "{}", out.output);
1323        assert!(!outside.path().join("x.txt").exists());
1324    }
1325
1326    #[tokio::test]
1327    async fn seatbelt_blocks_writes_outside_workspace() {
1328        let backend = SeatbeltSandbox::new();
1329        if !backend.is_available() {
1330            println!("skipping: sandbox-exec is not available");
1331            return;
1332        }
1333        let ws = tempfile::tempdir().unwrap();
1334        let root = dunce::canonicalize(ws.path()).unwrap();
1335        let outside = tempfile::tempdir().unwrap();
1336        let mut s = SandboxCommand::new(
1337            format!(
1338                "echo ok > inside.txt; echo bad > {}/x.txt",
1339                outside.path().display()
1340            ),
1341            &root,
1342        );
1343        s.env = vec![("PATH".into(), "/usr/bin:/bin".into())];
1344        backend.run(&s).await.unwrap();
1345        assert!(root.join("inside.txt").exists());
1346        assert!(!outside.path().join("x.txt").exists());
1347    }
1348}