diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 27c721324e..a35a3f67cd 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -828,6 +828,8 @@ Recognition rules that hold for every ecosystem: | Hosted: a discovered patch-host reference (or a live pre-v5 redirect-ledger record) | The installed copies the build **consumes** through the hosted wiring are hash-verified when any exist: the Go replacement module, never the pristine `M@v` in the module cache; the Socket-registry cargo source dir; maven's suffixed version. Installed evidence wins: `hash_mismatch` / `not_applied` are omitted. With **nothing installed**, a discovered reference whose lock pins the artifact (or whose format's rewriter never writes a pin) attests from that pin, which is the same evidence as in-run `scan --mode hosted --vex`. A pre-v5 ledger-only record, or a reference whose required pin is missing, stays `package_not_found`. So do purls that `--ecosystems` kept out of the crawl, because "not installed" has to mean the crawler looked. The same goes for npm purls when an installed pnpm tree records its virtual store outside the project (`enableGlobalVirtualStore`, or a `virtualStoreDir` that climbs out): transitive deps there are invisible to the crawler. A pnpm `modulesDir` inside the project is crawled. A Composer purl is omitted as `composer_install_unread` instead when `composer.json`'s `config.vendor-dir` puts the install outside the project (an absolute path, `~/…`, `$VAR/…`, or one that climbs out) and an install is there (its `composer/installed.json` exists, or the directory cannot be resolved): the crawler reads no tree outside the project that only a project file names, so that install was not checked and may predate the redirect (#686). While nothing is installed there the pin still attests, and with `COMPOSER_VENDOR_DIR` set to the directory the crawler reads it and the installed bytes decide. A yarn Plug'n'Play project (`.pnp.cjs` / `.pnp.js`) has no tree to crawl: an npm purl there attests from the lock's pin only when the PnP loader itself resolves it through the patch (berry names the hosted url, yarn 1 the resolved url's `#` in its cache folder). A loader written before the lock was rewired runs the registry copy, so the purl stays omitted until `yarn install` rewrites it (#519). | `(redirected)` | | Agent: a manifest record with no live hosted/vendored wiring | The installed tree, unchanged. **Every** installed copy the crawler finds for the purl (npm nests duplicates of one `name@version`; pnpm, vlt, Bun and Deno stores add peer-variant copies and copies bundled inside other packages) must hash to the patched bytes, as `apply` patches every copy (Maven: every copy a build consumes, Gradle hash dirs included — see [Gradle builds](#gradle-builds-v50)). One unpatched copy omits the purl with that copy's tag (`not_applied` / `hash_mismatch`). | none | +**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `@socket-+` for a release routed through the registry of its patch and `@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `@` entry stays in the store, pristine. An entry that no link leads into is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. For pnpm this applies to a package version only when its copies sit in two or more entries of one store and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. For a version in two entries, every symbolic link is read below the scanned directory (or below the project that holds the store, when the scan started inside it), in every directory whatever its name; nothing above that directory is read. A link that leads nowhere (no target, a loop, a path through a file) is left out. An entry is hashed when a link outside the store's entries resolves into it, or a link inside a hashed entry does; the entries left out are those that only other left-out entries link, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (a hosted scan leaves such a pair when the patched package is a peer dependency: the dependent gets a new entry, and its old entry keeps its link to the old one). A copy in the store but in none of its entries is always hashed. Only links are read, not a path to an entry that a file spells out or `NODE_PATH` names. Every store is judged once per run, by the same links for the record check and the hosted one. Where a link may have gone unread, every entry is hashed: on Windows; when the scanned directory and the store's project are unrelated (`--global`, a `node_modules` linked from another checkout), or the store's project lies above the git checkout the run started in; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the store's project (also a `modulesDir` of more than one level); when a directory or a link cannot be read, or the directory holds more than 500,000 directories and links; when a link resolves to a directory outside the directory that was read, to a file outside it that has a `node_modules` in a directory above it (the home directory and above are not looked at), to the store itself, or into the store by a path that names none of its entries (another spelling of the store's path or of an entry's name); and when no link resolves into any entry (`docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list). `rollback` and `remove` restore unlinked entries too. + **Liveness gates.** These gates run before hashing, and `--no-verify` / `--vex-no-verify` skips only the hashing, never the gates: * A **vendor ledger entry** attests only while some lockfile or config still wires its artifact. Otherwise it is omitted as `vendor_unwired`. The exception is a hosted takeover: the same package with a live redirect record falls through to that hosted claim. diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 32539a0da2..73fd8173bb 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -36,7 +36,7 @@ use crate::commands::vex_sources::{ self, Plan, RunApiClient, Sources, GO_WORKSPACE_OVERRIDE, RECORD_MISMATCH, RECORD_UNAVAILABLE, REDIRECT_UNWIRED, VENDOR_UNWIRED, WIRING_CONFLICT, }; -use crate::ecosystem_dispatch::{find_manifest_package_copies_reusing, JvmScope}; +use crate::ecosystem_dispatch::{find_manifest_package_copies_judged, JvmScope}; use crate::json_envelope::{Command, Envelope, EnvelopeError, PatchAction, PatchEvent, RunWarning}; use crate::ui::plural; @@ -1006,8 +1006,8 @@ async fn generate_vex( if quiet { verifying.set("Finding installed packages"); } - let copies = - find_manifest_package_copies_reusing(&purls, common, quiet, params.npm_prior.as_ref()) + let (copies, mut live_stores) = + find_manifest_package_copies_judged(&purls, common, quiet, params.npm_prior.as_ref()) .await; verifying.set("Verifying installed patches"); // The record check: every copy of each purl; for Maven, every copy @@ -1026,6 +1026,7 @@ async fn generate_vex( &plan.hosted, &copies, params.npm_prior.as_ref(), + &mut live_stores, ) .await; let vendor = VendorContext { diff --git a/crates/socket-patch-cli/src/commands/vex_consumed.rs b/crates/socket-patch-cli/src/commands/vex_consumed.rs index eb184a5d61..de1cb3c302 100644 --- a/crates/socket-patch-cli/src/commands/vex_consumed.rs +++ b/crates/socket-patch-cli/src/commands/vex_consumed.rs @@ -42,6 +42,7 @@ use std::path::{Path, PathBuf}; #[cfg(not(test))] use socket_patch_core::crawlers::npm_crawler::with_store_peer_variant_copies; +use socket_patch_core::crawlers::npm_crawler::LiveStoreEntries; use socket_patch_core::crawlers::{ CargoCrawler, CrawlerOptions, Ecosystem, GoCrawler, MavenCrawler, }; @@ -65,7 +66,9 @@ use crate::ecosystem_dispatch::{ /// the installed-tree lookup. `installed` is that lookup's every-copy /// result ([`crate::ecosystem_dispatch::find_manifest_package_copies_reusing`] over /// the record view, which holds every hosted purl), including npm store -/// variants. The shared-location ecosystems read it instead of crawling +/// variants, and `live` the judgement of the npm stores' live entries that +/// lookup made, which this one shares: it drops no copy that lookup kept. +/// The shared-location ecosystems read it instead of crawling /// the tree a second time. `prior` /// (embedded hosted `scan --vex` only) is scan's npm crawl of the same /// tree: the identity fallback takes its packages instead of crawling the @@ -75,6 +78,7 @@ pub(crate) async fn hosted_consumed_copies( hosted: &BTreeMap, installed: &HashMap>, prior: Option<&NpmCrawlSnapshot>, + live: &mut LiveStoreEntries, ) -> HashMap { let mut out = HashMap::new(); if hosted.is_empty() { @@ -115,10 +119,10 @@ pub(crate) async fn hosted_consumed_copies( }, ); } - // An orphaned Bun store entry is no consumed copy; the + // An orphaned Bun or pnpm store entry is no consumed copy; the // installed lookup dropped its own, this drops the ones the alias // and identity fallbacks' variant expansion added. - socket_patch_core::crawlers::npm_crawler::retain_live_store_copies( + live.retain_live_copies( out.iter_mut() .filter(|(purl, _)| npm.contains(purl)) .map(|(_, copies)| &mut copies.paths), @@ -464,7 +468,11 @@ mod tests { )]); VARIANT_INPUTS .scope(std::cell::RefCell::new(Vec::new()), async { - let mut found = hosted_consumed_copies(common, &hosted, installed, None).await; + // The judgement `vex` hands over: the installed lookup's, + // made for the scanned directory. + let mut live = LiveStoreEntries::new(Some(common.cwd.clone())); + let mut found = + hosted_consumed_copies(common, &hosted, installed, None, &mut live).await; let paths = found.remove(&purl).unwrap().paths; let calls = VARIANT_INPUTS.with(|inputs| inputs.borrow().clone()); (paths, calls) diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index e5c28f452e..65afd35a72 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -9,7 +9,7 @@ use std::path::{Path, PathBuf}; use crate::args::GlobalArgs; use socket_patch_core::crawlers::npm_crawler::{ - build_npm_purl, parse_package_name, retain_live_store_copies, with_store_peer_variant_copies, + build_npm_purl, parse_package_name, with_store_peer_variant_copies, LiveStoreEntries, }; use socket_patch_core::crawlers::walk_pool; use socket_patch_core::crawlers::CargoCrawler; @@ -1338,6 +1338,21 @@ pub async fn find_manifest_package_copies_reusing( quiet: bool, prior: Option<&NpmCrawlSnapshot>, ) -> HashMap> { + find_manifest_package_copies_judged(purls, common, quiet, prior) + .await + .0 +} + +/// [`find_manifest_package_copies_reusing`], with the judgement of the npm +/// stores' live entries that its copies went through. A caller that +/// resolves more copies of the same tree (`vex`'s hosted lookup) filters +/// them by it, so the two lookups agree on every store entry. +pub(crate) async fn find_manifest_package_copies_judged( + purls: &[String], + common: &GlobalArgs, + quiet: bool, + prior: Option<&NpmCrawlSnapshot>, +) -> (HashMap>, LiveStoreEntries) { let partitioned = partition_purls(purls, common.ecosystems.as_deref()); let crawler_options = common.crawler_options(); let mut copies = dispatch_find_with_npm_links( @@ -1361,10 +1376,13 @@ pub async fn find_manifest_package_copies_reusing( with_store_peer_variant_copies(common.read_scope(), std::mem::take(paths)).await; } } - // A Bun store entry nothing links any more (Bun never prunes `.bun`) - // is no copy the install loads, so the check skips it (#599). Rollback - // and remove, which resolve without this, still restore it. - retain_live_store_copies( + // A Bun or pnpm store entry nothing links any more (Bun never prunes + // `.bun`; pnpm keeps the entry an in-place install replaced) is no + // copy the install loads, so the check skips it (#599, #2353). A pnpm + // entry is judged by every link below the scanned project. + // Rollback and remove, which resolve without this, still restore it. + let mut live = LiveStoreEntries::new((!common.is_global()).then(|| common.cwd.clone())); + live.retain_live_copies( copies .iter_mut() .filter(|(purl, _)| purl.starts_with("pkg:npm/")) @@ -1422,7 +1440,7 @@ pub async fn find_manifest_package_copies_reusing( .await; } copies.retain(|_, paths| !paths.is_empty()); - copies + (copies, live) } // ── JVM copies ────────────────────────────────────────────────────────── diff --git a/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs b/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs index 348299f831..e895ff6bed 100644 --- a/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs +++ b/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs @@ -513,3 +513,214 @@ fn check_remedy_keeps_global_prefix_and_heals_the_checked_tree() { assert_eq!(code, 0, "the remedy healed the checked tree: {stderr}"); assert_eq!(std::fs::read(&index).unwrap(), PATCHED); } + +/// #2353: pnpm keeps a store entry it no longer uses (pnpm 7 to 11 for up +/// to 7 days, pnpm 12 until `pnpm prune`), with nothing linking to it. Such +/// an entry is no installed copy for `--check`, as for `vex`: the copy the +/// importer links decides. A patched linked copy is in sync beside an +/// unlinked entry of another peer set that holds the original bytes, and +/// an unpatched linked copy is drift beside a patched unlinked one. +/// +/// Every link below the project counts, also one in a `node_modules` +/// that no lockfile names and that leads to the entry through another +/// package: a directory that left the workspace still loads what its +/// links lead to, so the original bytes there are drift until that +/// `node_modules` is gone. +#[cfg(unix)] +#[test] +fn check_judges_the_pnpm_store_entry_the_install_links() { + for (linked_bytes, unlinked_bytes, in_sync) in + [(PATCHED, ORIGINAL, true), (ORIGINAL, PATCHED, false)] + { + let tmp = project(None); + let nm = tmp.path().join("node_modules"); + let store = nm.join(".pnpm"); + let linked = "check-target@1.0.0_peer@2.0.0"; + for (entry, bytes) in [ + (linked, linked_bytes), + ("check-target@1.0.0_peer@1.0.0", unlinked_bytes), + ] { + let pkg = store.join(entry).join("node_modules/check-target"); + std::fs::create_dir_all(&pkg).unwrap(); + std::fs::write( + pkg.join("package.json"), + r#"{ "name": "check-target", "version": "1.0.0" }"#, + ) + .unwrap(); + std::fs::write(pkg.join("index.js"), bytes).unwrap(); + } + // What the install records beside the packages (pnpm 12.25.1). + std::fs::write( + nm.join(".modules.yaml"), + r#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm"}"#, + ) + .unwrap(); + std::fs::write( + store.join("lock.yaml"), + "lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies:\n \ + check-target:\n specifier: 1.0.0\n version: 1.0.0(peer@2.0.0)\n\n\ + packages:\n\n check-target@1.0.0:\n resolution: {integrity: sha512-x}\n\n\ + snapshots:\n\n check-target@1.0.0(peer@2.0.0): {}\n", + ) + .unwrap(); + std::os::unix::fs::symlink( + format!(".pnpm/{linked}/node_modules/check-target"), + nm.join("check-target"), + ) + .unwrap(); + + let check = |in_sync: bool, what: &str| { + let (code, stdout, stderr) = run_check(tmp.path(), &["--json"]); + let env = parse_json_envelope(stdout.trim()); + if in_sync { + assert_eq!(code, 0, "{what}: {env}\n{stderr}"); + } else { + assert_eq!(code, 1, "{what}: {env}\n{stderr}"); + assert!( + events(&env).iter().any(|e| e["action"] == "failed" + && e["purl"] == PURL + && e["errorCode"] == "not_applied"), + "{what}: {env}" + ); + } + }; + check(in_sync, "the copy the importer links decides"); + if !in_sync { + continue; + } + + // `tools/x` is no importer of the lockfile, and its `dep` reaches + // the entry that holds the original bytes. + let dep = store.join("dep@1.0.0/node_modules"); + std::fs::create_dir_all(dep.join("dep")).unwrap(); + std::fs::write( + dep.join("dep/package.json"), + r#"{ "name": "dep", "version": "1.0.0" }"#, + ) + .unwrap(); + std::os::unix::fs::symlink( + "../../check-target@1.0.0_peer@1.0.0/node_modules/check-target", + dep.join("check-target"), + ) + .unwrap(); + let stray = tmp.path().join("tools/x/node_modules"); + std::fs::create_dir_all(&stray).unwrap(); + std::os::unix::fs::symlink( + "../../../node_modules/.pnpm/dep@1.0.0/node_modules/dep", + stray.join("dep"), + ) + .unwrap(); + check(false, "tools/x loads the original copy through dep"); + std::fs::remove_dir_all(&stray).unwrap(); + check(true, "nothing reaches the original copy any more"); + } +} + +/// #2353: a run from inside a workspace member reads the links of the +/// whole project that holds the store, not of the member alone. The +/// member's manifest patches `check-target`, and the member links the +/// patched entry; the entry of another peer set holds the original bytes +/// with nothing linking to it, so the member is in sync. A link to that +/// entry from `vendor/` at the workspace root, outside the member, is a +/// way to load it, and is drift until it is gone. +#[cfg(unix)] +#[test] +fn check_from_a_workspace_member_reads_the_links_of_the_whole_project() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_root_package_json(root); + let member = root.join("packages/a"); + std::fs::create_dir_all(&member).unwrap(); + std::fs::write( + member.join("package.json"), + r#"{ "name": "a", "version": "1.0.0", "dependencies": { "check-target": "1.0.0" } }"#, + ) + .unwrap(); + write_manifest( + &member, + json!({ PURL: patch_record( + "28282828-2828-4282-8282-282828282828", + one_file("index.js", ORIGINAL, PATCHED), + )}), + ); + let nm = root.join("node_modules"); + let store = nm.join(".pnpm"); + let (linked, unlinked) = ( + "check-target@1.0.0_peer@2.0.0", + "check-target@1.0.0_peer@1.0.0", + ); + for (entry, bytes) in [(linked, PATCHED), (unlinked, ORIGINAL)] { + let pkg = store.join(entry).join("node_modules/check-target"); + std::fs::create_dir_all(&pkg).unwrap(); + std::fs::write( + pkg.join("package.json"), + r#"{ "name": "check-target", "version": "1.0.0" }"#, + ) + .unwrap(); + std::fs::write(pkg.join("index.js"), bytes).unwrap(); + } + // What the install records beside the packages (pnpm 12.25.1). + std::fs::write( + nm.join(".modules.yaml"), + r#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm"}"#, + ) + .unwrap(); + std::fs::write( + store.join("lock.yaml"), + "lockfileVersion: '9.0'\n\nimporters:\n\n .: {}\n\n packages/a:\n dependencies:\n \ + check-target:\n specifier: 1.0.0\n version: 1.0.0(peer@2.0.0)\n\n\ + packages:\n\n check-target@1.0.0:\n resolution: {integrity: sha512-x}\n\n\ + snapshots:\n\n check-target@1.0.0(peer@2.0.0): {}\n", + ) + .unwrap(); + std::fs::create_dir_all(member.join("node_modules")).unwrap(); + std::os::unix::fs::symlink( + format!("../../../node_modules/.pnpm/{linked}/node_modules/check-target"), + member.join("node_modules/check-target"), + ) + .unwrap(); + + let check = |in_sync: bool, what: &str| { + let (code, stdout, stderr) = run_check(&member, &["--json"]); + let env = parse_json_envelope(stdout.trim()); + if in_sync { + assert_eq!(code, 0, "{what}: {env}\n{stderr}"); + } else { + assert_eq!(code, 1, "{what}: {env}\n{stderr}"); + assert!( + events(&env).iter().any(|e| e["action"] == "failed" + && e["purl"] == PURL + && e["errorCode"] == "not_applied"), + "{what}: {env}" + ); + } + }; + check( + true, + "nothing links the entry that holds the original bytes", + ); + + let stray = root.join("vendor/check-target"); + std::fs::create_dir_all(stray.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink( + format!("../node_modules/.pnpm/{unlinked}/node_modules/check-target"), + &stray, + ) + .unwrap(); + check( + false, + "vendor/ at the workspace root loads the original copy", + ); + std::fs::remove_file(&stray).unwrap(); + check(true, "the link is gone"); + + // The member's own link decides as before. + std::fs::write( + store + .join(linked) + .join("node_modules/check-target/index.js"), + ORIGINAL, + ) + .unwrap(); + check(false, "the copy the member links holds the original bytes"); +} diff --git a/crates/socket-patch-cli/tests/common/mod.rs b/crates/socket-patch-cli/tests/common/mod.rs index b561772c2d..9bd2974d34 100644 --- a/crates/socket-patch-cli/tests/common/mod.rs +++ b/crates/socket-patch-cli/tests/common/mod.rs @@ -57,6 +57,10 @@ pub mod fs_tree; /// The mock public proxy the hermetic `scan` suites answer with. pub mod scan_proxy; +/// An independent reading of the links into a pnpm virtual store, for the +/// real-pnpm suites to hold `vex` against. +pub mod pnpm_links; + // ── Binary discovery + invocation ───────────────────────────────────── /// Quick check whether `cmd` is on PATH. Used to soft-skip diff --git a/crates/socket-patch-cli/tests/common/pnpm_links.rs b/crates/socket-patch-cli/tests/common/pnpm_links.rs new file mode 100644 index 0000000000..3c4b6c6e80 --- /dev/null +++ b/crates/socket-patch-cli/tests/common/pnpm_links.rs @@ -0,0 +1,142 @@ +//! An independent reading of which entries of a pnpm virtual store an +//! install can load (#2353), for the real-pnpm suites to hold `vex` +//! against. It shares no code with the crates under test: its own walk of +//! the tree and its own reading of every link. Reached as +//! `common::pnpm_links`, or on its own with +//! `#[path = "common/pnpm_links.rs"] mod pnpm_links;`. + +#![allow(dead_code)] + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; + +/// The entry of `store` that the real path `path` lies in: the name of +/// the store's child directory that holds it, unless that child is hidden +/// or the hoist directory `node_modules`. +fn entry_of(store: &Path, path: &Path) -> Option { + let name = path.strip_prefix(store).ok()?.components().next()?; + let name = name.as_os_str().to_str()?; + let is_entry = !name.starts_with('.') + && name != "node_modules" + && std::fs::symlink_metadata(store.join(name)).is_ok_and(|meta| meta.is_dir()); + is_entry.then(|| name.to_string()) +} + +/// Every symbolic link below `tree` with the real path it resolves to, +/// found by listing every real directory, whatever its name. A link whose +/// target is not there is left out. +fn links_below(tree: &Path) -> Vec<(PathBuf, PathBuf)> { + let mut links = Vec::new(); + let mut dirs = vec![tree.to_path_buf()]; + while let Some(dir) = dirs.pop() { + for child in std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{dir:?}: {e}")) { + let child = child.unwrap(); + let kind = child.file_type().unwrap(); + if kind.is_dir() { + dirs.push(child.path()); + } else if kind.is_symlink() { + if let Ok(target) = std::fs::canonicalize(child.path()) { + links.push((child.path(), target)); + } + } + } + } + links +} + +/// The entries of the virtual store `store` that a path which starts +/// below `tree` and outside the store's entries leads into: each entry +/// that a link outside the entries resolves into, each entry that a link +/// inside one of those resolves into, and so on. +pub fn reachable_store_entries(tree: &Path, store: &Path) -> BTreeSet { + let tree = std::fs::canonicalize(tree).unwrap(); + let store = std::fs::canonicalize(store).unwrap(); + let links = links_below(&tree); + let mut reachable = BTreeSet::new(); + loop { + let before = reachable.len(); + for (link, target) in &links { + let Some(to) = entry_of(&store, target) else { + continue; + }; + let from_reachable = + entry_of(&store, link).is_none_or(|from| reachable.contains(&from)); + if from_reachable { + reachable.insert(to); + } + } + if reachable.len() == before { + return reachable; + } + } +} + +/// The regular files below `tree` that spell out the directory of one of +/// the entries `entries` of the virtual store `store` (`/`), read +/// in every real directory but `.git` and those entries themselves. pnpm +/// writes such a path into the launcher of a package's command +/// (`node_modules/.bin`), where no link shows it. +pub fn files_naming_store_entries( + tree: &Path, + store: &Path, + entries: &BTreeSet, +) -> Vec { + let tree = std::fs::canonicalize(tree).unwrap(); + let store = std::fs::canonicalize(store).unwrap(); + let needles: Vec> = entries + .iter() + .map(|entry| format!("{entry}/").into_bytes()) + .collect(); + let mut naming = Vec::new(); + let mut dirs = vec![tree.clone()]; + while let Some(dir) = dirs.pop() { + for child in std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{dir:?}: {e}")) { + let child = child.unwrap(); + let kind = child.file_type().unwrap(); + let path = child.path(); + if kind.is_dir() { + let skipped = path == tree.join(".git") + || entries.iter().any(|entry| path == store.join(entry)); + if !skipped { + dirs.push(path); + } + } else if kind.is_file() { + let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{path:?}: {e}")); + let names = |needle: &Vec| { + bytes + .windows(needle.len()) + .any(|window| window == needle.as_slice()) + }; + if needles.iter().any(names) { + naming.push(path); + } + } + } + } + naming.sort(); + naming +} + +/// The entries of the virtual store `store` that hold the package `name` +/// as a real directory whose `file` satisfies `holds`. +pub fn store_entries_holding( + store: &Path, + name: &str, + file: &str, + holds: impl Fn(&[u8]) -> bool, +) -> BTreeSet { + let store = std::fs::canonicalize(store).unwrap(); + let mut entries = BTreeSet::new(); + for child in std::fs::read_dir(&store).unwrap() { + let child = child.unwrap(); + let Some(entry) = entry_of(&store, &child.path()) else { + continue; + }; + let package = child.path().join("node_modules").join(name); + let real = std::fs::symlink_metadata(&package).is_ok_and(|meta| meta.is_dir()); + if real && std::fs::read(package.join(file)).is_ok_and(|bytes| holds(&bytes)) { + entries.insert(entry); + } + } + entries +} diff --git a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs index 5e1e14ab98..de10c2e2db 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs @@ -91,6 +91,8 @@ mod fs_tree; mod cache_env; #[path = "common/hermetic.rs"] mod hermetic; +#[path = "common/pnpm_links.rs"] +mod pnpm_links; #[path = "vex_e2e_common/mod.rs"] mod vex_e2e_common; use vex_e2e_common::{ @@ -1249,11 +1251,13 @@ struct RoutePackage { /// The packages the default registry of the registry-route legs serves: /// `peer-user` has a peer dependency and a dependency of its own (the /// shape a bare registry declaration loses on `pnpm add`), `leaf` is -/// reached only through other packages, `extra` is there to be added. +/// reached only through other packages and ships a command (pnpm writes +/// the path of its store entry into the command's launchers), `extra` is +/// there to be added. fn route_packages() -> Vec { let package = |name, fields| RoutePackage { name, fields }; vec![ - package("leaf", serde_json::json!({})), + package("leaf", serde_json::json!({"bin": {"leaf": "index.js"}})), package( "mid", serde_json::json!({"dependencies": {"leaf": "^1.0.0"}}), @@ -1885,42 +1889,146 @@ async fn registry_route_survives_resolution_and_cleans_up(pm: &str, tag: &str) { patch.name ); } - let (code, stdout, stderr) = run_socket( - &fresh, - &[ - "vex", - "--product", - "pkg:npm/app@1.0.0", - "--api-url", - &server.uri(), - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - &server.uri(), - ], - ); - assert_eq!(code, 0, "{tag}: verified VEX failed: {stdout}\n{stderr}"); - let vex: serde_json::Value = serde_json::from_str(&stdout).unwrap(); - let attested: Vec<(&str, &str)> = vex["statements"] - .as_array() - .into_iter() - .flatten() - .filter_map(|statement| { - Some(( - statement["vulnerability"]["name"].as_str()?, - statement["status"].as_str()?, - )) - }) - .collect(); + // The advisories `vex` attests in `dir`, each with its status. + let vex_statements = |dir: &Path, when: &str| -> Vec<(String, String)> { + let (code, stdout, stderr) = run_socket( + dir, + &[ + "vex", + "--product", + "pkg:npm/app@1.0.0", + "--api-url", + &server.uri(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + &server.uri(), + ], + ); + assert_eq!( + code, 0, + "{tag} {when}: verified VEX failed: {stdout}\n{stderr}" + ); + let vex: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + vex["statements"] + .as_array() + .into_iter() + .flatten() + .filter_map(|statement| { + Some(( + statement["vulnerability"]["name"].as_str()?.to_string(), + statement["status"].as_str()?.to_string(), + )) + }) + .collect() + }; + let not_affected = |patch: &RoutePatch| (patch.advisory(), "not_affected".to_string()); + let attested = vex_statements(&fresh, "a fresh checkout"); for patch in &ROUTE_PATCHES { assert!( - attested.contains(&(patch.advisory().as_str(), "not_affected")), - "{tag}: {} must be attested from the routed lock: {vex}", + attested.contains(¬_affected(patch)), + "{tag}: {} must be attested from the routed lock: {attested:?}", patch.name ); } + + // ── the install the scan asks for, over an installed tree ── + // A second checkout that holds the upstream packages (a developer's + // `node_modules`, a CI job that restores it from a cache), then the + // scan's two files and a plain `pnpm install`. pnpm links the project + // to the entries of the patches' registries and keeps the upstream + // entries in the store with nothing linking to them. `vex` judges the + // copies the install links: both patches attest, and a linked copy + // put back on the upstream bytes is refused again. + // + // pnpm links directories with junctions on Windows, which vex does not + // read as links: it judges every entry there. + if !cfg!(windows) { + let warm = tmp.path().join("warm"); + std::fs::create_dir_all(&warm).unwrap(); + for file in ["package.json", ".npmrc"] { + std::fs::copy(proj.join(file), warm.join(file)).unwrap(); + } + std::fs::write(warm.join("pnpm-lock.yaml"), &lock_before).unwrap(); + let install = |flags: &[&str], what: &str| { + let flag = store("store-warm"); + let mut args = vec!["install"]; + args.extend_from_slice(flags); + args.push(&flag); + let out = route_pnpm(&cache, &warm, pm, &args); + assert!(out.status.success(), "{tag} {what}:\n{}", chatter(&out)); + }; + install(&["--frozen-lockfile"], "the upstream install"); + // Written anew, as a scan would: a copy that kept the files' + // modification times could read as unchanged to pnpm. + for file in ["pnpm-lock.yaml", "pnpm-workspace.yaml"] { + std::fs::write(warm.join(file), std::fs::read(proj.join(file)).unwrap()).unwrap(); + } + install(&[], "the in-place install"); + assert_eq!( + read(&warm.join("pnpm-lock.yaml")), + read(&lock_path), + "{tag}: the in-place install keeps the scan's lock" + ); + // Both entries of the leaf are in the store, or this leg would + // prove nothing; the project is linked to the patched ones. + let entries = warm.join("node_modules/.pnpm"); + for entry in [ + "leaf@1.0.0".to_string(), + format!("leaf@{}+1.0.0", leaf.alias()), + ] { + assert!( + entries.join(&entry).is_dir(), + "{tag}: {entry} must be in the store after the in-place install" + ); + } + for (through, name) in [("peer-user", "peer-user"), ("mid", "leaf")] { + assert!( + installed_index(&warm, through, name).starts_with(MARKER), + "{tag}: the in-place install links the patched {name}" + ); + } + let attested = vex_statements(&warm, "the in-place install"); + for patch in &ROUTE_PATCHES { + assert!( + attested.contains(¬_affected(patch)), + "{tag}: {} must be attested after the in-place install: {attested:?}", + patch.name + ); + } + // An independent reading of every link below the checkout agrees: + // no path from outside the store's entries leads into an entry + // that holds the upstream leaf. + let unpatched = pnpm_links::store_entries_holding(&entries, "leaf", "index.js", |bytes| { + !bytes.starts_with(MARKER.as_bytes()) + }); + let reachable = pnpm_links::reachable_store_entries(&warm, &entries); + assert!( + unpatched.contains("leaf@1.0.0") && unpatched.is_disjoint(&reachable), + "{tag}: {unpatched:?} hold the upstream leaf, and a link leads into one: {reachable:?}" + ); + + // The leaf the install links, back on the upstream bytes (a new + // file: pnpm's are hard links into its store). + let linked_leaf = warm + .join("node_modules/mid") + .canonicalize() + .unwrap() + .parent() + .unwrap() + .join("leaf/index.js"); + std::fs::remove_file(&linked_leaf).unwrap(); + std::fs::write(&linked_leaf, route_index("leaf", false)).unwrap(); + let attested = vex_statements(&warm, "an unpatched linked leaf"); + assert!( + !attested.iter().any(|(name, _)| *name == leaf.advisory()) + && attested.contains(¬_affected(peer_user)), + "{tag}: an unpatched copy the install links must not be attested: {attested:?}" + ); + } + for (step, args) in [ ("add", vec!["add", "extra@1.0.0"]), ("update", vec!["update"]), @@ -3491,6 +3599,441 @@ async fn pnpm11_registry_route_is_left_for_a_bazel_hub_added_later() { registry_route_is_left_for_a_bazel_hub_added_later(PNPM_TERTIARY, "pnpm11-bazel-hub").await; } +// ── the in-place install in a workspace (#2353) ───────────────────────── + +/// A workspace of the registry-route packages in `proj` that takes `leaf` +/// every way a patched package can be taken: member `a` through `mid` (so +/// pnpm hoists it), member `b` directly and as the peer dependency of the +/// local tarball `needs-leaf`, and the root through `peer-user`, itself +/// patched. `modules_dir` is the workspace's `modulesDir` setting, when it +/// has one; the root then pins pnpm in `engines`, since the scan takes the +/// pnpm that installed the project from `node_modules/.modules.yaml`, and +/// that record is written below the `modulesDir`. +#[cfg(unix)] +fn write_route_workspace(proj: &Path, registry: &MockServer, modules_dir: Option<&str>) { + let put = |path: &str, bytes: &[u8]| { + let path = proj.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + }; + let engines = match modules_dir { + Some(_) => r#","engines":{"pnpm":">=11.20.0"}"#, + None => "", + }; + put( + "package.json", + format!( + r#"{{"name":"app","version":"1.0.0","private":true,"dependencies":{{"host":"1.0.0","peer-user":"1.0.0"}}{engines}}}"# + ) + .as_bytes(), + ); + put( + "packages/a/package.json", + br#"{"name":"a","version":"1.0.0","private":true,"dependencies":{"mid":"1.0.0"}}"#, + ); + put( + "packages/b/package.json", + br#"{"name":"b","version":"1.0.0","private":true,"dependencies":{"leaf":"1.0.0","needs-leaf":"file:../../needs-leaf-1.0.0.tgz"}}"#, + ); + let needs_leaf = RoutePackage { + name: "needs-leaf", + fields: serde_json::json!({"peerDependencies": {"leaf": "*"}}), + }; + put("needs-leaf-1.0.0.tgz", &route_tgz(&needs_leaf, false)); + let modules_dir = modules_dir.map_or(String::new(), |dir| format!("modulesDir: {dir}\n")); + put( + "pnpm-workspace.yaml", + format!("packages:\n - packages/*\n{modules_dir}").as_bytes(), + ); + put( + ".npmrc", + format!("registry={}/\n", registry.uri()).as_bytes(), + ); +} + +/// What `vex` says of the project at `dir`: its exit code, the advisories +/// it attests with their status, and its stderr. +#[cfg(unix)] +fn route_vex(dir: &Path, server: &MockServer) -> (i32, Vec<(String, String)>, String) { + let (code, stdout, stderr) = run_socket( + dir, + &[ + "vex", + "--product", + "pkg:npm/app@1.0.0", + "--api-url", + &server.uri(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + &server.uri(), + ], + ); + let statements = serde_json::from_str::(&stdout) + .ok() + .and_then(|vex| vex["statements"].as_array().cloned()) + .into_iter() + .flatten() + .filter_map(|statement| { + Some(( + statement["vulnerability"]["name"].as_str()?.to_string(), + statement["status"].as_str()?.to_string(), + )) + }) + .collect(); + (code, statements, stderr) +} + +/// The workspace of [`write_route_workspace`] in `proj`, installed from +/// the default registry, scanned, and installed again over the same +/// `node_modules`, as a scan asks. `None` when the fixture install fails +/// where the toolchain is not required. +#[cfg(unix)] +fn route_workspace_installed_in_place( + tmp: &Path, + proj: &Path, + pm: &str, + tag: &str, + server: &MockServer, +) -> Option<()> { + let cache = tmp.join("pnpm-cache"); + let store = format!("--store-dir={}", tmp.join("store").display()); + let chatter = |out: &Output| { + format!( + "stdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) + }; + let install = route_pnpm(&cache, proj, pm, &["install", &store]); + if !install.status.success() { + assert!( + !pnpm_required(), + "fixture install failed:\n{}", + chatter(&install) + ); + println!("SKIP {tag}: fixture install failed:\n{}", chatter(&install)); + return None; + } + let (code, stdout, stderr) = run_hosted(HostedDriver::Scan, proj, &server.uri(), &[]); + assert_eq!( + code, 0, + "{tag}: scan failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let workspace = std::fs::read_to_string(proj.join("pnpm-workspace.yaml")).unwrap(); + for patch in &ROUTE_PATCHES { + assert!( + workspace.contains(&patch.override_line()), + "{tag}: the scan routes {}:\n{workspace}", + patch.name + ); + } + let install = route_pnpm(&cache, proj, pm, &["install", &store]); + assert!( + install.status.success(), + "{tag}: the in-place install:\n{}", + chatter(&install) + ); + Some(()) +} + +/// THE IN-PLACE INSTALL IN A WORKSPACE against a real pnpm (#2353), with +/// the patched `leaf` hoisted and also the peer dependency of a tarball +/// package. +/// +/// pnpm links every importer, the hoist directory and each dependent to +/// the entries of the patches' registries, and keeps the upstream entries +/// in the store. `needs-leaf`, which names `leaf` as a peer, gets a new +/// entry as well, and its old entry keeps its link to the upstream `leaf`: +/// the two old entries link each other and nothing else links either. +/// +/// * `vex` attests both patches. An independent reading of every link +/// below the project (`common/pnpm_links.rs`) agrees: no path that +/// starts outside the store's entries leads into an entry that holds +/// the upstream bytes. +/// * A link to the upstream `leaf` from `vendor/`, `dist/`, a hidden +/// directory or a real package's own `node_modules` is a path node can +/// load it by. The independent reading finds it, and `vex` refuses the +/// patch as `not_applied` until the link is gone. +#[cfg(unix)] +async fn registry_route_in_place_install_is_judged_by_every_link(pm: &str, tag: &str) { + if !has_corepack_pm(pm) { + println!("SKIP {tag}: `corepack {pm}` unavailable"); + return; + } + let registry = MockServer::start().await; + mount_route_registry(®istry).await; + let server = MockServer::start().await; + mount_route_patch_server(&server).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + write_route_workspace(&proj, ®istry, None); + if route_workspace_installed_in_place(tmp.path(), &proj, pm, tag, &server).is_none() { + return; + } + let [leaf, peer_user] = &ROUTE_PATCHES; + let not_affected = |patch: &RoutePatch| (patch.advisory(), "not_affected".to_string()); + let upstream = |bytes: &[u8]| !bytes.starts_with(MARKER.as_bytes()); + + // What pnpm left: both entries of each patched package, and the old + // entry of the peer-dependent tarball, still linked to the old leaf. + let store = proj.join("node_modules/.pnpm"); + let old_leaf = store.join("leaf@1.0.0/node_modules/leaf"); + for entry in [ + "leaf@1.0.0".to_string(), + format!("leaf@{}+1.0.0", leaf.alias()), + ] { + assert!( + store.join(&entry).is_dir(), + "{tag}: {entry} must be in the store after the in-place install" + ); + } + let old_dependents: Vec = std::fs::read_dir(&store) + .unwrap() + .filter_map(|child| child.unwrap().file_name().into_string().ok()) + .filter(|entry| entry.starts_with("needs-leaf@")) + .filter(|entry| { + std::fs::canonicalize(store.join(entry).join("node_modules/leaf")) + .is_ok_and(|real| real == std::fs::canonicalize(&old_leaf).unwrap()) + }) + .collect(); + assert_eq!( + old_dependents.len(), + 1, + "{tag}: the old entry of the peer-dependent package keeps its link to the old leaf" + ); + for (through, name) in [ + ("node_modules/peer-user", "peer-user"), + ("packages/b/node_modules/leaf", "leaf"), + ("packages/b/node_modules/needs-leaf/../leaf", "leaf"), + ("packages/a/node_modules/mid/../leaf", "leaf"), + ("node_modules/.pnpm/node_modules/leaf", "leaf"), + ] { + let index = std::fs::read_to_string(proj.join(through).join("index.js")) + .unwrap_or_else(|e| panic!("{tag}: {name} through {through}: {e}")); + assert!( + index.starts_with(MARKER), + "{tag}: {through} loads the patched {name}:\n{index}" + ); + } + + // The independent reading: entries hold the upstream bytes, and no + // path from outside the entries leads into one. + let unpatched = + |name: &str| pnpm_links::store_entries_holding(&store, name, "index.js", upstream); + let reachable = pnpm_links::reachable_store_entries(&proj, &store); + for patch in &ROUTE_PATCHES { + let unpatched = unpatched(patch.name); + assert!( + !unpatched.is_empty(), + "{tag}: an entry must still hold the upstream {}", + patch.name + ); + assert!( + unpatched.is_disjoint(&reachable), + "{tag}: {unpatched:?} hold the upstream {}, and a link leads into one: {reachable:?}", + patch.name + ); + } + assert!( + !reachable.contains(&old_dependents[0]), + "{tag}: nothing links the old entry of the peer-dependent package: {reachable:?}" + ); + // A launcher of `leaf`'s command spells out the path of a store entry, + // which no link shows. The install rewrote each one: they name the + // entry of the patch's registry, and no file outside the upstream + // entries names one of those. + let mut upstream_entries = unpatched("leaf"); + upstream_entries.extend(unpatched("peer-user")); + upstream_entries.insert(old_dependents[0].clone()); + let naming = pnpm_links::files_naming_store_entries(&proj, &store, &upstream_entries); + assert!( + naming.is_empty(), + "{tag}: a file names the directory of an upstream entry ({upstream_entries:?}): {naming:?}" + ); + let routed_leaf = std::collections::BTreeSet::from([format!("leaf@{}+1.0.0", leaf.alias())]); + let launchers = pnpm_links::files_naming_store_entries(&proj, &store, &routed_leaf); + assert!( + launchers.iter().any(|file| file.ends_with(".bin/leaf")), + "{tag}: a launcher of leaf's command must name the routed entry: {launchers:?}" + ); + let (code, attested, stderr) = route_vex(&proj, &server); + assert_eq!(code, 0, "{tag}: vex after the in-place install:\n{stderr}"); + for patch in &ROUTE_PATCHES { + assert!( + attested.contains(¬_affected(patch)), + "{tag}: {} must be attested after the in-place install: {attested:?}\n{stderr}", + patch.name + ); + } + + // A link to the upstream leaf, wherever it sits, is a way to load it. + let host = std::fs::canonicalize(proj.join("node_modules/host")).unwrap(); + for (from, link) in [ + ("vendor/", proj.join("vendor/leaf")), + ("dist/", proj.join("dist/leaf")), + ("a hidden directory", proj.join(".cache/tool/leaf")), + ( + "a real package's own node_modules", + host.join("node_modules/leaf"), + ), + ] { + std::fs::create_dir_all(link.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink(&old_leaf, &link).unwrap(); + assert_eq!( + std::fs::read_to_string(link.join("index.js")).unwrap(), + route_index("leaf", false), + "{tag}: a link from {from} loads the upstream leaf" + ); + let reachable = pnpm_links::reachable_store_entries(&proj, &store); + assert!( + reachable.contains("leaf@1.0.0"), + "{tag}: the independent reading must find the link from {from}: {reachable:?}" + ); + let (code, attested, stderr) = route_vex(&proj, &server); + assert_eq!(code, 0, "{tag}: vex with a link from {from}:\n{stderr}"); + assert!( + !attested.contains(¬_affected(leaf)) && attested.contains(¬_affected(peer_user)), + "{tag}: a link from {from} to the upstream leaf must refuse its patch alone: \ + {attested:?}\n{stderr}" + ); + assert!( + stderr.contains("leaf@1.0.0") && stderr.contains("not_applied"), + "{tag}: a link from {from}: the refusal says why:\n{stderr}" + ); + std::fs::remove_file(&link).unwrap(); + } + let (code, attested, stderr) = route_vex(&proj, &server); + assert_eq!(code, 0, "{tag}: vex without the links:\n{stderr}"); + assert!( + attested.contains(¬_affected(leaf)), + "{tag}: without the links leaf is attested again: {attested:?}\n{stderr}" + ); +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +#[serial_test::serial] +#[ignore = "wall-bound real-pnpm installs (~1min); runs on Linux and macOS as an e2e CI matrix leg"] +async fn pnpm12_registry_route_in_place_install_is_judged_by_every_link() { + registry_route_in_place_install_is_judged_by_every_link(PNPM_NAMED_REGISTRY, "pnpm12-in-place") + .await; +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +#[serial_test::serial] +#[ignore = "wall-bound real-pnpm installs (~1min); runs on Linux and macOS as an e2e CI matrix leg"] +async fn pnpm11_registry_route_in_place_install_is_judged_by_every_link() { + registry_route_in_place_install_is_judged_by_every_link(PNPM_TERTIARY, "pnpm11-in-place").await; +} + +/// THE IN-PLACE INSTALL UNDER A NESTED `modulesDir` against a real pnpm +/// (#2353). With `modulesDir: sub/node_modules`, pnpm 10.12 and later put +/// the virtual store in `sub/node_modules/.pnpm` and link each member's +/// dependencies in `/sub/node_modules` (measured on 10.12.1, +/// 10.34.9, 11.29.0 and 12.25.1; earlier ones keep the store in +/// `node_modules/.pnpm`). The lockfile in the store still names the +/// members by their paths from the workspace root, and none of them is a +/// directory below `sub/`, the directory that holds the store's +/// `node_modules`. `vex` cannot tell which directory the members' links +/// are below, so it keeps every entry: the upstream entries the in-place +/// install left behind refuse both patches as `not_applied`, as before +/// #2353, although nothing links them. A run from a member finds no patch +/// to attest: the scan's files are the workspace root's. +#[cfg(unix)] +async fn registry_route_in_place_install_under_a_nested_modules_dir(pm: &str, tag: &str) { + if !has_corepack_pm(pm) { + println!("SKIP {tag}: `corepack {pm}` unavailable"); + return; + } + let registry = MockServer::start().await; + mount_route_registry(®istry).await; + let server = MockServer::start().await; + mount_route_patch_server(&server).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + write_route_workspace(&proj, ®istry, Some("sub/node_modules")); + if route_workspace_installed_in_place(tmp.path(), &proj, pm, tag, &server).is_none() { + return; + } + let [leaf, _] = &ROUTE_PATCHES; + + // Where pnpm put the store and the members' links. + let store = proj.join("sub/node_modules/.pnpm"); + assert!( + store.is_dir() && !proj.join("node_modules/.pnpm").exists(), + "{tag}: the virtual store follows modulesDir" + ); + let routed = format!("leaf@{}+1.0.0", leaf.alias()); + for entry in ["leaf@1.0.0", routed.as_str()] { + assert!( + store.join(entry).is_dir(), + "{tag}: {entry} must be in the store after the in-place install" + ); + } + assert_eq!( + std::fs::canonicalize(proj.join("packages/b/sub/node_modules/leaf")).unwrap(), + std::fs::canonicalize(store.join(&routed).join("node_modules/leaf")).unwrap(), + "{tag}: a member's links sit in its own modulesDir" + ); + let current = std::fs::read_to_string(store.join("lock.yaml")).unwrap(); + assert!( + current.contains("\n packages/b:\n") && !proj.join("sub/packages").exists(), + "{tag}: the lockfile in the store names the members from the workspace root:\n{current}" + ); + // Nothing links the upstream entries here either. + let upstream = |bytes: &[u8]| !bytes.starts_with(MARKER.as_bytes()); + let unpatched = pnpm_links::store_entries_holding(&store, "leaf", "index.js", upstream); + let reachable = pnpm_links::reachable_store_entries(&proj, &store); + assert!( + unpatched.contains("leaf@1.0.0") && unpatched.is_disjoint(&reachable), + "{tag}: {unpatched:?} hold the upstream leaf, unlinked: {reachable:?}" + ); + + let (code, attested, stderr) = route_vex(&proj, &server); + assert_ne!(code, 0, "{tag}: vex from the root: {attested:?}\n{stderr}"); + assert!(attested.is_empty(), "{tag}: {attested:?}\n{stderr}"); + for patch in &ROUTE_PATCHES { + // Named as `@`, in a purl when it is the only one. + let release = format!("{}@{ROUTE_VERSION}", patch.name); + assert!( + stderr.contains(&release) && stderr.contains("not_applied"), + "{tag}: every entry is judged, so {} is refused:\n{stderr}", + patch.name + ); + } + let (code, attested, stderr) = route_vex(&proj.join("packages/b"), &server); + assert_ne!(code, 0, "{tag}: vex from a member: {attested:?}\n{stderr}"); + assert!(attested.is_empty(), "{tag}: {attested:?}\n{stderr}"); +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +#[serial_test::serial] +#[ignore = "wall-bound real-pnpm installs (~1min); runs on Linux and macOS as an e2e CI matrix leg"] +async fn pnpm12_registry_route_in_place_install_under_a_nested_modules_dir() { + registry_route_in_place_install_under_a_nested_modules_dir( + PNPM_NAMED_REGISTRY, + "pnpm12-nested-modules-dir", + ) + .await; +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +#[serial_test::serial] +#[ignore = "wall-bound real-pnpm installs (~1min); runs on Linux and macOS as an e2e CI matrix leg"] +async fn pnpm11_registry_route_in_place_install_under_a_nested_modules_dir() { + registry_route_in_place_install_under_a_nested_modules_dir( + PNPM_TERTIARY, + "pnpm11-nested-modules-dir", + ) + .await; +} + /// #1074: with pnpm's `lockfile` setting off, pnpm neither reads nor /// writes `pnpm-lock.yaml` and installs the upstream package from the /// registry, so a hosted pin in the committed lock patches nothing. Over a diff --git a/crates/socket-patch-cli/tests/e2e_vendor_pnpm_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_pnpm_build.rs index 3d7f72b66b..b3299aeb98 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_pnpm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_pnpm_build.rs @@ -586,6 +586,12 @@ async fn run_pnpm_capstone(pm: &str, driver: VendorDriver) { code, 0, "vex failed ({pm}).\nstdout:\n{stdout}\nstderr:\n{stderr}" ); + // No install has run since vendoring: the copy the project links is + // still the upstream one, and vex says so. + assert!( + stderr.contains(TREE_OUT_OF_SYNC), + "{pm}: the installed tree still holds the upstream package:\n{stderr}" + ); let vex_doc: serde_json::Value = serde_json::from_slice(&std::fs::read(&vex_path).unwrap()).unwrap(); let vex_stmts = vex_doc["statements"].as_array().unwrap(); @@ -669,6 +675,15 @@ async fn run_pnpm_capstone(pm: &str, driver: VendorDriver) { } eprintln!("VENDOR OK ({pm}, {driver:?})"); + assert_in_place_install_verifies( + tmp.path(), + &proj, + pm, + &store, + (pkg_before.as_slice(), lock_before.as_slice()), + (orig.as_slice(), patched.as_slice()), + ); + // 4. FRESH-CHECKOUT PROOF: committable files only, EMPTY store, // spike-proven `--frozen-lockfile --offline`. let fresh = tmp.path().join("fresh"); @@ -835,6 +850,200 @@ async fn run_pnpm_capstone(pm: &str, driver: VendorDriver) { eprintln!("REVERT OK ({pm})"); } +// ── the in-place install ─────────────────────────────────────────────── + +/// What `vex` says of a vendored package whose installed copy does not +/// hold the artifact's bytes (`vendored_tree_out_of_sync`). +const TREE_OUT_OF_SYNC: &str = "the installed tree does not match its vendored artifact"; + +/// The install `vendor` asks for, run over a `node_modules` that already +/// holds the upstream package (a developer's checkout, a CI job that +/// restores `node_modules` from a cache). pnpm links the project to the +/// entry of the vendored tarball and keeps the upstream entry in the +/// store with nothing linking to it. `vex` judges the copy the install +/// links: no `vendored_tree_out_of_sync` warning while that copy is +/// patched, and the warning again once it holds the upstream bytes. An +/// independent reading of every link below the checkout +/// (`common/pnpm_links.rs`) agrees that nothing leads into the upstream +/// entry, and a link to it from `vendor/` brings the warning back. +/// +/// Runs in `tmp/warm`, a second checkout installed from `before` (the +/// pre-vendor `package.json` and `pnpm-lock.yaml`) and the fixture's +/// `store`, with `proj`'s vendored files copied over it, so `proj` stays +/// as vendoring left it. `bytes` are the upstream and the patched +/// `index.js`. +fn assert_in_place_install_verifies( + tmp: &Path, + proj: &Path, + pm: &str, + store: &Path, + before: (&[u8], &[u8]), + bytes: (&[u8], &[u8]), +) { + // pnpm links directories with junctions on Windows, which vex does not + // read as links: it judges every entry there. + if cfg!(windows) { + return; + } + let (pkg_before, lock_before) = before; + let (orig, patched) = bytes; + let warm = tmp.join("warm"); + std::fs::create_dir_all(&warm).unwrap(); + std::fs::write(warm.join("package.json"), pkg_before).unwrap(); + std::fs::write(warm.join("pnpm-lock.yaml"), lock_before).unwrap(); + let install = |flag: Option<&str>, what: &str| { + let mut args = vec![ + "install", + "--offline", + "--store-dir", + store.to_str().unwrap(), + ]; + args.extend(flag); + let out = corepack(&warm, pm, &args); + assert!( + out.status.success(), + "{what} failed ({pm}).\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); + }; + install(Some("--frozen-lockfile"), "the upstream install"); + let installed = warm.join("node_modules").join(DEP); + assert_eq!( + std::fs::read(installed.join("index.js")).unwrap(), + orig, + "{pm}: the first install holds the upstream package" + ); + + // Written anew, not copied with their modification times: pnpm 10.0 + // takes files no newer than its last install for unchanged and skips + // the install ("Already up to date"). + for file in ["package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"] { + if let Ok(bytes) = std::fs::read(proj.join(file)) { + std::fs::write(warm.join(file), bytes).unwrap(); + } + } + common::fs_tree::copy_tree(&proj.join(".socket"), &warm.join(".socket")); + // pnpm 9.0.0-9.0.4 refuse the vendored lock frozen (see the fresh + // checkout below), which is how pnpm installs where `CI` is set. + install( + absolutizes_file_overrides(pm).then_some("--no-frozen-lockfile"), + "the in-place install", + ); + + // The project links another entry now, and the upstream one is still + // in the store: without it this leg would prove nothing. + let entries = std::fs::canonicalize(warm.join("node_modules/.pnpm")).unwrap(); + let linked = std::fs::canonicalize(&installed).unwrap(); + let linked_entry = linked + .strip_prefix(&entries) + .unwrap_or_else(|_| panic!("{pm}: {linked:?} is outside the virtual store")) + .components() + .next() + .unwrap() + .as_os_str() + .to_string_lossy() + .into_owned(); + let upstream_entry = format!("{DEP}@{DEP_VERSION}"); + assert_ne!( + linked_entry, upstream_entry, + "{pm}: the in-place install links the vendored tarball's entry" + ); + let stale = entries + .join(&upstream_entry) + .join("node_modules") + .join(DEP) + .join("index.js"); + assert_eq!( + std::fs::read(&stale).ok().as_deref(), + Some(orig), + "{pm}: pnpm keeps the upstream entry it no longer links" + ); + assert_eq!( + std::fs::read(linked.join("index.js")).unwrap(), + patched, + "{pm}: the linked copy is the vendored one" + ); + + let vex_warnings = |what: &str| { + let vex_path = warm.join("out.vex.json"); + let (code, stdout, stderr) = run_socket( + &warm, + &[ + "vex", + "--cwd", + warm.to_str().unwrap(), + "--output", + vex_path.to_str().unwrap(), + "--product", + "pkg:npm/app@1.0.0", + ], + ); + assert_eq!( + code, 0, + "vex failed, {what} ({pm}).\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let doc: serde_json::Value = + serde_json::from_slice(&std::fs::read(&vex_path).unwrap()).unwrap(); + assert_eq!( + doc["statements"].as_array().map(Vec::len), + Some(1), + "{what} ({pm}): {doc}" + ); + stderr + }; + let stderr = vex_warnings("after the in-place install"); + assert!( + !stderr.contains(TREE_OUT_OF_SYNC), + "{pm}: the linked copy is patched, and nothing links the upstream entry:\n{stderr}" + ); + // An independent reading of every link below the checkout agrees: the + // upstream entry holds the upstream bytes, and no path from outside + // the store's entries leads into it. + let reachable = || common::pnpm_links::reachable_store_entries(&warm, &entries); + let unpatched = + common::pnpm_links::store_entries_holding(&entries, DEP, "index.js", |bytes| bytes == orig); + assert!( + unpatched.contains(&upstream_entry) && unpatched.is_disjoint(&reachable()), + "{pm}: {unpatched:?} hold the upstream package, and a link leads into one: {:?}", + reachable() + ); + + // A link to the upstream entry is a way to load it, in whatever + // directory it sits: the warning is back until the link is gone. + let stray = warm.join("vendor/old"); + std::fs::create_dir_all(stray.parent().unwrap()).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(stale.parent().unwrap(), &stray).unwrap(); + assert!( + reachable().contains(&upstream_entry), + "{pm}: the independent reading must find the link: {:?}", + reachable() + ); + let stderr = vex_warnings("with a link to the upstream entry"); + assert!( + stderr.contains(TREE_OUT_OF_SYNC), + "{pm}: a link in vendor/ loads the upstream entry, so it must warn:\n{stderr}" + ); + std::fs::remove_file(&stray).unwrap(); + let stderr = vex_warnings("without the link to the upstream entry"); + assert!( + !stderr.contains(TREE_OUT_OF_SYNC), + "{pm}: nothing links the upstream entry any more:\n{stderr}" + ); + + // The linked copy back on the upstream bytes (a new file: pnpm's are + // hard links into its store). + std::fs::remove_file(linked.join("index.js")).unwrap(); + std::fs::write(linked.join("index.js"), orig).unwrap(); + let stderr = vex_warnings("with an unpatched linked copy"); + assert!( + stderr.contains(TREE_OUT_OF_SYNC), + "{pm}: an unpatched copy the install links must still warn:\n{stderr}" + ); + eprintln!("IN-PLACE INSTALL OK ({pm})"); +} + // ── manifest-less VEX (lockfile discovery) ───────────────────────────── /// The vulnerability set every vendored fixture's record carries. diff --git a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs index f981d445c1..91e3082482 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs @@ -2475,6 +2475,388 @@ fn bun_hosted_ref_ignores_orphaned_registry_store_entry() { } } +/// #2353: on pnpm 11.20 and later a hosted scan routes the patched release +/// through the registry of its patch, so the in-place `pnpm install` +/// writes the entry `left-pad@socket-+1.3.0`, links the importer to it +/// and leaves the upstream `left-pad@1.3.0` entry in the store with +/// nothing linking to it (real pnpm 12.25.1 / 11.29.0 layout; pnpm 12 +/// keeps it until `pnpm prune`). Nothing can load the orphan, so it is no +/// installed copy: the patched linked copy attests, where vex refused the +/// patch as `not_applied` and the reinstall it asked for changed nothing. +/// +/// The link decides, never the entry's name or its bytes. While the copy +/// the importer links is pristine, the patch is refused, whichever entry +/// that copy is in, and a patched entry nothing links does not vouch for +/// it. +#[cfg(unix)] +#[test] +fn pnpm_hosted_ref_is_judged_by_the_store_entry_the_install_links() { + let (pristine, patched) = ( + &b"module.exports = 'pristine'\n"[..], + &b"module.exports = 'patched'\n"[..], + ); + let purl = "pkg:npm/left-pad@1.3.0"; + let url = hosted_npm_url("left-pad", "1.3.0", UUID); + let alias = format!("socket-{}", &UUID[..8]); + let registry = url.strip_suffix("left-pad-1.3.0.tgz").unwrap(); + let lock = format!( + "lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n \ + excludeLinksFromLockfile: false\n\noverrides:\n left-pad@1.3.0: {alias}:1.3.0\n\n\ + importers:\n\n .:\n dependencies:\n left-pad:\n \ + specifier: {alias}:1.3.0\n version: {alias}:1.3.0\n\npackages:\n\n \ + left-pad@{alias}:1.3.0:\n resolution: {{integrity: {SRI}, tarball: {url}}}\n\n\ + snapshots:\n\n left-pad@{alias}:1.3.0: {{}}\n" + ); + let upstream_entry = "left-pad@1.3.0"; + let routed_entry = format!("left-pad@{alias}+1.3.0"); + // (the entry the importer links, its bytes, the other entry's bytes, + // whether the patch attests) + for (linked, linked_bytes, other_bytes, attests) in [ + (routed_entry.as_str(), patched, pristine, true), + (routed_entry.as_str(), pristine, patched, false), + (upstream_entry, pristine, patched, false), + ] { + let label = format!("the importer links {linked}, attests {attests}"); + let tmp = tempfile::tempdir().unwrap(); + let cwd = &tmp.path().join("app"); + put( + cwd, + "package.json", + br#"{ "name": "app", "version": "1.0.0", "dependencies": { "left-pad": "1.3.0" } }"#, + ); + put( + cwd, + "pnpm-workspace.yaml", + format!( + "packages:\n - '.'\nnamedRegistries:\n {alias}: {registry}\noverrides:\n \ + 'left-pad@1.3.0': '{alias}:1.3.0'\n" + ) + .as_bytes(), + ); + put(cwd, "pnpm-lock.yaml", lock.as_bytes()); + // What the install records beside the packages (pnpm 12.25.1). + put( + cwd, + "node_modules/.modules.yaml", + br#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm"}"#, + ); + put(cwd, "node_modules/.pnpm/lock.yaml", lock.as_bytes()); + for entry in [upstream_entry, routed_entry.as_str()] { + let dir = format!("node_modules/.pnpm/{entry}/node_modules/left-pad"); + put( + cwd, + &format!("{dir}/package.json"), + br#"{ "name": "left-pad", "version": "1.3.0" }"#, + ); + let bytes = if entry == linked { + linked_bytes + } else { + other_bytes + }; + put(cwd, &format!("{dir}/index.js"), bytes); + } + std::os::unix::fs::symlink( + format!(".pnpm/{linked}/node_modules/left-pad"), + cwd.join("node_modules/left-pad"), + ) + .unwrap(); + let (_rt, server) = serve_patch_views(vec![( + UUID.to_string(), + one_file_view(UUID, purl, "package/index.js", pristine, patched), + )]); + + let (code, env) = vex_json(cwd, &["--proxy-url", &server.uri()]); + if attests { + assert_attested(cwd, code, &env, UUID, &label); + } else { + assert_eq!(code, Some(1), "{label}: {env}"); + assert_eq!(skipped_reason(&env, purl), "not_applied", "{label}: {env}"); + } + for entry in [upstream_entry, routed_entry.as_str()] { + assert!( + cwd.join("node_modules/.pnpm").join(entry).is_dir(), + "{label}: vex leaves both entries in the store" + ); + } + } +} + +/// The committed files of a pnpm workspace at `cwd` whose member +/// `packages/a` takes `left-pad@1.3.0` from the registry of its patch +/// (the route a hosted scan writes on pnpm 11.20 and later). +#[cfg(unix)] +fn write_pnpm_member_routing_left_pad(cwd: &Path) { + let url = hosted_npm_url("left-pad", "1.3.0", UUID); + let alias = format!("socket-{}", &UUID[..8]); + let registry = url.strip_suffix("left-pad-1.3.0.tgz").unwrap(); + put( + cwd, + "package.json", + br#"{ "name": "app", "version": "1.0.0", "private": true }"#, + ); + put( + cwd, + "packages/a/package.json", + br#"{ "name": "a", "version": "1.0.0", "dependencies": { "left-pad": "1.3.0" } }"#, + ); + put( + cwd, + "pnpm-workspace.yaml", + format!( + "packages:\n - packages/a\nnamedRegistries:\n {alias}: {registry}\noverrides:\n \ + 'left-pad@1.3.0': '{alias}:1.3.0'\n" + ) + .as_bytes(), + ); + put( + cwd, + "pnpm-lock.yaml", + format!( + "lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n \ + excludeLinksFromLockfile: false\n\noverrides:\n left-pad@1.3.0: {alias}:1.3.0\n\n\ + importers:\n\n .: {{}}\n\n packages/a:\n dependencies:\n left-pad:\n \ + specifier: {alias}:1.3.0\n version: {alias}:1.3.0\n\npackages:\n\n \ + left-pad@{alias}:1.3.0:\n resolution: {{integrity: {SRI}, tarball: {url}}}\n\n\ + snapshots:\n\n left-pad@{alias}:1.3.0: {{}}\n" + ) + .as_bytes(), + ); +} + +/// What a pnpm install (12.25.1) records in `nm` beside the packages: the +/// install record, and `lock` as the lockfile in the store. +#[cfg(unix)] +fn write_pnpm_install_record(nm: &Path, lock: &[u8]) { + put( + nm, + ".modules.yaml", + br#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm"}"#, + ); + put(nm, ".pnpm/lock.yaml", lock); +} + +/// `name@version`, its `index.js` holding `index`, in the entry `entry` of +/// the store under `nm`. +#[cfg(unix)] +fn put_pnpm_entry(nm: &Path, entry: &str, name: &str, version: &str, index: &[u8]) { + let dir = format!(".pnpm/{entry}/node_modules/{name}"); + put( + nm, + &format!("{dir}/package.json"), + format!(r#"{{ "name": "{name}", "version": "{version}" }}"#).as_bytes(), + ); + put(nm, &format!("{dir}/index.js"), index); +} + +/// A link at `at` to `target`, as pnpm writes its package links. +#[cfg(unix)] +fn pnpm_link(target: &str, at: &Path) { + std::fs::create_dir_all(at.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink(target, at).unwrap(); +} + +/// #2353: a `node_modules` that no lockfile names still loads what it +/// links. Member `b` (on `dep@1.0.0`, which depends on `left-pad`) left +/// the workspace, and member `a`'s `left-pad@1.3.0` was installed again +/// from the registry of its patch (real pnpm 11.27.0 layout): `a` and the +/// hoist dir link the routed entry, and neither lockfile names +/// `packages/b`. But `packages/b/node_modules/dep` still links `dep@1.0.0`, +/// whose `left-pad` link still points at the upstream entry, and node run +/// from `packages/b` loads that pristine copy. The patch is refused for as +/// long as that `node_modules` is there, and attested once it is gone. +#[cfg(unix)] +#[test] +fn pnpm_hosted_ref_is_refused_while_a_node_modules_no_lockfile_names_loads_the_upstream_copy() { + let (pristine, patched) = ( + &b"module.exports = 'pristine'\n"[..], + &b"module.exports = 'patched'\n"[..], + ); + let purl = "pkg:npm/left-pad@1.3.0"; + let tmp = tempfile::tempdir().unwrap(); + let cwd = &tmp.path().join("app"); + write_pnpm_member_routing_left_pad(cwd); + let nm = cwd.join("node_modules"); + write_pnpm_install_record(&nm, &std::fs::read(cwd.join("pnpm-lock.yaml")).unwrap()); + let routed = format!("left-pad@socket-{}+1.3.0", &UUID[..8]); + put_pnpm_entry(&nm, "left-pad@1.3.0", "left-pad", "1.3.0", pristine); + put_pnpm_entry(&nm, &routed, "left-pad", "1.3.0", patched); + put_pnpm_entry(&nm, "dep@1.0.0", "dep", "1.0.0", b"require('left-pad')\n"); + pnpm_link( + "../../left-pad@1.3.0/node_modules/left-pad", + &nm.join(".pnpm/dep@1.0.0/node_modules/left-pad"), + ); + pnpm_link( + &format!("../{routed}/node_modules/left-pad"), + &nm.join(".pnpm/node_modules/left-pad"), + ); + pnpm_link( + &format!("../../../node_modules/.pnpm/{routed}/node_modules/left-pad"), + &cwd.join("packages/a/node_modules/left-pad"), + ); + put( + cwd, + "packages/b/package.json", + br#"{ "name": "b", "version": "1.0.0", "dependencies": { "dep": "1.0.0" } }"#, + ); + pnpm_link( + "../../../node_modules/.pnpm/dep@1.0.0/node_modules/dep", + &cwd.join("packages/b/node_modules/dep"), + ); + let (_rt, server) = serve_patch_views(vec![( + UUID.to_string(), + one_file_view(UUID, purl, "package/index.js", pristine, patched), + )]); + let args = ["--proxy-url", &server.uri()]; + + let (code, env) = vex_json(cwd, &args); + assert_eq!(code, Some(1), "packages/b loads the pristine copy: {env}"); + assert_eq!(skipped_reason(&env, purl), "not_applied", "{env}"); + + std::fs::remove_dir_all(cwd.join("packages/b/node_modules")).unwrap(); + let (code, env) = vex_json(cwd, &args); + assert_attested( + cwd, + code, + &env, + UUID, + "nothing reaches the upstream entry any more", + ); +} + +/// #2353: a `node_modules` that is a link to another checkout's belongs +/// to a project elsewhere. A git worktree shares the main checkout's +/// install (`worktree/node_modules -> ../main/node_modules`), which holds +/// both `left-pad` entries after the in-place install. The worktree's +/// member `a` still links `dep@1.0.0`, whose `left-pad` link points at the +/// pristine `left-pad@1.3.0` entry; nothing in the main checkout links +/// either. The store is in neither the scanned worktree nor a directory +/// that holds it, so its entries are not judged from there: every copy is +/// hashed, and the pristine one refuses the hosted patch. From the main +/// checkout, which the worktree is no part of, nothing links the pristine +/// entry, and the patch attests. +#[cfg(unix)] +#[test] +fn pnpm_hosted_ref_is_hashed_in_a_store_reached_through_a_linked_node_modules() { + let (pristine, patched) = ( + &b"module.exports = 'pristine'\n"[..], + &b"module.exports = 'patched'\n"[..], + ); + let purl = "pkg:npm/left-pad@1.3.0"; + let tmp = tempfile::tempdir().unwrap(); + // The main checkout holds the install. + let main = &tmp.path().join("main"); + write_pnpm_member_routing_left_pad(main); + let nm = main.join("node_modules"); + write_pnpm_install_record(&nm, &std::fs::read(main.join("pnpm-lock.yaml")).unwrap()); + let routed = format!("left-pad@socket-{}+1.3.0", &UUID[..8]); + put_pnpm_entry(&nm, "left-pad@1.3.0", "left-pad", "1.3.0", pristine); + put_pnpm_entry(&nm, &routed, "left-pad", "1.3.0", patched); + put_pnpm_entry(&nm, "dep@1.0.0", "dep", "1.0.0", b"require('left-pad')\n"); + pnpm_link( + "../../left-pad@1.3.0/node_modules/left-pad", + &nm.join(".pnpm/dep@1.0.0/node_modules/left-pad"), + ); + pnpm_link( + &format!("../{routed}/node_modules/left-pad"), + &nm.join(".pnpm/node_modules/left-pad"), + ); + pnpm_link( + &format!("../../../node_modules/.pnpm/{routed}/node_modules/left-pad"), + &main.join("packages/a/node_modules/left-pad"), + ); + // The worktree: the scan's files, the main checkout's install, and + // its own member's link. + let cwd = &tmp.path().join("worktree"); + write_pnpm_member_routing_left_pad(cwd); + pnpm_link("../main/node_modules", &cwd.join("node_modules")); + pnpm_link( + "../../../node_modules/.pnpm/dep@1.0.0/node_modules/dep", + &cwd.join("packages/a/node_modules/dep"), + ); + let (_rt, server) = serve_patch_views(vec![( + UUID.to_string(), + one_file_view(UUID, purl, "package/index.js", pristine, patched), + )]); + let args = ["--proxy-url", &server.uri()]; + + let (code, env) = vex_json(cwd, &args); + assert_eq!( + code, + Some(1), + "the worktree's member loads the pristine copy: {env}" + ); + assert_eq!(skipped_reason(&env, purl), "not_applied", "{env}"); + + let (code, env) = vex_json(main, &args); + assert_attested( + main, + code, + &env, + UUID, + "nothing in the main checkout reaches the pristine entry", + ); +} + +/// #2353: with a `modulesDir` of more than one level, pnpm 10.12 and +/// later put the virtual store in `/.pnpm` and link each +/// member's dependencies in `/` (real pnpm 12.25.1 +/// layout). The lockfile in the store names the members from the +/// workspace root, and none of them is a directory below `sub/`, which +/// holds the store's `node_modules`. The store's entries are not judged +/// then: the pristine upstream entry is hashed and refuses the patch, +/// although nothing links it. The same workspace without the setting is +/// judged, and attests. +#[cfg(unix)] +#[test] +fn pnpm_hosted_ref_is_hashed_in_a_store_under_a_nested_modules_dir() { + let (pristine, patched) = ( + &b"module.exports = 'pristine'\n"[..], + &b"module.exports = 'patched'\n"[..], + ); + let purl = "pkg:npm/left-pad@1.3.0"; + let routed = format!("left-pad@socket-{}+1.3.0", &UUID[..8]); + for (modules_dir, attests) in [("node_modules", true), ("sub/node_modules", false)] { + let tmp = tempfile::tempdir().unwrap(); + let cwd = &tmp.path().join("app"); + write_pnpm_member_routing_left_pad(cwd); + if modules_dir != "node_modules" { + let workspace = cwd.join("pnpm-workspace.yaml"); + let text = std::fs::read_to_string(&workspace).unwrap(); + std::fs::write(workspace, format!("{text}modulesDir: {modules_dir}\n")).unwrap(); + } + let nm = cwd.join(modules_dir); + write_pnpm_install_record(&nm, &std::fs::read(cwd.join("pnpm-lock.yaml")).unwrap()); + put_pnpm_entry(&nm, "left-pad@1.3.0", "left-pad", "1.3.0", pristine); + put_pnpm_entry(&nm, &routed, "left-pad", "1.3.0", patched); + pnpm_link( + &format!("../{routed}/node_modules/left-pad"), + &nm.join(".pnpm/node_modules/left-pad"), + ); + // From `packages/a/` up to the workspace root. + let up = "../".repeat(2 + modules_dir.split('/').count()); + pnpm_link( + &format!("{up}{modules_dir}/.pnpm/{routed}/node_modules/left-pad"), + &cwd.join("packages/a").join(modules_dir).join("left-pad"), + ); + let (_rt, server) = serve_patch_views(vec![( + UUID.to_string(), + one_file_view(UUID, purl, "package/index.js", pristine, patched), + )]); + + let (code, env) = vex_json(cwd, &["--proxy-url", &server.uri()]); + if attests { + assert_attested(cwd, code, &env, UUID, modules_dir); + } else { + assert_eq!(code, Some(1), "{modules_dir}: {env}"); + assert_eq!( + skipped_reason(&env, purl), + "not_applied", + "{modules_dir}: {env}" + ); + } + } +} + /// The patch view for `name@version` (the [`left_pad_view`] shape). fn npm_view(name: &str, version: &str, after_hash: &str) -> Value { let mut view = left_pad_view(after_hash); diff --git a/crates/socket-patch-cli/tests/e2e_vex_vendor.rs b/crates/socket-patch-cli/tests/e2e_vex_vendor.rs index 0efc064f9d..588126ef05 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_vendor.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_vendor.rs @@ -1445,6 +1445,128 @@ fn vendored_bun_orphaned_store_entry_is_not_out_of_sync() { } } +/// REGRESSION (#2353): pnpm keeps a store entry it no longer uses (pnpm +/// 7 to 11 for up to 7 days, pnpm 12 until `pnpm prune`). After the +/// in-place `pnpm install` that consumes a vendored tarball, the +/// pre-vendor `lodash@4.17.21` registry entry stays in +/// `node_modules/.pnpm`, pristine, while the importer links the tarball's +/// entry (`lodash@file+.socket+vendor+npm++lodash-4.17.21.tgz`, the +/// name real pnpm 10.34.9 and 12.25.1 give it). Nothing can load the +/// orphan, so it is no installed copy: no `vendored_tree_out_of_sync` +/// warning, which re-running the install could never clear. The control's +/// linked copy is unpatched beside a patched entry nothing links, and +/// must still warn. +#[cfg(unix)] +#[test] +fn vendored_pnpm_store_entry_nothing_links_is_not_out_of_sync() { + let purl = "pkg:npm/lodash@4.17.21"; + let uuid = "0a0a0a0a-1111-4111-8111-0a0a0a0a0a0a"; + let patched = b"patched npm bytes\n"; + let pristine = b"original unpatched bytes\n"; + for live_patched in [true, false] { + let label = format!("linked copy patched {live_patched}"); + let tmp = tempfile::tempdir().expect("create tempdir"); + let cwd = &tmp.path().join("app"); + std::fs::create_dir_all(cwd).unwrap(); + + let after_hash = compute_git_sha256_from_bytes(patched); + let rel = format!(".socket/vendor/npm/{uuid}/lodash-4.17.21.tgz"); + let sha256 = sha256_hex(&write_member_tgz( + &cwd.join(&rel), + "package/index.js", + patched, + )); + let record = make_record( + uuid, + "package/index.js", + &after_hash, + "GHSA-sync-aaaa", + &["CVE-2026-10"], + ); + let wiring = write_matrix_wiring(cwd, "npm", uuid, &rel); + let mut state = VendorState::new(); + state.entries.insert( + purl.to_string(), + detached_matrix_entry("npm", purl, uuid, &rel, sha256, record, wiring), + ); + std::fs::write( + cwd.join(".socket/vendor/state.json"), + serde_json::to_string_pretty(&state).expect("serialize vendor state"), + ) + .expect("write vendor state.json"); + + // What a pnpm install records beside the packages (pnpm 12.25.1). + let nm = cwd.join("node_modules"); + let store = nm.join(".pnpm"); + std::fs::create_dir_all(&store).unwrap(); + std::fs::write( + nm.join(".modules.yaml"), + r#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm"}"#, + ) + .unwrap(); + std::fs::write( + store.join("lock.yaml"), + format!( + "lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies:\n lodash:\n \ + specifier: file:{rel}\n version: file:{rel}\n\npackages:\n\n \ + lodash@file:{rel}:\n resolution: {{integrity: sha512-cGF0Y2hlZA==, \ + tarball: file:{rel}}}\n version: 4.17.21\n\nsnapshots:\n\n \ + lodash@file:{rel}: {{}}\n" + ), + ) + .unwrap(); + let live_entry = format!("lodash@file+.socket+vendor+npm+{uuid}+lodash-4.17.21.tgz"); + let (live_bytes, orphan_bytes) = if live_patched { + (&patched[..], &pristine[..]) + } else { + (&pristine[..], &patched[..]) + }; + for (entry, bytes) in [ + ("lodash@4.17.21", orphan_bytes), + (live_entry.as_str(), live_bytes), + ] { + let pkg = store.join(entry).join("node_modules/lodash"); + std::fs::create_dir_all(&pkg).unwrap(); + std::fs::write( + pkg.join("package.json"), + r#"{"name":"lodash","version":"4.17.21"}"#, + ) + .unwrap(); + std::fs::write(pkg.join("index.js"), bytes).unwrap(); + } + std::os::unix::fs::symlink( + format!(".pnpm/{live_entry}/node_modules/lodash"), + nm.join("lodash"), + ) + .unwrap(); + + let vex_path = cwd.join("out.vex.json"); + let out = cli() + .args([ + "vex", + "--cwd", + cwd.to_str().unwrap(), + "--json", + "--output", + vex_path.to_str().unwrap(), + "--product", + "pkg:npm/app@1.0.0", + ]) + .output() + .expect("invoke vex"); + let env: Value = serde_json::from_slice(&out.stdout).expect("envelope JSON on stdout"); + assert!(out.status.success(), "{label}: {env}"); + assert_eq!(env["status"], "success", "{label}: {env}"); + let out_of_sync = env["warnings"].as_array().is_some_and(|ws| { + ws.iter().any(|w| { + w["code"] == "vendored_tree_out_of_sync" + && w["detail"].as_str().is_some_and(|d| d.contains(purl)) + }) + }); + assert_eq!(out_of_sync, !live_patched, "{label}: {env}"); + } +} + /// REGRESSION (#325): the lock rewires the hoisted `lodash@4.17.21` to the /// vendored tarball, but a parent package also BUNDLES `lodash@4.17.21` /// (`inBundle: true`). npm unpacks that copy from the parent's tarball, so diff --git a/crates/socket-patch-cli/tests/rollback/rollback_failure_paths.rs b/crates/socket-patch-cli/tests/rollback/rollback_failure_paths.rs index 5b1cc1c405..e0b118075f 100644 --- a/crates/socket-patch-cli/tests/rollback/rollback_failure_paths.rs +++ b/crates/socket-patch-cli/tests/rollback/rollback_failure_paths.rs @@ -482,6 +482,93 @@ fn bun_orphaned_store_entry_is_still_rolled_back() { ); } +/// #2353: pnpm keeps a store entry it no longer uses (pnpm 12 until +/// `pnpm prune`). A patched `is-number@6.0.0` entry the project has since +/// moved off (an in-place `pnpm install` of 7.0.0 re-linked the importer +/// to the new entry) is an orphan nothing loads now, but a later install +/// that resolves back to 6.0.0 re-links it as it is. Rollback must still +/// restore it, as it restores the entry an in-place install leaves behind +/// when a package changes its source: leaving an unlinked entry out is +/// for the checks of the live install (`vex`, `apply --check`) only. +#[cfg(unix)] +#[test] +fn pnpm_store_entry_nothing_links_is_still_rolled_back() { + let before: &[u8] = b"module.exports = 'original'\n"; + let after: &[u8] = b"module.exports = 'original' // PATCHED-2353\n"; + let (before_hash, after_hash) = (git_sha256(before), git_sha256(after)); + let purl = "pkg:npm/is-number@6.0.0"; + + let tmp = tempfile::tempdir().expect("tempdir"); + let root = tmp.path(); + std::fs::write( + root.join("package.json"), + r#"{ "name": "app", "version": "0.0.0", "dependencies": { "is-number": "7.0.0" } }"#, + ) + .expect("write root package.json"); + let orphan = install_npm_pkg( + root, + "node_modules/.pnpm/is-number@6.0.0/node_modules", + "is-number", + "6.0.0", + after, + ); + install_npm_pkg( + root, + "node_modules/.pnpm/is-number@7.0.0/node_modules", + "is-number", + "7.0.0", + b"module.exports = 7\n", + ); + // What the install records beside the packages (pnpm 12.25.1). + std::fs::write( + root.join("node_modules/.modules.yaml"), + r#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm"}"#, + ) + .expect("install record"); + std::fs::write( + root.join("node_modules/.pnpm/lock.yaml"), + "lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies:\n is-number:\n \ + specifier: 7.0.0\n version: 7.0.0\n\npackages:\n\n is-number@7.0.0:\n \ + resolution: {integrity: sha512-x}\n\nsnapshots:\n\n is-number@7.0.0: {}\n", + ) + .expect("current lockfile"); + std::os::unix::fs::symlink( + ".pnpm/is-number@7.0.0/node_modules/is-number", + root.join("node_modules/is-number"), + ) + .expect("importer link"); + let socket = write_socket_manifest( + root, + &[manifest_entry( + purl, + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + &before_hash, + &after_hash, + )], + ); + common::write_blob(&socket, &before_hash, before); + common::write_blob(&socket, &after_hash, after); + + let (code, stdout, stderr) = run(root, &["rollback", "--json", "--offline", "--yes"]); + assert_eq!(code, 0, "stdout=\n{stdout}\nstderr=\n{stderr}"); + let v = parse_json_envelope(&stdout); + assert_eq!( + rollback_json::not_installed(&v), + json!([]), + "the orphaned entry must be found; stdout=\n{stdout}" + ); + assert_eq!( + rollback_json::agent_rolled_back(&v), + json!([purl]), + "stdout=\n{stdout}" + ); + assert_eq!( + std::fs::read(orphan.join("index.js")).expect("read orphan index.js"), + before, + "the orphaned entry must be restored; stdout=\n{stdout}\nstderr=\n{stderr}" + ); +} + /// A ledger entry whose ecosystem has no vendor backend in this build /// fails the vendored leg: exit 1, the purl + error in `vendoredFailed` /// with `vendor_revert_failed`, and the manifest entry retained diff --git a/crates/socket-patch-core/src/crawlers/npm_crawler.rs b/crates/socket-patch-core/src/crawlers/npm_crawler.rs index 9a748c56d4..7106de993d 100644 --- a/crates/socket-patch-core/src/crawlers/npm_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/npm_crawler.rs @@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet, VecDeque}; use std::ffi::{OsStr, OsString}; use std::fs::FileType; use std::path::{Path, PathBuf}; +use std::sync::Arc; use serde::Deserialize; @@ -838,6 +839,11 @@ fn pnpm_current_lockfile_sync( /// by the entry (a registry `name@version` entry, or a `name@file+…` /// tarball entry) and confirmed by its package.json — is not in the /// current lockfile. An entry that cannot be named or read stays. +/// +/// This tells which packages the install holds, by name and version, +/// which is what the scan lists. Which of two entries holding the same +/// name and version the install loads is another question, answered by +/// [`live_pnpm_store_entries_sync`]. fn orphaned_pnpm_store_entry_sync( store_path: &Path, entry_name: &str, @@ -870,6 +876,468 @@ fn orphaned_pnpm_store_entry_sync( && !installed.contains(&name, &found_version) } +/// The `.pnpm` store entries an install can still load, by name (#2353); +/// `None` when that cannot be told, and every entry must be kept. pnpm +/// keeps an entry it no longer uses (see +/// [`orphaned_pnpm_store_entry_sync`]), and an in-place `pnpm install` +/// that takes a package from another source under the same name and +/// version (a hosted patch routed through its own registry, a vendored +/// `file:` tarball) writes a new entry, links the project to it and +/// leaves the old `@` dir behind. The current lockfile +/// still lists that name and version, so a check of each installed copy +/// (`vex`) judges an entry by the links instead, as for Bun (see +/// [`live_bun_store_entries_sync`]); rollback and remove still restore +/// the orphan. +/// +/// The links read are all the links there are, not the ones pnpm should +/// have written: every symbolic link below `tree`, whatever its directory +/// is named (see [`links_below_sync`]; `sweeps` holds the trees read so +/// far). An entry is live when a link that sits outside the store's +/// entries resolves into it, or a link inside a live entry does. So an +/// entry left out is one that only other left-out entries link, and no +/// path that starts outside them leads into it. Such chains are what a +/// hosted scan leaves: a dependent that names the patched package as a +/// peer gets a new entry of its own +/// (`_@socket-+`), and its old entry keeps +/// its link to the old one (measured on pnpm 11.29.0 and 12.25.1). +/// +/// `tree` is the outer of the directory `scanned` and the directory that +/// holds the store's `node_modules`. A link outside it is not read (one +/// in a `node_modules` above it, which pnpm does not write into this +/// store, or in another checkout), so every entry is kept wherever pnpm +/// may have written one there, or the links cannot all be read or +/// followed: +/// +/// - on Windows, where pnpm links directories with junctions; +/// - when neither of the two directories holds the other (a +/// `node_modules` that is a link to another checkout's, a global +/// install), or the directory that holds the store's `node_modules` +/// lies above the git checkout the scan runs in, which a project run +/// does not read +/// ([`upward_readable`](crate::utils::repo_root::upward_readable)); +/// - when the store is not the one `node_modules/.modules.yaml` records, +/// or the record is not of the isolated linker over a flat store (see +/// [`Layout::is_isolated`](crate::formats::pnpm::modules_yaml::Layout::is_isolated): +/// `node-linker=hoisted` and `pnp`, whose loaders name store paths +/// without a link, `shamefully-hoist`, another layout version); +/// - without the lockfile pnpm writes in the store, or when it or +/// `pnpm-lock.yaml` cannot be read or lays its importers out in a way +/// pnpm does not write; +/// - when a workspace member one of the two lockfiles names is not a +/// directory inside the directory that holds the store's +/// `node_modules`. pnpm links each member's dependencies below the +/// member, so a member outside has links the sweep does not read, and +/// members that are not found there show that this directory is not +/// the workspace's root (a `modulesDir` of more than one level puts the +/// store below it); +/// - when a directory below `tree`, the type of one of its children or +/// the target of a link cannot be read, or `tree` holds more than +/// [`LINK_SWEEP_BUDGET`] directories and links; +/// - when a link resolves to a directory outside `tree` (a `link:` +/// dependency on another checkout, a former workspace member): what +/// the `node_modules` below it link is not read. Nor is what a file +/// outside `tree` loads, so a link to one counts the same way when a +/// directory above the file holds a `node_modules` (see +/// [`node_modules_above_sync`]); +/// - when a link resolves to the store itself, into it by a path that is +/// spelled another way than the store's (macOS reaches a volume under +/// `/System/Volumes/Data` as well, and a file system that folds case +/// need not give one spelling back), or to a child of the store that +/// could be an entry and is not one of those listed, so that its entry +/// cannot be named; +/// - when no link reaches any entry (`symlink=false`). +fn live_pnpm_store_entries_sync( + store_path: &Path, + scanned: &Path, + sweeps: &mut HashMap>>>, +) -> Option> { + use crate::constants::npm_family::PNPM_LOCK; + use crate::formats::pnpm::grammar::is_pnpm_lock_text; + use crate::formats::pnpm::modules_yaml::Layout; + use crate::formats::pnpm::workspace::lock_text_member_importers_exact; + use crate::utils::fs::read_regular_to_string_sync; + use crate::utils::relpath::normalize_lexically; + use crate::utils::repo_root::{upward_readable, ReadScope}; + + if cfg!(windows) { + return None; + } + let store = std::fs::canonicalize(store_path).ok()?; + let nm = store.parent()?; + let project = nm.parent()?; + let scanned = std::fs::canonicalize(scanned).ok()?; + let tree = if project.starts_with(&scanned) { + scanned.as_path() + } else if scanned.starts_with(project) { + // The project above the scanned directory is read like any other + // file a project run looks up above it: not past the checkout. + if !upward_readable(ReadScope::Workspace, &scanned, project) { + return None; + } + project + } else { + return None; + }; + let record = read_regular_to_string_sync(&nm.join(PNPM_MODULES_YAML)).ok()?; + let layout = Layout::parse(&record).filter(Layout::is_isolated)?; + if std::fs::canonicalize(nm.join(layout.virtual_store_dir?)).ok()? != store { + return None; + } + let current = read_regular_to_string_sync(&store.join("lock.yaml")) + .ok() + .filter(|text| is_pnpm_lock_text(text))?; + let wanted = match read_regular_to_string_sync(&project.join(PNPM_LOCK)) { + Ok(wanted) => Some(wanted), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(_) => return None, + }; + for lock in [Some(¤t), wanted.as_ref()].into_iter().flatten() { + for member in lock_text_member_importers_exact(lock)? { + let member = Path::new(&member); + if member.is_absolute() { + return None; + } + // A member that climbs out of `project` does not normalize. + let member = std::fs::canonicalize(project.join(normalize_lexically(member)?)).ok()?; + if !member.starts_with(project) || !std::fs::metadata(&member).ok()?.is_dir() { + return None; + } + } + } + let entries = pnpm_store_entry_names(list_dir_sync(&store))?; + let links = sweeps + .entry(tree.to_path_buf()) + .or_insert_with(|| links_below_sync(tree).map(Arc::new)) + .clone()?; + + // A link whose target is not below `store` as the store is spelled. + // A directory outside `tree` behind it is not read. And wherever it + // leads, it may still lie in the store by another spelling of the + // store's path, so each directory above it is held against the store + // by identity, once (nothing is opened: a target may be a pipe). + let store_id = file_id(&store)?; + let mut elsewhere: HashSet<&Path> = HashSet::new(); + let home = crate::utils::repo_root::home(); + // The directories above the files that links out of `tree` lead to. + let mut above_files: HashSet<&Path> = HashSet::new(); + for link in links.iter() { + if link.target.starts_with(&store) { + // The store itself: a path through the link names any entry. + if link.target == store { + return None; + } + continue; + } + // Out of `tree`: nothing behind a directory is read, and node + // loads a file from where it really is, with the packages of the + // `node_modules` above it. + if !link.target.starts_with(tree) + && (link.target.is_dir() + || node_modules_above_sync(&link.target, home.as_deref(), &mut above_files)?) + { + return None; + } + for dir in link.target.ancestors() { + if !elsewhere.insert(dir) { + break; + } + if file_id(dir).is_none_or(|id| id == store_id) { + return None; + } + } + } + + // The entry of this store that a real path lies in. + let entry_of = |path: &Path| -> Option<&OsStr> { + match path.strip_prefix(&store).ok()?.components().next()? { + std::path::Component::Normal(name) => entries.get(name).map(OsString::as_os_str), + _ => None, + } + }; + // Whether a real path lies in a child of this store that could be an + // entry and is not one of the listed ones: a file, or an entry spelled + // another way than it is listed (not every file system that folds + // case gives the one spelling back). + let in_unlisted_child = |path: &Path| { + let child = path.strip_prefix(&store).ok(); + match child.and_then(|rest| rest.components().next()) { + Some(std::path::Component::Normal(name)) => { + is_pnpm_store_entry_name(name) && !entries.contains(name) + } + _ => false, + } + }; + let mut live: HashSet<&OsStr> = HashSet::new(); + let mut frontier: Vec<&OsStr> = Vec::new(); + // The entries each entry's own links resolve into. + let mut linked: HashMap<&OsStr, Vec<&OsStr>> = HashMap::new(); + for link in links.iter() { + let Some(target) = entry_of(&link.target) else { + if in_unlisted_child(&link.target) { + return None; + } + continue; + }; + match entry_of(&link.path) { + Some(source) if source == target => {} + Some(source) => linked.entry(source).or_default().push(target), + None => { + if live.insert(target) { + frontier.push(target); + } + } + } + } + while let Some(entry) = frontier.pop() { + for target in linked.remove(entry).into_iter().flatten() { + if live.insert(target) { + frontier.push(target); + } + } + } + (!live.is_empty()).then(|| live.into_iter().map(OsStr::to_os_string).collect()) +} + +/// Whether a link failed to resolve because it leads nowhere: its target +/// is not there, a level of its path is a file, or it loops. Nothing is +/// loaded through such a link, so it is left out; any other failure (a +/// directory that cannot be searched) leaves the answer unknown. +fn leads_nowhere(error: &std::io::Error) -> bool { + use std::io::ErrorKind; + if matches!(error.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) { + return true; + } + #[cfg(unix)] + { + error.raw_os_error() == Some(libc::ELOOP) + } + #[cfg(not(unix))] + { + false + } +} + +/// Whether a directory above the file `file` holds a `node_modules` dir, +/// which is where node looks up the packages of a file it loads from +/// there. pnpm links a workspace member's dependencies in the member's +/// `node_modules`, and a member that left the workspace keeps them. The +/// home directory and what lies above it are not looked at (git's own +/// home rule, see [`at_or_above_home`](crate::utils::repo_root::at_or_above_home)): +/// a stray `~/node_modules` says nothing of this project. `seen` holds +/// the directories already found to have none. `None` when one cannot be +/// told. +fn node_modules_above_sync<'a>( + file: &'a Path, + home: Option<&Path>, + seen: &mut HashSet<&'a Path>, +) -> Option { + for dir in file.ancestors().skip(1) { + if crate::utils::repo_root::at_or_above_home(dir, home) || !seen.insert(dir) { + break; + } + match std::fs::metadata(dir.join("node_modules")) { + Ok(meta) if meta.is_dir() => return Some(true), + Ok(_) => {} + Err(e) if leads_nowhere(&e) => {} + Err(_) => return None, + } + } + Some(false) +} + +/// The device and inode of the file at `path`, which name one file however +/// its path is spelled. Read with `stat`, so nothing is opened. `None` +/// when it cannot be read, and on a platform without the pair. +fn file_id(path: &Path) -> Option<(u64, u64)> { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let meta = std::fs::metadata(path).ok()?; + Some((meta.dev(), meta.ino())) + } + #[cfg(not(unix))] + { + let _ = path; + None + } +} + +/// Whether a child of a pnpm store named `name` can be an entry dir: not +/// the hidden metadata, and not the `node_modules` hoist dir. +fn is_pnpm_store_entry_name(name: &OsStr) -> bool { + !name.as_encoded_bytes().starts_with(b".") && name != "node_modules" +} + +/// The names of the entry dirs of a pnpm store, from its listing: every +/// real dir but the hidden metadata and the `node_modules` hoist dir. +/// `None` when the listing is cut short or the type of a child that is +/// not hidden cannot be read: an entry left out would read as one nothing +/// links. +fn pnpm_store_entry_names(listing: Listing) -> Option> { + if !listing.complete { + return None; + } + let mut entries = HashSet::new(); + for child in listing.entries { + if child.name_str.starts_with('.') { + continue; + } + if child.file_type?.is_dir() && is_pnpm_store_entry_name(&child.name) { + entries.insert(child.name); + } + } + Some(entries) +} + +/// A symbolic link [`links_below_sync`] found. +struct SweptLink { + /// Where the link is: a path below the swept tree, through real + /// directories alone. + path: PathBuf, + /// The real path it resolves to. + target: PathBuf, +} + +/// How many directories and links [`links_below_sync`] reads before it +/// gives up: a tree this large is no single project (a home directory, a +/// disk), and the caller keeps every store entry instead of waiting on +/// it. A monorepo with a store of 5,200 entries holds about 98,000 +/// directories and 20,000 links. The links are kept, so this bounds the +/// memory as well. +const LINK_SWEEP_BUDGET: usize = 500_000; + +/// [`links_below_within_sync`] under [`LINK_SWEEP_BUDGET`]. +fn links_below_sync(tree: &Path) -> Option> { + links_below_within_sync(tree, LINK_SWEEP_BUDGET) +} + +/// Every symbolic link below the real directory `tree` that resolves, +/// with the real path it resolves to. No directory is skipped by name +/// (hidden ones, `vendor`, `dist`, a package's own `node_modules`: a +/// loader can start in any of them), and a link is listed, never +/// followed: what lies behind it is either in the tree, and read there, +/// or outside it. A link that leads nowhere (see [`leads_nowhere`]) is +/// left out. +/// +/// `None` when the answer would not be complete: a directory, the type of +/// a child or the target of a link cannot be read, or the tree holds more +/// than `budget` directories (itself included) and links. Each level of +/// the tree is read in parallel. +fn links_below_within_sync(tree: &Path, mut budget: usize) -> Option> { + let mut links = Vec::new(); + let mut frontier = vec![tree.to_path_buf()]; + while !frontier.is_empty() { + budget = budget.checked_sub(frontier.len())?; + let reads = par_map(frontier, |dir| { + let mut links = Vec::new(); + let mut dirs = Vec::new(); + let children = match std::fs::read_dir(&dir) { + Ok(children) => children, + // Removed since the directory above it was listed (a + // build's temp dir): it holds no link any more. + Err(e) if e.kind() == std::io::ErrorKind::NotFound && dir != tree => { + return Some((links, dirs)); + } + Err(_) => return None, + }; + for child in children { + let child = child.ok()?; + let file_type = child.file_type().ok()?; + if file_type.is_dir() { + dirs.push(child.path()); + } else if file_type.is_symlink() { + let path = child.path(); + match std::fs::canonicalize(&path) { + Ok(target) => links.push(SweptLink { path, target }), + Err(e) if leads_nowhere(&e) => {} + Err(_) => return None, + } + } + } + Some((links, dirs)) + }); + frontier = Vec::new(); + for read in reads { + let (found, dirs) = read?; + budget = budget.checked_sub(found.len())?; + links.extend(found); + frontier.extend(dirs); + } + } + Some(links) +} + +/// How much of one copy [`package_bytes_digest_sync`] reads before it +/// gives up, in bytes and in files and links. +const SAME_BYTES_BUDGET: (u64, usize) = (64 * 1024 * 1024, 50_000); + +/// Whether the package dirs `copies` hold the same files with the same +/// bytes. Copies of one release that came from one tarball do, as the +/// peer variants of a package; a copy that an install left behind and +/// the one it wrote from another source do not. `false` as well when a +/// copy cannot be read through, so that it is never taken for the same. +fn same_package_bytes_sync<'a>(copies: impl IntoIterator) -> bool { + let mut digests = copies.into_iter().map(package_bytes_digest_sync); + let Some(Some(first)) = digests.next() else { + return false; + }; + digests.all(|digest| digest == Some(first)) +} + +/// A digest of every file and link below the package dir `package`, by +/// path and bytes, the `.bin` of the package's own `node_modules` left +/// aside: pnpm writes the launchers of the package's commands there (and +/// nothing else, on 11.29.0 and 12.25.1), and those name the entry. The +/// dependencies a package bundles sit beside it and count. `None` when a +/// directory, a file or a link cannot be read, when a child is none of +/// the three, or past [`SAME_BYTES_BUDGET`]. +fn package_bytes_digest_sync(package: &Path) -> Option<[u8; 32]> { + use sha2::{Digest, Sha256}; + + let (mut bytes_left, mut files_left) = SAME_BYTES_BUDGET; + // Every file and link, by its path from `package`. + let mut files: Vec<(PathBuf, bool)> = Vec::new(); + let mut dirs = vec![PathBuf::new()]; + while let Some(dir) = dirs.pop() { + for child in std::fs::read_dir(package.join(&dir)).ok()? { + let child = child.ok()?; + let kind = child.file_type().ok()?; + let path = dir.join(child.file_name()); + if kind.is_dir() { + if !(dir == Path::new("node_modules") && child.file_name() == ".bin") { + dirs.push(path); + } + } else if kind.is_file() || kind.is_symlink() { + files_left = files_left.checked_sub(1)?; + files.push((path, kind.is_symlink())); + } else { + return None; + } + } + } + files.sort(); + let mut hasher = Sha256::new(); + for (path, is_link) in files { + let bytes = if is_link { + std::fs::read_link(package.join(&path)) + .ok()? + .into_os_string() + .into_encoded_bytes() + } else { + let file = package.join(&path); + bytes_left = bytes_left.checked_sub(std::fs::metadata(&file).ok()?.len())?; + crate::utils::fs::read_regular_to_bytes_sync(&file).ok()? + }; + let name = path.as_os_str().as_encoded_bytes(); + hasher.update((name.len() as u64).to_le_bytes()); + hasher.update(name); + hasher.update([u8::from(is_link)]); + hasher.update((bytes.len() as u64).to_le_bytes()); + hasher.update(&bytes); + } + Some(hasher.finalize().into()) +} + /// What [`live_bun_store_entries_sync`] found, by index into the /// candidates it was given: the scan walks thousands of entries, so they /// are tracked by position instead of hashed and cloned by name (#578). @@ -1068,75 +1536,193 @@ fn expand_workspace_pattern_sync(root: &Path, pattern: &str) -> Option HashSet { - let mut stores: HashMap>> = HashMap::new(); - let mut orphans = HashSet::new(); - for path in paths { - let Ok(real) = std::fs::canonicalize(path) else { - continue; - }; - let Some((store, entry)) = bun_store_entry_of(&real).or_else(|| { - let (store, entry) = bun_store_entry_of( - &crate::utils::relpath::normalize_lexically_keeping_escapes(path), - )?; - Some((std::fs::canonicalize(store).ok()?, entry)) - }) else { - continue; - }; - let live = stores.entry(store).or_insert_with_key(|store| { - let candidates = pnpm_shaped_store_candidates_sync(store, StoreLayout::Bun); - live_bun_store_entries_sync(store, &candidates).map(|live| live.into_names(&candidates)) - }); - if live.as_ref().is_some_and(|live| !live.contains(&entry)) { - orphans.insert(path.clone()); +/// Which entries of the Bun and pnpm stores of a crawled tree the install +/// still links (#599, #2353): an entry no link leads to is no installed +/// copy (see [`live_bun_store_entries_sync`] and +/// [`live_pnpm_store_entries_sync`]; a path to an entry that a file +/// spells out is not read), so a check of the live install +/// (`vex`, `apply --check`) drops the copies in it. Never for an +/// operation that restores copies. Each store is judged once, by the +/// same links whichever copies are asked about. +/// +/// A pnpm store is judged only for a package version whose copies sit in +/// two or more of its entries and do not hold the same bytes in each (see +/// [`same_package_bytes_sync`]), which is what an in-place install that +/// changed the package's source leaves. Any other copy is kept as it is, +/// and the project is not read for it: one entry cannot hide a leftover, +/// and leaving out a copy that holds the same bytes as the others changes +/// no verdict (the peer variants of a package). +#[derive(Default)] +pub struct LiveStoreEntries { + /// The directory the crawl scanned: the links below it decide which + /// pnpm entries are live. `None` when there is none (a global + /// install), and no pnpm entry is dropped. + scanned: Option, + /// The stores judged so far, by real path: the names of their live + /// entries, or `None` where that could not be told. + stores: HashMap>>, + /// The trees whose links were read so far (see [`links_below_sync`]), + /// so that several pnpm stores below one scanned directory share one + /// read of it. + sweeps: HashMap>>>, +} + +impl LiveStoreEntries { + /// For a crawl of the project at `scanned` (the crawl's `cwd`); `None` + /// for one that scans no project directory. + pub fn new(scanned: Option) -> Self { + Self { + scanned, + ..Self::default() + } + } + + /// Drop from each list, the copies of one package version, every copy + /// that sits in an orphaned store entry. Each store is judged once, + /// however many lists and calls name it. + pub async fn retain_live_copies<'a>( + &mut self, + lists: impl IntoIterator>, + ) { + let lists: Vec<&mut Vec> = lists.into_iter().collect(); + let copies: Vec> = lists.iter().map(|list| list.to_vec()).collect(); + if copies.iter().all(Vec::is_empty) { + return; + } + let mut judged = std::mem::take(self); + let (orphans, judged) = run_walk(move || { + let orphans: Vec> = copies + .iter() + .map(|copies| judged.orphaned_copies_sync(copies)) + .collect(); + (orphans, judged) + }) + .await; + *self = judged; + for (list, orphans) in lists.into_iter().zip(orphans) { + if !orphans.is_empty() { + list.retain(|path| !orphans.contains(path)); + } + } + } + + /// Paths among `paths`, the copies of one package version, that are + /// copies inside an orphaned `.bun` or `.pnpm` store entry, judged by + /// where each canonicalizes, or, when that is out of every store (a + /// Bun global store entry's shared dir, #635), by the `.bun` entry the + /// path itself names. + fn orphaned_copies_sync(&mut self, paths: &[PathBuf]) -> HashSet { + let located: Vec<(&PathBuf, StoreLayout, PathBuf, OsString, PathBuf)> = paths + .iter() + .filter_map(|path| { + let real = std::fs::canonicalize(path).ok()?; + let (layout, store, entry) = unpruned_store_entry_of(&real).or_else(|| { + let (layout, store, entry) = unpruned_store_entry_of( + &crate::utils::relpath::normalize_lexically_keeping_escapes(path), + )?; + if layout != StoreLayout::Bun { + return None; + } + Some((layout, std::fs::canonicalize(store).ok()?, entry)) + })?; + Some((path, layout, store, entry, real)) + }) + .collect(); + // The pnpm stores that hold these copies in more than one entry + // dir, and not as the same bytes in each. + let mut entry_copies: HashMap<&Path, HashMap<&OsStr, &Path>> = HashMap::new(); + for (_, layout, store, entry, real) in &located { + if *layout == StoreLayout::Pnpm && is_pnpm_store_entry_name(entry) { + entry_copies + .entry(store.as_path()) + .or_default() + .entry(entry.as_os_str()) + .or_insert(real.as_path()); + } + } + // Nothing is read for a store that cannot be judged in any case. + let judged = !cfg!(windows) && self.scanned.is_some(); + let split: HashSet<&Path> = entry_copies + .into_iter() + .filter(|(store, copies)| { + judged + && copies.len() > 1 + && !matches!(self.stores.get(*store), Some(None)) + && !same_package_bytes_sync(copies.values().copied()) + }) + .map(|(store, _)| store) + .collect(); + // A pnpm entry is left out only beside a linked entry of the same + // version: with none linked, the version is judged as it stands. + let mut orphans = HashSet::new(); + let mut unlinked: HashMap<&Path, Vec<&PathBuf>> = HashMap::new(); + let mut linked: HashSet<&Path> = HashSet::new(); + for (path, layout, store, entry, _) in &located { + // Only an entry dir is judged: a copy that the hoist dir or a + // hidden child of the store holds is in no entry. + if *layout == StoreLayout::Pnpm + && !(split.contains(store.as_path()) && is_pnpm_store_entry_name(entry)) + { + continue; + } + let live = match self.stores.get(store) { + Some(live) => live, + None => { + let live = if *layout == StoreLayout::Pnpm { + self.scanned.as_deref().and_then(|scanned| { + live_pnpm_store_entries_sync(store, scanned, &mut self.sweeps) + }) + } else { + let candidates = pnpm_shaped_store_candidates_sync(store, StoreLayout::Bun); + live_bun_store_entries_sync(store, &candidates) + .map(|live| live.into_names(&candidates)) + }; + self.stores.entry(store.clone()).or_insert(live) + } + }; + let Some(orphaned) = live.as_ref().map(|live| !live.contains(entry)) else { + continue; + }; + if *layout != StoreLayout::Pnpm { + if orphaned { + orphans.insert((*path).clone()); + } + } else if orphaned { + unlinked.entry(store.as_path()).or_default().push(*path); + } else { + linked.insert(store.as_path()); + } } + for (store, paths) in unlinked { + if linked.contains(store) { + orphans.extend(paths.into_iter().cloned()); + } + } + orphans } - orphans } -/// The `node_modules/.bun` store a real path lies in, and the name of the -/// entry holding it. -fn bun_store_entry_of(real: &Path) -> Option<(PathBuf, OsString)> { +/// The `node_modules/.bun` or `node_modules/.pnpm` store a real path lies +/// in (the stores that keep entries nothing links any more), its layout, +/// and the name of the entry holding the path. +fn unpruned_store_entry_of(real: &Path) -> Option<(StoreLayout, PathBuf, OsString)> { let mut child: Option<&OsStr> = None; for dir in real.ancestors() { - if dir + let layout = dir .file_name() .and_then(OsStr::to_str) .and_then(pnpm_shaped_store_layout) - == Some(StoreLayout::Bun) - && dir.parent().and_then(Path::file_name) == Some(OsStr::new("node_modules")) - { - return Some((dir.to_path_buf(), child?.to_os_string())); + .filter(|layout| matches!(layout, StoreLayout::Bun | StoreLayout::Pnpm)); + if let Some(layout) = layout { + if dir.parent().and_then(Path::file_name) == Some(OsStr::new("node_modules")) { + return Some((layout, dir.to_path_buf(), child?.to_os_string())); + } } child = dir.file_name(); } None } -/// Drop from each list every copy that sits in an orphaned Bun store entry -/// (#599): one no link from the install reaches, which nothing can load. -/// For a check of the live install (`vex`), never for an operation that -/// restores copies. Each store is walked once across all the lists. -pub async fn retain_live_store_copies<'a>(lists: impl IntoIterator>) { - let lists: Vec<&mut Vec> = lists.into_iter().collect(); - let paths: Vec = lists.iter().flat_map(|list| list.iter().cloned()).collect(); - if paths.is_empty() { - return; - } - let orphans = run_walk(move || orphaned_bun_store_copies_sync(&paths)).await; - if orphans.is_empty() { - return; - } - for list in lists { - list.retain(|path| !orphans.contains(path)); - } -} - /// The quick walk's guesses: a link named for a package only one `.bun` /// entry holds points at that entry, and a `@scope` dir none of whose /// packages has a second entry links (at most) that scope's entries, so @@ -7654,7 +8240,9 @@ mod tests { pad12.clone(), odd.clone(), ]; - retain_live_store_copies([&mut copies]).await; + LiveStoreEntries::new(None) + .retain_live_copies([&mut copies]) + .await; assert_eq!(copies, vec![number6, number7, pad12, odd]); } @@ -7785,81 +8373,1648 @@ mod tests { ); } - /// #599: Bun never prunes `.bun`. After an in-place `bun install` that - /// rewires packages to hosted tarballs (or bumps a version), the old - /// `@` entries stay on disk with nothing linking to - /// them, while the importers, the `.bun/node_modules` hoist links and - /// the dependents' entries all point at the new entries (the layout - /// real Bun 1.3.14 / 1.4.2 writes). An orphan is no installed copy, so - /// the scan and the live-copy filter `vex` uses skip it. The resolver - /// and the peer-variant finder keep it: rollback must restore a patched - /// orphan, which a later install that resolves back re-links as is. - /// - /// A live entry linked only from a workspace member (an unhoisted - /// second version) stays live wherever the member sits: under a dir - /// the workspace walk skips (`vendor/`), under a hidden dir listed only - /// by `bun.lock`'s `workspaces`, or under `packages/`. - #[tokio::test] - async fn test_bun_isolated_store_orphaned_entries_are_not_live_copies() { - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); - let nm = root.join("node_modules"); - let store = nm.join(".bun"); - let hoist = store.join("node_modules"); - std::fs::write( - root.join("package.json"), - r#"{"name":"app","workspaces":["packages/*","vendor/*"]}"#, - ) - .unwrap(); - std::fs::write( - root.join("bun.lock"), - "{\n \"lockfileVersion\": 1,\n \"workspaces\": {\n \"\": {\n \ - \"name\": \"app\",\n },\n \".internal/c\": {\n \"name\": \"c\",\n \ - },\n },\n \"packages\": {\n }\n}\n", + /// The record pnpm 12 leaves in `node_modules/.modules.yaml` for an + /// install with the isolated linker. + const PNPM_ISOLATED_RECORD: &str = r#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm","virtualStoreDirMaxLength":120}"#; + + /// A pnpm lock (lockfileVersion 9.0) whose importers are the root and + /// `members`. + fn pnpm_lock_of(members: &[&str]) -> String { + let importers: String = std::iter::once(&".") + .chain(members) + .map(|importer| { + format!( + " {importer}:\n dependencies:\n dep:\n specifier: 1.0.0\n \ + version: 1.0.0\n\n" + ) + }) + .collect(); + format!( + "lockfileVersion: '9.0'\n\nimporters:\n\n{importers}packages:\n\n dep@1.0.0:\n \ + resolution: {{integrity: sha512-x}}\n\nsnapshots:\n\n dep@1.0.0: {{}}\n" ) - .unwrap(); - let member_a = root.join("packages/a/node_modules"); - let member_b = root.join("vendor/b/node_modules"); - let member_c = root.join(".internal/c/node_modules"); - for dir in [&hoist.join("@s"), &member_a, &member_b, &member_c] { - std::fs::create_dir_all(dir).unwrap(); - } + } - // Live: the hosted rewires, and three left-pad versions (1.3.0 - // hoisted, 1.2.0 and 1.0.0 each linked only from one member). - let odd = store.join("is-odd@http+++127.0.0.1+is-odd.tgz/node_modules"); - write_pkg(&odd.join("is-odd"), "is-odd", "3.0.1"); - let number = store.join("is-number@http+++127.0.0.1+is-number.tgz/node_modules/is-number"); - write_pkg(&number, "is-number", "6.0.0"); - link_dir(&number, &odd.join("is-number")); - let pad = store.join("left-pad@1.3.0/node_modules/left-pad"); - write_pkg(&pad, "left-pad", "1.3.0"); - let vendor_pad = store.join("left-pad@1.2.0/node_modules/left-pad"); - write_pkg(&vendor_pad, "left-pad", "1.2.0"); - let hidden_pad = store.join("left-pad@1.0.0/node_modules/left-pad"); - write_pkg(&hidden_pad, "left-pad", "1.0.0"); - link_dir(&odd.join("is-odd"), &nm.join("is-odd")); - link_dir(&odd.join("is-odd"), &hoist.join("is-odd")); - link_dir(&number, &hoist.join("is-number")); - link_dir(&pad, &hoist.join("left-pad")); - link_dir(&number, &member_a.join("is-number")); - link_dir(&pad, &member_a.join("left-pad")); - link_dir(&vendor_pad, &member_b.join("left-pad")); - link_dir(&hidden_pad, &member_c.join("left-pad")); - let frame = store.join("@s+frame@http+++127.0.0.1+frame.tgz/node_modules/@s/frame"); - write_pkg(&frame, "@s/frame", "7.0.0"); - link_dir(&frame, &hoist.join("@s/frame")); + /// What a pnpm install leaves below `root` besides the packages: the + /// install record and the current lockfile, naming the root and + /// `members` as importers. Returns `node_modules` and its store. + fn pnpm_install(root: &Path, members: &[&str]) -> (PathBuf, PathBuf) { + let nm = root.join("node_modules"); + let store = nm.join(".pnpm"); + std::fs::create_dir_all(&store).unwrap(); + std::fs::write(nm.join(".modules.yaml"), PNPM_ISOLATED_RECORD).unwrap(); + std::fs::write(store.join("lock.yaml"), pnpm_lock_of(members)).unwrap(); + (nm, store) + } - // Orphans: the pre-rewire registry entries (still linked to each - // other) and a churned-away version. - let stale_odd = store.join("is-odd@3.0.1/node_modules"); - write_pkg(&stale_odd.join("is-odd"), "is-odd", "3.0.1"); - let stale_number = store.join("is-number@6.0.0/node_modules/is-number"); - write_pkg(&stale_number, "is-number", "6.0.0"); - link_dir(&stale_number, &stale_odd.join("is-number")); - let stale_frame = store.join("@s+frame@7.0.0/node_modules/@s/frame"); - write_pkg(&stale_frame, "@s/frame", "7.0.0"); - let churned = store.join("left-pad@1.1.0/node_modules/left-pad"); + /// The package dir of `name@version` in the entry `entry` of `store`. + /// Its `index.js` names the entry, so two entries of one version hold + /// other bytes, as a leftover and the copy that replaced it do. + fn pnpm_entry(store: &Path, entry: &str, name: &str, version: &str) -> PathBuf { + let dir = store.join(entry).join("node_modules").join(name); + write_pkg(&dir, name, version); + std::fs::write(dir.join("index.js"), format!("// {entry}\n")).unwrap(); + dir + } + + /// A fresh temp dir, its path, and a project directory two levels + /// below it (`ws/app`), so that a test owns the directories above the + /// project. + fn pnpm_project_dir() -> (tempfile::TempDir, PathBuf, PathBuf) { + let tmp = tempfile::tempdir().unwrap(); + let base: PathBuf = tmp.path().components().collect(); + let root = base.join("ws/app"); + std::fs::create_dir_all(&root).unwrap(); + (tmp, base, root) + } + + /// A link at `link` to the absolute path `target`, in a directory made + /// for it. Returns `link`. + #[cfg(unix)] + fn abs_link(target: &Path, link: &Path) -> PathBuf { + std::fs::create_dir_all(link.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink(target, link).unwrap(); + link.to_path_buf() + } + + /// What `vex`'s live-copy filter keeps of each list of `lists` (the + /// copies of one package version each) for a crawl of the directory + /// `scanned`, and the judgement it made. + async fn judge_lists( + scanned: &Path, + lists: &[&[&PathBuf]], + ) -> (Vec>, LiveStoreEntries) { + let mut lists: Vec> = lists + .iter() + .map(|copies| copies.iter().map(|path| (*path).clone()).collect()) + .collect(); + let mut live = LiveStoreEntries::new(Some(scanned.to_path_buf())); + live.retain_live_copies(lists.iter_mut()).await; + (lists, live) + } + + /// [`judge_lists`] for the copies of one package version. + async fn live_copies(scanned: &Path, copies: &[&PathBuf]) -> Vec { + judge_lists(scanned, &[copies]).await.0.remove(0) + } + + /// The trees `live` read the links of that lie below `base`, sorted. + #[cfg(unix)] + fn swept_below(live: &LiveStoreEntries, base: &Path) -> Vec { + let base = std::fs::canonicalize(base).unwrap(); + let mut trees: Vec = live + .sweeps + .keys() + .filter(|tree| tree.starts_with(&base)) + .cloned() + .collect(); + trees.sort(); + trees + } + + /// The upstream copy a hosted scan leaves behind, below the project. + const LEFTOVER: &str = "node_modules/.pnpm/minimist@1.2.2/node_modules/minimist"; + /// The entry of the registry of the patch of `minimist@1.2.2`. + const ROUTED_ENTRY: &str = "minimist@socket-642d7f02+1.2.2"; + + /// The store a hosted scan and the in-place `pnpm install` it asks for + /// leave (real pnpm 12.25.1 and 11.29.0): the importer links the entry + /// of the patch's registry, and the upstream `minimist@1.2.2` entry + /// stays behind with nothing linking to it. Returns `node_modules`, + /// the leftover copy and the linked one. + fn pnpm_hosted_route_leftover(root: &Path) -> (PathBuf, PathBuf, PathBuf) { + let (nm, store) = pnpm_install(root, &[]); + let stale = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); + assert_eq!(stale, root.join(LEFTOVER)); + let routed = pnpm_entry(&store, ROUTED_ENTRY, "minimist", "1.2.2"); + rel_link( + &format!(".pnpm/{ROUTED_ENTRY}/node_modules/minimist"), + &nm.join("minimist"), + ); + (nm, stale, routed) + } + + /// #2353: on pnpm 11.20 and later a hosted scan routes a patched + /// release through the registry of its patch, so the in-place install + /// writes `minimist@socket-+1.2.2`, links the importer to it and + /// leaves the upstream `minimist@1.2.2` entry behind (a one-package + /// project has no hoist dir). The leftover is no installed copy for + /// `vex`, whatever it holds, and the entry the importer links stays + /// one; the resolver still finds the leftover, so rollback restores + /// it, and the scan still lists the package once. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_a_hosted_route_leaves_behind_is_not_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, stale, routed) = pnpm_hosted_route_leftover(&root); + + assert_eq!( + live_copies(&root, &[&nm.join("minimist"), &stale, &routed]).await, + vec![nm.join("minimist"), routed.clone()] + ); + assert_eq!( + live_copies(&root, &[&stale, &routed]).await, + vec![routed.clone()] + ); + + let purls = vec!["pkg:npm/minimist@1.2.2".to_string()]; + let found = NpmCrawler::new().find_by_purls(&nm, &purls).await.unwrap(); + let mut copies: Vec = found["pkg:npm/minimist@1.2.2"] + .iter() + .map(|copy| copy.path.clone()) + .collect(); + for copy in copies.clone() { + copies.extend( + find_store_peer_variant_copies( + crate::utils::repo_root::ReadScope::Workspace, + ©, + ) + .await, + ); + } + assert!(copies.contains(&stale), "{copies:?}"); + assert_eq!( + scan_paths(&root).await, + vec![("pkg:npm/minimist@1.2.2".to_string(), nm.join("minimist"))] + ); + } + + /// #2353: a vendored scan re-keys the package to its `file:` tarball on + /// every pnpm, so the in-place install links the importer to + /// `minimist@file+.socket+vendor+npm++minimist-1.2.2.tgz` and + /// leaves the upstream entry behind the same way. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_a_vendored_tarball_leaves_behind_is_not_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, store) = pnpm_install(&root, &[]); + let stale = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); + let entry = + "minimist@file+.socket+vendor+npm+642d7f02-ebc1-4ab0-99e2-07f5dd8463cb+minimist-1.2.2.tgz"; + let vendored = pnpm_entry(&store, entry, "minimist", "1.2.2"); + rel_link( + &format!(".pnpm/{entry}/node_modules/minimist"), + &nm.join("minimist"), + ); + + assert_eq!( + live_copies(&root, &[&stale, &vendored, &nm.join("minimist")]).await, + vec![vendored, nm.join("minimist")] + ); + } + + /// #2353: a linked entry is an installed copy whatever its name. Before + /// the in-place install the importer still links the upstream + /// `minimist@1.2.2` entry, so that copy is the one `vex` must judge, + /// and an entry of the patch's registry that nothing links (a later + /// rollback's leftover) is the one left out. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_the_importer_links_stays_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, store) = pnpm_install(&root, &[]); + let upstream = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); + let routed = pnpm_entry(&store, ROUTED_ENTRY, "minimist", "1.2.2"); + rel_link( + ".pnpm/minimist@1.2.2/node_modules/minimist", + &nm.join("minimist"), + ); + + assert_eq!( + live_copies(&root, &[&nm.join("minimist"), &upstream, &routed]).await, + vec![nm.join("minimist"), upstream] + ); + } + + /// The workspace real pnpm 12.25.1 leaves after a hosted scan and the + /// in-place install: the root depends on `mkdirp`, member `a` on + /// `minimist@1.2.2` and member `b` on `minimist@1.2.5` and on `a`. + /// Each routed `minimist` entry is linked from one place only: 1.2.2 + /// from member `a` (and the hoist dir), 1.2.5 from member `b` alone, + /// 0.0.8 from `mkdirp`'s entry alone. The three upstream entries are + /// left behind. Returns the root's store, and the routed and the + /// leftover copy of each version in that order. + #[cfg(unix)] + fn pnpm_workspace_route_leftovers(root: &Path) -> (PathBuf, [PathBuf; 3], [PathBuf; 3]) { + let (nm, store) = pnpm_install(root, &["packages/a", "packages/b"]); + let entry = |entry: &str, version: &str| pnpm_entry(&store, entry, "minimist", version); + let routed = [ + entry("minimist@socket-642d7f02+1.2.2", "1.2.2"), + entry("minimist@socket-a8b05a61+1.2.5", "1.2.5"), + entry("minimist@socket-8cccd65b+0.0.8", "0.0.8"), + ]; + let stale = [ + entry("minimist@1.2.2", "1.2.2"), + entry("minimist@1.2.5", "1.2.5"), + entry("minimist@0.0.8", "0.0.8"), + ]; + pnpm_entry(&store, "mkdirp@0.5.1", "mkdirp", "0.5.1"); + rel_link(".pnpm/mkdirp@0.5.1/node_modules/mkdirp", &nm.join("mkdirp")); + rel_link( + "../../minimist@socket-8cccd65b+0.0.8/node_modules/minimist", + &store.join("mkdirp@0.5.1/node_modules/minimist"), + ); + let hoist = store.join("node_modules"); + rel_link( + "../minimist@socket-642d7f02+1.2.2/node_modules/minimist", + &hoist.join("minimist"), + ); + for member in ["a", "b"] { + write_pkg(&root.join("packages").join(member), member, "1.0.0"); + rel_link(&format!("../../../packages/{member}"), &hoist.join(member)); + } + rel_link( + "../../../node_modules/.pnpm/minimist@socket-642d7f02+1.2.2/node_modules/minimist", + &root.join("packages/a/node_modules/minimist"), + ); + rel_link( + "../../../node_modules/.pnpm/minimist@socket-a8b05a61+1.2.5/node_modules/minimist", + &root.join("packages/b/node_modules/minimist"), + ); + rel_link("../../a", &root.join("packages/b/node_modules/a")); + (store, routed, stale) + } + + /// What the filter keeps of the leftover and the routed copy of each + /// version of [`pnpm_workspace_route_leftovers`], one list a version. + #[cfg(unix)] + async fn live_route_pairs( + scanned: &Path, + routed: &[PathBuf; 3], + stale: &[PathBuf; 3], + ) -> Vec> { + let pairs: Vec<[&PathBuf; 2]> = stale.iter().zip(routed).map(|(s, r)| [s, r]).collect(); + let lists: Vec<&[&PathBuf]> = pairs.iter().map(|pair| pair.as_slice()).collect(); + judge_lists(scanned, &lists).await.0 + } + + /// #2353: in a workspace an entry may be linked from one member alone, + /// or from another entry alone. Every link below the project is read, + /// so the entry only member `b` links and the one only `mkdirp`'s + /// entry links stay live, and the three upstream entries nothing links + /// are left out. It makes no difference which of the two lockfiles + /// names a member. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_only_a_workspace_member_links_is_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); + let (store, routed, stale) = pnpm_workspace_route_leftovers(&root); + let kept: Vec> = routed.iter().map(|copy| vec![copy.clone()]).collect(); + + assert_eq!(live_route_pairs(&root, &routed, &stale).await, kept); + + std::fs::write(store.join("lock.yaml"), pnpm_lock_of(&["packages/a"])).unwrap(); + std::fs::write( + root.join("pnpm-lock.yaml"), + pnpm_lock_of(&["packages/a", "packages/b"]), + ) + .unwrap(); + assert_eq!(live_route_pairs(&root, &routed, &stale).await, kept); + } + + /// #2353: a transitive dependency has no link but the one in its + /// dependent's entry. `minimist@socket-8cccd65b+0.0.8` is reached only + /// through `mkdirp@0.5.1/node_modules/minimist`, and stays live for as + /// long as that entry is. Once nothing links `mkdirp`'s entry either, + /// no copy of `minimist@0.0.8` is linked: an entry is left out only + /// beside a linked one of its version, so both are judged as before. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_only_a_live_entry_links_is_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); + let (_, routed, stale) = pnpm_workspace_route_leftovers(&root); + let [_, _, transitive] = &routed; + let [_, _, stale_transitive] = &stale; + + assert_eq!( + live_copies(&root, &[stale_transitive, transitive]).await, + vec![transitive.clone()] + ); + + std::fs::remove_file(root.join("node_modules/mkdirp")).unwrap(); + assert_eq!( + live_copies(&root, &[stale_transitive, transitive]).await, + vec![stale_transitive.clone(), transitive.clone()] + ); + } + + /// #2353: a `node_modules` that no lockfile names still loads what it + /// links. Member `b` (on `mkdirp@0.5.1`) left the workspace, and member + /// `a`'s `minimist@0.0.8` was installed again from the registry of its + /// patch (real pnpm 11.27.0): `a` and the hoist dir link the routed + /// entry, and neither lockfile names `packages/b`. Yet + /// `packages/b/node_modules/mkdirp` still links `mkdirp@0.5.1`, whose + /// `minimist` link still points at the upstream entry, and node run + /// from `packages/b` loads that copy. It stays live for as long as + /// that link is there; without it, the upstream entry is left out. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_a_former_member_reaches_is_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); + let (_, store) = pnpm_install(&root, &["packages/a"]); + std::fs::write(root.join("pnpm-lock.yaml"), pnpm_lock_of(&["packages/a"])).unwrap(); + let upstream = pnpm_entry(&store, "minimist@0.0.8", "minimist", "0.0.8"); + let routed = pnpm_entry( + &store, + "minimist@socket-8cccd65b+0.0.8", + "minimist", + "0.0.8", + ); + pnpm_entry(&store, "mkdirp@0.5.1", "mkdirp", "0.5.1"); + rel_link( + "../../minimist@0.0.8/node_modules/minimist", + &store.join("mkdirp@0.5.1/node_modules/minimist"), + ); + rel_link( + "../minimist@socket-8cccd65b+0.0.8/node_modules/minimist", + &store.join("node_modules/minimist"), + ); + for member in ["a", "b"] { + write_pkg(&root.join("packages").join(member), member, "1.0.0"); + } + rel_link( + "../../../node_modules/.pnpm/minimist@socket-8cccd65b+0.0.8/node_modules/minimist", + &root.join("packages/a/node_modules/minimist"), + ); + rel_link( + "../../../node_modules/.pnpm/mkdirp@0.5.1/node_modules/mkdirp", + &root.join("packages/b/node_modules/mkdirp"), + ); + + // Named by their store paths: no copy's own path leads to an entry. + assert_eq!( + live_copies(&root, &[&upstream, &routed]).await, + vec![upstream.clone(), routed.clone()] + ); + + std::fs::remove_dir_all(root.join("packages/b/node_modules")).unwrap(); + assert_eq!( + live_copies(&root, &[&upstream, &routed]).await, + vec![routed] + ); + } + + /// #2353: when the patched package is a peer dependency of another + /// package, a hosted scan gives the dependent a new entry as well, and + /// the dependent's old entry keeps its link to the old `minimist` entry + /// (real pnpm 12.25.1 and 11.29.0). Neither old entry is linked from + /// outside the store's entries, so both are left out: a link inside an + /// entry nothing reaches keeps nothing. One link to the old dependent + /// from outside brings both back. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entries_only_each_other_links_are_not_live_copies() { + const OLD: &str = "needs-minimist@file+needs-minimist-1.0.0.tgz_minimist@1.2.2"; + const NEW: &str = + "needs-minimist@file+needs-minimist-1.0.0.tgz_minimist@socket-642d7f02+1.2.2"; + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, stale, routed) = pnpm_hosted_route_leftover(&root); + let store = nm.join(".pnpm"); + let dependent = |entry: &str, peer_entry: &str| { + let dir = pnpm_entry(&store, entry, "needs-minimist", "1.0.0"); + rel_link( + &format!("../../{peer_entry}/node_modules/minimist"), + &store.join(entry).join("node_modules/minimist"), + ); + dir + }; + let old_dependent = dependent(OLD, "minimist@1.2.2"); + let new_dependent = dependent(NEW, ROUTED_ENTRY); + rel_link( + &format!(".pnpm/{NEW}/node_modules/needs-minimist"), + &nm.join("needs-minimist"), + ); + let lists: [&[&PathBuf]; 2] = [&[&stale, &routed], &[&old_dependent, &new_dependent]]; + + assert_eq!( + judge_lists(&root, &lists).await.0, + vec![vec![routed.clone()], vec![new_dependent.clone()]] + ); + + abs_link( + &old_dependent, + &root.join("tools/node_modules/needs-minimist"), + ); + assert_eq!( + judge_lists(&root, &lists).await.0, + vec![vec![stale, routed], vec![old_dependent, new_dependent]] + ); + } + + /// #2353: every link there is counts, wherever it sits and whatever it + /// points at inside the entry: node, or any other loader, started from + /// that path loads the leftover copy. Each case adds one link to the + /// store of [`pnpm_hosted_route_leftover`], whose leftover is left out + /// as it stands, and the leftover is a live copy for as long as that + /// link is there. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_any_link_reaches_is_a_live_copy() { + // Adds the link; returns the path that takes it away again. + type AddLink = Box PathBuf>; + let to_the_package = |at: &'static str| -> AddLink { + Box::new(move |root: &Path| abs_link(&root.join(LEFTOVER), &root.join(at))) + }; + let cases: Vec<(&str, AddLink)> = vec![ + ("vendor/", to_the_package("vendor/x")), + ("dist/", to_the_package("dist/x")), + ("build/", to_the_package("build/x")), + ("a hidden directory", to_the_package(".cache/tool/x")), + ( + "a former member's node_modules", + to_the_package("packages/gone/node_modules/minimist"), + ), + ( + "the hoist directory", + to_the_package("node_modules/.pnpm/node_modules/minimist"), + ), + ("a scoped link", to_the_package("node_modules/@s/pkg")), + ( + "a real package's node_modules in a live entry", + Box::new(|root: &Path| { + let nested = format!( + "node_modules/.pnpm/{ROUTED_ENTRY}/node_modules/minimist/node_modules/old" + ); + abs_link(&root.join(LEFTOVER), &root.join(nested)) + }), + ), + ( + "a real package's node_modules in a member", + Box::new(|root: &Path| { + std::fs::write( + root.join("node_modules/.pnpm/lock.yaml"), + pnpm_lock_of(&["packages/a"]), + ) + .unwrap(); + let real = root.join("packages/a/node_modules/real"); + write_pkg(&real, "real", "1.0.0"); + abs_link(&root.join(LEFTOVER), &real.join("node_modules/minimist")) + }), + ), + ( + "a nested project's node_modules", + Box::new(|root: &Path| { + let (nm, _) = pnpm_install(&root.join("apps/web"), &[]); + abs_link(&root.join(LEFTOVER), &nm.join("minimist")) + }), + ), + ( + "a link that is a child of the store", + Box::new(|root: &Path| { + let store = root.join("node_modules/.pnpm"); + abs_link(&store.join("minimist@1.2.2"), &store.join("alias")) + }), + ), + // Node loads a linked file from where it is: beside the + // `node_modules` of a member that left the workspace, which is + // not read, so every entry is kept while the link is there. + ( + "a link to a file of a former member outside the project", + Box::new(|root: &Path| { + let shared = root.parent().unwrap().join("shared"); + abs_link(&root.join(LEFTOVER), &shared.join("node_modules/minimist")); + std::fs::write(shared.join("gen.js"), "").unwrap(); + abs_link(&shared.join("gen.js"), &root.join("scripts/gen.js")) + }), + ), + ( + "a link to a file two directories below a former member's scoped link", + Box::new(|root: &Path| { + let shared = root.parent().unwrap().join("shared"); + abs_link(&root.join(LEFTOVER), &shared.join("node_modules/@s/mini")); + std::fs::create_dir_all(shared.join("lib/deep")).unwrap(); + std::fs::write(shared.join("lib/deep/gen.js"), "").unwrap(); + abs_link( + &shared.join("lib/deep/gen.js"), + &root.join("scripts/gen.js"), + ) + }), + ), + ( + "a link to a file beside a node_modules that is a link into the entry", + Box::new(|root: &Path| { + let shared = root.parent().unwrap().join("shared"); + abs_link( + root.join(LEFTOVER).parent().unwrap(), + &shared.join("node_modules"), + ); + std::fs::write(shared.join("gen.js"), "").unwrap(); + abs_link(&shared.join("gen.js"), &root.join("scripts/gen.js")) + }), + ), + ( + "a link to the entry's node_modules", + Box::new(|root: &Path| { + abs_link( + root.join(LEFTOVER).parent().unwrap(), + &root.join("vendor/modules"), + ) + }), + ), + ( + "a link to a file of the package", + Box::new(|root: &Path| { + abs_link( + &root.join(LEFTOVER).join("package.json"), + &root.join("vendor/minimist.json"), + ) + }), + ), + ( + "a chain of two links, the second outside the project", + Box::new(|root: &Path| { + let hop = root.ancestors().nth(2).unwrap().join("hop"); + abs_link(&root.join(LEFTOVER), &hop); + abs_link(&hop, &root.join("tools/x")) + }), + ), + ( + "a chain through the link of an entry nothing reaches", + Box::new(|root: &Path| { + let store = root.join("node_modules/.pnpm"); + pnpm_entry(&store, "dep@0.9.0", "dep", "0.9.0"); + let inner = store.join("dep@0.9.0/node_modules/minimist"); + rel_link("../../minimist@1.2.2/node_modules/minimist", &inner); + abs_link(&inner, &root.join("vendor/x")) + }), + ), + ]; + for (case, add_link) in cases { + let (_tmp, _, root) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&root); + let copies = [&stale, &routed]; + assert_eq!( + live_copies(&root, &copies).await, + vec![routed.clone()], + "{case}: before the link" + ); + let link = add_link(&root); + assert_eq!( + live_copies(&root, &copies).await, + vec![stale.clone(), routed.clone()], + "{case}" + ); + // The link kept it, not a store that could no longer be judged. + std::fs::remove_file(&link).unwrap(); + assert_eq!( + live_copies(&root, &copies).await, + vec![routed.clone()], + "{case}: without the link" + ); + } + } + + /// #2353: a link may spell an entry in another case than the store + /// lists it. On a file system that folds case the link resolves, and + /// the entry is a live copy (`canonicalize` gives the listed spelling + /// back on macOS; where it does not, the entry cannot be named and + /// every entry is kept). Where case is kept, the link leads nowhere. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_a_link_in_another_case_reaches_is_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&root); + let link = root.join("vendor/x"); + rel_link( + "../node_modules/.PNPM/Minimist@1.2.2/node_modules/minimist", + &link, + ); + let kept = live_copies(&root, &[&stale, &routed]).await; + if link.join("package.json").is_file() { + assert_eq!(kept, vec![stale, routed], "the file system folds case"); + } else { + assert_eq!(kept, vec![routed], "the link leads nowhere"); + } + } + + /// #2353: what does not reach the leftover entry does not keep it, and + /// does not stop the store from being judged. Each case changes one + /// thing about the store of [`pnpm_hosted_route_leftover`], and the + /// leftover is left out all the same. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_no_link_reaches_from_outside_is_not_a_live_copy() { + type Change = Box; + let member = |key: &'static str, dir: &'static str, wanted: bool| -> Change { + Box::new(move |root: &Path| { + write_pkg(&root.join(dir), "member", "1.0.0"); + let lock = if wanted { + root.join("pnpm-lock.yaml") + } else { + root.join("node_modules/.pnpm/lock.yaml") + }; + std::fs::write(lock, pnpm_lock_of(&[key])).unwrap(); + }) + }; + let real_dir = |at: &'static str, name: &'static str| -> Change { + Box::new(move |root: &Path| write_pkg(&root.join(at), name, "1.3.0")) + }; + let cases: Vec<(&str, Change)> = vec![ + ( + "a link inside an entry nothing reaches", + Box::new(|root: &Path| { + let store = root.join("node_modules/.pnpm"); + pnpm_entry(&store, "dep@0.9.0", "dep", "0.9.0"); + rel_link( + "../../minimist@1.2.2/node_modules/minimist", + &store.join("dep@0.9.0/node_modules/minimist"), + ); + }), + ), + ( + "links inside the leftover entry to itself", + Box::new(|root: &Path| { + let package = root.join(LEFTOVER); + rel_link(".", &package.join("self")); + rel_link( + "../minimist/package.json", + &package.join("../.bin/minimist"), + ); + rel_link("../..", &package.join("node_modules/up")); + }), + ), + ( + "a link whose target is not there", + Box::new(|root: &Path| { + abs_link(&root.join(LEFTOVER).join("gone"), &root.join("vendor/x")); + rel_link("nowhere", &root.join("dist/x")); + }), + ), + ( + "a link that loops", + Box::new(|root: &Path| rel_link("loop", &root.join("vendor/loop"))), + ), + ( + "a link through a file", + Box::new(|root: &Path| { + std::fs::write(root.join("file"), "").unwrap(); + rel_link("../file/child", &root.join("vendor/x")); + }), + ), + // Opening a pipe nothing writes to never returns. + ( + "a link to a named pipe", + Box::new(|root: &Path| { + let pipe = root.join("run/pipe"); + std::fs::create_dir_all(pipe.parent().unwrap()).unwrap(); + mkfifo(&pipe); + abs_link(&pipe, &root.join("tools/own")); + }), + ), + ( + "a link to a directory inside the project", + Box::new(|root: &Path| { + abs_link(root, &root.join("packages/a/node_modules/root")); + abs_link(&root.join("node_modules"), &root.join("vendor/modules")); + }), + ), + ( + "a package as a real directory of the importer", + real_dir("node_modules/left-pad", "left-pad"), + ), + ( + "a package as a real directory of an importer's scope", + real_dir("node_modules/@s/lp", "@s/lp"), + ), + ( + "a linked entry whose node_modules is a link", + Box::new(|root: &Path| { + let entry = root.join("node_modules/.pnpm").join(ROUTED_ENTRY); + std::fs::rename(entry.join("node_modules"), entry.join("moved")).unwrap(); + rel_link("moved", &entry.join("node_modules")); + }), + ), + ( + "a member the lockfile in the store names", + member("packages/a", "packages/a", false), + ), + ( + "a member pnpm-lock.yaml names", + member("packages/a", "packages/a", true), + ), + ( + "a member under a key in single quotes", + member("'@apps/vendor/web'", "@apps/vendor/web", false), + ), + ( + "a member under a key in double quotes", + member("\"@apps/vendor/web\"", "@apps/vendor/web", true), + ), + ( + "a member that is a link to a directory inside the project", + Box::new(|root: &Path| { + write_pkg(&root.join("real/member"), "member", "1.0.0"); + abs_link(&root.join("real/member"), &root.join("packages/linked")); + std::fs::write( + root.join("node_modules/.pnpm/lock.yaml"), + pnpm_lock_of(&["packages/linked"]), + ) + .unwrap(); + }), + ), + // Nothing above the scanned directory is read: pnpm writes no + // link there into a store below it. + ( + "a link in the node_modules of a directory above the project", + Box::new(|root: &Path| { + let above = root.parent().unwrap().join("node_modules"); + abs_link(&root.join(LEFTOVER), &above.join("@up/minimist")); + abs_link(root.parent().unwrap(), &above.join("out")); + std::fs::create_dir_all(above.join("private")).unwrap(); + }), + ), + ]; + // A link to a file outside the project, with no `node_modules` in + // a directory above the file: a file named so, and a link named + // so whose target is not there, are none. Only on a machine with + // no `node_modules` above the temp dir itself. + let mut cases = cases; + let temp = std::fs::canonicalize(std::env::temp_dir()).unwrap(); + let home = crate::utils::repo_root::home(); + let above_temp = + node_modules_above_sync(&temp.join("x/file"), home.as_deref(), &mut HashSet::new()); + if above_temp == Some(false) { + cases.push(( + "a link to a file outside the project", + Box::new(|root: &Path| { + let outside = root.ancestors().nth(2).unwrap().join("elsewhere"); + std::fs::create_dir_all(outside.join("deep")).unwrap(); + std::fs::write(outside.join("deep/file"), "").unwrap(); + abs_link(&outside.join("deep/file"), &root.join("tools/file")); + std::fs::write(outside.join("node_modules"), "").unwrap(); + rel_link("nowhere", &outside.join("deep/node_modules")); + }), + )); + cases.push(( + "a link to a named pipe outside the project", + Box::new(|root: &Path| { + let pipe = root.ancestors().nth(2).unwrap().join("pipe"); + mkfifo(&pipe); + abs_link(&pipe, &root.join("tools/ctl")); + }), + )); + } + for (case, change) in cases { + let (_tmp, _, root) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&root); + change(&root); + assert_eq!( + live_copies(&root, &[&stale, &routed]).await, + vec![routed], + "{case}" + ); + } + } + + /// A named pipe at `path`, which nothing writes to. + #[cfg(unix)] + fn mkfifo(path: &Path) { + let made = std::process::Command::new("mkfifo") + .arg(path) + .status() + .unwrap(); + assert!(made.success(), "mkfifo {path:?}"); + } + + /// #2353: node looks up the packages of a file in the `node_modules` + /// of each directory above it, up to the home directory, which is + /// not looked at, nor is anything above it. A file or a dangling link + /// named `node_modules` is none. + #[cfg(unix)] + #[test] + fn test_node_modules_above_a_file_stops_at_the_home_directory() { + let tmp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(tmp.path()).unwrap(); + let home = base.join("home"); + let file = home.join("projects/shared/lib/gen.js"); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, "").unwrap(); + let above = |home: &Path| node_modules_above_sync(&file, Some(home), &mut HashSet::new()); + + assert_eq!(above(&home), Some(false)); + std::fs::write(home.join("projects/shared/lib/node_modules"), "").unwrap(); + rel_link("nowhere", &home.join("projects/shared/node_modules")); + std::fs::create_dir_all(home.join("node_modules")).unwrap(); + std::fs::create_dir_all(base.join("node_modules")).unwrap(); + assert_eq!(above(&home), Some(false), "not in the home directory"); + assert_eq!( + above(&base.join("elsewhere")), + Some(true), + "with the home directory elsewhere" + ); + std::fs::create_dir_all(home.join("projects/node_modules")).unwrap(); + assert_eq!(above(&home), Some(true), "below the home directory"); + + // A directory found to have none is not asked again. + let mut seen = HashSet::new(); + let other = home.join("other/a/file"); + assert_eq!( + node_modules_above_sync(&other, Some(&home), &mut seen), + Some(false) + ); + std::fs::create_dir_all(home.join("other/node_modules")).unwrap(); + assert_eq!( + node_modules_above_sync(&other, Some(&home), &mut seen), + Some(false) + ); + assert_eq!( + node_modules_above_sync(&other, Some(&home), &mut HashSet::new()), + Some(true) + ); + } + + /// #2353: a pnpm store is judged for a package version only when its + /// copies sit in two or more entries of the store, which is what an + /// in-place install that changed the package's source leaves. A + /// removed package and an upgraded-away version (#1197) hold their + /// version in one entry: each is kept though nothing links it, and + /// the project is not read for them. Where one version does sit in + /// two entries, the others are still kept as they are. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_is_judged_only_for_a_version_in_two_of_its_entries() { + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, store) = pnpm_install(&root, &[]); + let linked = pnpm_entry(&store, "is-number@7.0.0", "is-number", "7.0.0"); + let link = nm.join("is-number"); + rel_link(".pnpm/is-number@7.0.0/node_modules/is-number", &link); + let removed = pnpm_entry(&store, "left-pad@1.3.0", "left-pad", "1.3.0"); + let upgraded = pnpm_entry(&store, "is-number@6.0.0", "is-number", "6.0.0"); + + let lists: [&[&PathBuf]; 3] = [&[&removed], &[&upgraded], &[&linked, &link]]; + let (kept, live) = judge_lists(&root, &lists).await; + assert_eq!( + kept, + vec![ + vec![removed.clone()], + vec![upgraded.clone()], + vec![linked.clone(), link.clone()] + ] + ); + assert!( + live.stores.is_empty() && live.sweeps.is_empty(), + "no store is judged and no tree is read" + ); + + // Two peer variants of one version come from one tarball and hold + // the same bytes: leaving one out would change no verdict, so + // neither is judged and the project is not read, linked or not. + // The launcher pnpm writes into a package's own `node_modules` + // names the entry, and does not count. + let peers = [ + pnpm_entry(&store, "dep@1.0.0_peer@1.0.0", "dep", "1.0.0"), + pnpm_entry(&store, "dep@1.0.0_peer@2.0.0", "dep", "1.0.0"), + ]; + for (peer, entry) in peers.iter().zip(["peer@1.0.0", "peer@2.0.0"]) { + std::fs::write(peer.join("index.js"), "module.exports = 'dep'\n").unwrap(); + let bin = peer.join("node_modules/.bin"); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::write(bin.join("dep"), format!("exec node dep@1.0.0_{entry}\n")).unwrap(); + } + let (kept, live) = judge_lists(&root, &[&[&peers[0], &peers[1]], &[&removed]]).await; + assert_eq!(kept, vec![peers.to_vec(), vec![removed.clone()]]); + assert!( + live.stores.is_empty() && live.sweeps.is_empty(), + "copies that hold the same bytes are not judged" + ); + + // With other bytes in one of them they are judged by the links: + // both are kept while both are linked, and the project is read. + std::fs::write(peers[1].join("index.js"), "module.exports = 'other'\n").unwrap(); + rel_link( + ".pnpm/dep@1.0.0_peer@1.0.0/node_modules/dep", + &nm.join("dep"), + ); + let hoisted = store.join("node_modules/dep"); + rel_link("../dep@1.0.0_peer@2.0.0/node_modules/dep", &hoisted); + let (kept, live) = judge_lists(&root, &[&[&peers[0], &peers[1]], &[&removed]]).await; + assert_eq!(kept, vec![peers.to_vec(), vec![removed.clone()]]); + assert_eq!( + swept_below(&live, &root), + vec![std::fs::canonicalize(&root).unwrap()] + ); + std::fs::remove_file(&hoisted).unwrap(); + assert_eq!( + live_copies(&root, &[&peers[0], &peers[1]]).await, + vec![peers[0].clone()] + ); + + // The leftover of an in-place install is left out, and the store's + // judgement is not turned on the versions that sit in one entry. + let stale = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); + let routed = pnpm_entry(&store, ROUTED_ENTRY, "minimist", "1.2.2"); + rel_link( + &format!(".pnpm/{ROUTED_ENTRY}/node_modules/minimist"), + &nm.join("minimist"), + ); + let lists: [&[&PathBuf]; 3] = [&[&removed], &[&stale, &routed], &[&upgraded]]; + let (kept, live) = judge_lists(&root, &lists).await; + assert_eq!(kept, vec![vec![removed], vec![routed], vec![upgraded]]); + assert_eq!(live.stores.len(), 1); + } + + /// #2353: a copy that sits in the store but in none of its entry dirs + /// is never left out. Every package of the store resolves through the + /// hoist dir `.pnpm/node_modules`, so a package that is a real + /// directory there loads without any link, and a hidden child of the + /// store is not judged at all. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_copy_in_none_of_its_entries_is_always_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, stale, routed) = pnpm_hosted_route_leftover(&root); + let hoisted = nm.join(".pnpm/node_modules/minimist"); + write_pkg(&hoisted, "minimist", "1.2.2"); + let hidden = nm.join(".pnpm/.staging/node_modules/minimist"); + write_pkg(&hidden, "minimist", "1.2.2"); + let through = abs_link(&hoisted, &root.join("vendor/hoisted")); + + assert_eq!( + live_copies(&root, &[&stale, &hoisted, &hidden, &through, &routed]).await, + vec![hoisted.clone(), hidden.clone(), through, routed] + ); + // A copy in no entry is no second entry: with the leftover's the + // only entry that holds the version, nothing is judged. + let (kept, live) = judge_lists(&root, &[&[&stale, &hoisted, &hidden]]).await; + assert_eq!(kept, vec![vec![stale, hoisted, hidden]]); + assert!(live.stores.is_empty() && live.sweeps.is_empty()); + } + + /// #2353: the links are read below the outer of the scanned directory + /// and the project that holds the store. A run from inside a workspace + /// member reads the whole project, and a run from a directory above + /// the project reads everything below that directory, so a link in + /// another checkout there counts. The same link is out of reach of a + /// scan of the project alone. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_is_judged_by_the_links_below_the_outer_directory() { + let (_tmp, base, root) = pnpm_project_dir(); + let (nm, stale, routed) = pnpm_hosted_route_leftover(&root); + std::fs::write(nm.join(".pnpm/lock.yaml"), pnpm_lock_of(&["packages/a"])).unwrap(); + let member = root.join("packages/a"); + write_pkg(&member, "a", "1.0.0"); + let copies: [&PathBuf; 2] = [&stale, &routed]; + let both = vec![stale.clone(), routed.clone()]; + + let (kept, live) = judge_lists(&member, &[&copies]).await; + assert_eq!(kept, vec![vec![routed.clone()]]); + assert_eq!( + swept_below(&live, &base), + vec![std::fs::canonicalize(&root).unwrap()] + ); + let link = abs_link(&stale, &root.join("vendor/x")); + assert_eq!(live_copies(&member, &copies).await, both); + std::fs::remove_file(link).unwrap(); + + // A project run reads no project file above its git checkout. With + // the member a checkout of its own, the project above it is not + // read and every entry is kept; with the checkout at the project, + // it is. + std::fs::create_dir(member.join(".git")).unwrap(); + let (kept, live) = judge_lists(&member, &[&copies]).await; + assert_eq!(kept, vec![both.clone()]); + assert!(live.sweeps.is_empty(), "nothing above the checkout is read"); + std::fs::create_dir(root.join(".git")).unwrap(); + std::fs::remove_dir(member.join(".git")).unwrap(); + assert_eq!(live_copies(&member, &copies).await, vec![routed.clone()]); + std::fs::remove_dir(root.join(".git")).unwrap(); + + let (kept, live) = judge_lists(&base, &[&copies]).await; + assert_eq!(kept, vec![vec![routed.clone()]]); + assert_eq!( + swept_below(&live, &base), + vec![std::fs::canonicalize(&base).unwrap()] + ); + abs_link(&stale, &base.join("other/checkout/dist/x")); + assert_eq!(live_copies(&base, &copies).await, both); + assert_eq!(live_copies(&root, &copies).await, vec![routed.clone()]); + assert_eq!(live_copies(&member, &copies).await, vec![routed]); + } + + /// #2353: several pnpm stores below one scanned directory are judged + /// from one read of its links, and a link in one project's + /// `node_modules` keeps an entry of the other's store. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_stores_below_one_scanned_directory_share_one_sweep() { + let (_tmp, base, root) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&root); + let nested = root.join("apps/web"); + let (nested_nm, nested_stale, nested_routed) = pnpm_hosted_route_leftover(&nested); + let lists: [&[&PathBuf]; 2] = [&[&stale, &routed], &[&nested_stale, &nested_routed]]; + + let (kept, live) = judge_lists(&root, &lists).await; + assert_eq!( + kept, + vec![vec![routed.clone()], vec![nested_routed.clone()]] + ); + assert_eq!(live.stores.len(), 2); + assert_eq!( + swept_below(&live, &base), + vec![std::fs::canonicalize(&root).unwrap()] + ); + + abs_link(&stale, &nested_nm.join("old-minimist")); + assert_eq!( + judge_lists(&root, &lists).await.0, + vec![vec![stale, routed], vec![nested_routed]] + ); + } + + /// #2353: the sweep lists every link below a tree, in whatever + /// directory, with the real path it resolves to, and follows none: a + /// link behind a link to a directory outside the tree is not read. A + /// link whose target is not there is left out. One directory or link + /// more than the budget, and there is no answer. + #[cfg(unix)] + #[test] + fn test_links_below_lists_every_link_and_follows_none() { + let tmp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(tmp.path()).unwrap(); + let (tree, outside) = (base.join("tree"), base.join("outside")); + std::fs::create_dir_all(outside.join("deep")).unwrap(); + std::fs::write(outside.join("file"), "").unwrap(); + abs_link(&outside.join("file"), &outside.join("deep/unread")); + // Ten directories, the tree itself among them. + for dir in [ + "vendor", + "dist/a/b", + ".hidden", + "node_modules/pkg/node_modules/@s", + ] { + std::fs::create_dir_all(tree.join(dir)).unwrap(); + } + std::fs::write(tree.join("file"), "").unwrap(); + let mut expected = vec![ + (tree.join(".hidden/up"), tree.clone()), + (tree.join("chain"), outside.clone()), + (tree.join("dist/a/b/file"), tree.join("file")), + ( + tree.join("node_modules/pkg/node_modules/@s/x"), + tree.join("vendor"), + ), + (tree.join("vendor/dir"), outside.clone()), + ]; + abs_link(&tree, &tree.join(".hidden/up")); + abs_link(&tree.join("vendor/dir"), &tree.join("chain")); + abs_link(&tree.join("file"), &tree.join("dist/a/b/file")); + abs_link( + &tree.join("vendor"), + &tree.join("node_modules/pkg/node_modules/@s/x"), + ); + abs_link(&outside, &tree.join("vendor/dir")); + rel_link("nowhere", &tree.join("dangling")); + + let found = |budget: usize| { + let mut links: Vec<(PathBuf, PathBuf)> = links_below_within_sync(&tree, budget)? + .into_iter() + .map(|link| (link.path, link.target)) + .collect(); + links.sort(); + Some(links) + }; + expected.sort(); + // Ten directories and the five links that resolve. + assert_eq!(found(15), Some(expected.clone())); + assert_eq!(found(14), None); + assert_eq!( + links_below_sync(&tree).map(|links| links.len()), + Some(expected.len()) + ); + assert!(links_below_sync(&tree.join("missing")).is_none()); + } + + /// #2353: two copies of a package hold the same bytes when every file + /// and link below them does, by path and content, whatever launchers + /// sit in the `.bin` of each package's own `node_modules`. A copy that + /// cannot be read through is never the same as another. + #[cfg(unix)] + #[test] + fn test_same_package_bytes_compares_every_file_and_link() { + let tmp = tempfile::tempdir().unwrap(); + let copy = |name: &str| { + let dir = tmp.path().join(name); + write_pkg(&dir, "dep", "1.0.0"); + std::fs::create_dir_all(dir.join("lib/node_modules/inner")).unwrap(); + std::fs::write(dir.join("lib/index.js"), "module.exports = 1\n").unwrap(); + std::fs::write(dir.join("lib/node_modules/inner/index.js"), "inner\n").unwrap(); + std::os::unix::fs::symlink("lib/index.js", dir.join("main.js")).unwrap(); + std::fs::create_dir_all(dir.join("node_modules/.bin")).unwrap(); + std::fs::write(dir.join("node_modules/.bin/dep"), name).unwrap(); + std::fs::create_dir_all(dir.join("node_modules/bundled")).unwrap(); + std::fs::write(dir.join("node_modules/bundled/index.js"), "bundled\n").unwrap(); + dir + }; + let (a, b) = (copy("a"), copy("b")); + let same = |a: &Path, b: &Path| same_package_bytes_sync([a, b]); + assert!(same(&a, &b)); + assert!(same_package_bytes_sync([a.as_path()])); + assert!(!same_package_bytes_sync(std::iter::empty::<&Path>())); + + type Change = fn(&Path); + let changes: [(&str, Change); 8] = [ + ("other bytes in a dependency the package bundles", |b| { + std::fs::write(b.join("node_modules/bundled/index.js"), "other\n").unwrap() + }), + ("other bytes in a file", |b| { + std::fs::write(b.join("lib/index.js"), "module.exports = 2\n").unwrap() + }), + ("other bytes in a nested node_modules", |b| { + std::fs::write(b.join("lib/node_modules/inner/index.js"), "other\n").unwrap() + }), + ("one file more", |b| { + std::fs::write(b.join("lib/extra.js"), "").unwrap() + }), + ("a file under another name", |b| { + std::fs::rename(b.join("lib/index.js"), b.join("lib/main.js")).unwrap() + }), + ("a link to another target", |b| { + std::fs::remove_file(b.join("main.js")).unwrap(); + std::os::unix::fs::symlink("lib/other.js", b.join("main.js")).unwrap(); + }), + ("a file in place of a link", |b| { + std::fs::remove_file(b.join("main.js")).unwrap(); + std::fs::write(b.join("main.js"), "lib/index.js").unwrap(); + }), + ("a copy that is not there", |b| { + std::fs::remove_dir_all(b).unwrap() + }), + ]; + for (case, change) in changes { + std::fs::remove_dir_all(&b).unwrap(); + let b = copy("b"); + assert!(same(&a, &b), "{case}: before the change"); + change(&b); + assert!(!same(&a, &b), "{case}"); + assert!(!same(&b, &a), "{case}, the other way round"); + } + } + + /// #2353: the entries of a store are its real dirs, read from a whole + /// listing with the type of every child that is not hidden. A child + /// whose type cannot be read may be an entry, and a listing cut short + /// may lack one: neither names the entries. + #[test] + fn test_pnpm_store_entry_names_need_the_type_of_every_child() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join("file"), "").unwrap(); + let type_of = |path: &Path| std::fs::symlink_metadata(path).unwrap().file_type(); + let (dir, file) = (type_of(tmp.path()), type_of(&tmp.path().join("file"))); + let names = |children: &[(&str, Option)], complete: bool| { + pnpm_store_entry_names(Listing { + entries: children + .iter() + .map(|(name, file_type)| ListedEntry { + name: OsString::from(name), + name_str: name.to_string(), + file_type: *file_type, + }) + .collect(), + complete, + }) + }; + let store = [ + ("a@1.0.0", Some(dir)), + ("lock.yaml", Some(file)), + ("node_modules", Some(dir)), + (".hidden", None), + ]; + assert_eq!( + names(&store, true), + Some(HashSet::from([OsString::from("a@1.0.0")])) + ); + assert_eq!(names(&store, false), None); + for unread in ["b@1.0.0", "node_modules"] { + let mut store = store.to_vec(); + store.retain(|(name, _)| *name != unread); + store.push((unread, None)); + assert_eq!(names(&store, true), None, "{unread}"); + } + } + + /// #2353: wherever a link that reaches an entry may have gone unread, + /// nothing is left out. Each case changes one thing about the store of + /// [`pnpm_hosted_route_leftover`], whose leftover is left out as it + /// stands. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_that_cannot_be_judged_keeps_every_entry() { + use std::os::unix::fs::PermissionsExt; + + type Change = Box; + let record = |from: &'static str, to: &'static str| -> Change { + Box::new(move |root: &Path| { + let path = root.join("node_modules/.modules.yaml"); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains(from), "{from}"); + std::fs::write(path, text.replace(from, to)).unwrap(); + }) + }; + // `lock` in place of the lockfile in the store, or of + // `pnpm-lock.yaml`. + fn write_lock(root: &Path, wanted: bool, lock: &str) { + let path = if wanted { + root.join("pnpm-lock.yaml") + } else { + root.join("node_modules/.pnpm/lock.yaml") + }; + std::fs::write(path, lock).unwrap(); + } + // The directory `ws/x`, beside the project. + fn beside(root: &Path) -> PathBuf { + let dir = root.parent().unwrap().join("x"); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + let misplaced_importers = |wanted: bool| -> Change { + Box::new(move |root: &Path| { + let lock = pnpm_lock_of(&[]).replace("\n .:\n", "\n .:\n"); + assert!(lock.contains("\n .:\n")); + write_lock(root, wanted, &lock); + }) + }; + let member_missing = |wanted: bool| -> Change { + Box::new(move |root: &Path| write_lock(root, wanted, &pnpm_lock_of(&["packages/gone"]))) + }; + let member_a_file = |wanted: bool| -> Change { + Box::new(move |root: &Path| { + std::fs::write(root.join("member"), "").unwrap(); + write_lock(root, wanted, &pnpm_lock_of(&["member"])); + }) + }; + let member_climbing_out = |wanted: bool| -> Change { + Box::new(move |root: &Path| { + beside(root); + write_lock(root, wanted, &pnpm_lock_of(&["../x"])); + }) + }; + let mut cases: Vec<(&str, Change)> = vec![ + ( + "no install record", + Box::new(|root: &Path| { + std::fs::remove_file(root.join("node_modules/.modules.yaml")).unwrap() + }), + ), + ( + "an install record that does not parse", + Box::new(|root: &Path| { + std::fs::write(root.join("node_modules/.modules.yaml"), "{ not json").unwrap() + }), + ), + ( + "node-linker=hoisted", + record(r#""nodeLinker":"isolated""#, r#""nodeLinker":"hoisted""#), + ), + ( + "shamefully-hoist", + record( + r#""publicHoistPattern":[]"#, + r#""publicHoistPattern":["*"]"#, + ), + ), + ( + "another layout version", + record(r#""layoutVersion":5"#, r#""layoutVersion":4"#), + ), + ( + "a record of another virtual store", + record( + r#""virtualStoreDir":".pnpm""#, + r#""virtualStoreDir":"../.store""#, + ), + ), + ( + "no lockfile in the store", + Box::new(|root: &Path| { + std::fs::remove_file(root.join("node_modules/.pnpm/lock.yaml")).unwrap() + }), + ), + ( + "a lockfile in the store that is no pnpm lock", + Box::new(|root: &Path| write_lock(root, false, "not: a lock\n")), + ), + ( + "a lockfile in the store laid out as pnpm does not write it", + misplaced_importers(false), + ), + ( + "a pnpm-lock.yaml laid out as pnpm does not write it", + misplaced_importers(true), + ), + ( + "a pnpm-lock.yaml that cannot be read", + Box::new(|root: &Path| std::fs::create_dir(root.join("pnpm-lock.yaml")).unwrap()), + ), + ( + "a member of the lockfile in the store that climbs out", + member_climbing_out(false), + ), + ( + "a member of pnpm-lock.yaml that climbs out", + member_climbing_out(true), + ), + ( + "a member named by an absolute path", + Box::new(|root: &Path| { + let member = beside(root); + let member = member.to_str().unwrap(); + let lock = pnpm_lock_of(&[member]); + assert_eq!( + crate::formats::pnpm::workspace::lock_text_member_importers_exact(&lock), + Some(vec![member.to_string()]) + ); + write_lock(root, false, &lock); + }), + ), + ( + "a member of the lockfile in the store that is not on disk", + member_missing(false), + ), + ( + "a member of pnpm-lock.yaml that is not on disk", + member_missing(true), + ), + ( + "a member of the lockfile in the store that is a file", + member_a_file(false), + ), + ( + "a member of pnpm-lock.yaml that is a file", + member_a_file(true), + ), + ( + "a member that is a link to a directory outside the project", + Box::new(|root: &Path| { + abs_link(&beside(root), &root.join("packages/out")); + write_lock(root, false, &pnpm_lock_of(&["packages/out"])); + }), + ), + ( + "a link to a directory outside the project", + Box::new(|root: &Path| { + abs_link(&beside(root), &root.join("node_modules/linked")); + }), + ), + ( + "a link to the store itself", + Box::new(|root: &Path| { + abs_link(&root.join("node_modules/.pnpm"), &root.join("vendor/store")); + }), + ), + ( + "a link to a file outside the project below an empty node_modules", + Box::new(|root: &Path| { + let shared = beside(root); + std::fs::create_dir_all(shared.join("node_modules")).unwrap(); + std::fs::create_dir_all(shared.join("lib/deep")).unwrap(); + std::fs::write(shared.join("lib/deep/gen.js"), "").unwrap(); + abs_link( + &shared.join("lib/deep/gen.js"), + &root.join("scripts/gen.js"), + ); + }), + ), + ( + "a link into the store that names none of its entries", + Box::new(|root: &Path| { + abs_link( + &root.join("node_modules/.pnpm/lock.yaml"), + &root.join("vendor/lock.yaml"), + ); + }), + ), + ( + "no link into the store", + Box::new(|root: &Path| { + std::fs::remove_file(root.join("node_modules/minimist")).unwrap() + }), + ), + ]; + // macOS reaches the data volume under `/System/Volumes/Data` as + // well, and `canonicalize` keeps that spelling. Only where the + // temp dir is on that volume. + #[cfg(target_os = "macos")] + { + let data = Path::new("/System/Volumes/Data"); + let tmp = std::fs::canonicalize(std::env::temp_dir()).unwrap(); + if data.join(tmp.strip_prefix("/").unwrap()).is_dir() { + cases.push(( + "a link into the leftover entry spelled through /System/Volumes/Data", + Box::new(move |root: &Path| { + let real = std::fs::canonicalize(root.join(LEFTOVER)).unwrap(); + let spelled = data + .join(real.strip_prefix("/").unwrap()) + .join("package.json"); + assert!(spelled.is_file(), "{spelled:?}"); + abs_link(&spelled, &root.join("vendor/minimist.json")); + }), + )); + } + } + for (case, change) in cases { + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, stale, routed) = pnpm_hosted_route_leftover(&root); + assert_eq!( + live_copies(&root, &[&stale, &routed]).await, + vec![routed.clone()], + "{case}: before the change" + ); + change(&root); + let copies = [&stale, &routed, &nm.join("minimist")]; + let kept: Vec = copies + .iter() + .filter(|copy| copy.exists()) + .map(|copy| (*copy).clone()) + .collect(); + assert_eq!( + live_copies(&root, &kept.iter().collect::>()).await, + kept, + "{case}" + ); + } + + // A scanned directory that neither holds the project nor lies in + // it, and a crawl that scans no project directory (`--global`). + let (_tmp, base, root) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&root); + let copies: [&PathBuf; 2] = [&stale, &routed]; + let both = vec![stale.clone(), routed.clone()]; + let other = base.join("ws/other"); + std::fs::create_dir_all(&other).unwrap(); + assert_eq!(live_copies(&other, &copies).await, both); + assert_eq!(live_copies(&base.join("missing"), &copies).await, both); + let mut global = both.clone(); + LiveStoreEntries::new(None) + .retain_live_copies([&mut global]) + .await; + assert_eq!(global, both); + + // Directories that cannot be read (not as root, which reads them + // all the same): one below the project, and one that the target + // of a link lies behind. That target is a file outside the + // project, which keeps every entry by itself on a machine with a + // `node_modules` above the temp dir. + let mut locked_dirs = vec![( + "an unreadable directory below the project", + "ws/app/dist/private", + None, + )]; + let temp = std::fs::canonicalize(std::env::temp_dir()).unwrap(); + let home = crate::utils::repo_root::home(); + let above_temp = + node_modules_above_sync(&temp.join("x/file"), home.as_deref(), &mut HashSet::new()); + if above_temp == Some(false) { + locked_dirs.push(( + "a link whose target lies behind an unreadable directory", + "locked", + Some(("locked/file", "ws/app/vendor/x")), + )); + } + for (case, locked, link) in locked_dirs { + let (_tmp, base, root) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&root); + let locked = base.join(locked); + std::fs::create_dir_all(&locked).unwrap(); + std::fs::write(locked.join("file"), "").unwrap(); + if let Some((target, link)) = link { + std::fs::write(base.join(target), "").unwrap(); + abs_link(&base.join(target), &base.join(link)); + } + assert_eq!( + live_copies(&root, &[&stale, &routed]).await, + vec![routed.clone()], + "{case}: while it can be read" + ); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap(); + let unreadable = std::fs::read_dir(&locked).is_err(); + let kept = live_copies(&root, &[&stale, &routed]).await; + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); + if unreadable { + assert_eq!(kept, vec![stale, routed], "{case}"); + } + } + } + + /// #2353: a `node_modules` that is a link to another checkout's (a git + /// worktree that shares the main checkout's install) belongs to a + /// project elsewhere. Its store is in neither the scanned worktree nor + /// a directory that holds it, so every entry is kept there, and the + /// leftover that only the worktree's member links stays a copy. From + /// the main checkout, which the worktree is no part of, nothing links + /// the leftover. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_of_another_checkout_keeps_every_entry() { + let (_tmp, base, main) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&main); + // The worktree: the main checkout's install, its own member links. + let worktree = base.join("ws/worktree"); + write_pkg(&worktree.join("packages/a"), "a", "1.0.0"); + rel_link("../app/node_modules", &worktree.join("node_modules")); + rel_link( + "../../../node_modules/.pnpm/minimist@1.2.2/node_modules/minimist", + &worktree.join("packages/a/node_modules/minimist"), + ); + let copies: [&PathBuf; 2] = [&stale, &routed]; + let both = vec![stale.clone(), routed.clone()]; + + assert_eq!(live_copies(&main, &copies).await, vec![routed.clone()]); + assert_eq!(live_copies(&worktree, &copies).await, both); + assert_eq!( + live_copies(&worktree.join("packages/a"), &copies).await, + both + ); + } + + /// #2353: pnpm links directories with junctions on Windows, which the + /// sweep does not read, so nothing is left out there. + #[cfg(windows)] + #[tokio::test] + async fn test_pnpm_store_leftovers_are_kept_on_windows() { + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, stale, routed) = pnpm_hosted_route_leftover(&root); + assert_eq!( + live_copies(&root, &[&nm.join("minimist"), &stale, &routed]).await, + vec![nm.join("minimist"), stale, routed] + ); + } + + /// #599: Bun never prunes `.bun`. After an in-place `bun install` that + /// rewires packages to hosted tarballs (or bumps a version), the old + /// `@` entries stay on disk with nothing linking to + /// them, while the importers, the `.bun/node_modules` hoist links and + /// the dependents' entries all point at the new entries (the layout + /// real Bun 1.3.14 / 1.4.2 writes). An orphan is no installed copy, so + /// the scan and the live-copy filter `vex` uses skip it. The resolver + /// and the peer-variant finder keep it: rollback must restore a patched + /// orphan, which a later install that resolves back re-links as is. + /// + /// A live entry linked only from a workspace member (an unhoisted + /// second version) stays live wherever the member sits: under a dir + /// the workspace walk skips (`vendor/`), under a hidden dir listed only + /// by `bun.lock`'s `workspaces`, or under `packages/`. + #[tokio::test] + async fn test_bun_isolated_store_orphaned_entries_are_not_live_copies() { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let nm = root.join("node_modules"); + let store = nm.join(".bun"); + let hoist = store.join("node_modules"); + std::fs::write( + root.join("package.json"), + r#"{"name":"app","workspaces":["packages/*","vendor/*"]}"#, + ) + .unwrap(); + std::fs::write( + root.join("bun.lock"), + "{\n \"lockfileVersion\": 1,\n \"workspaces\": {\n \"\": {\n \ + \"name\": \"app\",\n },\n \".internal/c\": {\n \"name\": \"c\",\n \ + },\n },\n \"packages\": {\n }\n}\n", + ) + .unwrap(); + let member_a = root.join("packages/a/node_modules"); + let member_b = root.join("vendor/b/node_modules"); + let member_c = root.join(".internal/c/node_modules"); + for dir in [&hoist.join("@s"), &member_a, &member_b, &member_c] { + std::fs::create_dir_all(dir).unwrap(); + } + + // Live: the hosted rewires, and three left-pad versions (1.3.0 + // hoisted, 1.2.0 and 1.0.0 each linked only from one member). + let odd = store.join("is-odd@http+++127.0.0.1+is-odd.tgz/node_modules"); + write_pkg(&odd.join("is-odd"), "is-odd", "3.0.1"); + let number = store.join("is-number@http+++127.0.0.1+is-number.tgz/node_modules/is-number"); + write_pkg(&number, "is-number", "6.0.0"); + link_dir(&number, &odd.join("is-number")); + let pad = store.join("left-pad@1.3.0/node_modules/left-pad"); + write_pkg(&pad, "left-pad", "1.3.0"); + let vendor_pad = store.join("left-pad@1.2.0/node_modules/left-pad"); + write_pkg(&vendor_pad, "left-pad", "1.2.0"); + let hidden_pad = store.join("left-pad@1.0.0/node_modules/left-pad"); + write_pkg(&hidden_pad, "left-pad", "1.0.0"); + link_dir(&odd.join("is-odd"), &nm.join("is-odd")); + link_dir(&odd.join("is-odd"), &hoist.join("is-odd")); + link_dir(&number, &hoist.join("is-number")); + link_dir(&pad, &hoist.join("left-pad")); + link_dir(&number, &member_a.join("is-number")); + link_dir(&pad, &member_a.join("left-pad")); + link_dir(&vendor_pad, &member_b.join("left-pad")); + link_dir(&hidden_pad, &member_c.join("left-pad")); + let frame = store.join("@s+frame@http+++127.0.0.1+frame.tgz/node_modules/@s/frame"); + write_pkg(&frame, "@s/frame", "7.0.0"); + link_dir(&frame, &hoist.join("@s/frame")); + + // Orphans: the pre-rewire registry entries (still linked to each + // other) and a churned-away version. + let stale_odd = store.join("is-odd@3.0.1/node_modules"); + write_pkg(&stale_odd.join("is-odd"), "is-odd", "3.0.1"); + let stale_number = store.join("is-number@6.0.0/node_modules/is-number"); + write_pkg(&stale_number, "is-number", "6.0.0"); + link_dir(&stale_number, &stale_odd.join("is-number")); + let stale_frame = store.join("@s+frame@7.0.0/node_modules/@s/frame"); + write_pkg(&stale_frame, "@s/frame", "7.0.0"); + let churned = store.join("left-pad@1.1.0/node_modules/left-pad"); write_pkg(&churned, "left-pad", "1.1.0"); let scanned = scan_paths(&root).await; @@ -7917,7 +10072,9 @@ mod tests { stale_odd.join("is-odd"), ]; let mut other = vec![pad.clone(), churned.clone()]; - retain_live_store_copies([&mut copies, &mut other]).await; + LiveStoreEntries::new(None) + .retain_live_copies([&mut copies, &mut other]) + .await; assert_eq!( copies, vec![ @@ -7957,7 +10114,9 @@ mod tests { "{scanned:?}" ); let mut copies = vec![pad.clone(), member_pad.clone()]; - retain_live_store_copies([&mut copies]).await; + LiveStoreEntries::new(None) + .retain_live_copies([&mut copies]) + .await; assert_eq!(copies, vec![pad, member_pad]); } @@ -7992,7 +10151,9 @@ mod tests { link_dir(&member_pad, &member_nm.join("left-pad")); let mut copies = vec![pad.clone(), member_pad.clone(), churned]; - retain_live_store_copies([&mut copies]).await; + LiveStoreEntries::new(None) + .retain_live_copies([&mut copies]) + .await; assert_eq!(copies, vec![pad, member_pad]); } @@ -8027,7 +10188,9 @@ mod tests { "{scanned:?}" ); let mut copies = vec![pad.clone(), lp]; - retain_live_store_copies([&mut copies]).await; + LiveStoreEntries::new(None) + .retain_live_copies([&mut copies]) + .await; assert_eq!(copies, vec![pad]); } diff --git a/crates/socket-patch-core/src/formats/pnpm/modules_yaml.rs b/crates/socket-patch-core/src/formats/pnpm/modules_yaml.rs index 8047cefc0d..8baa1a4065 100644 --- a/crates/socket-patch-core/src/formats/pnpm/modules_yaml.rs +++ b/crates/socket-patch-core/src/formats/pnpm/modules_yaml.rs @@ -17,10 +17,150 @@ pub(crate) fn field(text: &str, key: &str) -> Option { super::workspace::top_level_scalar(text, key) } +/// The fields of a `.modules.yaml` that say how the install is laid out +/// on disk. +#[derive(Debug, Default, serde::Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub(crate) struct Layout { + layout_version: Option, + node_linker: Option, + /// pnpm <= 4's spelling of a `publicHoistPattern` of `*`. + shamefully_hoist: Option, + public_hoist_pattern: Option>, + /// The virtual store, relative to `node_modules` (absolute on old + /// pnpm). + pub(crate) virtual_store_dir: Option, +} + +/// The `layoutVersion` pnpm 6 to 12 record: a flat virtual store of +/// `/node_modules/` dirs. +const FLAT_STORE_LAYOUT_VERSION: u64 = 5; + +impl Layout { + /// Read a record, JSON or YAML; `None` when it parses as neither, or + /// a field holds a value that is not of its type. + pub(crate) fn parse(text: &str) -> Option { + let text = strip_bom(text); + serde_json::from_str(text) + .ok() + .or_else(|| serde_saphyr::from_str(text).ok()) + } + + /// Whether the install is one of pnpm's isolated linker over a flat + /// virtual store, without `shamefully-hoist`: every package is then a + /// dir of a store entry, reached through links alone. A record of + /// another linker (`hoisted`, `pnp`), of another store layout or of a + /// `publicHoistPattern` of `*` is not. + pub(crate) fn is_isolated(&self) -> bool { + self.layout_version == Some(FLAT_STORE_LAYOUT_VERSION) + && self + .node_linker + .as_deref() + .is_none_or(|linker| linker == "isolated") + && self.shamefully_hoist != Some(true) + && !self + .public_hoist_pattern + .iter() + .flatten() + .any(|pattern| pattern == "*") + } +} + #[cfg(test)] mod tests { use super::*; + /// The records pnpm 12.25.1 (JSON) and pnpm 9.15.9 (YAML) write for a + /// default install, the paths shortened. + const PNPM_12_RECORD: &str = r#"{ + "hoistedDependencies": {}, + "hoistPattern": [ + "*" + ], + "included": { + "dependencies": true, + "devDependencies": true, + "optionalDependencies": true + }, + "layoutVersion": 5, + "nodeLinker": "isolated", + "packageManager": "pnpm@12.25.1", + "pendingBuilds": [], + "prunedAt": "Tue, 01 Dec 2026 14:46:07 GMT", + "publicHoistPattern": [], + "skipped": [], + "storeDir": "/home/dev/.local/share/pnpm/store/v11", + "virtualStoreDir": ".pnpm", + "virtualStoreDirMaxLength": 120, + "allowBuilds": {} +}"#; + const PNPM_9_RECORD: &str = "hoistPattern:\n - '*'\nhoistedDependencies: {}\nincluded:\n \ + dependencies: true\n devDependencies: true\n optionalDependencies: true\n\ + injectedDeps: {}\nlayoutVersion: 5\nnodeLinker: isolated\npackageManager: pnpm@9.15.9\n\ + pendingBuilds: []\nprunedAt: Tue, 01 Dec 2026 14:59:43 GMT\npublicHoistPattern:\n \ + - '*eslint*'\n - '*prettier*'\nregistries:\n default: https://registry.npmjs.org/\n\ + skipped: []\nstoreDir: /home/dev/.local/share/pnpm/store/v3\nvirtualStoreDir: .pnpm\n\ + virtualStoreDirMaxLength: 120\n"; + + #[test] + fn layout_reads_the_isolated_linker_of_json_and_yaml_records() { + for record in [PNPM_12_RECORD, PNPM_9_RECORD] { + let layout = Layout::parse(record).unwrap(); + assert!(layout.is_isolated(), "{record}"); + assert_eq!(layout.virtual_store_dir.as_deref(), Some(".pnpm")); + } + // pnpm 6 records no linker: it has the isolated one alone. + let pnpm_6 = PNPM_9_RECORD.replace("nodeLinker: isolated\n", ""); + assert!(Layout::parse(&pnpm_6).unwrap().is_isolated()); + } + + #[test] + fn layout_is_not_isolated_for_another_linker_layout_or_public_hoist() { + for (from, to) in [ + ("nodeLinker: isolated", "nodeLinker: hoisted"), + ("nodeLinker: isolated", "nodeLinker: pnp"), + ("layoutVersion: 5", "layoutVersion: 4"), + ("layoutVersion: 5\n", ""), + (" - '*eslint*'\n", " - '*'\n"), + ( + "layoutVersion: 5", + "layoutVersion: 5\nshamefullyHoist: true", + ), + ] { + let record = PNPM_9_RECORD.replace(from, to); + assert_ne!(record, PNPM_9_RECORD, "{from}"); + assert!(!Layout::parse(&record).unwrap().is_isolated(), "{record}"); + } + for (from, to) in [ + (r#""nodeLinker": "isolated""#, r#""nodeLinker": "hoisted""#), + ( + r#""publicHoistPattern": []"#, + r#""publicHoistPattern": ["*"]"#, + ), + ] { + let record = PNPM_12_RECORD.replace(from, to); + assert_ne!(record, PNPM_12_RECORD, "{from}"); + assert!(!Layout::parse(&record).unwrap().is_isolated(), "{record}"); + } + } + + #[test] + fn layout_of_an_unreadable_record_is_never_isolated() { + for record in [ + "", + "{ not json", + "- a\n- list\n", + r#"{"layoutVersion": [5], "nodeLinker": "isolated"}"#, + "layoutVersion: five\nnodeLinker: isolated\n", + "publicHoistPattern: '*'\nlayoutVersion: 5\n", + ] { + assert!( + !Layout::parse(record).is_some_and(|layout| layout.is_isolated()), + "{record:?}" + ); + } + } + #[test] fn reads_json_and_yaml_records_alike() { for text in [ diff --git a/crates/socket-patch-core/src/formats/pnpm/workspace.rs b/crates/socket-patch-core/src/formats/pnpm/workspace.rs index cfd43e4485..2ebfe889d1 100644 --- a/crates/socket-patch-core/src/formats/pnpm/workspace.rs +++ b/crates/socket-patch-core/src/formats/pnpm/workspace.rs @@ -246,6 +246,72 @@ pub(crate) fn lock_text_member_importers(text: &str) -> Vec { members } +/// The importers besides the root `.` that a pnpm lock names, for a caller +/// that must not miss one: `None` when an `importers` section is not laid +/// out the way pnpm writes it, so that a key may be misread. pnpm writes +/// the section as a block, its keys at two spaces, plain or in quotes +/// (`'@apps/web':`), up to the next top-level key; a key that holds an +/// escape, a flow mapping, any other indentation and a section that a +/// line at column 0 which is no such key cuts short (a merge conflict +/// marker) are not read. Every document counts (the env document of pnpm +/// 11 and later names the root alone), and a lock without the section, +/// which pnpm 6 to 8 write for a project that is no workspace, names no +/// member. +pub(crate) fn lock_text_member_importers_exact(text: &str) -> Option> { + let mut members = Vec::new(); + for (span, _) in super::grammar::documents(text) { + // Inside an `importers` section, and whether its first key is + // still to come. + let (mut in_importers, mut first) = (false, false); + for line in strip_bom(&text[span]).split('\n') { + let line = line.strip_suffix('\r').unwrap_or(line); + let content = line.trim_start_matches(' '); + if content.is_empty() || content.starts_with('#') { + continue; + } + let indent = line.len() - content.len(); + if content.starts_with('\t') { + if in_importers { + return None; + } + } else if indent == 0 { + // pnpm's top-level keys are plain words; anything else at + // column 0 is no end of the section pnpm wrote. + let key = top_level_key(line) + .filter(|(key, _)| key.bytes().all(|b| b.is_ascii_alphanumeric())); + if in_importers && key.is_none() { + return None; + } + in_importers = false; + if let Some((key, value)) = key { + if key == "importers" { + match value { + "" => (in_importers, first) = (true, true), + "{}" => {} + _ => return None, + } + } + } + } else if in_importers { + if indent < 2 || (first && indent != 2) { + return None; + } + first = false; + if indent == 2 { + let (key, written, _) = super::lines::parse_key_line(line, 2)?; + if written.starts_with('"') && key.contains('\\') { + return None; + } + if key != "." { + members.push(key.to_string()); + } + } + } + } + } + Some(members) +} + /// Insert `block` at line `at` of `lines` (a file split at `\n`), ending /// its lines as the file ends its own (`eol`, the file's /// [`terminator`](crate::utils::line_endings::terminator)): in a CRLF file @@ -741,6 +807,82 @@ mod tests { ); } + /// The exact reader names every member pnpm writes, quoted keys + /// included, and answers `None` for a section it may misread. + #[test] + fn exact_member_importers_refuse_a_section_they_may_misread() { + let lock = |importers: &str| { + format!( + "lockfileVersion: '9.0'\n\nimporters:\n{importers}\npackages:\n\n \ + a@1.0.0:\n resolution: {{}}\n" + ) + }; + let exact = |importers: &str| lock_text_member_importers_exact(&lock(importers)); + let named = |members: &[&str]| Some(members.iter().map(|m| m.to_string()).collect()); + assert_eq!( + exact( + "\n .:\n dependencies:\n a:\n specifier: 1.0.0\n\n \ + apps/web: {}\n\n '@apps/web':\n dependencies: {}\n\n \ + \"@apps/api\": {}\n # apps/old: {}\n# kept\n ../shared: {}\n" + ), + named(&["apps/web", "@apps/web", "@apps/api", "../shared"]) + ); + // CRLF, the env document of pnpm 11 and later, and no section. + assert_eq!( + lock_text_member_importers_exact( + "---\nlockfileVersion: '9.0'\r\nimporters:\r\n .:\r\n \ + configDependencies: {}\r\n---\nlockfileVersion: '9.0'\r\nimporters:\r\n \ + '.': {}\r\n 'packages/a': {}\r\n" + ), + named(&["packages/a"]) + ); + assert_eq!( + lock_text_member_importers_exact("lockfileVersion: '6.0'\n\ndependencies: {}\n"), + named(&[]) + ); + assert_eq!( + lock_text_member_importers_exact("lockfileVersion: '9.0'\nimporters: {}\n"), + named(&[]) + ); + for misread in [ + // An escape in a quoted key. + "\n 'it''s': {}\n", + "\n \"a\\\\b\": {}\n", + "\n \"a\\\"b\": {}\n", + // Keys at another indentation. + "\n .: {}\n packages/a: {}\n", + "\n .: {}\n", + "\n .: {}\n packages/a: {}\n", + "\n\t.: {}\n", + // A line that is no key. + "\n .: {}\n ? complex\n", + "\n - .\n", + // A line at column 0 that is no top-level key: the markers + // of a merge conflict, which would cut the section short. + "\n .: {}\n<<<<<<< HEAD\n packages/a: {}\n=======\n packages/b: {}\n>>>>>>> theirs\n", + "\n .: {}\n=======\n packages/b: {}\n", + "\n .: {}\n>>>>>>> theirs: with a colon\n packages/b: {}\n", + "\n .: {}\n...\n", + ] { + assert_eq!(exact(misread), None, "{misread:?}"); + } + // Outside the section such a line cuts nothing short. + assert_eq!( + lock_text_member_importers_exact( + "<<<<<<< HEAD\nlockfileVersion: '9.0'\n\nimporters:\n\n .: {}\n\n \ + packages/a: {}\n\npackages:\n\n a@1.0.0:\n resolution: {}\n" + ), + named(&["packages/a"]) + ); + // A flow mapping. + assert_eq!( + lock_text_member_importers_exact( + "lockfileVersion: '9.0'\nimporters: {.: {}, packages/a: {}}\n" + ), + None + ); + } + /// #1952: a commented-out importer is not a member, a column-0 comment /// does not end `importers:`, and the env document's importers never /// count; the line and text forms agree. diff --git a/docs/ecosystems.md b/docs/ecosystems.md index cd0c19270f..3e4c6ea4a1 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -844,7 +844,128 @@ while after `pnpm remove` or an upgrade (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). Scans skip such an entry when the current lockfile pnpm writes in the store (`node_modules/.pnpm/lock.yaml`) no longer lists its package, so a vendored scan does not fail on a package -the install dropped. `rollback` still reaches it. A recorded virtual store outside the project is not +the install dropped. `rollback` still reaches it. + +pnpm keeps an entry the same way when an install takes a package from +another source under the same name and version. The `pnpm install` that a +scan asks for, run over an existing `node_modules`, links the project to a +new entry: `node_modules/.pnpm/@socket-+` after a +hosted scan that routes the release through the registry of its patch +(pnpm 11.20 and later), `@file+…` after a vendored scan (`file+…` +on pnpm 8 and earlier). The upstream `@` entry stays in the +store with nothing linking to it. `vex` and `apply --check` judge the +copies the install loads, so they leave that entry out, as they leave out +an unlinked entry of Bun's store, which Bun never prunes. + +For pnpm the rule is narrow: + +- It applies to a package version only when its copies sit in two or more + entries of one store and do not hold the same bytes in each, which is + what such an install leaves. A version that sits in one entry is judged + as before, whether or not anything links it (a removed package, an + upgraded-away version). So are copies that hold the same bytes, file + for file, as the peer variants of a package do: leaving one of them out + would change no verdict. The project is not read for either. Copies of + more than 64 MB or 50,000 files are not compared, and count as holding + other bytes. +- For a version in two entries, every symbolic link below one directory + is read: the scanned directory, or the project that holds the store's + `node_modules` when the scan started inside it (a run from a workspace + member reads the whole project). No directory is skipped by name, so a + link in `vendor/`, `dist/`, a hidden directory, a package's own + `node_modules` or a directory that left the workspace counts. A link is + resolved, never followed. Nothing above that directory is read: pnpm + writes no link there into a store below it. +- An entry is judged when a link that sits outside the store's entries + resolves into it (into its package, a file of it, or the entry itself), + or when a link inside a judged entry does. The store's hoist directory, + `node_modules/.pnpm/node_modules`, is outside the entries. The entries + left out are those that only other left-out entries link. +- An entry is left out only beside a judged entry of the same version. + When none of a version's entries is linked, all of them are judged as + before. + +Entries that only link each other do occur. When the patched package is a +peer dependency of another package, a hosted scan gives the dependent a new entry as well +(`_@socket-+`), and the dependent's old +entry keeps its link to the old `@` entry (measured on pnpm +11.29.0 and 12.25.1). Nothing outside the two links either, so both are +left out. A vendored scan keeps the dependent's entry and points its link +at the new one. + +A copy in a judged entry is always hashed, whatever the entry is named: an +unpatched one still omits the patch (`not_applied`) or warns +(`vendored_tree_out_of_sync`). So is a copy that sits in the store but in +none of its entries (a package that is a real directory of the hoist +directory). + +Only links are read. A file that spells out the path of a store entry is +not, and neither is `NODE_PATH`. pnpm writes such a path into the +launchers of a package's commands (`node_modules/.bin`), and the install +that changes the entry rewrites them: after it, no file outside the +left-out entries names one of them (measured on pnpm 11.29.0 and 12.25.1, +hosted and vendored, for a patched package that ships a command and has a +dependent). + +Wherever a link into an entry may have gone unread, every entry is +judged, as before: + +- on Windows, where pnpm links directories with junctions; +- when the scanned directory neither holds the store's project nor lies + inside it: a `--global` run, or a `node_modules` that is a link to + another checkout's (a git worktree that shares an install); +- when the project that holds the store lies above the git checkout the + run started in: a project run reads no project file outside its + checkout; +- when the install record (`node_modules/.modules.yaml`) is missing or + unreadable, or records `node-linker=hoisted` or `pnp`, `shamefully-hoist` + (a `publicHoistPattern` of `*`), a store layout other than the one pnpm + 6 to 12 write, or another virtual store (`virtualStoreDir`); +- when the lockfile pnpm writes in the store + (`node_modules/.pnpm/lock.yaml`) is missing or unreadable, + `pnpm-lock.yaml` is unreadable, or either one does not list its + importers the way pnpm writes them (a merge conflict left in the file, + for one); +- when an importer that either lockfile names is not a directory inside + the project that holds the store: one outside it (`../shared`, an + absolute path, a link that leads out), one that is not on disk (a + checkout of part of a workspace), or a file. pnpm links each importer's + dependencies below the importer, so such links would not be read. A + `modulesDir` of more than one level falls under this too: pnpm 10.12 + and later put the store in `/.pnpm` and each member's links + in `/`, so no member is below the directory that + holds the store; +- when a directory below the one that is read, the type of one of its + children or the target of a link cannot be read, or it holds more than + 500,000 directories and links. A link that leads nowhere is left out: + its target is not there, it loops, or its path passes through a file; +- when a link resolves to a directory outside the one that is read: what + the `node_modules` of that directory links is not read. A `link:` + dependency on another checkout is such a link, and so is a + convenience link to a build tool's output elsewhere on the disk. A + link to a file outside counts the same way when a directory above the + file holds a `node_modules`: node loads the file from where it is, + with the packages it finds there, and a member that left the + workspace keeps the links pnpm wrote for it. The home directory and + what lies above it are not looked at for this, so a link to an + interpreter under the home directory (a virtualenv's `python`) and a + stray `~/node_modules` change nothing; +- when a link resolves to the store itself, or into it by a path that + names none of its entries: the store's own path spelled another way (macOS reaches a + volume under `/System/Volumes/Data` as well, and a file system that + folds case need not give one spelling back), or a child of the store + that is not one of the entries it lists (a name in another case, on a + file system that folds case); +- when no link resolves into any entry at all. + +In such a layout the leftover entry reads as an unpatched copy until it is +gone. `pnpm prune` removes it (measured on pnpm 11.29.0 and 12.25.1), and +an install into a clean `node_modules` never writes it. + +`rollback` and `remove` restore an unlinked entry too: a later install +that resolves back to it links it as it is. + +A recorded virtual store outside the project is not listed: other projects on the machine load the same files, so patching it in place would patch them as well. For pnpm's global virtual store (`enableGlobalVirtualStore`, `/v/links` under the pnpm store diff --git a/docs/testing/pnpm-compatibility.md b/docs/testing/pnpm-compatibility.md index d11deb9c47..decfab2f41 100644 --- a/docs/testing/pnpm-compatibility.md +++ b/docs/testing/pnpm-compatibility.md @@ -257,6 +257,11 @@ project with a peer-dependent package and a transitive leaf, both patched, each leg checks that `pnpm install --lockfile-only` leaves the scan's lock byte for byte; that a fresh checkout frozen-installs the patched bytes from an empty store with no flags, asking each patch's own registry for its package; +that the `pnpm install` the scan asks for, run over a `node_modules` that +holds the upstream packages, links the patched entries and keeps the upstream +ones in the store, where `vex` attests both patches from the linked copies and +refuses a linked copy that is put back on the upstream bytes (see "The install +over an existing `node_modules`" below; not on Windows); that `pnpm add`, `pnpm update`, `pnpm dedupe` and `pnpm install --fix-lockfile` keep both packages routed and patched; and that after each cleanup (a @@ -341,6 +346,77 @@ neither mode creates the file when every pnpm pin of the project (the setting from it. With no pin, or any pin that may be a later pnpm, the file is created as before. +### The install over an existing `node_modules` + +On the registry route, and in vendored mode on every pnpm, the patched +release has another lock key than the upstream one, so pnpm installs it as +another entry of its virtual store. Measured with pnpm 12.25.1 and 11.29.0 +(both modes) and 10.34.9, 9.15.9 and 8.15.9 (vendored): `pnpm install` over a +`node_modules` that holds the upstream package links the project (the +importer, the hoist directory, each dependent's entry) to +`node_modules/.pnpm/@socket-+` or `@file+…` (`file+…` +on pnpm 8), and leaves `node_modules/.pnpm/@` in the store with the upstream +bytes and nothing linking to it. pnpm 7–11 remove such an entry after 7 days, +pnpm 12 on `pnpm prune`. With `trustLockfile` the lock key stays, and pnpm +keeps the one entry. + +When the patched package is a peer dependency of another package, the +registry route gives the dependent a new entry as well +(`_@socket-+`), and the dependent's old entry +keeps its link to the old `@` entry (pnpm 11.29.0 and +12.25.1). Vendored mode keeps the dependent's entry and points its link at +the new one (pnpm 8.15.9, 9.15.9, 10.34.9 and 12.25.1). + +pnpm writes the path of a store entry into `.bin` launchers: 12.25.1 into +each one, 11.29.0 into those inside a dependent's own `node_modules` (the +importer's and the hoist directory's go through the package link beside +them, as on pnpm 8.15.9, 9.15.9 and 10.34.9). The install rewrites them. +Measured with a patched package that ships a command and has a dependent +(`json5@1.0.1`), in a single project and a workspace, hosted and vendored, +on 11.29.0 and 12.25.1: after the install the only file that names the +upstream entry's directory is the launcher inside that entry itself. + +`vex` and `apply --check` judge the copies the install links. For a package +version that sits in two entries of one store with other bytes in each +they read every link below the scanned directory, and leave out an entry that no path from outside +the store's entries leads into (see "npm: which `node_modules` trees are +crawled" in [ecosystems](../ecosystems.md) for the rule and for the layouts +where every entry is still judged, Windows among them). There the upstream +entry reads as an unpatched copy until it is gone: `vex` omits a hosted +patch as `not_applied`, or warns `vendored_tree_out_of_sync` for a vendored +one. `pnpm prune` removes the entry at once (measured on 11.29.0 and +12.25.1, on the registry route), and a clean `node_modules` has no such +entry. + +One such layout is a workspace with a `modulesDir` of more than one level. +Measured with `modulesDir: sub/node_modules`: pnpm 10.12.1, 10.34.9, 11.29.0 +and 12.25.1 put the virtual store in `sub/node_modules/.pnpm` and each +member's links in `/sub/node_modules`; pnpm 9.15.9 and 10.11.1 put +the links and the install record there too, but keep the virtual store in +`node_modules/.pnpm`. Either way every entry is judged, so the upstream +entry refuses the patch until it is gone. + +The registry-route legs above and the vendored capstone +(`e2e_vendor_pnpm_build`, on each pnpm of its matrix from 9 up) run that +install in a second checkout and end in `vex`, with the linked copy patched +and then put back on the upstream bytes; the capstone also links the +upstream entry from `vendor/`, which brings the warning back. Two more +registry-route legs run the install in a workspace whose patched package is +hoisted and is also the peer dependency of a tarball package +(`*_in_place_install_is_judged_by_every_link`, +`*_in_place_install_under_a_nested_modules_dir`; not on Windows): `vex` +attests both patches; a link to the upstream entry from `vendor/`, `dist/`, +a hidden directory or a package's own `node_modules` refuses the patch +until the link is gone; and under the nested `modulesDir` the patches stay +refused. Where `vex` attests, a second reading of the links +(`tests/common/pnpm_links.rs`, which shares no code with the CLI) checks +that no path from outside the store's entries leads into an entry that +holds the upstream bytes, and where a link was added it must find that +link. Hand-built stores of the same shapes cover the rule offline: +`crawlers::npm_crawler` (`test_pnpm_store_*`, `test_links_below_*`), +`e2e_vex_redirect`, `e2e_vex_vendor`, the `apply --check` suite and the +`rollback` suite, which restores an unlinked entry. + ## Run locally ```sh