merry-process 0.1.3

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
Documentation
//! Seatbelt profile applied by `/usr/bin/sandbox-exec` on macOS.
//!
//! The profile is pure text, so Linux tests can check it. This host cannot
//! execute Seatbelt.

#[cfg(any(test, target_os = "macos"))]
use super::SandboxLaunch;

#[cfg(any(test, target_os = "macos"))]
pub(crate) fn profile(launch: &SandboxLaunch) -> String {
    let mut lines = vec![
        "(version 1)".to_owned(),
        "(deny default)".to_owned(),
        "(allow process-exec)".to_owned(),
        "(allow process-fork)".to_owned(),
        "(allow signal (target self))".to_owned(),
        "(allow sysctl-read)".to_owned(),
        "(allow mach-lookup)".to_owned(),
        "(allow ipc-posix*)".to_owned(),
        "(allow system-socket)".to_owned(),
        "(allow file-ioctl)".to_owned(),
        "(allow file-read-metadata)".to_owned(),
        "(allow file-read-data (literal \"/\"))".to_owned(),
    ];
    if launch.network() {
        lines.push("(allow network*)".to_owned());
    } else {
        lines.push("(deny network*)".to_owned());
    }
    for path in &launch.read_only {
        lines.push(format!(
            "(allow file-read* (subpath {escaped}))",
            escaped = quote(path)
        ));
    }
    for path in &launch.read_write {
        let escaped = quote(path);
        lines.push(format!("(allow file-read* (subpath {escaped}))"));
        lines.push(format!("(allow file-write* (subpath {escaped}))"));
        if !launch.network() {
            // Keep AF_UNIX available inside granted writable paths and enabled
            // host-integration sockets (matching Linux seccomp) while IP
            // sockets remain blocked by `(deny network*)`.
            lines.push(format!(
                "(allow network-bind (local unix-socket (subpath {escaped})))"
            ));
            lines.push(format!(
                "(allow network-inbound (local unix-socket (subpath {escaped})))"
            ));
            lines.push(format!(
                "(allow network-outbound (remote unix-socket (subpath {escaped})))"
            ));
        }
    }
    // Seatbelt evaluates matching rules last-wins, so emitting explicit deny
    // rules after allows still protects private subtrees when a user grants a
    // broader parent directory (such as `~/.local/share` or `~`).
    for path in &launch.deny {
        let escaped = quote(path);
        lines.push(format!("(deny file-read* (subpath {escaped}))"));
        lines.push(format!("(deny file-write* (subpath {escaped}))"));
    }
    // Product-owned read-only subtrees (such as `$XDG_STATE_HOME/merry`) stay
    // readable even when nested under a broader grant or denied parent, while
    // writes remain explicitly denied. Strictly deeper writable subtrees (such
    // as durable memory when `XDG_STATE_HOME == XDG_DATA_HOME`) are re-allowed
    // next, and any even deeper denied path (such as `<state_dir>/providers` or
    // an external secret file) is re-denied last to match most-specific-prefix
    // precedence.
    for path in &launch.read_only_overrides {
        let escaped = quote(path);
        lines.push(format!("(allow file-read* (subpath {escaped}))"));
        lines.push(format!("(deny file-write* (subpath {escaped}))"));
    }
    for path in &launch.read_write {
        if is_same_or_descendant_of_any(path, &launch.read_only_overrides) {
            let escaped = quote(path);
            lines.push(format!("(allow file-read* (subpath {escaped}))"));
            lines.push(format!("(allow file-write* (subpath {escaped}))"));
        }
    }
    for path in &launch.deny {
        if is_same_or_descendant_of_any(path, &launch.read_only_overrides) {
            let escaped = quote(path);
            lines.push(format!("(deny file-read* (subpath {escaped}))"));
            lines.push(format!("(deny file-write* (subpath {escaped}))"));
        }
    }
    // Re-allow single-action user-approved targets inside built-in
    // `ProductPrivate` subtrees (never broader parents, never user-configured
    // hard denies) so the user retains final authority on macOS Seatbelt.
    for path in &launch.approved_private_read_only {
        let escaped = quote(path);
        lines.push(format!("(allow file-read* (subpath {escaped}))"));
    }
    for path in &launch.approved_private_read_write {
        let escaped = quote(path);
        lines.push(format!("(allow file-read* (subpath {escaped}))"));
        lines.push(format!("(allow file-write* (subpath {escaped}))"));
    }
    lines.join("\n")
}

#[cfg(any(test, target_os = "macos"))]
fn is_same_or_descendant_of_any(path: &str, parents: &[String]) -> bool {
    let path_ref = std::path::Path::new(path);
    parents
        .iter()
        .any(|parent| path_ref.starts_with(std::path::Path::new(parent)))
}

#[cfg(any(test, target_os = "macos"))]
pub(crate) fn command_args(launch: &SandboxLaunch) -> Vec<String> {
    let mut args = Vec::with_capacity(launch.args.len() + 4);
    args.push("-p".to_owned());
    args.push(profile(launch));
    args.push("--".to_owned());
    args.push(launch.program.clone());
    args.extend(launch.args.iter().cloned());
    args
}

#[cfg(target_os = "macos")]
pub(crate) fn build_tokio_command(launch: &SandboxLaunch) -> tokio::process::Command {
    let mut command = tokio::process::Command::new("/usr/bin/sandbox-exec");
    command
        .args(command_args(launch))
        .current_dir(&launch.cwd)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .kill_on_drop(true);
    for (name, value) in &launch.env {
        command.env(name, value);
    }
    for name in &launch.remove_env {
        command.env_remove(name);
    }
    command
        .env_remove(super::HELPER_ENV)
        .env_remove(super::POLICY_ENV);
    command
}

#[cfg(any(test, target_os = "macos"))]
fn quote(path: &str) -> String {
    let mut escaped = String::with_capacity(path.len() + 2);
    escaped.push('"');
    for ch in path.chars() {
        match ch {
            '\\' => escaped.push_str("\\\\"),
            '"' => escaped.push_str("\\\""),
            '\n' => escaped.push_str("\\n"),
            '\r' => escaped.push_str("\\r"),
            '\t' => escaped.push_str("\\t"),
            other => escaped.push(other),
        }
    }
    escaped.push('"');
    escaped
}

#[cfg(target_os = "macos")]
pub(super) fn probe() -> Result<(), String> {
    if std::path::Path::new("/usr/bin/sandbox-exec").is_file() {
        Ok(())
    } else {
        Err(
            "workspace sandbox needs /usr/bin/sandbox-exec. Pass --sandbox off to run without it."
                .to_owned(),
        )
    }
}

/// Replaces this process with `sandbox-exec -p`.
///
/// The profile is an argument, so a successful exec does not leave a profile
/// file behind. This returns only when `sandbox-exec` itself cannot start.
#[cfg(target_os = "macos")]
pub(super) fn apply(launch: &SandboxLaunch) -> Result<(), String> {
    use super::CommandExec;
    use std::process::Command;

    let mut command = Command::new("/usr/bin/sandbox-exec");
    command.args(command_args(launch));
    command.current_dir(&launch.cwd);
    for (name, value) in &launch.env {
        command.env(name, value);
    }
    for name in &launch.remove_env {
        command.env_remove(name);
    }
    let error = command.exec_error();
    Err(format!("sandbox-exec failed: {error}"))
}