merry-process 0.1.3

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
Documentation
use super::*;
use std::fs;

fn outside_tmp_fixture_root() -> PathBuf {
    for candidate in [env::var_os("XDG_RUNTIME_DIR"), env::var_os("HOME")] {
        let Some(value) = candidate else {
            continue;
        };
        let path = PathBuf::from(value);
        if path.is_dir() && !is_tmp_root(&path) {
            return path;
        }
    }
    let manifest_target = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target");
    if manifest_target.is_dir() && !is_tmp_root(&manifest_target) {
        return manifest_target;
    }
    panic!("need a writable test directory outside /tmp, /var/tmp, and /dev");
}

fn is_tmp_root(path: &Path) -> bool {
    let resolved = resolve_host_path(path);
    [
        "/tmp",
        "/private/tmp",
        "/var/tmp",
        "/private/var/tmp",
        "/dev",
    ]
    .iter()
    .any(|prefix| {
        let root = resolve_host_path(Path::new(prefix));
        resolved == root || resolved.starts_with(&root)
    })
}

#[test]
fn browser_sandbox_profile_isolates_workspace_home_and_providers_in_launch_and_seatbelt() {
    let profile_dir = tempfile::tempdir().expect("temp profile dir");
    let workspace = PathBuf::from("/srv/merry-workspace");
    let fake_home = PathBuf::from("/home/alice");
    let providers = PathBuf::from("/home/alice/.local/share/merry/providers");

    let profile = BrowserSandboxProfile::new(
        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
        profile_dir.path(),
    )
    .with_denied_paths([workspace.clone(), fake_home.clone(), providers.clone()]);

    let launch = profile
        .prepare_launch(&["--headless=new".to_owned(), "about:blank".to_owned()])
        .expect("browser sandbox launch prepares");
    let resolved_profile = resolve_host_path(profile_dir.path());
    let resolved_profile_str = resolved_profile.to_str().expect("utf-8 profile");

    assert!(
        launch.network(),
        "browser sandbox must allow loopback CDP + HTTP(S)"
    );
    assert!(
        launch
            .read_write()
            .iter()
            .any(|p| p == resolved_profile_str)
    );
    for forbidden in [
        "/srv/merry-workspace",
        "/home/alice",
        "/home/alice/.local/share/merry/providers",
    ] {
        assert!(
            !launch.read_only().iter().any(|p| p == forbidden),
            "read_only must not include {forbidden}"
        );
        assert!(
            !launch.read_write().iter().any(|p| p == forbidden),
            "read_write must not include {forbidden}"
        );
    }
    assert!(
        launch
            .env()
            .iter()
            .any(|(k, v)| k == "HOME" && v == resolved_profile_str),
        "browser HOME must point to the ephemeral profile_dir"
    );
    assert!(
        launch.remove_env().iter().any(|k| k == "SSH_AUTH_SOCK"),
        "browser sandbox must strip host IPC socket env vars"
    );

    let seatbelt = profile
        .seatbelt_profile_for_test(&["--headless=new".to_owned()])
        .expect("seatbelt profile renders");
    assert!(seatbelt.contains("(allow network*)"));
    assert!(seatbelt.contains(&format!(
        "(allow file-write* (subpath \"{resolved_profile_str}\"))"
    )));
    assert!(seatbelt.contains("(deny file-read* (subpath \"/srv/merry-workspace\"))"));
    assert!(seatbelt.contains("(deny file-read* (subpath \"/home/alice\"))"));
    assert!(
        seatbelt
            .contains("(deny file-read* (subpath \"/home/alice/.local/share/merry/providers\"))")
    );
    assert!(
        !seatbelt.contains("(allow file-read* (subpath \"/Applications\"))"),
        "macOS browser sandbox must never grant all of /Applications"
    );
}

#[test]
fn browser_sandbox_profile_hardens_tmp_workspace_home_profile_and_root_executable() {
    // 1. A workspace located under `/tmp` must prevent `/tmp` from being added
    //    to `read_write` (otherwise Linux Landlock would expose the workspace).
    let tmp_workspace = PathBuf::from("/tmp/merry-tmp-workspace");
    let profile_dir = tempfile::tempdir().expect("temp profile dir");
    let tmp_profile = BrowserSandboxProfile::new("/chrome", profile_dir.path())
        .with_denied_paths([tmp_workspace.clone()]);
    let tmp_launch = tmp_profile
        .prepare_launch(&["about:blank".to_owned()])
        .expect("launch prepares");
    let resolved_tmp = resolve_host_path(Path::new("/tmp"));
    let resolved_tmp_str = resolved_tmp.to_str().expect("utf-8 /tmp");
    assert!(
        !tmp_launch
            .read_write()
            .iter()
            .any(|p| p == "/tmp" || p == resolved_tmp_str),
        "workspace under /tmp must exclude /tmp from read_write: {:?}",
        tmp_launch.read_write()
    );
    assert!(
        !tmp_launch.read_only().iter().any(|p| p == "/"),
        "root-level executable /chrome must never grant / as read_only: {:?}",
        tmp_launch.read_only()
    );

    // 2. When `profile_dir` lives inside `$HOME` (e.g. TMPDIR=$HOME/tmp), `$HOME`
    //    stays in `deny` while Seatbelt re-allows only the exact `profile_dir`.
    let fake_home = PathBuf::from("/home/bob");
    let nested_profile = fake_home.join("tmp/merry-browser-123");
    let nested = BrowserSandboxProfile::new("/usr/bin/chromium", &nested_profile)
        .with_denied_paths([fake_home.clone()]);
    let seatbelt = nested
        .seatbelt_profile_for_test(&["about:blank".to_owned()])
        .expect("seatbelt renders");
    let deny_pos = seatbelt
        .find("(deny file-read* (subpath \"/home/bob\"))")
        .expect("$HOME must remain explicitly denied");
    let allow_profile_pos = seatbelt
        .rfind("(allow file-write* (subpath \"/home/bob/tmp/merry-browser-123\"))")
        .expect("exact profile_dir must be re-allowed after $HOME deny");
    assert!(
        allow_profile_pos > deny_pos,
        "Seatbelt must re-allow exact profile_dir after denying $HOME:\n{seatbelt}"
    );
}

#[cfg(target_os = "linux")]
#[tokio::test]
async fn linux_browser_sandbox_blocks_workspace_home_and_providers_while_allowing_profile_and_no_seccomp()
 {
    if let Err(reason) = crate::probe_workspace_sandbox() {
        eprintln!("skipping Linux Landlock browser sandbox test: {reason}");
        return;
    }

    let host_root = tempfile::tempdir_in(outside_tmp_fixture_root()).expect("host fixture dir");
    let workspace = host_root.path().join("workspace");
    let fake_home = host_root.path().join("home");
    let providers = fake_home.join(".local/share/merry/providers");
    fs::create_dir_all(&workspace).expect("workspace dir");
    fs::create_dir_all(&providers).expect("providers dir");

    let workspace_secret = workspace.join("workspace-secret.txt");
    let home_secret = fake_home.join("home-secret.txt");
    let provider_secret = providers.join("providers.toml");
    fs::write(&workspace_secret, "TOP_SECRET_WORKSPACE\n").expect("write workspace secret");
    fs::write(&home_secret, "TOP_SECRET_HOME\n").expect("write home secret");
    fs::write(&provider_secret, "api_key = \"sk-secret\"\n").expect("write provider secret");

    let profile_dir = tempfile::tempdir().expect("temp profile dir");
    let profile = BrowserSandboxProfile::new("/bin/sh", profile_dir.path()).with_denied_paths([
        workspace.clone(),
        fake_home.clone(),
        providers.clone(),
    ]);

    let script = format!(
        concat!(
            "set -u\n",
            "printf 'ok' > \"$HOME/profile-write-check.txt\" || exit 10\n",
            "if cat '{ws}' >/dev/null 2>&1; then echo LEAK_WORKSPACE >&2; exit 21; fi\n",
            "if cat '{hm}' >/dev/null 2>&1; then echo LEAK_HOME >&2; exit 22; fi\n",
            "if cat '{pr}' >/dev/null 2>&1; then echo LEAK_PROVIDERS >&2; exit 23; fi\n",
            "grep '^Seccomp:' /proc/self/status >&2\n",
            "printf 'HOME=%s\\n' \"$HOME\" >&2\n",
        ),
        ws = workspace_secret.display(),
        hm = home_secret.display(),
        pr = provider_secret.display(),
    );

    let child = profile
        .spawn(&["-c".to_owned(), script])
        .await
        .expect("sandboxed browser helper spawns");
    let output = child
        .wait_with_output()
        .await
        .expect("wait sandboxed child");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "sandboxed browser child should succeed without leaking files; status={:?}, stderr={stderr}",
        output.status
    );
    assert!(
        profile_dir.path().join("profile-write-check.txt").is_file(),
        "browser must be able to write inside its ephemeral profile_dir"
    );
    assert!(
        stderr.contains("Seccomp:\t0"),
        "Linux browser sandbox must apply Landlock only (no seccomp filter) to stay compatible with Chromium renderer sandbox; stderr={stderr}"
    );
    let resolved_profile = resolve_host_path(profile_dir.path());
    assert!(
        stderr.contains(&format!("HOME={}", resolved_profile.display())),
        "browser HOME must be redirected to ephemeral profile_dir; stderr={stderr}"
    );
}