Skip to main content

merry_process/confinement/
browser.rs

1//! Dedicated desktop OS sandbox profile for headless Chrome/Chromium.
2//!
3//! Completely decoupled from [`crate::WorkspaceProcessRunner`]:
4//! - Zero workspace access, zero host `$HOME` access, zero Merry `providers/` access.
5//! - Read-only access limited to system libraries, fonts, CA bundles, and the
6//!   browser installation; read-write access limited to the ephemeral empty
7//!   profile directory (`TempDir`), `/tmp`, `/var/tmp`, `/dev/shm`, `/dev`,
8//!   and (on Linux) `/proc` so Chromium's own `CLONE_NEWUSER` namespace sandbox
9//!   can write `/proc/<pid>/{setgroups,uid_map,gid_map,oom_score_adj}` under
10//!   Landlock's mandatory `PR_SET_NO_NEW_PRIVS`.
11//! - Allows loopback CDP and outbound HTTP(S) (governed by upper-layer SSRF
12//!   and domain admission). On Linux, applies Landlock filesystem confinement
13//!   without seccomp (with `/proc` writable) so Chromium's own user-namespace
14//!   renderer sandbox stays active. On macOS, applies an outer Seatbelt profile
15//!   with scoped `MachPortRendezvousServer` registration, Darwin user temp dir
16//!   access, and `--no-sandbox` (since XNU Seatbelt forbids nested
17//!   `sandbox_init`).
18//! - Spawns private child processes owned exclusively by the browser session
19//!   manager, never registering them in the user-visible `BackgroundSupervisor`.
20
21use super::{
22    HELPER_ENV, POLICY_ENV, SandboxLaunch, encode_policy, helper_env_name, helper_program,
23    path_to_string, policy_env_name, policy_stdin_sentinel, push_directory, push_if_exists,
24    push_path, strings_from_paths,
25};
26use crate::{ProcessEnvIsolation, resolve_host_path};
27use merry_runtime::ProcessRunnerError;
28use std::{
29    env,
30    path::{Path, PathBuf},
31    process::Stdio,
32};
33use tokio::io::AsyncWriteExt;
34
35const BROWSER_READ_ONLY_DIRECTORIES: &[&str] = &[
36    "/usr",
37    "/bin",
38    "/sbin",
39    "/lib",
40    "/lib64",
41    "/opt",
42    "/nix/store",
43    "/nix/var/nix/profiles",
44    "/run/current-system/sw",
45    "/sys",
46    "/etc/ld.so.conf.d",
47    "/etc/ssl",
48    "/etc/ca-certificates",
49    "/etc/pki",
50    "/etc/alternatives",
51    "/etc/fonts",
52    "/etc/chromium",
53    "/etc/opt/chrome",
54    "/etc/opt/chromium",
55    "/etc/xdg",
56    "/var/cache/fontconfig",
57];
58
59const BROWSER_READ_ONLY_FILES: &[&str] = &[
60    "/etc/ld.so.cache",
61    "/etc/ld.so.conf",
62    "/etc/resolv.conf",
63    "/etc/hosts",
64    "/etc/nsswitch.conf",
65    "/etc/protocols",
66    "/etc/services",
67    "/etc/gai.conf",
68    "/etc/mime.types",
69    "/etc/passwd",
70    "/etc/group",
71    "/etc/localtime",
72];
73
74const BROWSER_TEMP_READ_WRITE_DIRECTORIES: &[&str] = &["/tmp", "/var/tmp"];
75const BROWSER_DEVICE_READ_WRITE_DIRECTORIES: &[&str] = &["/dev", "/dev/shm"];
76
77#[cfg(target_os = "macos")]
78const MACOS_BROWSER_READ_ONLY_DIRECTORIES: &[&str] =
79    &["/System", "/Library", "/private/etc", "/private/var/select"];
80
81const BROWSER_DEFAULT_PATH: &str = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
82
83/// Dedicated OS sandbox profile for launching a session-scoped headless browser
84/// under desktop `--sandbox workspace`.
85#[derive(Debug, Clone)]
86pub struct BrowserSandboxProfile {
87    executable: PathBuf,
88    profile_dir: PathBuf,
89    env_isolation: ProcessEnvIsolation,
90    denied_paths: Vec<PathBuf>,
91}
92
93impl BrowserSandboxProfile {
94    /// Creates a browser sandbox profile for `executable` using an isolated
95    /// temporary `profile_dir` (which also serves as the browser's `HOME` and
96    /// `TMPDIR`).
97    #[must_use]
98    pub fn new(executable: impl Into<PathBuf>, profile_dir: impl Into<PathBuf>) -> Self {
99        Self {
100            executable: executable.into(),
101            profile_dir: profile_dir.into(),
102            env_isolation: ProcessEnvIsolation::default(),
103            denied_paths: Vec::new(),
104        }
105    }
106
107    /// Overrides the environment isolation policy stripped before launching the
108    /// sandboxed browser process.
109    #[must_use]
110    pub fn with_env_isolation(mut self, env_isolation: ProcessEnvIsolation) -> Self {
111        self.env_isolation = env_isolation;
112        self
113    }
114
115    /// Adds explicit paths that must stay inaccessible to the browser (such as
116    /// the workspace root, host `$HOME`, and Merry `providers/`).
117    ///
118    /// On Linux Landlock these paths are omitted from the allowlist; on macOS
119    /// Seatbelt they are also emitted as explicit last-wins `(deny file-*)`
120    /// rules.
121    #[must_use]
122    pub fn with_denied_paths(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
123        self.denied_paths.extend(paths);
124        self
125    }
126
127    /// Prepares the low-level [`SandboxLaunch`] applied by Landlock (Linux) or
128    /// Seatbelt (macOS).
129    pub(crate) fn prepare_launch(
130        &self,
131        args: &[String],
132    ) -> Result<SandboxLaunch, ProcessRunnerError> {
133        let resolved_profile = resolve_host_path(&self.profile_dir);
134        if resolved_profile.as_os_str().is_empty() || !resolved_profile.is_absolute() {
135            return Err(ProcessRunnerError::infrastructure(format!(
136                "browser sandbox profile_dir `{}` must be an absolute path",
137                self.profile_dir.display()
138            )));
139        }
140
141        let mut deny = Vec::new();
142        for path in &self.denied_paths {
143            let resolved = resolve_host_path(path);
144            if !resolved.as_os_str().is_empty() && resolved != resolved_profile {
145                push_path(&mut deny, &resolved);
146            }
147        }
148        if let Some(host_home) = env::var_os("HOME")
149            .map(PathBuf::from)
150            .filter(|path| path.is_absolute())
151        {
152            let resolved_home = resolve_host_path(&host_home);
153            if resolved_home != resolved_profile {
154                push_path(&mut deny, &resolved_home);
155            }
156        }
157
158        let mut read_only = Vec::new();
159        for path in BROWSER_READ_ONLY_DIRECTORIES {
160            push_if_exists(&mut read_only, Path::new(path));
161        }
162        #[cfg(target_os = "macos")]
163        for path in MACOS_BROWSER_READ_ONLY_DIRECTORIES {
164            push_if_exists(&mut read_only, Path::new(path));
165        }
166        for path in BROWSER_READ_ONLY_FILES {
167            push_if_exists(&mut read_only, Path::new(path));
168        }
169
170        let mut read_write = Vec::new();
171        push_directory(&mut read_write, &resolved_profile);
172        // Only grant `/tmp` or `/var/tmp` when no denied tree (such as a
173        // workspace or `$HOME` located under `/tmp`) overlaps it, because
174        // Linux Landlock is allowlist-only and cannot carve out denied
175        // subdirectories from `/tmp`. `TMPDIR` already points to `profile_dir`.
176        for path in BROWSER_TEMP_READ_WRITE_DIRECTORIES {
177            let candidate = Path::new(path);
178            let resolved = resolve_host_path(candidate);
179            if !overlaps_any(&resolved, &deny) && (candidate.exists() || !cfg!(target_os = "macos"))
180            {
181                push_directory(&mut read_write, candidate);
182            }
183        }
184        for path in BROWSER_DEVICE_READ_WRITE_DIRECTORIES {
185            let candidate = Path::new(path);
186            if candidate.exists() || !cfg!(target_os = "macos") {
187                push_directory(&mut read_write, candidate);
188            }
189        }
190        // On Linux, Landlock sets `PR_SET_NO_NEW_PRIVS`, which disables Chrome's
191        // setuid sandbox helper and requires its unprivileged user-namespace
192        // sandbox (`CLONE_NEWUSER`) instead. Setting up that namespace writes
193        // `/proc/<pid>/{setgroups,uid_map,gid_map,oom_score_adj}`, which fails
194        // with exit code 82 if `/proc` is Landlock read-only.
195        #[cfg(target_os = "linux")]
196        push_if_exists(&mut read_write, Path::new("/proc"));
197        // On macOS, Chrome's `ProcessSingleton` creates its lock socket under
198        // `NSTemporaryDirectory()` (`confstr(_CS_DARWIN_USER_TEMP_DIR)` =
199        // `/private/var/folders/.../T`), ignoring `$TMPDIR`. Grant that per-user
200        // Darwin temp directory when it does not overlap any denied subtree.
201        #[cfg(target_os = "macos")]
202        if let Some(darwin_temp) = macos_darwin_user_temp_dir() {
203            let resolved = resolve_host_path(&darwin_temp);
204            if !overlaps_any(&resolved, &deny) && resolved.is_dir() {
205                push_directory(&mut read_write, &resolved);
206            }
207        }
208
209        // If the ephemeral `profile_dir` itself sits inside a denied ancestor
210        // (for example `TMPDIR=$HOME/tmp`), keep `$HOME` in `deny` and re-allow
211        // only the exact `profile_dir` at the end of macOS Seatbelt rules.
212        let mut approved_private_read_write = Vec::new();
213        if overlaps_any(&resolved_profile, &deny) {
214            push_directory(&mut approved_private_read_write, &resolved_profile);
215        }
216
217        // Allow the browser executable (and its installation / `.app` bundle
218        // root when outside standard system directories), provided it does not
219        // fall inside a denied tree such as `$HOME`, workspace, or `providers/`.
220        for candidate in executable_read_only_grants(&self.executable) {
221            let resolved = resolve_host_path(&candidate);
222            if !is_covered_by_any(&resolved, &read_only)
223                && !is_covered_by_any(&resolved, &read_write)
224                && !overlaps_any(&resolved, &deny)
225            {
226                push_if_exists(&mut read_only, &resolved);
227            }
228        }
229
230        let mut remove_env = vec![
231            HELPER_ENV.to_owned(),
232            POLICY_ENV.to_owned(),
233            "SSH_AUTH_SOCK".to_owned(),
234            "DBUS_SESSION_BUS_ADDRESS".to_owned(),
235            "GNUPGHOME".to_owned(),
236        ];
237        for name in self.env_isolation.resolve_removed_names() {
238            if let Some(name) = name.to_str()
239                && !name.contains('\0')
240                && !remove_env.iter().any(|existing| existing == name)
241            {
242                remove_env.push(name.to_owned());
243            }
244        }
245
246        let profile_str = path_to_string(&resolved_profile, "browser sandbox profile_dir")?;
247        let env_vars = vec![
248            ("PATH".to_owned(), BROWSER_DEFAULT_PATH.to_owned()),
249            ("HOME".to_owned(), profile_str.clone()),
250            ("TMPDIR".to_owned(), profile_str.clone()),
251            (
252                "XDG_CONFIG_HOME".to_owned(),
253                path_to_string(&resolved_profile.join(".config"), "browser XDG_CONFIG_HOME")?,
254            ),
255            (
256                "XDG_CACHE_HOME".to_owned(),
257                path_to_string(&resolved_profile.join(".cache"), "browser XDG_CACHE_HOME")?,
258            ),
259            (
260                "XDG_DATA_HOME".to_owned(),
261                path_to_string(
262                    &resolved_profile.join(".local/share"),
263                    "browser XDG_DATA_HOME",
264                )?,
265            ),
266            (
267                "XDG_STATE_HOME".to_owned(),
268                path_to_string(
269                    &resolved_profile.join(".local/state"),
270                    "browser XDG_STATE_HOME",
271                )?,
272            ),
273            ("PWD".to_owned(), profile_str.clone()),
274        ];
275
276        let launch_args = browser_launch_args(args);
277
278        Ok(SandboxLaunch {
279            program: path_to_string(&self.executable, "browser executable")?,
280            args: launch_args,
281            cwd: profile_str,
282            env: env_vars,
283            remove_env,
284            // Browser sandbox keeps loopback CDP + HTTP(S) open; SSRF and
285            // domain admission enforce network boundaries at the tool layer.
286            // On Linux, `network: true` skips seccomp so Chromium's own
287            // renderer sandbox stays compatible.
288            network: true,
289            read_only: strings_from_paths(&read_only)?,
290            read_write: strings_from_paths(&read_write)?,
291            deny: strings_from_paths(&deny)?,
292            read_only_overrides: Vec::new(),
293            approved_private_read_only: Vec::new(),
294            approved_private_read_write: strings_from_paths(&approved_private_read_write)?,
295            required_paths: Vec::new(),
296            allow_browser_mach_rendezvous: true,
297        })
298    }
299
300    /// Spawns a private, sandboxed browser child process owned solely by the
301    /// caller (never registered in `BackgroundSupervisor`).
302    ///
303    /// The returned child has `stdin = null`, `stdout = null`, `stderr = piped`,
304    /// and `kill_on_drop(true)`.
305    pub async fn spawn(
306        &self,
307        args: &[String],
308    ) -> Result<tokio::process::Child, ProcessRunnerError> {
309        let profile = self.clone();
310        let owned_args = args.to_vec();
311        let launch = tokio::task::spawn_blocking(move || profile.prepare_launch(&owned_args))
312            .await
313            .map_err(|source| {
314                ProcessRunnerError::infrastructure(format!(
315                    "browser sandbox launch preparation task failed: {source}"
316                ))
317            })??;
318
319        #[cfg(target_os = "macos")]
320        if super::explicit_helper_program().is_none() {
321            let mut command = super::seatbelt::build_tokio_command(&launch);
322            command
323                .stdin(Stdio::null())
324                .stdout(Stdio::null())
325                .stderr(Stdio::piped())
326                .kill_on_drop(true);
327            return command.spawn().map_err(|source| {
328                ProcessRunnerError::infrastructure(format!(
329                    "failed spawning sandboxed browser via sandbox-exec: {source}"
330                ))
331            });
332        }
333
334        let helper = helper_program()?;
335        let policy_bytes = encode_policy(&launch)?;
336        let mut command = tokio::process::Command::new(&helper);
337        for name in launch.remove_env() {
338            if name != helper_env_name() && name != policy_env_name() {
339                command.env_remove(name);
340            }
341        }
342        command
343            .env(helper_env_name(), "1")
344            .env(policy_env_name(), policy_stdin_sentinel())
345            .stdin(Stdio::piped())
346            .stdout(Stdio::null())
347            .stderr(Stdio::piped())
348            .kill_on_drop(true);
349
350        let mut child = command.spawn().map_err(|source| {
351            ProcessRunnerError::infrastructure(format!(
352                "failed spawning sandbox helper `{}` for browser: {source}",
353                helper.display()
354            ))
355        })?;
356        if let Some(mut stdin) = child.stdin.take() {
357            if let Err(source) = stdin.write_all(&policy_bytes).await {
358                let _ = child.start_kill();
359                return Err(ProcessRunnerError::infrastructure(format!(
360                    "failed writing browser sandbox policy to helper stdin: {source}"
361                )));
362            }
363            if let Err(source) = stdin.shutdown().await {
364                let _ = child.start_kill();
365                return Err(ProcessRunnerError::infrastructure(format!(
366                    "failed closing browser sandbox helper stdin: {source}"
367                )));
368            }
369        }
370        Ok(child)
371    }
372
373    #[cfg(test)]
374    pub(crate) fn seatbelt_profile_for_test(
375        &self,
376        args: &[String],
377    ) -> Result<String, ProcessRunnerError> {
378        let launch = self.prepare_launch(args)?;
379        Ok(super::seatbelt::profile(&launch))
380    }
381}
382
383fn executable_read_only_grants(executable: &Path) -> Vec<PathBuf> {
384    let mut grants = Vec::new();
385    for path in [executable.to_path_buf(), resolve_host_path(executable)] {
386        if let Some(app_bundle) = enclosing_macos_app_bundle(&path) {
387            grants.push(app_bundle);
388        } else if let Some(parent) = path.parent()
389            && parent != Path::new("/")
390            && !parent.as_os_str().is_empty()
391        {
392            grants.push(parent.to_path_buf());
393        } else {
394            grants.push(path);
395        }
396    }
397    grants
398}
399
400fn enclosing_macos_app_bundle(path: &Path) -> Option<PathBuf> {
401    path.ancestors().find_map(|ancestor| {
402        ancestor
403            .extension()
404            .is_some_and(|ext| ext.eq_ignore_ascii_case("app"))
405            .then(|| ancestor.to_path_buf())
406    })
407}
408
409fn is_covered_by_any(target: &Path, grants: &[PathBuf]) -> bool {
410    grants
411        .iter()
412        .any(|grant| target == grant || target.starts_with(grant))
413}
414
415fn overlaps_any(target: &Path, denied: &[PathBuf]) -> bool {
416    denied.iter().any(|entry| path_overlaps(target, entry))
417}
418
419fn path_overlaps(left: &Path, right: &Path) -> bool {
420    left == right || left.starts_with(right) || right.starts_with(left)
421}
422
423fn browser_launch_args(args: &[String]) -> Vec<String> {
424    #[cfg(target_os = "macos")]
425    {
426        // macOS Seatbelt (`sandbox-exec`) forbids nested `sandbox_init` calls
427        // from Chromium helper/renderer processes, causing them to abort with
428        // `Operation not permitted`. Merry's outer Seatbelt profile already
429        // confines the entire browser process tree (zero workspace, zero
430        // `$HOME`, zero `providers/`), while `--sandbox off` runs Chrome
431        // directly without `--no-sandbox`.
432        let mut launch_args = Vec::with_capacity(args.len() + 1);
433        if !args.iter().any(|arg| arg == "--no-sandbox") {
434            launch_args.push("--no-sandbox".to_owned());
435        }
436        launch_args.extend(args.iter().cloned());
437        launch_args
438    }
439    #[cfg(not(target_os = "macos"))]
440    {
441        args.to_vec()
442    }
443}
444
445#[cfg(target_os = "macos")]
446fn macos_darwin_user_temp_dir() -> Option<PathBuf> {
447    let env_tmp = resolve_host_path(&env::temp_dir());
448    if is_darwin_user_temp_dir(&env_tmp) {
449        return Some(env_tmp);
450    }
451    let output = std::process::Command::new("/usr/bin/getconf")
452        .arg("DARWIN_USER_TEMP_DIR")
453        .output()
454        .ok()?;
455    if !output.status.success() {
456        return None;
457    }
458    let trimmed = String::from_utf8(output.stdout).ok()?;
459    let trimmed = trimmed.trim();
460    if trimmed.is_empty() {
461        return None;
462    }
463    let resolved = resolve_host_path(Path::new(trimmed));
464    is_darwin_user_temp_dir(&resolved).then_some(resolved)
465}
466
467#[cfg(any(test, target_os = "macos"))]
468fn is_darwin_user_temp_dir(path: &Path) -> bool {
469    use std::{ffi::OsStr, path::Component};
470
471    let mut components = path.components();
472    let is_literal = |component: Option<Component<'_>>, expected: &str| matches!(component, Some(Component::Normal(value)) if value == OsStr::new(expected));
473    let is_non_empty = |component: Option<Component<'_>>| matches!(component, Some(Component::Normal(value)) if !value.is_empty());
474    matches!(components.next(), Some(Component::RootDir))
475        && is_literal(components.next(), "private")
476        && is_literal(components.next(), "var")
477        && is_literal(components.next(), "folders")
478        && is_non_empty(components.next())
479        && is_non_empty(components.next())
480        && is_literal(components.next(), "T")
481        && components.next().is_none()
482}
483
484#[cfg(test)]
485#[path = "browser_tests.rs"]
486mod tests;