merry-process 0.1.3

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
Documentation
//! Dedicated desktop OS sandbox profile for headless Chrome/Chromium.
//!
//! Completely decoupled from [`crate::WorkspaceProcessRunner`]:
//! - Zero workspace access, zero host `$HOME` access, zero Merry `providers/` access.
//! - Read-only access limited to system libraries, fonts, CA bundles, and the
//!   browser installation; read-write access limited to the ephemeral empty
//!   profile directory (`TempDir`), `/tmp`, `/var/tmp`, `/dev/shm`, and `/dev`.
//! - Allows loopback CDP and outbound HTTP(S) (governed by upper-layer SSRF
//!   and domain admission); Linux applies Landlock filesystem confinement only
//!   without seccomp so Chromium's own renderer sandbox remains compatible.
//! - Spawns private child processes owned exclusively by the browser session
//!   manager, never registering them in the user-visible `BackgroundSupervisor`.

use super::{
    HELPER_ENV, POLICY_ENV, SandboxLaunch, encode_policy, helper_env_name, helper_program,
    path_to_string, policy_env_name, policy_stdin_sentinel, push_directory, push_if_exists,
    push_path, strings_from_paths,
};
use crate::{ProcessEnvIsolation, resolve_host_path};
use merry_runtime::ProcessRunnerError;
use std::{
    env,
    path::{Path, PathBuf},
    process::Stdio,
};
use tokio::io::AsyncWriteExt;

const BROWSER_READ_ONLY_DIRECTORIES: &[&str] = &[
    "/usr",
    "/bin",
    "/sbin",
    "/lib",
    "/lib64",
    "/opt",
    "/nix/store",
    "/nix/var/nix/profiles",
    "/run/current-system/sw",
    "/proc",
    "/sys",
    "/etc/ld.so.conf.d",
    "/etc/ssl",
    "/etc/ca-certificates",
    "/etc/pki",
    "/etc/alternatives",
    "/etc/fonts",
    "/etc/chromium",
    "/etc/opt/chrome",
    "/etc/opt/chromium",
    "/etc/xdg",
    "/var/cache/fontconfig",
];

const BROWSER_READ_ONLY_FILES: &[&str] = &[
    "/etc/ld.so.cache",
    "/etc/ld.so.conf",
    "/etc/resolv.conf",
    "/etc/hosts",
    "/etc/nsswitch.conf",
    "/etc/protocols",
    "/etc/services",
    "/etc/gai.conf",
    "/etc/mime.types",
    "/etc/passwd",
    "/etc/group",
    "/etc/localtime",
];

const BROWSER_TEMP_READ_WRITE_DIRECTORIES: &[&str] = &["/tmp", "/var/tmp"];
const BROWSER_DEVICE_READ_WRITE_DIRECTORIES: &[&str] = &["/dev", "/dev/shm"];

#[cfg(target_os = "macos")]
const MACOS_BROWSER_READ_ONLY_DIRECTORIES: &[&str] =
    &["/System", "/Library", "/private/etc", "/private/var/select"];

const BROWSER_DEFAULT_PATH: &str = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";

/// Dedicated OS sandbox profile for launching a session-scoped headless browser
/// under desktop `--sandbox workspace`.
#[derive(Debug, Clone)]
pub struct BrowserSandboxProfile {
    executable: PathBuf,
    profile_dir: PathBuf,
    env_isolation: ProcessEnvIsolation,
    denied_paths: Vec<PathBuf>,
}

impl BrowserSandboxProfile {
    /// Creates a browser sandbox profile for `executable` using an isolated
    /// temporary `profile_dir` (which also serves as the browser's `HOME` and
    /// `TMPDIR`).
    #[must_use]
    pub fn new(executable: impl Into<PathBuf>, profile_dir: impl Into<PathBuf>) -> Self {
        Self {
            executable: executable.into(),
            profile_dir: profile_dir.into(),
            env_isolation: ProcessEnvIsolation::default(),
            denied_paths: Vec::new(),
        }
    }

    /// Overrides the environment isolation policy stripped before launching the
    /// sandboxed browser process.
    #[must_use]
    pub fn with_env_isolation(mut self, env_isolation: ProcessEnvIsolation) -> Self {
        self.env_isolation = env_isolation;
        self
    }

    /// Adds explicit paths that must stay inaccessible to the browser (such as
    /// the workspace root, host `$HOME`, and Merry `providers/`).
    ///
    /// On Linux Landlock these paths are omitted from the allowlist; on macOS
    /// Seatbelt they are also emitted as explicit last-wins `(deny file-*)`
    /// rules.
    #[must_use]
    pub fn with_denied_paths(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
        self.denied_paths.extend(paths);
        self
    }

    /// Prepares the low-level [`SandboxLaunch`] applied by Landlock (Linux) or
    /// Seatbelt (macOS).
    pub(crate) fn prepare_launch(
        &self,
        args: &[String],
    ) -> Result<SandboxLaunch, ProcessRunnerError> {
        let resolved_profile = resolve_host_path(&self.profile_dir);
        if resolved_profile.as_os_str().is_empty() || !resolved_profile.is_absolute() {
            return Err(ProcessRunnerError::infrastructure(format!(
                "browser sandbox profile_dir `{}` must be an absolute path",
                self.profile_dir.display()
            )));
        }

        let mut deny = Vec::new();
        for path in &self.denied_paths {
            let resolved = resolve_host_path(path);
            if !resolved.as_os_str().is_empty() && resolved != resolved_profile {
                push_path(&mut deny, &resolved);
            }
        }
        if let Some(host_home) = env::var_os("HOME")
            .map(PathBuf::from)
            .filter(|path| path.is_absolute())
        {
            let resolved_home = resolve_host_path(&host_home);
            if resolved_home != resolved_profile {
                push_path(&mut deny, &resolved_home);
            }
        }

        let mut read_only = Vec::new();
        for path in BROWSER_READ_ONLY_DIRECTORIES {
            push_if_exists(&mut read_only, Path::new(path));
        }
        #[cfg(target_os = "macos")]
        for path in MACOS_BROWSER_READ_ONLY_DIRECTORIES {
            push_if_exists(&mut read_only, Path::new(path));
        }
        for path in BROWSER_READ_ONLY_FILES {
            push_if_exists(&mut read_only, Path::new(path));
        }

        let mut read_write = Vec::new();
        push_directory(&mut read_write, &resolved_profile);
        // Only grant `/tmp` or `/var/tmp` when no denied tree (such as a
        // workspace or `$HOME` located under `/tmp`) overlaps it, because
        // Linux Landlock is allowlist-only and cannot carve out denied
        // subdirectories from `/tmp`. `TMPDIR` already points to `profile_dir`.
        for path in BROWSER_TEMP_READ_WRITE_DIRECTORIES {
            let candidate = Path::new(path);
            let resolved = resolve_host_path(candidate);
            if !overlaps_any(&resolved, &deny) && (candidate.exists() || !cfg!(target_os = "macos"))
            {
                push_directory(&mut read_write, candidate);
            }
        }
        for path in BROWSER_DEVICE_READ_WRITE_DIRECTORIES {
            let candidate = Path::new(path);
            if candidate.exists() || !cfg!(target_os = "macos") {
                push_directory(&mut read_write, candidate);
            }
        }

        // If the ephemeral `profile_dir` itself sits inside a denied ancestor
        // (for example `TMPDIR=$HOME/tmp`), keep `$HOME` in `deny` and re-allow
        // only the exact `profile_dir` at the end of macOS Seatbelt rules.
        let mut approved_private_read_write = Vec::new();
        if overlaps_any(&resolved_profile, &deny) {
            push_directory(&mut approved_private_read_write, &resolved_profile);
        }

        // Allow the browser executable (and its installation / `.app` bundle
        // root when outside standard system directories), provided it does not
        // fall inside a denied tree such as `$HOME`, workspace, or `providers/`.
        for candidate in executable_read_only_grants(&self.executable) {
            let resolved = resolve_host_path(&candidate);
            if !is_covered_by_any(&resolved, &read_only)
                && !is_covered_by_any(&resolved, &read_write)
                && !overlaps_any(&resolved, &deny)
            {
                push_if_exists(&mut read_only, &resolved);
            }
        }

        let mut remove_env = vec![
            HELPER_ENV.to_owned(),
            POLICY_ENV.to_owned(),
            "SSH_AUTH_SOCK".to_owned(),
            "DBUS_SESSION_BUS_ADDRESS".to_owned(),
            "GNUPGHOME".to_owned(),
        ];
        for name in self.env_isolation.resolve_removed_names() {
            if let Some(name) = name.to_str()
                && !name.contains('\0')
                && !remove_env.iter().any(|existing| existing == name)
            {
                remove_env.push(name.to_owned());
            }
        }

        let profile_str = path_to_string(&resolved_profile, "browser sandbox profile_dir")?;
        let env_vars = vec![
            ("PATH".to_owned(), BROWSER_DEFAULT_PATH.to_owned()),
            ("HOME".to_owned(), profile_str.clone()),
            ("TMPDIR".to_owned(), profile_str.clone()),
            (
                "XDG_CONFIG_HOME".to_owned(),
                path_to_string(&resolved_profile.join(".config"), "browser XDG_CONFIG_HOME")?,
            ),
            (
                "XDG_CACHE_HOME".to_owned(),
                path_to_string(&resolved_profile.join(".cache"), "browser XDG_CACHE_HOME")?,
            ),
            (
                "XDG_DATA_HOME".to_owned(),
                path_to_string(
                    &resolved_profile.join(".local/share"),
                    "browser XDG_DATA_HOME",
                )?,
            ),
            (
                "XDG_STATE_HOME".to_owned(),
                path_to_string(
                    &resolved_profile.join(".local/state"),
                    "browser XDG_STATE_HOME",
                )?,
            ),
            ("PWD".to_owned(), profile_str.clone()),
        ];

        Ok(SandboxLaunch {
            program: path_to_string(&self.executable, "browser executable")?,
            args: args.to_vec(),
            cwd: profile_str,
            env: env_vars,
            remove_env,
            // Browser sandbox keeps loopback CDP + HTTP(S) open; SSRF and
            // domain admission enforce network boundaries at the tool layer.
            // On Linux, `network: true` skips seccomp so Chromium's own
            // renderer sandbox stays compatible.
            network: true,
            read_only: strings_from_paths(&read_only)?,
            read_write: strings_from_paths(&read_write)?,
            deny: strings_from_paths(&deny)?,
            read_only_overrides: Vec::new(),
            approved_private_read_only: Vec::new(),
            approved_private_read_write: strings_from_paths(&approved_private_read_write)?,
            required_paths: Vec::new(),
        })
    }

    /// Spawns a private, sandboxed browser child process owned solely by the
    /// caller (never registered in `BackgroundSupervisor`).
    ///
    /// The returned child has `stdin = null`, `stdout = null`, `stderr = piped`,
    /// and `kill_on_drop(true)`.
    pub async fn spawn(
        &self,
        args: &[String],
    ) -> Result<tokio::process::Child, ProcessRunnerError> {
        let profile = self.clone();
        let owned_args = args.to_vec();
        let launch = tokio::task::spawn_blocking(move || profile.prepare_launch(&owned_args))
            .await
            .map_err(|source| {
                ProcessRunnerError::infrastructure(format!(
                    "browser sandbox launch preparation task failed: {source}"
                ))
            })??;

        #[cfg(target_os = "macos")]
        if super::explicit_helper_program().is_none() {
            let mut command = super::seatbelt::build_tokio_command(&launch);
            command
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::piped())
                .kill_on_drop(true);
            return command.spawn().map_err(|source| {
                ProcessRunnerError::infrastructure(format!(
                    "failed spawning sandboxed browser via sandbox-exec: {source}"
                ))
            });
        }

        let helper = helper_program()?;
        let policy_bytes = encode_policy(&launch)?;
        let mut command = tokio::process::Command::new(&helper);
        for name in launch.remove_env() {
            if name != helper_env_name() && name != policy_env_name() {
                command.env_remove(name);
            }
        }
        command
            .env(helper_env_name(), "1")
            .env(policy_env_name(), policy_stdin_sentinel())
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .kill_on_drop(true);

        let mut child = command.spawn().map_err(|source| {
            ProcessRunnerError::infrastructure(format!(
                "failed spawning sandbox helper `{}` for browser: {source}",
                helper.display()
            ))
        })?;
        if let Some(mut stdin) = child.stdin.take() {
            if let Err(source) = stdin.write_all(&policy_bytes).await {
                let _ = child.start_kill();
                return Err(ProcessRunnerError::infrastructure(format!(
                    "failed writing browser sandbox policy to helper stdin: {source}"
                )));
            }
            if let Err(source) = stdin.shutdown().await {
                let _ = child.start_kill();
                return Err(ProcessRunnerError::infrastructure(format!(
                    "failed closing browser sandbox helper stdin: {source}"
                )));
            }
        }
        Ok(child)
    }

    #[cfg(test)]
    pub(crate) fn seatbelt_profile_for_test(
        &self,
        args: &[String],
    ) -> Result<String, ProcessRunnerError> {
        let launch = self.prepare_launch(args)?;
        Ok(super::seatbelt::profile(&launch))
    }
}

fn executable_read_only_grants(executable: &Path) -> Vec<PathBuf> {
    let mut grants = Vec::new();
    for path in [executable.to_path_buf(), resolve_host_path(executable)] {
        if let Some(app_bundle) = enclosing_macos_app_bundle(&path) {
            grants.push(app_bundle);
        } else if let Some(parent) = path.parent()
            && parent != Path::new("/")
            && !parent.as_os_str().is_empty()
        {
            grants.push(parent.to_path_buf());
        } else {
            grants.push(path);
        }
    }
    grants
}

fn enclosing_macos_app_bundle(path: &Path) -> Option<PathBuf> {
    path.ancestors().find_map(|ancestor| {
        ancestor
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("app"))
            .then(|| ancestor.to_path_buf())
    })
}

fn is_covered_by_any(target: &Path, grants: &[PathBuf]) -> bool {
    grants
        .iter()
        .any(|grant| target == grant || target.starts_with(grant))
}

fn overlaps_any(target: &Path, denied: &[PathBuf]) -> bool {
    denied.iter().any(|entry| path_overlaps(target, entry))
}

fn path_overlaps(left: &Path, right: &Path) -> bool {
    left == right || left.starts_with(right) || right.starts_with(left)
}

#[cfg(test)]
#[path = "browser_tests.rs"]
mod tests;