garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /workbench/src/sandbox.rs

raw

//! Where a job runs: the operating system's sandbox, with no network,
//! nothing writable but its task's worktree and target directory, and an
//! empty home but for the toolchain, read-only. Without one, no job runs:
//! a build runs code the agent may have written (`build.rs`, a proc macro,
//! a test), so a machine that cannot contain it does not run it.

use std::path::{Path, PathBuf};
use std::process::Command;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Sandbox {
    /// Linux: bubblewrap, every namespace unshared.
    Bwrap,
    /// macOS: the seatbelt profile `sandbox-exec` takes.
    Seatbelt,
}

impl Sandbox {
    /// The machine's sandbox, if it has one that works: one that is
    /// installed but cannot run (bubblewrap where the kernel keeps
    /// unprivileged user namespaces from it, as Ubuntu's AppArmor does) is
    /// none, so no job runs.
    pub fn find() -> Option<Sandbox> {
        let candidate = if cfg!(target_os = "linux") {
            Sandbox::Bwrap
        } else if cfg!(target_os = "macos") {
            Sandbox::Seatbelt
        } else {
            return None;
        };
        let dir = std::env::temp_dir().join(format!("workbench-probe-{}", std::process::id()));
        std::fs::create_dir_all(&dir).ok()?;
        let dir = dir.canonicalize().ok()?;
        let works = candidate
            .command(&["/bin/sh".into(), "-c".into(), "true".into()], &dir, &dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok_and(|s| s.success());
        let _ = std::fs::remove_dir_all(&dir);
        works.then_some(candidate)
    }

    pub fn name(self) -> &'static str {
        match self {
            Sandbox::Bwrap => "bubblewrap",
            Sandbox::Seatbelt => "sandbox-exec",
        }
    }

    /// `argv` to run in `worktree`, writing only there and in `target`.
    pub fn command(self, argv: &[String], worktree: &Path, target: &Path) -> Command {
        let home = std::env::var_os("HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|| "/nonexistent".into());
        let cargo_home = std::env::var_os("CARGO_HOME").map_or_else(|| home.join(".cargo"), PathBuf::from);
        let rustup_home = std::env::var_os("RUSTUP_HOME").map_or_else(|| home.join(".rustup"), PathBuf::from);
        let path = std::env::var("PATH").unwrap_or_default();
        let mut c = match self {
            Sandbox::Bwrap => {
                let mut c = Command::new("bwrap");
                let s = |p: &Path| p.display().to_string();
                c.args([
                    "--ro-bind",
                    "/",
                    "/",
                    "--dev",
                    "/dev",
                    "--proc",
                    "/proc",
                    "--tmpfs",
                    "/tmp",
                ]);
                // An empty home, then the toolchain in it, read-only, then
                // the task: binds made later lie over earlier ones.
                c.args(["--tmpfs", &s(&home)]);
                for dir in [&cargo_home, &rustup_home] {
                    if dir.exists() {
                        c.args(["--ro-bind", &s(dir), &s(dir)]);
                    }
                }
                c.args(["--bind", &s(worktree), &s(worktree)]);
                c.args(["--bind", &s(target), &s(target)]);
                c.args([
                    "--unshare-all",
                    "--die-with-parent",
                    "--new-session",
                    "--chdir",
                    &s(worktree),
                ]);
                c.arg("--");
                c.args(argv);
                c
            }
            Sandbox::Seatbelt => {
                let mut c = Command::new("/usr/bin/sandbox-exec");
                c.arg("-p").arg(seatbelt(&home, worktree, target));
                c.args(argv);
                c.current_dir(worktree);
                c
            }
        };
        // Temporary files in the task's target: on macOS the user's own
        // temporary folder is shared with everything they run.
        let tmp = match self {
            Sandbox::Bwrap => PathBuf::from("/tmp"),
            Sandbox::Seatbelt => target.join("tmp"),
        };
        let _ = std::fs::create_dir_all(target.join("tmp"));
        c.env_clear()
            .env("TMPDIR", tmp)
            .env("PATH", path)
            .env("HOME", &home)
            .env("CARGO_HOME", &cargo_home)
            .env("RUSTUP_HOME", &rustup_home)
            .env("CARGO_TARGET_DIR", target)
            .env("CARGO_NET_OFFLINE", "true")
            .env("CARGO_TERM_COLOR", "never");
        c
    }
}

/// The macOS profile: everything as the user may, but no network, no
/// writes outside the task (its temporary files are in its target, not
/// the user's temporary folders, which other programs share), and none of
/// the home's secrets read.
fn seatbelt(home: &Path, worktree: &Path, target: &Path) -> String {
    let quote = |p: &Path| p.display().to_string().replace('\\', "\\\\").replace('"', "\\\"");
    let (home, worktree, target) = (quote(home), quote(worktree), quote(target));
    format!(
        r#"(version 1)
(allow default)
(deny network*)
(deny file-write*)
(allow file-write* (subpath "{worktree}") (subpath "{target}") (literal "/dev/null") (literal "/dev/tty"))
(deny file-read* (subpath "{home}/.ssh") (subpath "{home}/.gnupg") (subpath "{home}/.config")
  (subpath "{home}/Library/Keychains") (subpath "{home}/.netrc") (subpath "{home}/.git-credentials"))
"#
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A job writes in its task and nowhere else, and reaches no network.
    /// Only where the machine has a sandbox: elsewhere no job runs at all.
    #[test]
    fn a_job_is_contained() {
        let Some(sandbox) = Sandbox::find() else {
            eprintln!("no sandbox here: jobs are off, nothing to check");
            return;
        };
        let base = std::env::temp_dir().join(format!("wb-sandbox-{}", std::process::id()));
        let (tree, target, outside) = (base.join("tree"), base.join("target"), base.join("outside"));
        for d in [&tree, &target, &outside] {
            std::fs::create_dir_all(d).unwrap();
        }
        let (tree, target, outside) = (
            tree.canonicalize().unwrap(),
            target.canonicalize().unwrap(),
            outside.canonicalize().unwrap(),
        );
        let sh = |script: String| {
            let argv = ["/bin/sh".to_string(), "-c".to_string(), script];
            sandbox
                .command(&argv, &tree, &target)
                .output()
                .unwrap()
                .status
                .success()
        };
        assert!(
            sh(format!("echo in > {}/a", tree.display())),
            "it could not write in its task"
        );
        assert!(
            sh(format!("echo in > {}/a", target.display())),
            "it could not write its target"
        );
        assert!(
            !sh(format!("echo out > {}/a", outside.display())),
            "it wrote outside its task"
        );
        assert!(!outside.join("a").exists());
        // No network: not even a connection to this machine.
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        let reached =
            sh(format!("exec 3<>/dev/tcp/127.0.0.1/{port}")) || sh(format!("nc -z 127.0.0.1 {port}"));
        assert!(!reached, "it reached the network");
        std::fs::remove_dir_all(&base).unwrap();
    }
}