Cotton code
126 lines · 5.8 KB · RustRaw
//! The declared PATH, held to its rules in a synthetic home: no real login//! file, no real agent and no real data folder is read.use super::*;use std::collections::BTreeMap;use std::os::unix::fs::PermissionsExt as _;use crate::login_env::{build, LoginEnv};/// An executable script called `name` in `dir`.fn stub(dir: &Path, name: &str, prints: &str) -> PathBuf {    std::fs::create_dir_all(dir).expect("the directory is made");    let path = dir.join(name);    std::fs::write(&path, format!("#!/bin/sh\necho {prints}\n")).expect("the stub is written");    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))        .expect("the stub is executable");    path}/// A home with nvm, its default naming a major version, and two installs.fn synthetic_home() -> (tempfile::TempDir, String) {    let dir = tempfile::tempdir().expect("a temporary home");    // Seatbelt matches real paths; a temp dir under /var is /private/var.    let home = dir.path().canonicalize().expect("the home resolves");    let nvm = home.join(".nvm");    std::fs::create_dir_all(nvm.join("alias")).expect("nvm's alias folder");    std::fs::write(nvm.join("alias").join("default"), "22\n").expect("nvm's default");    for version in ["v20.19.0", "v22.1.0", "v22.23.2"] {        std::fs::create_dir_all(nvm.join("versions/node").join(version).join("bin"))            .expect("an installed node");    }    (dir, home.display().to_string())}/// What the person's login shell printed: a PATH full of directories nobody/// declared, the declared ones missing.fn login_shell_said(home: &str) -> BTreeMap<String, String> {    BTreeMap::from([        (            "PATH".to_string(),            format!("/undeclared/bin:{home}/.rbenv/shims:/usr/bin:/bin::."),        ),        ("HOME".to_string(), home.to_string()),        ("LANG".to_string(), "en_GB.UTF-8".to_string()),    ])}/// RULE: A hosted session's PATH holds every declared directory, in the declared order, and no other — not the login shell's, not this process's — because a session may rely on exactly what launch_env lists.#[test]fn the_hosted_path_is_every_declared_entry_and_nothing_undeclared() {    let (_dir, home) = synthetic_home();    let env = build(login_shell_said(&home), &home);    let declared: Vec<String> = DECLARED_PATH        .iter()        .filter_map(|entry| entry.resolve(&home))        .map(|dir| dir.display().to_string())        .collect();    assert_eq!(declared.len(), DECLARED_PATH.len(), "nvm has a default here, so every entry resolves");    let on_path: Vec<&str> = env.path().split(':').collect();    assert_eq!(on_path, declared, "the PATH is the declaration, in order");    for undeclared in ["/undeclared/bin", ".", ""] {        assert!(!on_path.contains(&undeclared), "{undeclared:?} came through from the login shell");    }    assert_eq!(env.get("LANG"), Some("en_GB.UTF-8"), "the person's variables are kept");}/// RULE: A hosted session's child gets the planned environment and nothing this host process inherited, because inheritance would decide which program a session finds whenever the plan said nothing.#[tokio::test]async fn a_spawned_session_sees_only_its_planned_environment() {    // Cargo sets this for every test process; it is the stand-in for    // whatever launchd handed the host.    assert!(std::env::var_os("CARGO_MANIFEST_DIR").is_some());    let (output, mut bytes) = tokio::sync::mpsc::unbounded_channel();    let plan = crate::pty::SpawnPlan {        argv: vec!["/usr/bin/env".to_string()],        env: BTreeMap::from([("DECLARED".to_string(), "yes".to_string())]),        cwd: "/".to_string(),        cols: 80,        rows: 24,    };    let _session = crate::pty::PtySession::spawn(&plan, output).expect("env runs in a terminal");    let mut seen = Vec::new();    while let Ok(Some(chunk)) =        tokio::time::timeout(std::time::Duration::from_secs(5), bytes.recv()).await    {        seen.extend(chunk);    }    let seen = String::from_utf8_lossy(&seen);    assert!(seen.contains("DECLARED=yes"), "the plan's variable is there: {seen}");    assert!(!seen.contains("CARGO_MANIFEST_DIR"), "this process's environment leaked: {seen}");}/// RULE: argent resolves on a hosted session's PATH from nvm's default node, where `npm i -g` puts it, because a login shell never loads nvm and the argent MCP server failed to start without it.#[test]fn argent_resolves_from_nvm_s_default_node_in_a_synthetic_home() {    let (_dir, home) = synthetic_home();    let bin = Path::new(&home).join(".nvm/versions/node/v22.23.2/bin");    let argent = stub(&bin, "argent", "argent-stub");    stub(&Path::new(&home).join(".nvm/versions/node/v20.19.0/bin"), "argent", "the-wrong-one");    assert_eq!(nvm_default_bin(Path::new(&home)), Some(bin), "the newest install the default names");    let env = build(login_shell_said(&home), &home);    assert_eq!(env.program_path("argent"), argent.display().to_string());}#[test]fn nvm_without_a_default_is_no_node_toolchain_never_a_guess() {    let (_dir, home) = synthetic_home();    std::fs::remove_file(Path::new(&home).join(".nvm/alias/default")).expect("the default goes");    assert_eq!(nvm_default_bin(Path::new(&home)), None);    std::fs::write(Path::new(&home).join(".nvm/alias/default"), "18").expect("a default");    assert_eq!(nvm_default_bin(Path::new(&home)), None, "no node 18 is installed");    std::fs::write(Path::new(&home).join(".nvm/alias/default"), "lts/*").expect("a named default");    assert_eq!(        nvm_default_bin(Path::new(&home)),        Some(Path::new(&home).join(".nvm/versions/node/v22.23.2/bin")),        "a name that is no version matches every version, as nvm's `node` does"    );}#[test]fn a_login_with_no_home_gets_only_the_absolute_directories() {    for dir in path("").split(':') {        assert!(dir.starts_with('/') && !dir.starts_with("/.") , "{dir} has no home to be under");    }}