Skip to main content

merry_process/
baseline.rs

1//! Default local development toolchain and cache baseline rules for isolated
2//! process actions.
3
4use merry_core::host_paths::is_clean_absolute_path;
5use merry_runtime::{PathAccess, PathAccessRule, PathAccessRuleSource};
6use std::{
7    env,
8    ffi::OsString,
9    path::{Path, PathBuf},
10};
11
12/// Explicit programming-language, compiler, and package-manager cache
13/// subdirectories under `$XDG_CACHE_HOME` (default `~/.cache`).
14///
15/// Merry never grants all of `$XDG_CACHE_HOME`, which may hold browser caches,
16/// unrelated CLI caches, or Merry's own worktree cache
17/// (`$XDG_CACHE_HOME/merry/worktrees`). Each subdirectory is granted only when
18/// it already exists on disk; Merry never pre-creates unused cache directories.
19const XDG_CACHE_DEV_SUBDIRS: &[&str] = &[
20    // C / C++ / LLVM / Zig / Bazel
21    "ccache",
22    "sccache",
23    "clang",
24    "clangd",
25    "zig",
26    "bazel",
27    // Go
28    "go-build",
29    "golangci-lint",
30    // Python
31    "pip",
32    "uv",
33    "pypoetry",
34    "ruff",
35    "mypy",
36    "pre-commit",
37    // Node / JS / TS / Deno
38    "npm",
39    "pnpm",
40    "yarn",
41    "node",
42    "node-gyp",
43    "turbo",
44    "typescript",
45    "deno",
46    // Nix / JVM / PHP / Haskell / Ruby
47    "nix",
48    "coursier",
49    "composer",
50    "cabal",
51    "bundler",
52];
53
54/// Paths ordinary local development commands can use without another grant.
55///
56/// Covers common Rust, Python, Node/JS, Go, C/C++, Nix, and polyglot
57/// version-manager toolchains and build caches. Toolchain binaries,
58/// interpreters, and non-secret config files stay read-only; package and
59/// compiler caches are writable only when they already exist on disk (or are
60/// explicitly pointed to by toolchain environment variables), so Merry never
61/// opens all of `$XDG_CACHE_HOME` or creates empty directories in `$HOME` for
62/// unused languages. Credentials under `$HOME` (such as
63/// `~/.cargo/credentials.toml`, `~/.npmrc`, `~/.pypirc`, `~/.netrc`, `~/.ssh`,
64/// `~/.aws`, `~/.gnupg`) are never included.
65#[must_use]
66pub fn default_development_path_rules(home: &Path) -> Vec<PathAccessRule> {
67    default_development_path_rules_with_env(home, |name| env::var_os(name))
68}
69
70/// Pure testable variant of [`default_development_path_rules`].
71#[must_use]
72pub fn default_development_path_rules_with_env(
73    home: &Path,
74    env_var: impl Fn(&str) -> Option<OsString>,
75) -> Vec<PathAccessRule> {
76    let env_path = |name: &str| {
77        env_var(name)
78            .map(PathBuf::from)
79            .filter(|path| is_clean_absolute_path(path))
80    };
81
82    let cargo_home = env_path("CARGO_HOME").unwrap_or_else(|| home.join(".cargo"));
83    let rustup_home = env_path("RUSTUP_HOME").unwrap_or_else(|| home.join(".rustup"));
84    let cache_home = env_path("XDG_CACHE_HOME").unwrap_or_else(|| home.join(".cache"));
85    let data_home = env_path("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"));
86
87    let mut rules = vec![
88        // User binaries & Nix profile
89        (home.join(".local/bin"), PathAccess::ReadOnly),
90        (home.join(".nix-profile"), PathAccess::ReadOnly),
91        // Rust (`credentials.toml` stays excluded)
92        (cargo_home.join("bin"), PathAccess::ReadOnly),
93        (cargo_home.join("config.toml"), PathAccess::ReadOnly),
94        (cargo_home.join("config"), PathAccess::ReadOnly),
95        (rustup_home.join("settings.toml"), PathAccess::ReadOnly),
96        (rustup_home.join("toolchains"), PathAccess::ReadOnly),
97        // Python toolchains & managed interpreters (never all of `$XDG_DATA_HOME`)
98        (data_home.join("uv"), PathAccess::ReadOnly),
99        (data_home.join("pipx"), PathAccess::ReadOnly),
100        (data_home.join("pypoetry"), PathAccess::ReadOnly),
101        // Polyglot version managers (`mise`, `asdf`)
102        (data_home.join("mise/installs"), PathAccess::ReadOnly),
103        (data_home.join("mise/shims"), PathAccess::ReadOnly),
104    ];
105
106    for subdir in ["registry", "git"] {
107        let candidate = cargo_home.join(subdir);
108        if candidate.exists() {
109            rules.push((candidate, PathAccess::ReadWrite));
110        }
111    }
112
113    // Explicit dev-tool cache subdirectories under `$XDG_CACHE_HOME` (never
114    // the entire `~/.cache` tree). Only mount directories that already exist.
115    for subdir in XDG_CACHE_DEV_SUBDIRS {
116        let candidate = cache_home.join(subdir);
117        if candidate.exists() {
118            rules.push((candidate, PathAccess::ReadWrite));
119        }
120    }
121
122    let pyenv_root = env_path("PYENV_ROOT").unwrap_or_else(|| home.join(".pyenv"));
123    rules.push((pyenv_root.join("versions"), PathAccess::ReadOnly));
124    rules.push((pyenv_root.join("shims"), PathAccess::ReadOnly));
125
126    if let Some(uv_python) = env_path("UV_PYTHON_INSTALL_DIR") {
127        rules.push((uv_python, PathAccess::ReadOnly));
128    }
129    if let Some(poetry_home) = env_path("POETRY_HOME") {
130        rules.push((poetry_home, PathAccess::ReadOnly));
131    }
132    if let Some(mise_data) = env_path("MISE_DATA_DIR") {
133        rules.push((mise_data.join("installs"), PathAccess::ReadOnly));
134        rules.push((mise_data.join("shims"), PathAccess::ReadOnly));
135    }
136    let asdf_data = env_path("ASDF_DATA_DIR").unwrap_or_else(|| home.join(".asdf"));
137    rules.push((asdf_data.join("installs"), PathAccess::ReadOnly));
138    rules.push((asdf_data.join("shims"), PathAccess::ReadOnly));
139
140    // Node / JS / TS toolchains (`~/.npmrc` stays excluded)
141    let nvm_dir = env_path("NVM_DIR").unwrap_or_else(|| home.join(".nvm"));
142    rules.push((nvm_dir.join("versions"), PathAccess::ReadOnly));
143
144    if let Some(fnm_dir) = env_path("FNM_DIR") {
145        rules.push((fnm_dir, PathAccess::ReadOnly));
146    } else {
147        rules.push((data_home.join("fnm"), PathAccess::ReadOnly));
148        rules.push((home.join(".fnm"), PathAccess::ReadOnly));
149        #[cfg(target_os = "macos")]
150        rules.push((
151            home.join("Library/Application Support/fnm"),
152            PathAccess::ReadOnly,
153        ));
154    }
155
156    let volta_home = env_path("VOLTA_HOME").unwrap_or_else(|| home.join(".volta"));
157    rules.push((volta_home.join("bin"), PathAccess::ReadOnly));
158    rules.push((volta_home.join("tools"), PathAccess::ReadOnly));
159
160    let bun_env = env_path("BUN_INSTALL");
161    let bun_install = bun_env.clone().unwrap_or_else(|| home.join(".bun"));
162    rules.push((bun_install.join("bin"), PathAccess::ReadOnly));
163    if bun_env.is_some() || bun_install.exists() {
164        rules.push((bun_install.join("install/cache"), PathAccess::ReadWrite));
165    }
166
167    let pnpm_home = env_path("PNPM_HOME").unwrap_or_else(|| {
168        #[cfg(target_os = "macos")]
169        {
170            home.join("Library/pnpm")
171        }
172        #[cfg(not(target_os = "macos"))]
173        {
174            data_home.join("pnpm")
175        }
176    });
177    rules.push((pnpm_home.clone(), PathAccess::ReadOnly));
178    if pnpm_home.join("store").exists() {
179        rules.push((pnpm_home.join("store"), PathAccess::ReadWrite));
180    }
181
182    if let Some(npm_cache) = env_path("NPM_CONFIG_CACHE") {
183        rules.push((npm_cache, PathAccess::ReadWrite));
184    } else if home.join(".npm").exists() {
185        rules.push((home.join(".npm/_cacache"), PathAccess::ReadWrite));
186    }
187
188    // Go toolchain & module cache
189    let gopath_env = env_path("GOPATH");
190    let gopath = gopath_env.clone().unwrap_or_else(|| home.join("go"));
191    rules.push((gopath.join("bin"), PathAccess::ReadOnly));
192    if let Some(gomodcache) = env_path("GOMODCACHE") {
193        rules.push((gomodcache, PathAccess::ReadWrite));
194    } else if gopath_env.is_some() || gopath.exists() {
195        rules.push((gopath.join("pkg/mod"), PathAccess::ReadWrite));
196    } else {
197        rules.push((gopath.join("pkg/mod"), PathAccess::ReadOnly));
198    }
199
200    // Explicit env-configured compiler/package caches
201    for var in ["GOCACHE", "UV_CACHE_DIR", "PIP_CACHE_DIR"] {
202        if let Some(path) = env_path(var) {
203            rules.push((path, PathAccess::ReadWrite));
204        }
205    }
206
207    // macOS CLI dev caches live under `~/Library/Caches/<tool>` rather than
208    // `$XDG_CACHE_HOME`. Grant only explicit existing dev subdirectories, never
209    // the whole `~/Library/Caches` tree.
210    #[cfg(target_os = "macos")]
211    {
212        let library_caches = home.join("Library/Caches");
213        for subdir in ["go-build", "pip", "uv", "pnpm", "Yarn", "node-gyp", "clang"] {
214            let candidate = library_caches.join(subdir);
215            if candidate.exists() {
216                rules.push((candidate, PathAccess::ReadWrite));
217            }
218        }
219    }
220
221    // Windows CLI dev toolchains and caches live under `%LOCALAPPDATA%` /
222    // `%APPDATA%` / `%USERPROFILE%\scoop`. Grant only explicit dev
223    // subdirectories, never the whole AppData tree.
224    #[cfg(windows)]
225    {
226        if let Some(local_appdata) = env_path("LOCALAPPDATA") {
227            for subdir in [
228                "go-build",
229                "pip",
230                "uv",
231                "pnpm",
232                "Yarn",
233                "node-gyp",
234                "npm-cache",
235            ] {
236                let candidate = local_appdata.join(subdir);
237                if candidate.exists() {
238                    rules.push((candidate, PathAccess::ReadWrite));
239                }
240            }
241            for subdir in ["fnm", "Programs\\Python", "Programs\\Git"] {
242                let candidate = local_appdata.join(subdir);
243                if candidate.exists() {
244                    rules.push((candidate, PathAccess::ReadOnly));
245                }
246            }
247        }
248        let scoop_shims = home.join("scoop").join("shims");
249        if scoop_shims.exists() {
250            rules.push((scoop_shims, PathAccess::ReadOnly));
251        }
252    }
253
254    rules
255        .into_iter()
256        .filter(|(path, _)| is_clean_absolute_path(path))
257        .map(|(path, access)| {
258            PathAccessRule::new(
259                path,
260                access,
261                PathAccessRuleSource::DefaultDevelopmentBaseline,
262            )
263        })
264        .collect()
265}
266
267#[cfg(test)]
268mod tests {
269    use super::default_development_path_rules_with_env;
270    use merry_runtime::{PathAccess, PathAccessRule};
271    use std::{fs, path::PathBuf};
272
273    #[test]
274    fn default_development_baseline_covers_polyglot_toolchains_and_excludes_credentials() {
275        let home = tempfile::tempdir().expect("temp home");
276        let home_path = home.path();
277        fs::create_dir_all(home_path.join(".cargo/registry")).expect("cargo registry dir");
278        fs::create_dir_all(home_path.join(".cache/pip")).expect("pip cache dir");
279        fs::create_dir_all(home_path.join(".cache/go-build")).expect("go-build cache dir");
280        fs::create_dir_all(home_path.join(".cache/ccache")).expect("ccache dir");
281        fs::create_dir_all(home_path.join(".cache/chromium")).expect("browser cache dir");
282        fs::create_dir_all(home_path.join(".cache/merry/worktrees")).expect("merry worktree dir");
283        fs::create_dir_all(home_path.join("go/pkg/mod")).expect("go dir");
284        fs::create_dir_all(home_path.join(".npm")).expect("npm dir");
285        fs::create_dir_all(home_path.join(".bun")).expect("bun dir");
286        #[cfg(target_os = "macos")]
287        {
288            fs::create_dir_all(home_path.join("Library/Caches/go-build"))
289                .expect("macos go-build dir");
290            fs::create_dir_all(home_path.join("Library/Caches/uv")).expect("macos uv dir");
291        }
292
293        let rules = default_development_path_rules_with_env(home_path, |_| None);
294        let access_for = |path: PathBuf| {
295            rules
296                .iter()
297                .find(|rule| rule.path() == path)
298                .map(PathAccessRule::access)
299        };
300
301        assert_eq!(
302            access_for(home_path.join(".rustup/settings.toml")),
303            Some(PathAccess::ReadOnly)
304        );
305        assert_eq!(
306            access_for(home_path.join(".cargo/config.toml")),
307            Some(PathAccess::ReadOnly)
308        );
309        assert_eq!(
310            access_for(home_path.join(".cargo/registry")),
311            Some(PathAccess::ReadWrite)
312        );
313        assert_eq!(
314            access_for(home_path.join(".cargo/git")),
315            None,
316            "non-existent .cargo/git must not be granted"
317        );
318        assert_eq!(
319            access_for(home_path.join(".cache/pip")),
320            Some(PathAccess::ReadWrite)
321        );
322        assert_eq!(
323            access_for(home_path.join(".cache/go-build")),
324            Some(PathAccess::ReadWrite)
325        );
326        assert_eq!(
327            access_for(home_path.join(".cache/ccache")),
328            Some(PathAccess::ReadWrite)
329        );
330        assert_eq!(
331            access_for(home_path.join(".cache/uv")),
332            None,
333            "non-existent .cache/uv must not be granted"
334        );
335        assert_eq!(
336            access_for(home_path.join(".local/share/uv")),
337            Some(PathAccess::ReadOnly)
338        );
339        assert_eq!(
340            access_for(home_path.join(".nvm/versions")),
341            Some(PathAccess::ReadOnly)
342        );
343        assert_eq!(
344            access_for(home_path.join(".nix-profile")),
345            Some(PathAccess::ReadOnly)
346        );
347        assert_eq!(
348            access_for(home_path.join("go/bin")),
349            Some(PathAccess::ReadOnly)
350        );
351        assert_eq!(
352            access_for(home_path.join("go/pkg/mod")),
353            Some(PathAccess::ReadWrite)
354        );
355        assert_eq!(
356            access_for(home_path.join(".npm/_cacache")),
357            Some(PathAccess::ReadWrite)
358        );
359        assert_eq!(
360            access_for(home_path.join(".bun/install/cache")),
361            Some(PathAccess::ReadWrite)
362        );
363
364        #[cfg(target_os = "macos")]
365        {
366            assert_eq!(
367                access_for(home_path.join("Library/Caches/go-build")),
368                Some(PathAccess::ReadWrite)
369            );
370            assert_eq!(
371                access_for(home_path.join("Library/Caches/uv")),
372                Some(PathAccess::ReadWrite)
373            );
374            assert_eq!(
375                access_for(home_path.join("Library/Caches/pip")),
376                None,
377                "non-existent macOS cache subdir must not be granted"
378            );
379            assert!(
380                rules
381                    .iter()
382                    .all(|rule| rule.path() != home_path.join("Library/Caches")),
383                "whole ~/Library/Caches must not be granted"
384            );
385        }
386
387        // Credentials, whole `~/.cache`, browser caches, and Merry private
388        // directories must never be covered.
389        for forbidden in [
390            home_path.to_path_buf(),
391            home_path.join(".cache"),
392            home_path.join(".cache/chromium"),
393            home_path.join(".cache/merry/worktrees"),
394            home_path.join(".cargo"),
395            home_path.join(".cargo/credentials.toml"),
396            home_path.join(".npmrc"),
397            home_path.join(".pypirc"),
398            home_path.join(".netrc"),
399            home_path.join(".ssh"),
400            home_path.join(".local/share"),
401            home_path.join(".local/share/merry"),
402            home_path.join("Library/Caches/com.apple.Safari"),
403        ] {
404            assert!(
405                rules.iter().all(|rule| {
406                    forbidden != rule.path() && !forbidden.starts_with(rule.path())
407                }),
408                "forbidden path {} must not be covered by baseline rules",
409                forbidden.display()
410            );
411        }
412    }
413}