cant-launch 0.0.21

Sandbox setup (Landlock, seccomp) and exec for Cantainer capsules.
Documentation
//! Package-manager trees mounted read-only for cants that may write the project.
//!
//! pnpm, Bun and uv (and Yarn with `nmMode: hardlinks-*`) fill `node_modules` or `.venv` with
//! hard links into one store shared by all the user's projects. Landlock checks the path a file
//! is opened by, not the file, and can't take files out of a writable directory: a cant that may
//! write the project could change a stored package for every project. So such trees are found
//! with a few `stat` calls (no walk) and mounted read-only in the cant's own mount namespace
//! ([`crate::Plan::readonly`]); tool caches inside `node_modules` stay writable.

use std::path::{Path, PathBuf};

use cant_policy::{Grant, Origin, Policy};

/// Caches inside `node_modules` that tools write (eslint, babel, vite, vitest): mounted
/// writable again on top of the read-only tree. `.cache` is created when missing.
pub const WRITABLE_CACHES: &[&str] = &[".cache", ".vite", ".vite-temp", ".vitest"];

/// The package-manager trees under the directories `policy` lets the cant write: for each
/// writable directory `d` (from the manifest, the command line or `--grant`), `d/node_modules`
/// and `d/.venv` or `d/venv` with a `pyvenv.cfg`, and the same one level down (workspaces). A
/// tree the manifest grants writable itself (`$CWD/*` grants each entry) is one too. A tree the
/// user named (`--grant`, or as an argument), or that holds a path they named, is their choice
/// and is left alone. Sorted, distinct.
pub fn shared_trees(policy: &Policy) -> Vec<PathBuf> {
    let writable: Vec<&Grant> = policy
        .grants
        .iter()
        .filter(|g| {
            g.access.write
                && !g.create
                && matches!(
                    g.origin,
                    Origin::Manifest | Origin::Argument { .. } | Origin::User
                )
        })
        .collect();
    let named: Vec<&Path> = writable
        .iter()
        .filter(|g| g.origin != Origin::Manifest)
        .map(|g| g.path.as_path())
        .collect();
    let mut out = Vec::new();
    for dir in writable
        .iter()
        .map(|g| g.path.as_path())
        .filter(|d| is_dir(d))
    {
        if is_tree(dir) {
            out.push(dir.to_path_buf());
            continue;
        }
        let mut places = vec![dir.to_path_buf()];
        if let Ok(entries) = std::fs::read_dir(dir) {
            places.extend(
                entries
                    .flatten()
                    .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
                    .map(|e| e.path())
                    .filter(|p| !is_tree(p)),
            );
        }
        for place in places {
            for name in ["node_modules", ".venv", "venv"] {
                let tree = place.join(name);
                if is_tree(&tree) {
                    out.push(tree);
                }
            }
        }
    }
    out.retain(|t| !named.iter().any(|n| n.starts_with(t)));
    out.sort();
    out.dedup();
    out
}

/// The warning when the trees can't be mounted read-only here (no user namespaces).
pub fn not_locked(trees: &[PathBuf]) -> String {
    let list: Vec<String> = trees.iter().map(|t| t.display().to_string()).collect();
    format!(
        "{} stay{} writable here: user namespaces don't work, so a package store hardlinked \
         there could be changed (cant check says why)",
        list.join(", "),
        if trees.len() == 1 { "s" } else { "" }
    )
}

/// A real directory (not a symlink).
fn is_dir(p: &Path) -> bool {
    std::fs::symlink_metadata(p).is_ok_and(|m| m.is_dir())
}

/// `node_modules`, or a virtualenv (`pyvenv.cfg` inside).
fn is_tree(p: &Path) -> bool {
    match p.file_name().and_then(|n| n.to_str()) {
        Some("node_modules") => is_dir(p),
        Some(".venv" | "venv") => is_dir(p) && p.join("pyvenv.cfg").is_file(),
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cant_policy::Access;

    fn grant(path: &Path, access: Access, origin: Origin) -> Grant {
        Grant {
            path: path.to_path_buf(),
            access,
            origin,
            create: false,
            dir: false,
        }
    }

    #[test]
    fn package_trees_under_writable_directories() {
        let t = tempfile::tempdir().expect("tempdir");
        let proj = t.path().join("proj");
        for d in [
            "node_modules/.pnpm",
            ".venv",
            "venv",
            "packages/web/node_modules",
            "packages/api/.venv",
            "src",
        ] {
            std::fs::create_dir_all(proj.join(d)).expect("mkdir");
        }
        std::fs::write(proj.join(".venv/pyvenv.cfg"), "home = /usr\n").expect("write");
        std::fs::write(proj.join("packages/api/.venv/pyvenv.cfg"), "").expect("write");
        // `venv` without pyvenv.cfg is just a directory; a node_modules file isn't a tree.
        std::fs::write(proj.join("src/node_modules"), "").expect("write");
        let mut p = Policy {
            grants: vec![grant(&proj, Access::RW, Origin::Manifest)],
            ..Policy::default()
        };
        assert_eq!(
            shared_trees(&p),
            [proj.join(".venv"), proj.join("node_modules")],
            "one level down reaches packages/, not packages/web or packages/api"
        );
        // Workspaces one level down.
        let ws = t.path().join("ws");
        std::fs::create_dir_all(ws.join("app/node_modules")).expect("mkdir");
        p.grants = vec![grant(&ws, Access::RW, Origin::Argument { index: 0 })];
        assert_eq!(shared_trees(&p), [ws.join("app/node_modules")]);
        // Read-only grants, files, the can's own files and created data dirs don't count.
        p.grants = vec![
            grant(&proj, Access::R, Origin::Manifest),
            grant(
                &proj.join("src/node_modules"),
                Access::RW,
                Origin::Argument { index: 0 },
            ),
            grant(&proj, Access::RW, Origin::Can),
            Grant {
                create: true,
                dir: true,
                ..grant(&proj, Access::RW, Origin::Manifest)
            },
        ];
        assert!(shared_trees(&p).is_empty());
        // A tree the user granted writable (or something inside it) is left writable.
        p.grants = vec![
            grant(&proj, Access::RW, Origin::Manifest),
            grant(&proj.join("node_modules/.pnpm"), Access::RW, Origin::User),
        ];
        assert_eq!(shared_trees(&p), [proj.join(".venv")]);
        p.grants = vec![
            grant(&proj, Access::RW, Origin::Manifest),
            grant(&proj.join(".venv"), Access::RW, Origin::User),
        ];
        assert_eq!(shared_trees(&p), [proj.join("node_modules")]);
        // `$CWD/*` grants each entry: a tree granted by the manifest is read-only itself, and
        // nothing inside it is searched; `packages` is searched like any writable directory.
        std::fs::create_dir_all(proj.join("node_modules/dep/node_modules")).expect("mkdir");
        p.grants = [".venv", "node_modules", "packages", "src"]
            .iter()
            .map(|e| grant(&proj.join(e), Access::RW, Origin::Manifest))
            .collect();
        assert_eq!(
            shared_trees(&p),
            [
                proj.join(".venv"),
                proj.join("node_modules"),
                proj.join("packages/api/.venv"),
                proj.join("packages/web/node_modules"),
            ]
        );
        // The same tree named on the command line stays writable.
        p.grants.push(grant(
            &proj.join("node_modules"),
            Access::RW,
            Origin::Argument { index: 0 },
        ));
        assert_eq!(
            shared_trees(&p),
            [
                proj.join(".venv"),
                proj.join("packages/api/.venv"),
                proj.join("packages/web/node_modules"),
            ]
        );
        // A directory that can't be listed still has its own trees checked.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let shut = t.path().join("shut");
            std::fs::create_dir_all(shut.join("node_modules")).expect("mkdir");
            std::fs::set_permissions(&shut, std::fs::Permissions::from_mode(0o300)).expect("chmod");
            p.grants = vec![grant(&shut, Access::RW, Origin::Manifest)];
            assert_eq!(shared_trees(&p), [shut.join("node_modules")]);
            std::fs::set_permissions(&shut, std::fs::Permissions::from_mode(0o700)).expect("chmod");
        }
        // A symlinked node_modules isn't followed; a missing directory is skipped.
        let link = t.path().join("linked");
        std::fs::create_dir_all(&link).expect("mkdir");
        #[cfg(unix)]
        std::os::unix::fs::symlink(proj.join("node_modules"), link.join("node_modules"))
            .expect("symlink");
        p.grants = vec![
            grant(&link, Access::RW, Origin::Manifest),
            grant(&t.path().join("gone"), Access::RW, Origin::Manifest),
        ];
        assert!(shared_trees(&p).is_empty());
    }

    #[test]
    fn the_warning_names_the_trees() {
        assert_eq!(
            not_locked(&[PathBuf::from("/p/node_modules")]),
            "/p/node_modules stays writable here: user namespaces don't work, so a package \
             store hardlinked there could be changed (cant check says why)"
        );
        assert!(
            not_locked(&[PathBuf::from("/p/node_modules"), PathBuf::from("/p/.venv")])
                .starts_with("/p/node_modules, /p/.venv stay writable")
        );
    }
}