merry-process 0.1.4

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
Documentation
//! Session-bound desktop headless browser spawner.
//!
//! Tracks the owning [`crate::ProcessSession`]'s live sandbox mode so headless
//! Chromium runs inside [`crate::BrowserSandboxProfile`] whenever desktop
//! `--sandbox workspace` is active (with `feature = "sandbox"`), runs directly
//! on the host under `--sandbox off (unrestricted)`, and never registers the
//! browser process in the user-visible `BackgroundSupervisor`.

use crate::{ProcessBackendMode, ProcessEnvIsolation, confinement};
use merry_runtime::{LivePolicyHandle, ProcessRunnerError};
use std::{
    path::{Path, PathBuf},
    process::Stdio,
    sync::{Arc, RwLock},
};

/// Spawns private headless browser child processes according to the owning
/// process session's live sandbox mode, protected private paths, and
/// environment isolation policy.
#[derive(Debug, Clone)]
pub struct BrowserProcessSpawner {
    live_policy: LivePolicyHandle,
    workspace_root: PathBuf,
    live_env_isolation: Arc<RwLock<ProcessEnvIsolation>>,
}

impl BrowserProcessSpawner {
    pub(crate) fn new(
        live_policy: LivePolicyHandle,
        workspace_root: PathBuf,
        live_env_isolation: Arc<RwLock<ProcessEnvIsolation>>,
    ) -> Self {
        Self {
            live_policy,
            workspace_root,
            live_env_isolation,
        }
    }

    /// Returns the currently active sandbox mode observed by this spawner.
    #[must_use]
    pub fn current_mode(&self) -> ProcessBackendMode {
        if self.live_policy.is_restricted() {
            ProcessBackendMode::Isolated
        } else {
            ProcessBackendMode::Host
        }
    }

    fn current_denied_paths(&self) -> Vec<PathBuf> {
        let mut private = self.live_policy.product_private_paths();
        let mut denied_paths = Vec::with_capacity(private.len() + 1);
        denied_paths.push(self.workspace_root.clone());
        denied_paths.append(&mut private);
        denied_paths
    }

    fn current_env_isolation(&self) -> ProcessEnvIsolation {
        self.live_env_isolation
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
    }

    /// Spawns a private headless browser child process.
    ///
    /// In [`ProcessBackendMode::Isolated`], confines the process with
    /// `BrowserSandboxProfile` (zero workspace, zero `$HOME`, zero `providers/`)
    /// or fails closed when OS sandboxing is unavailable. In
    /// [`ProcessBackendMode::Host`], spawns directly on the host without a fake
    /// sandbox while still stripping isolated environment variables.
    pub async fn spawn(
        &self,
        executable: &Path,
        args: &[String],
        profile_dir: Option<&Path>,
    ) -> Result<tokio::process::Child, ProcessRunnerError> {
        let env_isolation = self.current_env_isolation();
        match self.current_mode() {
            ProcessBackendMode::Host => {
                let mut cmd = tokio::process::Command::new(executable);
                for name in env_isolation.resolve_removed_names() {
                    cmd.env_remove(name);
                }
                cmd.args(args)
                    .stdin(Stdio::null())
                    .stdout(Stdio::null())
                    .stderr(Stdio::piped())
                    .kill_on_drop(true);
                cmd.spawn().map_err(|source| {
                    ProcessRunnerError::infrastructure(format!(
                        "failed spawning Chrome/Chromium ({}): {source}",
                        executable.display()
                    ))
                })
            }
            ProcessBackendMode::Isolated => {
                let Some(profile_dir) = profile_dir else {
                    return Err(ProcessRunnerError::infrastructure(
                        "sandboxed browser launch requires an isolated temporary profile directory",
                    ));
                };
                let denied_paths = self.current_denied_paths();
                confinement::spawn_sandboxed_browser(
                    executable,
                    args,
                    profile_dir,
                    &denied_paths,
                    &env_isolation,
                )
                .await
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        LiveProcessBackend, ProcessBackend, ProcessBackendOptions, ProcessSessionRequest,
        SessionGrantClearPolicy,
    };
    use merry_core::CapabilityPolicy;
    use merry_runtime::NetworkAccessDecision;

    #[test]
    fn live_backend_replace_updates_spawner_mode_and_child_network_policy() {
        let temp = tempfile::tempdir().expect("tempdir");
        let backend = LiveProcessBackend::new(
            temp.path(),
            ProcessBackendMode::Host,
            ProcessBackendOptions::new()
                .with_network_policy(CapabilityPolicy::Ask)
                .with_allowed_domains(["docs.rs"]),
        )
        .expect("live host backend");

        let parent_session = backend.new_session();
        let child_session = backend
            .new_session_with(ProcessSessionRequest::new())
            .expect("child session");
        let parent_spawner = parent_session.browser_spawner(temp.path());
        let child_spawner = child_session.browser_spawner(temp.path());
        let child_policy = child_session.live_policy_handle(temp.path(), true);

        assert_eq!(parent_spawner.current_mode(), ProcessBackendMode::Host);
        assert_eq!(child_spawner.current_mode(), ProcessBackendMode::Host);
        assert_eq!(
            child_policy.evaluate_network_host("docs.rs", &[]),
            NetworkAccessDecision::Allow
        );

        let _ = backend
            .prepare_replace(
                temp.path(),
                ProcessBackendMode::Host,
                ProcessBackendOptions::new().with_network_policy(CapabilityPolicy::Deny),
                SessionGrantClearPolicy::PreserveAll,
            )
            .expect("prepare deny replace")
            .commit()
            .expect("commit deny replace");
        assert_eq!(
            child_policy.evaluate_network_host("docs.rs", &[]),
            NetworkAccessDecision::Deny
        );

        let _ = backend
            .prepare_replace(
                temp.path(),
                ProcessBackendMode::Host,
                ProcessBackendOptions::new()
                    .with_network_policy(CapabilityPolicy::Ask)
                    .with_allowed_domains(["crates.io"]),
                SessionGrantClearPolicy::PreserveAll,
            )
            .expect("prepare ask replace")
            .commit()
            .expect("commit ask replace");
        assert_eq!(
            child_policy.evaluate_network_host("crates.io", &[]),
            NetworkAccessDecision::Allow
        );
        assert_eq!(
            child_policy.evaluate_network_host("docs.rs", &[]),
            NetworkAccessDecision::RequireReview
        );
    }

    #[cfg(not(feature = "sandbox"))]
    #[tokio::test]
    async fn browser_spawner_without_sandbox_feature_fails_closed_in_isolated_mode() {
        let temp = tempfile::tempdir().expect("tempdir");
        let live_policy = LivePolicyHandle::new(merry_runtime::LivePolicyBaseline::new(
            true,
            None,
            Vec::new(),
            merry_runtime::NetworkAccessPolicy::default(),
        ));
        let spawner = BrowserProcessSpawner::new(
            live_policy.clone(),
            temp.path().to_path_buf(),
            Arc::new(RwLock::new(ProcessEnvIsolation::default())),
        );
        let err = spawner
            .spawn(
                Path::new("/bin/sh"),
                &["-c".to_owned(), "true".to_owned()],
                Some(temp.path()),
            )
            .await
            .expect_err("isolated browser spawn must fail closed without sandbox feature");
        assert!(
            err.to_string().contains("sandbox"),
            "expected sandbox unavailable error, got: {err}"
        );

        live_policy.replace_baseline(merry_runtime::LivePolicyBaseline::new(
            false,
            None,
            Vec::new(),
            merry_runtime::NetworkAccessPolicy::default(),
        ));
        assert_eq!(spawner.current_mode(), ProcessBackendMode::Host);
    }
}