Skip to main content

cant_launch/
readonly.rs

1//! Package-manager trees mounted read-only for cants that may write the project.
2//!
3//! pnpm, Bun and uv (and Yarn with `nmMode: hardlinks-*`) fill `node_modules` or `.venv` with
4//! hard links into one store shared by all the user's projects. Landlock checks the path a file
5//! is opened by, not the file, and can't take files out of a writable directory: a cant that may
6//! write the project could change a stored package for every project. So such trees are found
7//! with a few `stat` calls (no walk) and mounted read-only in the cant's own mount namespace
8//! ([`crate::Plan::readonly`]); tool caches inside `node_modules` stay writable.
9
10use std::path::{Path, PathBuf};
11
12use cant_policy::{Grant, Origin, Policy};
13
14/// Caches inside `node_modules` that tools write (eslint, babel, vite, vitest): mounted
15/// writable again on top of the read-only tree. `.cache` is created when missing.
16pub const WRITABLE_CACHES: &[&str] = &[".cache", ".vite", ".vite-temp", ".vitest"];
17
18/// The package-manager trees under the directories `policy` lets the cant write: for each
19/// writable directory `d` (from the manifest, the command line or `--grant`), `d/node_modules`
20/// and `d/.venv` or `d/venv` with a `pyvenv.cfg`, and the same one level down (workspaces). A
21/// tree the manifest grants writable itself (`$CWD/*` grants each entry) is one too. A tree the
22/// user named (`--grant`, or as an argument), or that holds a path they named, is their choice
23/// and is left alone. Sorted, distinct.
24pub fn shared_trees(policy: &Policy) -> Vec<PathBuf> {
25    let writable: Vec<&Grant> = policy
26        .grants
27        .iter()
28        .filter(|g| {
29            g.access.write
30                && !g.create
31                && matches!(
32                    g.origin,
33                    Origin::Manifest | Origin::Argument { .. } | Origin::User
34                )
35        })
36        .collect();
37    let named: Vec<&Path> = writable
38        .iter()
39        .filter(|g| g.origin != Origin::Manifest)
40        .map(|g| g.path.as_path())
41        .collect();
42    let mut out = Vec::new();
43    for dir in writable
44        .iter()
45        .map(|g| g.path.as_path())
46        .filter(|d| is_dir(d))
47    {
48        if is_tree(dir) {
49            out.push(dir.to_path_buf());
50            continue;
51        }
52        let mut places = vec![dir.to_path_buf()];
53        if let Ok(entries) = std::fs::read_dir(dir) {
54            places.extend(
55                entries
56                    .flatten()
57                    .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
58                    .map(|e| e.path())
59                    .filter(|p| !is_tree(p)),
60            );
61        }
62        for place in places {
63            for name in ["node_modules", ".venv", "venv"] {
64                let tree = place.join(name);
65                if is_tree(&tree) {
66                    out.push(tree);
67                }
68            }
69        }
70    }
71    out.retain(|t| !named.iter().any(|n| n.starts_with(t)));
72    out.sort();
73    out.dedup();
74    out
75}
76
77/// The warning when the trees can't be mounted read-only here (no user namespaces).
78pub fn not_locked(trees: &[PathBuf]) -> String {
79    let list: Vec<String> = trees.iter().map(|t| t.display().to_string()).collect();
80    format!(
81        "{} stay{} writable here: user namespaces don't work, so a package store hardlinked \
82         there could be changed (cant check says why)",
83        list.join(", "),
84        if trees.len() == 1 { "s" } else { "" }
85    )
86}
87
88/// A real directory (not a symlink).
89fn is_dir(p: &Path) -> bool {
90    std::fs::symlink_metadata(p).is_ok_and(|m| m.is_dir())
91}
92
93/// `node_modules`, or a virtualenv (`pyvenv.cfg` inside).
94fn is_tree(p: &Path) -> bool {
95    match p.file_name().and_then(|n| n.to_str()) {
96        Some("node_modules") => is_dir(p),
97        Some(".venv" | "venv") => is_dir(p) && p.join("pyvenv.cfg").is_file(),
98        _ => false,
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use cant_policy::Access;
106
107    fn grant(path: &Path, access: Access, origin: Origin) -> Grant {
108        Grant {
109            path: path.to_path_buf(),
110            access,
111            origin,
112            create: false,
113            dir: false,
114        }
115    }
116
117    #[test]
118    fn package_trees_under_writable_directories() {
119        let t = tempfile::tempdir().expect("tempdir");
120        let proj = t.path().join("proj");
121        for d in [
122            "node_modules/.pnpm",
123            ".venv",
124            "venv",
125            "packages/web/node_modules",
126            "packages/api/.venv",
127            "src",
128        ] {
129            std::fs::create_dir_all(proj.join(d)).expect("mkdir");
130        }
131        std::fs::write(proj.join(".venv/pyvenv.cfg"), "home = /usr\n").expect("write");
132        std::fs::write(proj.join("packages/api/.venv/pyvenv.cfg"), "").expect("write");
133        // `venv` without pyvenv.cfg is just a directory; a node_modules file isn't a tree.
134        std::fs::write(proj.join("src/node_modules"), "").expect("write");
135        let mut p = Policy {
136            grants: vec![grant(&proj, Access::RW, Origin::Manifest)],
137            ..Policy::default()
138        };
139        assert_eq!(
140            shared_trees(&p),
141            [proj.join(".venv"), proj.join("node_modules")],
142            "one level down reaches packages/, not packages/web or packages/api"
143        );
144        // Workspaces one level down.
145        let ws = t.path().join("ws");
146        std::fs::create_dir_all(ws.join("app/node_modules")).expect("mkdir");
147        p.grants = vec![grant(&ws, Access::RW, Origin::Argument { index: 0 })];
148        assert_eq!(shared_trees(&p), [ws.join("app/node_modules")]);
149        // Read-only grants, files, the can's own files and created data dirs don't count.
150        p.grants = vec![
151            grant(&proj, Access::R, Origin::Manifest),
152            grant(
153                &proj.join("src/node_modules"),
154                Access::RW,
155                Origin::Argument { index: 0 },
156            ),
157            grant(&proj, Access::RW, Origin::Can),
158            Grant {
159                create: true,
160                dir: true,
161                ..grant(&proj, Access::RW, Origin::Manifest)
162            },
163        ];
164        assert!(shared_trees(&p).is_empty());
165        // A tree the user granted writable (or something inside it) is left writable.
166        p.grants = vec![
167            grant(&proj, Access::RW, Origin::Manifest),
168            grant(&proj.join("node_modules/.pnpm"), Access::RW, Origin::User),
169        ];
170        assert_eq!(shared_trees(&p), [proj.join(".venv")]);
171        p.grants = vec![
172            grant(&proj, Access::RW, Origin::Manifest),
173            grant(&proj.join(".venv"), Access::RW, Origin::User),
174        ];
175        assert_eq!(shared_trees(&p), [proj.join("node_modules")]);
176        // `$CWD/*` grants each entry: a tree granted by the manifest is read-only itself, and
177        // nothing inside it is searched; `packages` is searched like any writable directory.
178        std::fs::create_dir_all(proj.join("node_modules/dep/node_modules")).expect("mkdir");
179        p.grants = [".venv", "node_modules", "packages", "src"]
180            .iter()
181            .map(|e| grant(&proj.join(e), Access::RW, Origin::Manifest))
182            .collect();
183        assert_eq!(
184            shared_trees(&p),
185            [
186                proj.join(".venv"),
187                proj.join("node_modules"),
188                proj.join("packages/api/.venv"),
189                proj.join("packages/web/node_modules"),
190            ]
191        );
192        // The same tree named on the command line stays writable.
193        p.grants.push(grant(
194            &proj.join("node_modules"),
195            Access::RW,
196            Origin::Argument { index: 0 },
197        ));
198        assert_eq!(
199            shared_trees(&p),
200            [
201                proj.join(".venv"),
202                proj.join("packages/api/.venv"),
203                proj.join("packages/web/node_modules"),
204            ]
205        );
206        // A directory that can't be listed still has its own trees checked.
207        #[cfg(unix)]
208        {
209            use std::os::unix::fs::PermissionsExt;
210            let shut = t.path().join("shut");
211            std::fs::create_dir_all(shut.join("node_modules")).expect("mkdir");
212            std::fs::set_permissions(&shut, std::fs::Permissions::from_mode(0o300)).expect("chmod");
213            p.grants = vec![grant(&shut, Access::RW, Origin::Manifest)];
214            assert_eq!(shared_trees(&p), [shut.join("node_modules")]);
215            std::fs::set_permissions(&shut, std::fs::Permissions::from_mode(0o700)).expect("chmod");
216        }
217        // A symlinked node_modules isn't followed; a missing directory is skipped.
218        let link = t.path().join("linked");
219        std::fs::create_dir_all(&link).expect("mkdir");
220        #[cfg(unix)]
221        std::os::unix::fs::symlink(proj.join("node_modules"), link.join("node_modules"))
222            .expect("symlink");
223        p.grants = vec![
224            grant(&link, Access::RW, Origin::Manifest),
225            grant(&t.path().join("gone"), Access::RW, Origin::Manifest),
226        ];
227        assert!(shared_trees(&p).is_empty());
228    }
229
230    #[test]
231    fn the_warning_names_the_trees() {
232        assert_eq!(
233            not_locked(&[PathBuf::from("/p/node_modules")]),
234            "/p/node_modules stays writable here: user namespaces don't work, so a package \
235             store hardlinked there could be changed (cant check says why)"
236        );
237        assert!(
238            not_locked(&[PathBuf::from("/p/node_modules"), PathBuf::from("/p/.venv")])
239                .starts_with("/p/node_modules, /p/.venv stay writable")
240        );
241    }
242}