Skip to main content

tinyharness_lib/
sandbox.rs

1//! OS-level process sandbox for shell-executing tools (`run`, custom tools).
2//!
3//! The built-in file tools are confined by [`PathGuard`](crate::path_guard::PathGuard)
4//! — a pure path check, because they run in-process. Shell commands cannot be
5//! confined that way: a command string is arbitrary, so there is nothing
6//! reliable to inspect before it runs. Those go through a real kernel-enforced
7//! sandbox instead, via `bwrap` (bubblewrap) or `firejail`.
8//!
9//! Both backends are auto-detected ([`Sandbox::detect`]); `bwrap` is preferred
10//! because it is deny-by-default and needs no setuid helper.
11//!
12//! # What the backends guarantee
13//!
14//! **bwrap** builds a fresh mount tree from a `tmpfs` root and binds *only*
15//! what the command needs, so anything not bound simply does not exist inside
16//! the sandbox: the workspace (read-write), the system libraries and `/etc`
17//! (read-only), the file `/etc/resolv.conf` points at when it is a symlink out
18//! of `/etc` (see `resolv_conf_target`), and whatever the user added via
19//! `allowed_paths`. It also unshares the PID, IPC, UTS and cgroup namespaces,
20//! clears the environment, and starts a new session so a command cannot grab
21//! the terminal.
22//!
23//! **firejail** takes the opposite approach: it mounts the *existing* host
24//! filesystem read-only and re-binds the workspace read-write, then drops
25//! capabilities and applies seccomp. Reads outside the workspace are
26//! therefore **still possible** under firejail — it is write/privilege
27//! containment, not visibility containment. It also normally relies on a
28//! setuid helper. Prefer bwrap when containment matters.
29//!
30//! # Network
31//!
32//! The network is **always available** to sandboxed commands, under both
33//! backends. A coding agent runs `git fetch`, `curl`, and `cargo add` constantly;
34//! blocking those would make the sandbox unusable rather than safe, and the
35//! exfiltration risk it would mitigate is already accepted by giving the model
36//! shell access. Network isolation is out of scope here.
37//!
38//! Reachability is not the same as *configuration*, though: name resolution
39//! needs `/etc/resolv.conf`, which on a systemd-resolved host is a symlink into
40//! the unbound `/run`. bwrap therefore binds that target explicitly, or every
41//! `curl`/`npm`/`git fetch` fails with a DNS error that looks exactly like a
42//! blocked network.
43//!
44//! # Limits
45//!
46//! Neither backend defends against a hostile *user*: the sandboxed process
47//! still runs as the same uid, so anything the workspace bind exposes (`.env`,
48//! `.git`, committed credentials) is in scope — and reachable over the network.
49//! Nor is either a container: no image, no uid remapping, no resource limits
50//! beyond what the flags here provide.
51//!
52//! # Widening the sandbox
53//!
54//! `allowed_paths` widens the filesystem view (read-only) and
55//! `sandbox.writable_paths` grants write access to specific extra directories.
56//! Both are reported in the startup banner.
57
58use std::ffi::OsString;
59use std::path::{Path, PathBuf};
60use std::process::{Command as StdCommand, Stdio};
61
62/// Which OS facility provides the sandbox.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum SandboxBackend {
65    /// bubblewrap — unprivileged user-namespace sandbox (preferred).
66    Bwrap,
67    /// firejail — setuid sandbox with a read-only host root.
68    Firejail,
69}
70
71/// Every backend, in preference order.
72pub const ALL_BACKENDS: [SandboxBackend; 2] = [SandboxBackend::Bwrap, SandboxBackend::Firejail];
73
74impl SandboxBackend {
75    /// The executable that implements this backend.
76    pub fn binary(self) -> &'static str {
77        match self {
78            SandboxBackend::Bwrap => "bwrap",
79            SandboxBackend::Firejail => "firejail",
80        }
81    }
82
83    /// Parse a configuration value naming a specific backend.
84    ///
85    /// `auto` and `off` select a *policy*, not a backend, so the caller
86    /// handles them via [`Self::is_auto`] / [`Self::is_off`] and this returns
87    /// `None` for both.
88    pub fn parse(value: &str) -> Option<Self> {
89        match value.trim().to_ascii_lowercase().as_str() {
90            "bwrap" | "bubblewrap" => Some(SandboxBackend::Bwrap),
91            "firejail" | "fj" => Some(SandboxBackend::Firejail),
92            _ => None,
93        }
94    }
95
96    /// `true` for the values that mean "no sandbox".
97    pub fn is_off(value: &str) -> bool {
98        matches!(
99            value.trim().to_ascii_lowercase().as_str(),
100            "off" | "none" | "no" | "false" | "0" | "disabled"
101        )
102    }
103
104    /// `true` for the values that mean "pick whatever is installed".
105    pub fn is_auto(value: &str) -> bool {
106        matches!(
107            value.trim().to_ascii_lowercase().as_str(),
108            "" | "auto" | "detect" | "yes" | "true" | "1" | "enabled"
109        )
110    }
111}
112
113impl std::fmt::Display for SandboxBackend {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        f.write_str(self.binary())
116    }
117}
118
119/// Host paths and tunables a [`Sandbox`] binds into the sandbox.
120///
121/// Everything here is resolved by the caller from settings and the host
122/// environment, so this module never reads `$HOME` itself — consistent with
123/// the [`Paths`](crate::paths::Paths) discipline that owns ambient lookups.
124#[derive(Debug, Clone, Default)]
125pub struct SandboxOptions {
126    /// Extra host paths bound read-only (from `allowed_paths`).
127    pub read_only_paths: Vec<PathBuf>,
128    /// Extra host paths bound read-write (from `allowed_paths`).
129    pub read_write_paths: Vec<PathBuf>,
130    /// Host `$HOME`, bound read-only so paths nested under it stay reachable.
131    pub home: Option<PathBuf>,
132    /// Writable directory exposed as `$CARGO_HOME`. A read-only toolchain
133    /// cannot update cargo's package-cache lock, so builds need *somewhere*
134    /// writable; pointing this at a cache directory under the data dir keeps
135    /// `~/.cargo` untouched at the cost of an empty registry.
136    pub cargo_home: Option<PathBuf>,
137    /// Host `$RUSTUP_HOME`, bound read-only so a rustup proxy resolves a
138    /// toolchain.
139    pub rustup_home: Option<PathBuf>,
140    /// Host `$CARGO_HOME/bin`, bound read-only so `cargo`/`rustc` are on
141    /// `PATH`. Separate from [`Self::cargo_home`] because that one must be
142    /// writable.
143    pub cargo_bin: Option<PathBuf>,
144}
145
146impl SandboxOptions {
147    /// The home directory, exposed to sandboxed commands only as `$HOME`.
148    ///
149    /// Never bound: bwrap creates mountpoint parents on demand, so a nested
150    /// read-only bind (say `~/.cargo/bin`) works without exposing the rest of
151    /// home — and binding home would defeat the point of the tmpfs root by
152    /// making every personal directory under it visible.
153    pub fn home(&self) -> Option<&Path> {
154        self.home.as_deref()
155    }
156}
157
158/// A configured OS-level sandbox for one workspace.
159///
160/// Cheap to clone, safe to share: host layout is resolved at construction and
161/// [`Sandbox::argv`] only assembles vectors.
162#[derive(Debug, Clone)]
163pub struct Sandbox {
164    backend: SandboxBackend,
165    workspace: PathBuf,
166    options: SandboxOptions,
167    /// `/lib`-style symlinks that must be recreated inside the bwrap mount
168    /// tree (empty for firejail, which sees the host tree).
169    symlinks: Vec<(PathBuf, PathBuf)>,
170    /// The real file behind `/etc/resolv.conf` when it is a symlink pointing
171    /// outside `/etc` (empty for firejail, which sees the host tree).
172    ///
173    /// See [`resolv_conf_target`].
174    resolv_conf: Option<PathBuf>,
175}
176
177/// The host's `/etc/resolv.conf` target, if it is a symlink leaving `/etc`.
178///
179/// bwrap binds `/etc` read-only but deliberately not `/run`, so on a
180/// systemd-resolved host — where `/etc/resolv.conf` is a symlink to
181/// `/run/systemd/resolve/stub-resolv.conf` — the link *dangles* inside the
182/// sandbox and every name resolution fails with `EAI_NONAME` / curl exit 6.
183/// That looks exactly like "the sandbox blocked the network", and it is not:
184/// the network is wide open. Binding the resolved target at its own path
185/// restores the link.
186///
187/// Returns `None` when `/etc/resolv.conf` is a regular file (already covered
188/// by the `/etc` bind) or unreadable, so a non-systemd host changes nothing.
189fn resolv_conf_target_at(link_path: &Path) -> Option<PathBuf> {
190    if !std::fs::symlink_metadata(link_path)
191        .ok()?
192        .file_type()
193        .is_symlink()
194    {
195        return None;
196    }
197    let target = std::fs::read_link(link_path).ok()?;
198    // Relative targets (`-> ../run/...`) resolve against the link's directory,
199    // which is what the sandbox also sees, so canonicalize against `/etc`.
200    let absolute = if target.is_absolute() {
201        target
202    } else {
203        link_path.parent()?.join(target)
204    };
205    let resolved = normalize_existing(&absolute)?;
206    // A target still inside `/etc` needs no extra bind. Compare against the
207    // *canonical* `/etc`: on macOS `/etc` is a symlink to `/private/etc`, and
208    // `resolved` is canonical, so a lexical parent would never match.
209    let etc = link_path.parent()?.canonicalize().ok()?;
210    if resolved.starts_with(&etc) || !resolved.is_file() {
211        return None;
212    }
213    Some(resolved)
214}
215
216/// The host's `/etc/resolv.conf` target, if it needs an extra bind.
217fn resolv_conf_target() -> Option<PathBuf> {
218    resolv_conf_target_at(Path::new("/etc/resolv.conf"))
219}
220
221/// Canonicalize `path`, but only if it exists — `None` otherwise.
222fn normalize_existing(path: &Path) -> Option<PathBuf> {
223    path.exists().then(|| path.canonicalize().ok()).flatten()
224}
225
226/// Is `path` a symlink whose target is exactly `target`?
227fn is_symlink_to(path: &Path, target: &str) -> bool {
228    std::fs::symlink_metadata(path)
229        .map(|m| m.file_type().is_symlink())
230        .unwrap_or(false)
231        && std::fs::read_link(path)
232            .map(|t| t == Path::new(target))
233            .unwrap_or(false)
234}
235
236impl Sandbox {
237    /// Build a sandbox for `workspace` using `backend`.
238    ///
239    /// The workspace is canonicalized so the bind target and `--chdir` value
240    /// agree with what tools see.
241    pub fn new(
242        backend: SandboxBackend,
243        workspace: &Path,
244        options: SandboxOptions,
245    ) -> Result<Self, String> {
246        let canonical = workspace.canonicalize().map_err(|e| {
247            format!(
248                "Failed to canonicalize sandbox workspace '{}': {}",
249                workspace.display(),
250                e
251            )
252        })?;
253        if !canonical.is_dir() {
254            return Err(format!(
255                "Sandbox workspace '{}' is not a directory",
256                workspace.display()
257            ));
258        }
259
260        // bwrap builds its own mount tree, so the merged-usr symlinks the host
261        // relies on (`/bin -> usr/bin`, `/lib64 -> usr/lib64`, …) have to be
262        // recreated inside it or the dynamic loader and `exec` stop working.
263        let symlinks = match backend {
264            SandboxBackend::Bwrap => [
265                ("/bin", "usr/bin"),
266                ("/sbin", "usr/sbin"),
267                ("/lib", "usr/lib"),
268                ("/lib64", "usr/lib64"),
269            ]
270            .iter()
271            .filter(|(link, target)| is_symlink_to(Path::new(link), target))
272            .map(|(link, target)| (PathBuf::from(*link), PathBuf::from(*target)))
273            .collect(),
274            SandboxBackend::Firejail => Vec::new(),
275        };
276
277        let resolv_conf = match backend {
278            SandboxBackend::Bwrap => resolv_conf_target(),
279            SandboxBackend::Firejail => None,
280        };
281
282        // Canonicalize the extra bind paths, like the workspace: on macOS a
283        // `/var/...` or `/tmp/...` spelling must bind the real
284        // `/private/var/...` target so the bind matches what the guard
285        // resolved.
286        let mut options = options;
287        options.read_only_paths = options
288            .read_only_paths
289            .iter()
290            .filter_map(|p| p.canonicalize().ok())
291            .collect();
292        options.read_write_paths = options
293            .read_write_paths
294            .iter()
295            .filter_map(|p| p.canonicalize().ok())
296            .collect();
297
298        Ok(Self {
299            backend,
300            workspace: canonical,
301            options,
302            symlinks,
303            resolv_conf,
304        })
305    }
306
307    /// The backend implementing this sandbox.
308    pub fn backend(&self) -> SandboxBackend {
309        self.backend
310    }
311
312    /// The canonicalized workspace root, exposed read-write inside the sandbox.
313    pub fn workspace(&self) -> &Path {
314        &self.workspace
315    }
316
317    /// The options this sandbox was built with.
318    pub fn options(&self) -> &SandboxOptions {
319        &self.options
320    }
321
322    /// Locate `backend`'s binary on `PATH`.
323    ///
324    /// Deliberately does not shell out to `which`: a lookup that only touches
325    /// `PATH` works everywhere without spawning anything.
326    pub fn locate(backend: SandboxBackend) -> Option<PathBuf> {
327        let exe = format!("{}{}", backend.binary(), std::env::consts::EXE_SUFFIX);
328        let path = std::env::var_os("PATH")?;
329        for dir in std::env::split_paths(&path) {
330            if dir.as_os_str().is_empty() {
331                continue;
332            }
333            let candidate = dir.join(&exe);
334            if candidate.is_file() {
335                return Some(candidate);
336            }
337        }
338        None
339    }
340
341    /// Every backend whose binary is installed, in preference order.
342    pub fn available() -> Vec<SandboxBackend> {
343        ALL_BACKENDS
344            .into_iter()
345            .filter(|b| Self::locate(*b).is_some())
346            .collect()
347    }
348
349    /// Build a sandbox on the best installed backend (bwrap first).
350    ///
351    /// The `Err` explains that neither is available and how to get one; the
352    /// caller turns it into a startup message rather than a hard failure, so a
353    /// machine without sandbox tooling still starts.
354    pub fn detect(workspace: &Path, options: SandboxOptions) -> Result<Self, String> {
355        match Self::available().first().copied() {
356            Some(backend) => Self::new(backend, workspace, options),
357            None => Err(
358                "No sandbox backend found. Install bubblewrap (`bwrap`) or firejail, \
359                 or start with --no-sandbox to run shell commands unsandboxed."
360                    .to_string(),
361            ),
362        }
363    }
364
365    /// Resolve a backend name (from `--sandbox=<value>` or `sandbox.backend`)
366    /// into a sandbox.
367    ///
368    /// `auto`/empty → [`Sandbox::detect`]; an explicit name → that backend,
369    /// with an actionable error if it is not installed.
370    pub fn from_setting(
371        value: &str,
372        workspace: &Path,
373        options: SandboxOptions,
374    ) -> Result<Self, String> {
375        if SandboxBackend::is_off(value) {
376            return Err(format!(
377                "sandbox backend '{value}' disables sandboxing — nothing to build"
378            ));
379        }
380        if SandboxBackend::is_auto(value) {
381            return Self::detect(workspace, options);
382        }
383        let backend = SandboxBackend::parse(value).ok_or_else(|| {
384            format!("Unknown sandbox backend '{value}'. Valid values: auto, bwrap, firejail, off")
385        })?;
386        if Self::locate(backend).is_none() {
387            return Err(format!(
388                "'{backend}' is not installed or not on PATH. \
389                 Available: {}.",
390                if Self::available().is_empty() {
391                    "none".to_string()
392                } else {
393                    Self::available()
394                        .into_iter()
395                        .map(|b| b.to_string())
396                        .collect::<Vec<_>>()
397                        .join(", ")
398                }
399            ));
400        }
401        Self::new(backend, workspace, options)
402    }
403
404    /// Assemble the full argv that runs `command` through `/bin/sh` inside
405    /// this sandbox.
406    ///
407    /// Returns `(program, args)`. `cwd` becomes the sandbox's `--chdir` value
408    /// when given; the caller must have already established that it is inside
409    /// the workspace, because an out-of-tree directory is simply not visible
410    /// in the sandbox mount tree and the command would fail confusingly.
411    pub fn argv(&self, command: &str, cwd: Option<&Path>) -> (PathBuf, Vec<OsString>) {
412        self.argv_with_env(command, cwd, &[])
413    }
414
415    /// [`Sandbox::argv`] with extra environment variables for the sandboxed
416    /// process.
417    ///
418    /// Needed because bwrap runs `--clearenv`: variables set on the *outer*
419    /// bwrap process (custom tools' `TH_*` parameters, for instance) do not
420    /// reach the sandboxed shell, so they have to travel as `--setenv`
421    /// arguments. firejail inherits the parent environment, where `extra` is
422    /// ignored — the caller should still set it on the spawned command so both
423    /// backends behave the same.
424    pub fn argv_with_env(
425        &self,
426        command: &str,
427        cwd: Option<&Path>,
428        extra: &[(String, String)],
429    ) -> (PathBuf, Vec<OsString>) {
430        let program =
431            Self::locate(self.backend).unwrap_or_else(|| PathBuf::from(self.backend.binary()));
432        let mut args: Vec<OsString> = match self.backend {
433            SandboxBackend::Bwrap => self.bwrap_args(cwd, extra),
434            SandboxBackend::Firejail => self.firejail_args(),
435        };
436        args.push(OsString::from("/bin/sh"));
437        args.push(OsString::from("-c"));
438        args.push(OsString::from(command));
439        (program, args)
440    }
441
442    fn bwrap_args(&self, cwd: Option<&Path>, extra_env: &[(String, String)]) -> Vec<OsString> {
443        let mut a: Vec<OsString> = vec![
444            // Namespaces. `--unshare-user` is what makes all of this work
445            // without root; the rest isolate process/identity views. The
446            // network namespace is deliberately *not* unshared — see the
447            // module docs.
448            os("--unshare-user"),
449            os("--unshare-ipc"),
450            os("--unshare-pid"),
451            os("--unshare-uts"),
452            os("--unshare-cgroup"),
453            // Exit when TinyHarness goes away, and take a new session so a
454            // command cannot seize the controlling terminal.
455            os("--die-with-parent"),
456            os("--new-session"),
457            // Strip the inherited environment: API keys and tokens must not
458            // reach a sandboxed command. Only what's needed is re-added below.
459            os("--clearenv"),
460            // Deny-by-default filesystem: a tmpfs root, then explicit binds.
461            // (Creating a mountpoint on a read-only `/` is impossible — bwrap
462            // reports "Can't create file …: Read-only file system" — so the
463            // tmpfs root is not a stylistic choice.)
464            os("--tmpfs"),
465            os("/"),
466            os("--tmpfs"),
467            os("/tmp"),
468            // A fresh procfs: `--ro-bind /proc /proc` would leak the host's
469            // entire process list into the sandbox.
470            os("--proc"),
471            os("/proc"),
472            // devtmpfs only — no host block devices, so /dev/sda-style reads
473            // fail outright.
474            os("--dev"),
475            os("/dev"),
476        ];
477
478        // No `--unshare-net`: sandboxed commands keep the host network so
479        // `git`, `curl`, and `cargo add` work. The containment offered here is
480        // filesystem and environment isolation; network access is not part of
481        // the threat model this sandbox addresses.
482
483        // System toolchain and config, read-only.
484        a.extend(bind_ro(Path::new("/usr")));
485        a.extend(bind_ro(Path::new("/etc")));
486        // `/etc/resolv.conf` is usually a symlink into `/run`, which is not
487        // bound — without its target the link dangles and DNS fails even
488        // though the network itself is open. `--ro-bind-try` so a target that
489        // vanished between construction and execution degrades to no DNS
490        // rather than to a sandbox that refuses to start.
491        if let Some(resolv) = self.resolv_conf.as_deref() {
492            a.push(os("--ro-bind-try"));
493            a.push(resolv.as_os_str().to_owned());
494            a.push(resolv.as_os_str().to_owned());
495        }
496        for (link, target) in &self.symlinks {
497            a.push(os("--symlink"));
498            a.push(target.as_os_str().to_owned());
499            a.push(link.as_os_str().to_owned());
500        }
501
502        // Rust toolchain: read-only install, writable $CARGO_HOME.
503        if let Some(bin) = self.options.cargo_bin.as_deref() {
504            a.extend(bind_ro(bin));
505        }
506        if let Some(rustup) = self.options.rustup_home.as_deref() {
507            a.extend(bind_ro(rustup));
508        }
509        if let Some(cargo_home) = self.options.cargo_home.as_deref() {
510            a.extend(bind_rw(cargo_home));
511        }
512
513        // User-selected extra paths. bwrap creates mountpoint parents on
514        // demand, so a nested path (e.g. `~/.cargo/bin`) binds fine without
515        // exposing the rest of `$HOME`.
516        for p in &self.options.read_only_paths {
517            a.extend(bind_ro(p));
518        }
519        for p in &self.options.read_write_paths {
520            a.extend(bind_rw(p));
521        }
522
523        // The workspace itself, read-write, last so it wins over any
524        // read-only ancestor bind.
525        a.extend(bind_rw(&self.workspace));
526
527        for (key, value) in self.environment() {
528            a.push(os("--setenv"));
529            a.push(os(&key));
530            a.push(OsString::from(value));
531        }
532        for (key, value) in extra_env {
533            a.push(os("--setenv"));
534            a.push(os(key));
535            a.push(OsString::from(value));
536        }
537
538        // An explicit `cwd` overrides the workspace root; both are bound
539        // inside the sandbox, so either is a valid `--chdir` target. A
540        // relative `cwd` is resolved against the workspace, because bwrap
541        // would otherwise resolve it against the sandbox's tmpfs root.
542        a.push(os("--chdir"));
543        a.push(match cwd {
544            Some(dir) if dir.is_absolute() => OsString::from(dir.as_os_str()),
545            Some(dir) => OsString::from(self.workspace.join(dir).as_os_str()),
546            None => self.workspace.as_os_str().to_owned(),
547        });
548
549        a
550    }
551
552    fn firejail_args(&self) -> Vec<OsString> {
553        // firejail sees the whole host filesystem; `--read-only /` makes it
554        // immutable and the workspace is re-bound writable. Unlike bwrap this
555        // does *not* hide files outside the workspace from reads.
556        let mut a: Vec<OsString> = vec![
557            os("--noprofile"),
558            os("--quiet"),
559            os("--read-only"),
560            os("/"),
561            os(&format!("--bind={}", self.workspace.display())),
562            // Privilege reduction.
563            os("--caps.drop=all"),
564            os("--nonewprivs"),
565            os("--nogroups"),
566            os("--seccomp"),
567            os("--disable-mnt"),
568        ];
569        // No `--net=none`: see the note in `bwrap_args` — network access is
570        // intentionally preserved for both backends.
571        for p in &self.options.read_only_paths {
572            if is_usable_dir(p) {
573                a.push(os(&format!("--bind-ro={}", p.display())));
574            }
575        }
576        for p in &self.options.read_write_paths {
577            if is_usable_dir(p) {
578                a.push(os(&format!("--bind={}", p.display())));
579            }
580        }
581        a
582    }
583
584    /// The environment re-injected into a bwrap sandbox.
585    ///
586    /// Only what a build/test command needs: nothing secret is inherited, and
587    /// the locale is forwarded so command output matches the host language.
588    fn environment(&self) -> Vec<(String, String)> {
589        let mut out = Vec::new();
590
591        let host_path = std::env::var_os("PATH")
592            .map(PathBuf::from)
593            .unwrap_or_default();
594        let mut dirs: Vec<PathBuf> = Vec::new();
595        if let Some(bin) = self
596            .options
597            .cargo_bin
598            .as_deref()
599            .filter(|p| is_usable_dir(p))
600        {
601            dirs.push(bin.to_path_buf());
602        }
603        dirs.extend(std::env::split_paths(&host_path));
604        dirs.push(PathBuf::from("/usr/bin"));
605        dirs.push(PathBuf::from("/bin"));
606        out.push((
607            "PATH".to_string(),
608            std::env::join_paths(&dirs)
609                .map(|p| p.to_string_lossy().into_owned())
610                .unwrap_or_else(|_| "/usr/bin:/bin".to_string()),
611        ));
612
613        // Only advertise the toolchain homes that are actually bound. An
614        // env var pointing at a path the sandbox cannot see makes a tool try
615        // to create it (bwrap's tmpfs root is writable, so that silently
616        // succeeds into an ephemeral directory) instead of failing clearly.
617        for (key, value) in [
618            ("HOME", self.options.home.as_deref()),
619            ("CARGO_HOME", self.options.cargo_home.as_deref()),
620            ("RUSTUP_HOME", self.options.rustup_home.as_deref()),
621        ] {
622            if let Some(v) = value.filter(|p| is_usable_dir(p)) {
623                out.push((key.to_string(), v.to_string_lossy().into_owned()));
624            }
625        }
626        for key in ["LANG", "LC_ALL", "LC_CTYPE", "TERM"] {
627            if let Some(value) = std::env::var_os(key) {
628                out.push((key.to_string(), value.to_string_lossy().into_owned()));
629            }
630        }
631        out
632    }
633
634    /// Quick self-check: run `true` through the sandbox.
635    ///
636    /// Used at startup so a broken backend (missing setuid bit on firejail,
637    /// user namespaces disabled by the distro) is reported before the first
638    /// tool call rather than as a mysterious command failure.
639    pub fn probe(&self) -> Result<(), String> {
640        let (program, args) = self.argv("true", None);
641        let output = StdCommand::new(&program)
642            .args(&args)
643            .stdin(Stdio::null())
644            .output()
645            .map_err(|e| format!("Failed to run {}: {e}", program.display()))?;
646        if output.status.success() {
647            Ok(())
648        } else {
649            Err(format!(
650                "{} exited with {}: {}",
651                program.display(),
652                output.status.code().unwrap_or(-1),
653                String::from_utf8_lossy(&output.stderr).trim()
654            ))
655        }
656    }
657}
658
659/// `OsString` shorthand — the argv builders are unreadable otherwise.
660fn os(value: &str) -> OsString {
661    OsString::from(value)
662}
663
664/// A bind target is only useful if it is a real directory; a missing or
665/// regular-file entry would make bwrap fail the whole sandbox.
666fn is_usable_dir(path: &Path) -> bool {
667    path.is_dir()
668}
669
670fn bind_ro(path: &Path) -> Vec<OsString> {
671    if !is_usable_dir(path) {
672        return Vec::new();
673    }
674    vec![
675        os("--ro-bind"),
676        path.as_os_str().to_owned(),
677        path.as_os_str().to_owned(),
678    ]
679}
680
681fn bind_rw(path: &Path) -> Vec<OsString> {
682    if !is_usable_dir(path) {
683        return Vec::new();
684    }
685    vec![
686        os("--bind"),
687        path.as_os_str().to_owned(),
688        path.as_os_str().to_owned(),
689    ]
690}
691
692#[cfg(all(test, unix))]
693mod tests {
694    use super::*;
695
696    fn sandbox_in(tmp: &Path, options: SandboxOptions) -> Sandbox {
697        Sandbox::new(SandboxBackend::Bwrap, tmp, options).unwrap()
698    }
699
700    #[test]
701    fn backend_parsing() {
702        assert_eq!(SandboxBackend::parse("bwrap"), Some(SandboxBackend::Bwrap));
703        assert_eq!(
704            SandboxBackend::parse("Bubblewrap"),
705            Some(SandboxBackend::Bwrap)
706        );
707        assert_eq!(
708            SandboxBackend::parse("Firejail"),
709            Some(SandboxBackend::Firejail)
710        );
711        // Policies, not backends.
712        assert_eq!(SandboxBackend::parse("auto"), None);
713        assert_eq!(SandboxBackend::parse("off"), None);
714        assert!(SandboxBackend::is_off("OFF"));
715        assert!(SandboxBackend::is_off("none"));
716        assert!(SandboxBackend::is_auto("auto"));
717        assert!(SandboxBackend::is_auto(""));
718        assert!(!SandboxBackend::is_auto("bwrap"));
719        assert!(!SandboxBackend::is_off("bwrap"));
720        assert_eq!(SandboxBackend::Bwrap.to_string(), "bwrap");
721        assert_eq!(SandboxBackend::Firejail.to_string(), "firejail");
722    }
723
724    /// The systemd-resolved layout: `/etc/resolv.conf` links out of `/etc`, so
725    /// the target must be found and reported at its own absolute path.
726    #[test]
727    fn resolv_conf_target_follows_a_link_out_of_etc() {
728        let tmp = tempfile::tempdir().unwrap();
729        let etc = tmp.path().join("etc");
730        let run = tmp.path().join("run/systemd/resolve");
731        std::fs::create_dir_all(&etc).unwrap();
732        std::fs::create_dir_all(&run).unwrap();
733        let real = run.join("stub-resolv.conf");
734        std::fs::write(&real, "nameserver 127.0.0.53\n").unwrap();
735        std::os::unix::fs::symlink(&real, etc.join("resolv.conf")).unwrap();
736
737        // The returned target is canonicalized, which on macOS resolves
738        // `/var` -> `/private/var` in the tempdir path.
739        assert_eq!(
740            resolv_conf_target_at(&etc.join("resolv.conf")),
741            Some(real.canonicalize().unwrap())
742        );
743    }
744
745    /// A relative link (`-> ../run/...`) resolves against `/etc`, not the CWD.
746    #[test]
747    fn resolv_conf_target_resolves_relative_links_against_etc() {
748        let tmp = tempfile::tempdir().unwrap();
749        let etc = tmp.path().join("etc");
750        let run = tmp.path().join("run/systemd/resolve");
751        std::fs::create_dir_all(&etc).unwrap();
752        std::fs::create_dir_all(&run).unwrap();
753        std::fs::write(run.join("stub-resolv.conf"), "nameserver 1.1.1.1\n").unwrap();
754        std::os::unix::fs::symlink(
755            "../run/systemd/resolve/stub-resolv.conf",
756            etc.join("resolv.conf"),
757        )
758        .unwrap();
759
760        let got = resolv_conf_target_at(&etc.join("resolv.conf")).unwrap();
761        assert_eq!(got, run.join("stub-resolv.conf").canonicalize().unwrap());
762    }
763
764    /// A regular file is already inside the `/etc` bind — binding it again would
765    /// be pointless, and a link still under `/etc` likewise.
766    #[test]
767    fn resolv_conf_target_is_none_for_plain_files_and_internal_links() {
768        let tmp = tempfile::tempdir().unwrap();
769        let etc = tmp.path().join("etc");
770        std::fs::create_dir_all(&etc).unwrap();
771
772        // Regular file.
773        let plain = etc.join("resolv.conf");
774        std::fs::write(&plain, "nameserver 8.8.8.8\n").unwrap();
775        assert_eq!(resolv_conf_target_at(&plain), None);
776
777        // Symlink whose target is still under /etc.
778        std::fs::write(etc.join("other.conf"), "nameserver 9.9.9.9\n").unwrap();
779        let internal = etc.join("resolv-link.conf");
780        std::os::unix::fs::symlink("other.conf", &internal).unwrap();
781        assert_eq!(resolv_conf_target_at(&internal), None);
782
783        // Dangling link: nothing to bind, and it must not panic.
784        let dangling = etc.join("resolv-dangling.conf");
785        std::os::unix::fs::symlink("/no/such/resolv.conf", &dangling).unwrap();
786        assert_eq!(resolv_conf_target_at(&dangling), None);
787
788        // Missing file entirely.
789        assert_eq!(resolv_conf_target_at(&etc.join("nope.conf")), None);
790    }
791
792    /// Whatever the host's layout, the bind must target the resolved file at its
793    /// own path — mounting onto the `/etc/resolv.conf` symlink itself is refused
794    /// by bwrap ("Can't mount on symlink destination"), which is how the first
795    /// attempt at this fix failed.
796    #[test]
797    fn bwrap_binds_dns_config_when_resolv_conf_is_a_link() {
798        let tmp = tempfile::tempdir().unwrap();
799        let sb = sandbox_in(tmp.path(), SandboxOptions::default());
800        let (_, args) = sb.argv("true", None);
801        let flat: Vec<String> = args
802            .iter()
803            .map(|a| a.to_string_lossy().into_owned())
804            .collect();
805
806        match resolv_conf_target() {
807            Some(target) => {
808                let t = target.to_string_lossy().into_owned();
809                assert!(
810                    flat.windows(3)
811                        .any(|w| w[0] == "--ro-bind-try" && w[1] == t && w[2] == t),
812                    "DNS config {t} not bound: {flat:?}"
813                );
814                assert!(
815                    !flat
816                        .windows(3)
817                        .any(|w| w[0] == "--ro-bind-try" && w[1] == "/etc/resolv.conf"),
818                    "must not mount onto the /etc/resolv.conf symlink: {flat:?}"
819                );
820            }
821            None => assert!(
822                !flat.iter().any(|a| a == "--ro-bind-try"),
823                "no extra DNS bind expected on this host: {flat:?}"
824            ),
825        }
826    }
827
828    /// firejail sees the host filesystem, so it never needs (and must not get)
829    /// bwrap's mount flags.
830    #[test]
831    fn firejail_gets_no_dns_bind() {
832        let tmp = tempfile::tempdir().unwrap();
833        let sb = Sandbox::new(
834            SandboxBackend::Firejail,
835            tmp.path(),
836            SandboxOptions::default(),
837        )
838        .unwrap();
839        assert!(
840            sb.resolv_conf.is_none(),
841            "firejail must not carry DNS state"
842        );
843        let (_, args) = sb.argv("true", None);
844        let flat: Vec<String> = args
845            .iter()
846            .map(|a| a.to_string_lossy().into_owned())
847            .collect();
848        assert!(
849            !flat.iter().any(|a| a == "--ro-bind-try"),
850            "unexpected bwrap flag: {flat:?}"
851        );
852    }
853
854    #[test]
855    fn new_requires_existing_workspace_dir() {
856        let err = Sandbox::new(
857            SandboxBackend::Bwrap,
858            Path::new("/definitely/not/a/real/dir"),
859            SandboxOptions::default(),
860        )
861        .unwrap_err();
862        assert!(
863            err.contains("canonicalize") || err.contains("directory"),
864            "{err}"
865        );
866    }
867
868    #[test]
869    fn workspace_is_canonicalized() {
870        let tmp = tempfile::tempdir().unwrap();
871        let sb = sandbox_in(tmp.path(), SandboxOptions::default());
872        assert_eq!(sb.workspace(), tmp.path().canonicalize().unwrap());
873        assert_eq!(sb.backend(), SandboxBackend::Bwrap);
874    }
875
876    #[test]
877    fn bwrap_argv_contains_the_containment_flags() {
878        let tmp = tempfile::tempdir().unwrap();
879        let sb = sandbox_in(tmp.path(), SandboxOptions::default());
880        let (program, args) = sb.argv("echo hi", None);
881        let flat: Vec<String> = args
882            .iter()
883            .map(|a| a.to_string_lossy().into_owned())
884            .collect();
885
886        assert_eq!(program.file_name().unwrap(), "bwrap");
887        assert_eq!(flat.last().map(|s| s.as_str()), Some("echo hi"));
888        assert_eq!(flat[flat.len() - 3], "/bin/sh");
889        assert_eq!(flat[flat.len() - 2], "-c");
890
891        for flag in [
892            "--unshare-user",
893            "--unshare-pid",
894            "--unshare-ipc",
895            "--unshare-uts",
896            "--unshare-cgroup",
897            "--die-with-parent",
898            "--new-session",
899            "--clearenv",
900            "--tmpfs",
901            "--proc",
902            "--dev",
903            "--chdir",
904        ] {
905            assert!(flat.iter().any(|a| a == flag), "missing {flag}: {flat:?}");
906        }
907        // The network must stay reachable: `git`/`curl`/`cargo add` are
908        // everyday agent operations, so no net-isolation flag may appear.
909        for flag in ["--unshare-net", "--net=none"] {
910            assert!(
911                !flat.iter().any(|a| a == flag),
912                "unexpected {flag}: {flat:?}"
913            );
914        }
915        // The host root must never be bound — that is what would make reads of
916        // arbitrary paths possible.
917        assert!(!flat.windows(2).any(|w| w[0] == "--ro-bind" && w[1] == "/"));
918        assert!(!flat.windows(2).any(|w| w[0] == "--bind" && w[1] == "/"));
919        // /usr and /etc are the minimum viable system view.
920        assert!(
921            flat.windows(3)
922                .any(|w| w[0] == "--ro-bind" && w[1] == "/usr")
923        );
924        assert!(
925            flat.windows(3)
926                .any(|w| w[0] == "--ro-bind" && w[1] == "/etc")
927        );
928        // And the workspace is the last bind, read-write, so it wins.
929        let ws = tmp
930            .path()
931            .canonicalize()
932            .unwrap()
933            .to_string_lossy()
934            .into_owned();
935        let last_bind = flat
936            .iter()
937            .rposition(|a| a == "--bind")
938            .expect("no rw bind");
939        assert_eq!(flat[last_bind + 1], ws);
940        assert_eq!(flat[last_bind + 2], ws);
941    }
942
943    #[test]
944    fn bwrap_chdir_follows_explicit_cwd() {
945        let tmp = tempfile::tempdir().unwrap();
946        let sub = tmp.path().canonicalize().unwrap().join("sub");
947        std::fs::create_dir(&sub).unwrap();
948        let sb = sandbox_in(tmp.path(), SandboxOptions::default());
949        let (_, args) = sb.argv("true", Some(&sub));
950        let flat: Vec<String> = args
951            .iter()
952            .map(|a| a.to_string_lossy().into_owned())
953            .collect();
954        let idx = flat.iter().rposition(|a| a == "--chdir").unwrap();
955        assert_eq!(flat[idx + 1], sub.to_string_lossy());
956    }
957
958    #[test]
959    fn bwrap_binds_extra_paths() {
960        let tmp = tempfile::tempdir().unwrap();
961        let ro = tempfile::tempdir().unwrap();
962        let rw = tempfile::tempdir().unwrap();
963        let sb = sandbox_in(
964            tmp.path(),
965            SandboxOptions {
966                read_only_paths: vec![ro.path().to_path_buf()],
967                read_write_paths: vec![rw.path().to_path_buf()],
968                ..SandboxOptions::default()
969            },
970        );
971        let (_, args) = sb.argv("true", None);
972        let flat: Vec<String> = args
973            .iter()
974            .map(|a| a.to_string_lossy().into_owned())
975            .collect();
976        let ro_s = ro
977            .path()
978            .canonicalize()
979            .unwrap()
980            .to_string_lossy()
981            .into_owned();
982        let rw_s = rw
983            .path()
984            .canonicalize()
985            .unwrap()
986            .to_string_lossy()
987            .into_owned();
988        assert!(flat.windows(3).any(|w| w[0] == "--ro-bind" && w[1] == ro_s));
989        assert!(flat.windows(3).any(|w| w[0] == "--bind" && w[1] == rw_s));
990    }
991
992    #[test]
993    fn missing_bind_targets_are_skipped() {
994        let tmp = tempfile::tempdir().unwrap();
995        let ghost = Path::new("/no/such/dir/anywhere");
996        let sb = sandbox_in(
997            tmp.path(),
998            SandboxOptions {
999                read_only_paths: vec![ghost.to_path_buf()],
1000                cargo_home: Some(ghost.to_path_buf()),
1001                ..SandboxOptions::default()
1002            },
1003        );
1004        let (_, args) = sb.argv("true", None);
1005        let flat: Vec<String> = args
1006            .iter()
1007            .map(|a| a.to_string_lossy().into_owned())
1008            .collect();
1009        assert!(
1010            !flat.iter().any(|a| a == "/no/such/dir/anywhere"),
1011            "{flat:?}"
1012        );
1013    }
1014
1015    #[test]
1016    fn environment_is_a_whitelist() {
1017        let tmp = tempfile::tempdir().unwrap();
1018        let home = tempfile::tempdir().unwrap();
1019        let cargo_home = tempfile::tempdir().unwrap();
1020        let rustup = tempfile::tempdir().unwrap();
1021        let bin = tempfile::tempdir().unwrap();
1022        let sb = sandbox_in(
1023            tmp.path(),
1024            SandboxOptions {
1025                home: Some(home.path().to_path_buf()),
1026                cargo_home: Some(cargo_home.path().to_path_buf()),
1027                rustup_home: Some(rustup.path().to_path_buf()),
1028                cargo_bin: Some(bin.path().to_path_buf()),
1029                ..SandboxOptions::default()
1030            },
1031        );
1032        let env = sb.environment();
1033        let keys: Vec<&str> = env.iter().map(|(k, _)| k.as_str()).collect();
1034        assert!(keys.contains(&"PATH"));
1035        assert!(keys.contains(&"HOME"));
1036        assert!(keys.contains(&"CARGO_HOME"));
1037        assert!(keys.contains(&"RUSTUP_HOME"));
1038        // Nothing secret: the whole set is known up front (plus locale/TERM,
1039        // which come from the host and are harmless).
1040        for key in keys.iter() {
1041            assert!(
1042                matches!(
1043                    *key,
1044                    "PATH"
1045                        | "HOME"
1046                        | "CARGO_HOME"
1047                        | "RUSTUP_HOME"
1048                        | "LANG"
1049                        | "LC_ALL"
1050                        | "LC_CTYPE"
1051                        | "TERM"
1052                ),
1053                "unexpected env var leaked into sandbox: {key}"
1054            );
1055        }
1056        // cargo/rustc must be reachable through the prepended bin dir.
1057        let path = env.iter().find(|(k, _)| k == "PATH").unwrap().1.clone();
1058        assert!(
1059            path.starts_with(&bin.path().to_string_lossy().to_string()),
1060            "{path}"
1061        );
1062    }
1063
1064    #[test]
1065    fn environment_omits_unbound_toolchain_paths() {
1066        // A $CARGO_HOME the sandbox cannot see would let cargo quietly create
1067        // an ephemeral one on the tmpfs root instead of failing visibly.
1068        let tmp = tempfile::tempdir().unwrap();
1069        let sb = sandbox_in(
1070            tmp.path(),
1071            SandboxOptions {
1072                cargo_home: Some(PathBuf::from("/no/such/cargo/home")),
1073                cargo_bin: Some(PathBuf::from("/no/such/bin")),
1074                ..SandboxOptions::default()
1075            },
1076        );
1077        let env = sb.environment();
1078        let keys: Vec<&str> = env.iter().map(|(k, _)| k.as_str()).collect();
1079        assert!(!keys.contains(&"CARGO_HOME"), "{keys:?}");
1080        assert!(!keys.contains(&"RUSTUP_HOME"), "{keys:?}");
1081        let path = env.iter().find(|(k, _)| k == "PATH").unwrap().1.clone();
1082        assert!(!path.contains("/no/such/bin"), "{path}");
1083    }
1084
1085    #[test]
1086    fn home_is_never_bound_but_nested_paths_are() {
1087        // Binding $HOME would expose ~/.ssh, ~/.bash_history and friends to
1088        // sandboxed commands. The profile relies on bwrap creating mountpoint
1089        // parents on demand instead, so a nested bind works without it.
1090        let tmp = tempfile::tempdir().unwrap();
1091        let home = tempfile::tempdir().unwrap();
1092        let nested = home.path().join(".local/share/data");
1093        std::fs::create_dir_all(&nested).unwrap();
1094
1095        let sb = sandbox_in(
1096            tmp.path(),
1097            SandboxOptions {
1098                home: Some(home.path().to_path_buf()),
1099                read_only_paths: vec![nested.clone()],
1100                ..SandboxOptions::default()
1101            },
1102        );
1103        let (_, args) = sb.argv("true", None);
1104        let flat: Vec<String> = args
1105            .iter()
1106            .map(|a| a.to_string_lossy().into_owned())
1107            .collect();
1108
1109        let home_s = home
1110            .path()
1111            .canonicalize()
1112            .unwrap()
1113            .to_string_lossy()
1114            .into_owned();
1115        assert!(
1116            !flat.windows(3).any(|w| w[1] == home_s && w[2] == home_s),
1117            "$HOME itself must never be bound: {flat:?}"
1118        );
1119
1120        // The nested path is bound, and only it. Binds are canonicalized (on
1121        // macOS `/var` -> `/private/var`), so compare against the canonical
1122        // spelling.
1123        let nested_s = nested
1124            .canonicalize()
1125            .unwrap()
1126            .to_string_lossy()
1127            .into_owned();
1128        assert!(
1129            flat.windows(3)
1130                .any(|w| w[0] == "--ro-bind" && w[1] == nested_s),
1131            "nested allowed path was not bound: {flat:?}"
1132        );
1133    }
1134
1135    #[test]
1136    fn extra_env_reaches_the_sandboxed_shell() {
1137        let tmp = tempfile::tempdir().unwrap();
1138        let sb = sandbox_in(tmp.path(), SandboxOptions::default());
1139        let extra = [("TH_QUERY".to_string(), "hello world".to_string())];
1140        let (_, args) = sb.argv_with_env("echo $TH_QUERY", None, &extra);
1141        let flat: Vec<String> = args
1142            .iter()
1143            .map(|a| a.to_string_lossy().into_owned())
1144            .collect();
1145        let idx = flat
1146            .iter()
1147            .position(|a| a == "TH_QUERY")
1148            .expect("TH_QUERY not passed through");
1149        assert_eq!(flat[idx - 1], "--setenv");
1150        assert_eq!(flat[idx + 1], "hello world");
1151        // The command itself is still the last three arguments.
1152        assert_eq!(flat[flat.len() - 3], "/bin/sh");
1153        assert_eq!(flat[flat.len() - 2], "-c");
1154        assert_eq!(flat[flat.len() - 1], "echo $TH_QUERY");
1155    }
1156
1157    #[test]
1158    fn firejail_argv_shapes_expected_options() {
1159        let tmp = tempfile::tempdir().unwrap();
1160        let sb = Sandbox::new(
1161            SandboxBackend::Firejail,
1162            tmp.path(),
1163            SandboxOptions::default(),
1164        )
1165        .unwrap();
1166        let (program, args) = sb.argv("ls", None);
1167        let flat: Vec<String> = args
1168            .iter()
1169            .map(|a| a.to_string_lossy().into_owned())
1170            .collect();
1171        assert_eq!(program.file_name().unwrap(), "firejail");
1172        let ws = tmp
1173            .path()
1174            .canonicalize()
1175            .unwrap()
1176            .to_string_lossy()
1177            .into_owned();
1178        assert!(flat.contains(&format!("--bind={ws}")), "{flat:?}");
1179        for flag in [
1180            "--noprofile",
1181            "--read-only",
1182            "--caps.drop=all",
1183            "--seccomp",
1184            "--nogroups",
1185        ] {
1186            assert!(flat.iter().any(|a| a == flag), "missing {flag}");
1187        }
1188        assert_eq!(flat.last().map(|s| s.as_str()), Some("ls"));
1189        // firejail never gets bwrap's mount flags.
1190        assert!(!flat.iter().any(|a| a == "--ro-bind"));
1191        // …and never isolates the network, same policy as bwrap.
1192        assert!(
1193            !flat.iter().any(|a| a == "--net=none"),
1194            "firejail must not block the network: {flat:?}"
1195        );
1196    }
1197
1198    #[test]
1199    fn available_backends_are_locatable() {
1200        let avail = Sandbox::available();
1201        for backend in &avail {
1202            assert!(Sandbox::locate(*backend).is_some());
1203        }
1204        // Preference order is stable: bwrap before firejail.
1205        if avail.len() == ALL_BACKENDS.len() {
1206            assert_eq!(avail, ALL_BACKENDS.to_vec());
1207        }
1208    }
1209
1210    #[test]
1211    fn detect_either_succeeds_or_explains_itself() {
1212        let tmp = tempfile::tempdir().unwrap();
1213        match Sandbox::detect(tmp.path(), SandboxOptions::default()) {
1214            Ok(sb) => assert!(
1215                ALL_BACKENDS.contains(&sb.backend()),
1216                "unexpected backend {:?}",
1217                sb.backend()
1218            ),
1219            Err(e) => assert!(
1220                e.contains("bubblewrap") && e.contains("firejail"),
1221                "unhelpful error: {e}"
1222            ),
1223        }
1224    }
1225
1226    #[test]
1227    fn from_setting_honours_explicit_backend_and_rejects_off() {
1228        let tmp = tempfile::tempdir().unwrap();
1229        // `off` is a policy the caller must handle before building.
1230        assert!(
1231            Sandbox::from_setting("off", tmp.path(), SandboxOptions::default())
1232                .unwrap_err()
1233                .contains("disables sandboxing")
1234        );
1235        // Unknown names are rejected with the valid list.
1236        let err =
1237            Sandbox::from_setting("docker", tmp.path(), SandboxOptions::default()).unwrap_err();
1238        assert!(err.contains("Unknown sandbox backend"), "{err}");
1239        assert!(err.contains("bwrap"), "{err}");
1240        // An installed backend builds; a missing one says so.
1241        match Sandbox::from_setting("bwrap", tmp.path(), SandboxOptions::default()) {
1242            Ok(sb) => assert_eq!(sb.backend(), SandboxBackend::Bwrap),
1243            Err(e) => assert!(e.contains("not installed"), "{e}"),
1244        }
1245        // `auto` behaves like detect(): ok iff some backend is installed.
1246        let auto = Sandbox::from_setting("auto", tmp.path(), SandboxOptions::default());
1247        assert_eq!(auto.is_ok(), !Sandbox::available().is_empty());
1248    }
1249
1250    #[test]
1251    fn symlink_detection_ignores_real_dirs_and_missing_paths() {
1252        // Merged-usr probing must not panic on a plain directory or a path
1253        // that does not exist.
1254        assert!(!is_symlink_to(Path::new("/definitely/missing"), "usr/bin"));
1255        let tmp = tempfile::tempdir().unwrap();
1256        assert!(!is_symlink_to(tmp.path(), "usr/bin"));
1257
1258        // The links this actually looks for are *relative* (`/bin -> usr/bin`),
1259        // so an absolute-target symlink must not be mistaken for one.
1260        let rel = tmp.path().join("rel");
1261        std::os::unix::fs::symlink("usr/bin", &rel).unwrap();
1262        assert!(is_symlink_to(&rel, "usr/bin"));
1263        assert!(!is_symlink_to(&rel, "usr/lib"));
1264
1265        let abs = tmp.path().join("abs");
1266        std::os::unix::fs::symlink("/usr/bin", &abs).unwrap();
1267        assert!(!is_symlink_to(&abs, "usr/bin"));
1268    }
1269}