merry-process 0.1.4

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! 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`, `/dev`,
//!   and (on Linux) `/proc` so Chromium's own `CLONE_NEWUSER` namespace sandbox
//!   can write `/proc/<pid>/{setgroups,uid_map,gid_map,oom_score_adj}` under
//!   Landlock's mandatory `PR_SET_NO_NEW_PRIVS`.
//! - Allows loopback CDP and outbound HTTP(S) (governed by upper-layer SSRF
//!   and domain admission). On Linux, applies Landlock filesystem confinement
//!   without seccomp (with `/proc` writable) so Chromium's own user-namespace
//!   renderer sandbox stays active. On macOS, applies an outer Seatbelt profile
//!   with scoped `MachPortRendezvousServer` registration, Darwin user temp dir
//!   access, and `--no-sandbox` (since XNU Seatbelt forbids nested
//!   `sandbox_init`).
//! - 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",
    "/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);
            }
        }
        // On Linux, Landlock sets `PR_SET_NO_NEW_PRIVS`, which disables Chrome's
        // setuid sandbox helper and requires its unprivileged user-namespace
        // sandbox (`CLONE_NEWUSER`) instead. Setting up that namespace writes
        // `/proc/<pid>/{setgroups,uid_map,gid_map,oom_score_adj}`, which fails
        // with exit code 82 if `/proc` is Landlock read-only.
        #[cfg(target_os = "linux")]
        push_if_exists(&mut read_write, Path::new("/proc"));
        // On macOS, Chrome's `ProcessSingleton` creates its lock socket under
        // `NSTemporaryDirectory()` (`confstr(_CS_DARWIN_USER_TEMP_DIR)` =
        // `/private/var/folders/.../T`), ignoring `$TMPDIR`. Grant that per-user
        // Darwin temp directory when it does not overlap any denied subtree.
        #[cfg(target_os = "macos")]
        if let Some(darwin_temp) = macos_darwin_user_temp_dir() {
            let resolved = resolve_host_path(&darwin_temp);
            if !overlaps_any(&resolved, &deny) && resolved.is_dir() {
                push_directory(&mut read_write, &resolved);
            }
        }

        // 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()),
        ];

        let launch_args = browser_launch_args(args);

        Ok(SandboxLaunch {
            program: path_to_string(&self.executable, "browser executable")?,
            args: launch_args,
            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(),
            allow_browser_mach_rendezvous: true,
        })
    }

    /// 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)
}

fn browser_launch_args(args: &[String]) -> Vec<String> {
    #[cfg(target_os = "macos")]
    {
        // macOS Seatbelt (`sandbox-exec`) forbids nested `sandbox_init` calls
        // from Chromium helper/renderer processes, causing them to abort with
        // `Operation not permitted`. Merry's outer Seatbelt profile already
        // confines the entire browser process tree (zero workspace, zero
        // `$HOME`, zero `providers/`), while `--sandbox off` runs Chrome
        // directly without `--no-sandbox`.
        let mut launch_args = Vec::with_capacity(args.len() + 1);
        if !args.iter().any(|arg| arg == "--no-sandbox") {
            launch_args.push("--no-sandbox".to_owned());
        }
        launch_args.extend(args.iter().cloned());
        launch_args
    }
    #[cfg(not(target_os = "macos"))]
    {
        args.to_vec()
    }
}

#[cfg(target_os = "macos")]
fn macos_darwin_user_temp_dir() -> Option<PathBuf> {
    let env_tmp = resolve_host_path(&env::temp_dir());
    if is_darwin_user_temp_dir(&env_tmp) {
        return Some(env_tmp);
    }
    let output = std::process::Command::new("/usr/bin/getconf")
        .arg("DARWIN_USER_TEMP_DIR")
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let trimmed = String::from_utf8(output.stdout).ok()?;
    let trimmed = trimmed.trim();
    if trimmed.is_empty() {
        return None;
    }
    let resolved = resolve_host_path(Path::new(trimmed));
    is_darwin_user_temp_dir(&resolved).then_some(resolved)
}

#[cfg(any(test, target_os = "macos"))]
fn is_darwin_user_temp_dir(path: &Path) -> bool {
    use std::{ffi::OsStr, path::Component};

    let mut components = path.components();
    let is_literal = |component: Option<Component<'_>>, expected: &str| matches!(component, Some(Component::Normal(value)) if value == OsStr::new(expected));
    let is_non_empty = |component: Option<Component<'_>>| matches!(component, Some(Component::Normal(value)) if !value.is_empty());
    matches!(components.next(), Some(Component::RootDir))
        && is_literal(components.next(), "private")
        && is_literal(components.next(), "var")
        && is_literal(components.next(), "folders")
        && is_non_empty(components.next())
        && is_non_empty(components.next())
        && is_literal(components.next(), "T")
        && components.next().is_none()
}

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