merry-process 0.1.1

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
//! Default local development toolchain and cache baseline rules for isolated
//! process actions.

use merry_core::host_paths::is_clean_absolute_path;
use merry_runtime::{PathAccess, PathAccessRule, PathAccessRuleSource};
use std::{
    env,
    ffi::OsString,
    path::{Path, PathBuf},
};

/// Explicit programming-language, compiler, and package-manager cache
/// subdirectories under `$XDG_CACHE_HOME` (default `~/.cache`).
///
/// Merry never grants all of `$XDG_CACHE_HOME`, which may hold browser caches,
/// unrelated CLI caches, or Merry's own worktree cache
/// (`$XDG_CACHE_HOME/merry/worktrees`). Each subdirectory is granted only when
/// it already exists on disk; Merry never pre-creates unused cache directories.
const XDG_CACHE_DEV_SUBDIRS: &[&str] = &[
    // C / C++ / LLVM / Zig / Bazel
    "ccache",
    "sccache",
    "clang",
    "clangd",
    "zig",
    "bazel",
    // Go
    "go-build",
    "golangci-lint",
    // Python
    "pip",
    "uv",
    "pypoetry",
    "ruff",
    "mypy",
    "pre-commit",
    // Node / JS / TS / Deno
    "npm",
    "pnpm",
    "yarn",
    "node",
    "node-gyp",
    "turbo",
    "typescript",
    "deno",
    // Nix / JVM / PHP / Haskell / Ruby
    "nix",
    "coursier",
    "composer",
    "cabal",
    "bundler",
];

/// Paths ordinary local development commands can use without another grant.
///
/// Covers common Rust, Python, Node/JS, Go, C/C++, Nix, and polyglot
/// version-manager toolchains and build caches. Toolchain binaries,
/// interpreters, and non-secret config files stay read-only; package and
/// compiler caches are writable only when they already exist on disk (or are
/// explicitly pointed to by toolchain environment variables), so Merry never
/// opens all of `$XDG_CACHE_HOME` or creates empty directories in `$HOME` for
/// unused languages. Credentials under `$HOME` (such as
/// `~/.cargo/credentials.toml`, `~/.npmrc`, `~/.pypirc`, `~/.netrc`, `~/.ssh`,
/// `~/.aws`, `~/.gnupg`) are never included.
#[must_use]
pub fn default_development_path_rules(home: &Path) -> Vec<PathAccessRule> {
    default_development_path_rules_with_env(home, |name| env::var_os(name))
}

/// Pure testable variant of [`default_development_path_rules`].
#[must_use]
pub fn default_development_path_rules_with_env(
    home: &Path,
    env_var: impl Fn(&str) -> Option<OsString>,
) -> Vec<PathAccessRule> {
    let env_path = |name: &str| {
        env_var(name)
            .map(PathBuf::from)
            .filter(|path| is_clean_absolute_path(path))
    };

    let cargo_home = env_path("CARGO_HOME").unwrap_or_else(|| home.join(".cargo"));
    let rustup_home = env_path("RUSTUP_HOME").unwrap_or_else(|| home.join(".rustup"));
    let cache_home = env_path("XDG_CACHE_HOME").unwrap_or_else(|| home.join(".cache"));
    let data_home = env_path("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"));

    let mut rules = vec![
        // User binaries & Nix profile
        (home.join(".local/bin"), PathAccess::ReadOnly),
        (home.join(".nix-profile"), PathAccess::ReadOnly),
        // Rust (`credentials.toml` stays excluded)
        (cargo_home.join("bin"), PathAccess::ReadOnly),
        (cargo_home.join("config.toml"), PathAccess::ReadOnly),
        (cargo_home.join("config"), PathAccess::ReadOnly),
        (rustup_home.join("settings.toml"), PathAccess::ReadOnly),
        (rustup_home.join("toolchains"), PathAccess::ReadOnly),
        // Python toolchains & managed interpreters (never all of `$XDG_DATA_HOME`)
        (data_home.join("uv"), PathAccess::ReadOnly),
        (data_home.join("pipx"), PathAccess::ReadOnly),
        (data_home.join("pypoetry"), PathAccess::ReadOnly),
        // Polyglot version managers (`mise`, `asdf`)
        (data_home.join("mise/installs"), PathAccess::ReadOnly),
        (data_home.join("mise/shims"), PathAccess::ReadOnly),
    ];

    for subdir in ["registry", "git"] {
        let candidate = cargo_home.join(subdir);
        if candidate.exists() {
            rules.push((candidate, PathAccess::ReadWrite));
        }
    }

    // Explicit dev-tool cache subdirectories under `$XDG_CACHE_HOME` (never
    // the entire `~/.cache` tree). Only mount directories that already exist.
    for subdir in XDG_CACHE_DEV_SUBDIRS {
        let candidate = cache_home.join(subdir);
        if candidate.exists() {
            rules.push((candidate, PathAccess::ReadWrite));
        }
    }

    let pyenv_root = env_path("PYENV_ROOT").unwrap_or_else(|| home.join(".pyenv"));
    rules.push((pyenv_root.join("versions"), PathAccess::ReadOnly));
    rules.push((pyenv_root.join("shims"), PathAccess::ReadOnly));

    if let Some(uv_python) = env_path("UV_PYTHON_INSTALL_DIR") {
        rules.push((uv_python, PathAccess::ReadOnly));
    }
    if let Some(poetry_home) = env_path("POETRY_HOME") {
        rules.push((poetry_home, PathAccess::ReadOnly));
    }
    if let Some(mise_data) = env_path("MISE_DATA_DIR") {
        rules.push((mise_data.join("installs"), PathAccess::ReadOnly));
        rules.push((mise_data.join("shims"), PathAccess::ReadOnly));
    }
    let asdf_data = env_path("ASDF_DATA_DIR").unwrap_or_else(|| home.join(".asdf"));
    rules.push((asdf_data.join("installs"), PathAccess::ReadOnly));
    rules.push((asdf_data.join("shims"), PathAccess::ReadOnly));

    // Node / JS / TS toolchains (`~/.npmrc` stays excluded)
    let nvm_dir = env_path("NVM_DIR").unwrap_or_else(|| home.join(".nvm"));
    rules.push((nvm_dir.join("versions"), PathAccess::ReadOnly));

    if let Some(fnm_dir) = env_path("FNM_DIR") {
        rules.push((fnm_dir, PathAccess::ReadOnly));
    } else {
        rules.push((data_home.join("fnm"), PathAccess::ReadOnly));
        rules.push((home.join(".fnm"), PathAccess::ReadOnly));
        #[cfg(target_os = "macos")]
        rules.push((
            home.join("Library/Application Support/fnm"),
            PathAccess::ReadOnly,
        ));
    }

    let volta_home = env_path("VOLTA_HOME").unwrap_or_else(|| home.join(".volta"));
    rules.push((volta_home.join("bin"), PathAccess::ReadOnly));
    rules.push((volta_home.join("tools"), PathAccess::ReadOnly));

    let bun_env = env_path("BUN_INSTALL");
    let bun_install = bun_env.clone().unwrap_or_else(|| home.join(".bun"));
    rules.push((bun_install.join("bin"), PathAccess::ReadOnly));
    if bun_env.is_some() || bun_install.exists() {
        rules.push((bun_install.join("install/cache"), PathAccess::ReadWrite));
    }

    let pnpm_home = env_path("PNPM_HOME").unwrap_or_else(|| {
        #[cfg(target_os = "macos")]
        {
            home.join("Library/pnpm")
        }
        #[cfg(not(target_os = "macos"))]
        {
            data_home.join("pnpm")
        }
    });
    rules.push((pnpm_home.clone(), PathAccess::ReadOnly));
    if pnpm_home.join("store").exists() {
        rules.push((pnpm_home.join("store"), PathAccess::ReadWrite));
    }

    if let Some(npm_cache) = env_path("NPM_CONFIG_CACHE") {
        rules.push((npm_cache, PathAccess::ReadWrite));
    } else if home.join(".npm").exists() {
        rules.push((home.join(".npm/_cacache"), PathAccess::ReadWrite));
    }

    // Go toolchain & module cache
    let gopath_env = env_path("GOPATH");
    let gopath = gopath_env.clone().unwrap_or_else(|| home.join("go"));
    rules.push((gopath.join("bin"), PathAccess::ReadOnly));
    if let Some(gomodcache) = env_path("GOMODCACHE") {
        rules.push((gomodcache, PathAccess::ReadWrite));
    } else if gopath_env.is_some() || gopath.exists() {
        rules.push((gopath.join("pkg/mod"), PathAccess::ReadWrite));
    } else {
        rules.push((gopath.join("pkg/mod"), PathAccess::ReadOnly));
    }

    // Explicit env-configured compiler/package caches
    for var in ["GOCACHE", "UV_CACHE_DIR", "PIP_CACHE_DIR"] {
        if let Some(path) = env_path(var) {
            rules.push((path, PathAccess::ReadWrite));
        }
    }

    // macOS CLI dev caches live under `~/Library/Caches/<tool>` rather than
    // `$XDG_CACHE_HOME`. Grant only explicit existing dev subdirectories, never
    // the whole `~/Library/Caches` tree.
    #[cfg(target_os = "macos")]
    {
        let library_caches = home.join("Library/Caches");
        for subdir in ["go-build", "pip", "uv", "pnpm", "Yarn", "node-gyp", "clang"] {
            let candidate = library_caches.join(subdir);
            if candidate.exists() {
                rules.push((candidate, PathAccess::ReadWrite));
            }
        }
    }

    // Windows CLI dev toolchains and caches live under `%LOCALAPPDATA%` /
    // `%APPDATA%` / `%USERPROFILE%\scoop`. Grant only explicit dev
    // subdirectories, never the whole AppData tree.
    #[cfg(windows)]
    {
        if let Some(local_appdata) = env_path("LOCALAPPDATA") {
            for subdir in [
                "go-build",
                "pip",
                "uv",
                "pnpm",
                "Yarn",
                "node-gyp",
                "npm-cache",
            ] {
                let candidate = local_appdata.join(subdir);
                if candidate.exists() {
                    rules.push((candidate, PathAccess::ReadWrite));
                }
            }
            for subdir in ["fnm", "Programs\\Python", "Programs\\Git"] {
                let candidate = local_appdata.join(subdir);
                if candidate.exists() {
                    rules.push((candidate, PathAccess::ReadOnly));
                }
            }
        }
        let scoop_shims = home.join("scoop").join("shims");
        if scoop_shims.exists() {
            rules.push((scoop_shims, PathAccess::ReadOnly));
        }
    }

    rules
        .into_iter()
        .filter(|(path, _)| is_clean_absolute_path(path))
        .map(|(path, access)| {
            PathAccessRule::new(
                path,
                access,
                PathAccessRuleSource::DefaultDevelopmentBaseline,
            )
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::default_development_path_rules_with_env;
    use merry_runtime::{PathAccess, PathAccessRule};
    use std::{fs, path::PathBuf};

    #[test]
    fn default_development_baseline_covers_polyglot_toolchains_and_excludes_credentials() {
        let home = tempfile::tempdir().expect("temp home");
        let home_path = home.path();
        fs::create_dir_all(home_path.join(".cargo/registry")).expect("cargo registry dir");
        fs::create_dir_all(home_path.join(".cache/pip")).expect("pip cache dir");
        fs::create_dir_all(home_path.join(".cache/go-build")).expect("go-build cache dir");
        fs::create_dir_all(home_path.join(".cache/ccache")).expect("ccache dir");
        fs::create_dir_all(home_path.join(".cache/chromium")).expect("browser cache dir");
        fs::create_dir_all(home_path.join(".cache/merry/worktrees")).expect("merry worktree dir");
        fs::create_dir_all(home_path.join("go/pkg/mod")).expect("go dir");
        fs::create_dir_all(home_path.join(".npm")).expect("npm dir");
        fs::create_dir_all(home_path.join(".bun")).expect("bun dir");
        #[cfg(target_os = "macos")]
        {
            fs::create_dir_all(home_path.join("Library/Caches/go-build"))
                .expect("macos go-build dir");
            fs::create_dir_all(home_path.join("Library/Caches/uv")).expect("macos uv dir");
        }

        let rules = default_development_path_rules_with_env(home_path, |_| None);
        let access_for = |path: PathBuf| {
            rules
                .iter()
                .find(|rule| rule.path() == path)
                .map(PathAccessRule::access)
        };

        assert_eq!(
            access_for(home_path.join(".rustup/settings.toml")),
            Some(PathAccess::ReadOnly)
        );
        assert_eq!(
            access_for(home_path.join(".cargo/config.toml")),
            Some(PathAccess::ReadOnly)
        );
        assert_eq!(
            access_for(home_path.join(".cargo/registry")),
            Some(PathAccess::ReadWrite)
        );
        assert_eq!(
            access_for(home_path.join(".cargo/git")),
            None,
            "non-existent .cargo/git must not be granted"
        );
        assert_eq!(
            access_for(home_path.join(".cache/pip")),
            Some(PathAccess::ReadWrite)
        );
        assert_eq!(
            access_for(home_path.join(".cache/go-build")),
            Some(PathAccess::ReadWrite)
        );
        assert_eq!(
            access_for(home_path.join(".cache/ccache")),
            Some(PathAccess::ReadWrite)
        );
        assert_eq!(
            access_for(home_path.join(".cache/uv")),
            None,
            "non-existent .cache/uv must not be granted"
        );
        assert_eq!(
            access_for(home_path.join(".local/share/uv")),
            Some(PathAccess::ReadOnly)
        );
        assert_eq!(
            access_for(home_path.join(".nvm/versions")),
            Some(PathAccess::ReadOnly)
        );
        assert_eq!(
            access_for(home_path.join(".nix-profile")),
            Some(PathAccess::ReadOnly)
        );
        assert_eq!(
            access_for(home_path.join("go/bin")),
            Some(PathAccess::ReadOnly)
        );
        assert_eq!(
            access_for(home_path.join("go/pkg/mod")),
            Some(PathAccess::ReadWrite)
        );
        assert_eq!(
            access_for(home_path.join(".npm/_cacache")),
            Some(PathAccess::ReadWrite)
        );
        assert_eq!(
            access_for(home_path.join(".bun/install/cache")),
            Some(PathAccess::ReadWrite)
        );

        #[cfg(target_os = "macos")]
        {
            assert_eq!(
                access_for(home_path.join("Library/Caches/go-build")),
                Some(PathAccess::ReadWrite)
            );
            assert_eq!(
                access_for(home_path.join("Library/Caches/uv")),
                Some(PathAccess::ReadWrite)
            );
            assert_eq!(
                access_for(home_path.join("Library/Caches/pip")),
                None,
                "non-existent macOS cache subdir must not be granted"
            );
            assert!(
                rules
                    .iter()
                    .all(|rule| rule.path() != home_path.join("Library/Caches")),
                "whole ~/Library/Caches must not be granted"
            );
        }

        // Credentials, whole `~/.cache`, browser caches, and Merry private
        // directories must never be covered.
        for forbidden in [
            home_path.to_path_buf(),
            home_path.join(".cache"),
            home_path.join(".cache/chromium"),
            home_path.join(".cache/merry/worktrees"),
            home_path.join(".cargo"),
            home_path.join(".cargo/credentials.toml"),
            home_path.join(".npmrc"),
            home_path.join(".pypirc"),
            home_path.join(".netrc"),
            home_path.join(".ssh"),
            home_path.join(".local/share"),
            home_path.join(".local/share/merry"),
            home_path.join("Library/Caches/com.apple.Safari"),
        ] {
            assert!(
                rules.iter().all(|rule| {
                    forbidden != rule.path() && !forbidden.starts_with(rule.path())
                }),
                "forbidden path {} must not be covered by baseline rules",
                forbidden.display()
            );
        }
    }
}