diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 9ac66ac81..89b59f08e 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -430,7 +430,7 @@ The route is taken only when **all** of these hold; otherwise the run takes the **pnpm per-member locks (#492)**: a workspace whose root `pnpm-workspace.yaml` sets `sharedWorkspaceLockfile: false` (or, when the YAML leaves the key unset, whose root `.npmrc` sets `shared-workspace-lockfile=false`; on disk, when neither file sets it, `pnpm_config_shared_workspace_lockfile` on pnpm 11 and newer, `npm_config_shared_workspace_lockfile` on pnpm 10 and older, either when the major is unknown (#1460, the major as for the `lockfile` setting below); booleans in any letter case, as pnpm's YAML reader takes them) installs each member from the member's own `pnpm-lock.yaml`. Run from the workspace root, hosted mode reads every member lock the `packages:` globs name (quoted `!` negations applied; `node_modules`, `bower_components`, `test` and `tests` trees and symlinked directories skipped) beside the root lock, which may be absent (pnpm 7): each is rewritten like the root lock, a 9.0 member lock engages the `trustLockfile: true` auto-config in the ROOT `pnpm-workspace.yaml` (heal-on-rerun included), and discovery (`list`, `vex`, `rollback`, `remove`) reads the same member locks. A root lock whose `importers:` lists a member is a shared lock, so member locks beside it are stale and never read or attested. When the members' locks cannot be listed or read (no `packages:` key, whose pnpm <= 8 default finds projects in every directory; a `packages:` value that is not a plain list of globs; no member lock and no root lock, or a member lock that exists but is not readable text), every pnpm lock (the root's included) is left untouched and the run warns `redirect_pnpm_member_locks_unresolved` instead of `redirect_pnpm_no_lockfile`; no pnpm pin is confirmed. The lockfile inventory reads the same member locks, so their dependencies are discovered without an installed tree. The in-memory engine gives the same result as a disk run from the workspace root: a directory whose `pnpm-lock.yaml` has no `pnpm-workspace.yaml` beside it is a workspace member, never a root of its own, when (with `npm` among the `ecosystems`) the nearest ancestor `pnpm-workspace.yaml` is readable and its `packages:` globs (read as above, no braces, classes or extglobs) list it, it holds a `package.json` / `package.yaml` / `package.json5`, the workspace root installs it from its own lock (`sharedWorkspaceLockfile: false` with the member list resolved) or from a root lock beside which its lock is a stale leftover, and socket.yml admits the workspace root. Its lock is then demoted into that workspace root, which becomes a root even with no lock of its own (pnpm 7), the way a Cargo member's lock is demoted; the member stays a root only when it holds another lock marker, without its pnpm lock. The workspace root then pins (or refuses) its member locks as above, trusts them in its own file, refuses a member's branch lock (#556) and leaves a member lock beside a shared root lock unread. A directory that fails any of those tests keeps its lock as a root of its own (pinned like any root, or refused with `redirect_pnpm_settings_elsewhere` while the trust auto-config is on and the ancestor file may list it). Path selection adds the workspace root above every candidate to `roots`, fetches it, and fetches the member locks, branch locks and manifests below it in every directory holding a package manifest; given those `roots` as `projectRoots`, the session drops a confirmed member named beside its workspace root (unless it holds another lock) and a lockless workspace root that pins no member, so it runs the roots it would detect. A confirmed member named in `projectRoots` without its workspace root is not pinned: its lock is dropped and the run-level `pnpm_member_lock_ignored` warning names the workspace root to scan. -**pnpm with its lockfile off (#1074)**: pnpm's `lockfile` setting off makes pnpm neither read nor write `pnpm-lock.yaml` (nor a member's own lock): it resolves every dependency from the registry, so a hosted pin in a committed lock never installs. Each pnpm major reads the setting from one file: pnpm 11 and newer a top-level `lockfile: false` in the project's `pnpm-workspace.yaml`, pnpm 10 and older `lockfile=false` in its `.npmrc`; when `lockfile` is unset (or not a boolean) pnpm falls back to npm's `package-lock` (`packageLock: false` / `package-lock=false`), which counts the same way. The major is the one `node_modules/.modules.yaml` records, else package.json's `packageManager` pin, else what the root lock's grammar implies (a pre-9 lock or `shrinkwrap.yaml`: pnpm 8 or older; an env lockfile document: pnpm 11 or newer); when none says, either file turning it off counts. Hosted mode also reads the setting from its environment, in the one variable family that major reads (#1460): `pnpm_config_lockfile` / `pnpm_config_package_lock` on pnpm 11 and newer, `npm_config_lockfile` / `npm_config_package_lock` on pnpm 10 and older, either family when the major is unknown (so the `npm_config_package_lock=` that `npx` / `npm exec` export from an npm-era `.npmrc` refuses nothing on pnpm 11+). Only the project's own files are read (a workspace member with no settings file of its own does not inherit its root's). In a pnpm project (a root pnpm lock or a `pnpm-workspace.yaml`), hosted mode then leaves every pnpm lock and `pnpm-workspace.yaml` untouched (no `trustLockfile` key is added), confirms no npm pin from them and warns `redirect_pnpm_lockfile_disabled` (in place of `redirect_pnpm_no_lockfile`), exiting 0 like the per-branch lock refusal below; the detail names the setting, and the remedy is `--mode vendored` when a pnpm lock exists (pnpm applies the `overrides` it wires without a lock), else removing the setting and running `pnpm install`. The check comes before the per-branch lock check. Manifest-less `vex` keeps the hosted references of such a lock but withholds their lockfile basis (see the pnpm row of the discovery table). Rush locks are not affected: Rush runs pnpm with its own settings. Vendored mode is unchanged. `vex` attests a vendored reference of such a lock only while the override map the governing pnpm reads without a lock routes the package (`name@version` or bare `name`) to the same artifact: package.json `pnpm.overrides` when `.npmrc` turns the lock off (pnpm 10 and older; a pinned pnpm 10 also reads the `pnpm-workspace.yaml` map), `pnpm-workspace.yaml` `overrides` when that file does (pnpm 11 and newer never read `pnpm.overrides`), both when both do and no major is known. Otherwise pnpm installs the registry release and the patch is omitted (`vex_lock_not_read`, see **Locks the package manager is told not to read**). +**pnpm with its lockfile off (#1074)**: pnpm's `lockfile` setting off makes pnpm neither read nor write `pnpm-lock.yaml` (nor a member's own lock): it resolves every dependency from the registry, so a hosted pin in a committed lock never installs. Each pnpm major reads the setting from one file: pnpm 11 and newer a top-level `lockfile: false` in the project's `pnpm-workspace.yaml`, pnpm 10 and older `lockfile=false` in its `.npmrc`; when `lockfile` is unset (or not a boolean) pnpm falls back to npm's `package-lock` (`packageLock: false` / `package-lock=false`), which counts the same way. The major is the one `node_modules/.modules.yaml` records, else package.json's `packageManager` pin, else what the root lock's grammar implies (a pre-9 lock or `shrinkwrap.yaml`: pnpm 8 or older; an env lockfile document: pnpm 11 or newer); when none says, either file turning it off counts. Hosted mode also reads the setting from its environment, in the one variable family that major reads (#1460): `pnpm_config_lockfile` / `pnpm_config_package_lock` on pnpm 11 and newer, `npm_config_lockfile` / `npm_config_package_lock` on pnpm 10 and older, either family when the major is unknown (so the `npm_config_package_lock=` that `npx` / `npm exec` export from an npm-era `.npmrc` refuses nothing on pnpm 11+). Only the project's own files are read (a workspace member with no settings file of its own does not inherit its root's). In a pnpm project (a root pnpm lock or a `pnpm-workspace.yaml`), hosted mode then leaves every pnpm lock and `pnpm-workspace.yaml` untouched (no `trustLockfile` key is added), confirms no npm pin from them and warns `redirect_pnpm_lockfile_disabled` (in place of `redirect_pnpm_no_lockfile`), exiting 0 like the per-branch lock refusal below; the detail names the setting, and the remedy is `--mode vendored` when a pnpm lock exists (pnpm applies the `overrides` it wires without a lock), else removing the setting and running `pnpm install`. The check comes before the per-branch lock check. Manifest-less `vex` keeps the hosted references of such a lock but withholds their lockfile basis (see the pnpm row of the discovery table). Rush locks are not affected: Rush runs pnpm with its own settings. Vendored mode is unchanged. `vex` attests a vendored reference of such a lock only while the override map the governing pnpm reads without a lock routes the package (`name@version` or bare `name`) to the same artifact. When `.npmrc` turns the lock off (pnpm 10 and older), the map follows that pnpm's release, as it does with the lock on (#2403): older than 10.5.1, package.json alone (`pnpm.overrides`, over the top-level `resolutions`); 10.5.1 through 10.x, package.json when it declares any override and `pnpm-workspace.yaml` `overrides` when it declares none (an empty table, `null` or an empty array declare none; a package.json that cannot be read counts as declaring). The releases are the one `node_modules/.modules.yaml` records and the one package.json's `packageManager` pins, which pnpm switches to at the next install: when they differ, the override has to be where each of them reads it (`pnpm-workspace.yaml` `overrides` for a pin of pnpm 11 or newer). Only one exact version names a release: pnpm does not switch to a `packageManager` such as `pnpm@10`. When neither names a release of pnpm 10 or older, the override has to be in package.json, where every such pnpm reads it. When `pnpm-workspace.yaml` turns the lock off, the map is its `overrides` (pnpm 11 and newer never read `pnpm.overrides`); both files have to route the package when both turn it off and no major is known. Otherwise pnpm installs the registry release and the patch is omitted (`vex_lock_not_read`, see **Locks the package manager is told not to read**). **pnpm per-branch locks (#556)**: with `gitBranchLockfile` on (a top-level `gitBranchLockfile: true` in the root `pnpm-workspace.yaml`; when the YAML leaves the key unset, `git-branch-lockfile=true` in the root `.npmrc`, as pnpm 10 and older read it; on disk also `pnpm_config_git_branch_lockfile` (pnpm 11 and newer) or `npm_config_git_branch_lockfile` (pnpm 10 and older; either when the major is unknown, read as for the `lockfile` setting above) set to `true`; a workspace member with no `pnpm-workspace.yaml` of its own reads the governing ancestor's file and the `.npmrc` beside it), pnpm installs a git branch from its own `pnpm-lock..yaml` whenever that lock exists, in every directory it installs a lock from: the root, and under `sharedWorkspaceLockfile: false` each member's (#492). When the setting is on AND at least one such `pnpm-lock..yaml` exists (at the root, or in a member that installs from its own lock), hosted mode leaves every root pnpm lock (`pnpm-lock.yaml`, `shrinkwrap.yaml`) and `pnpm-workspace.yaml` untouched (every member lock too), confirms no npm pin from them and warns `redirect_pnpm_git_branch_lockfile` (in place of `redirect_pnpm_no_lockfile` when the branch lock is the only one); the detail names the setting and the branch lock(s), and the remedy is to turn `gitBranchLockfile` off and fold the branch locks into `pnpm-lock.yaml` with `pnpm install --merge-git-branch-lockfiles`, then re-run. A vendored→hosted takeover of a pnpm-vendored purl is refused with the same code (the vendored wiring and ledger stay byte-for-byte). Vendored mode refuses the same projects with `vendor_pnpm_git_branch_lockfile`, before any write and in the pre-flight. The setting with no branch lock (main, or a branch whose dependencies never changed) installs from `pnpm-lock.yaml`, which both modes wire as usual; a stray branch lock with the setting off is ignored. The in-memory engine fetches root `pnpm-lock.*.yaml` names presence-only and refuses the same way. `vex` omits every pin of those pnpm locks (`vex_pnpm_git_branch_lockfile`) whenever such a branch lock exists, whatever the setting says (fail-closed; read from the project's files only, not the environment); see **Unattested references**. diff --git a/crates/socket-patch-cli/tests/e2e_vex_vendor.rs b/crates/socket-patch-cli/tests/e2e_vex_vendor.rs index ba3acf8e5..a43bce781 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_vendor.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_vendor.rs @@ -3133,6 +3133,111 @@ fn vendored_pin_in_a_lock_npm_install_ignores_is_not_attested() { assert_lock_not_read(cwd, purl); } +/// REGRESSION (#2403): with pnpm's lock off the vendored override has to +/// be in the map the project's pnpm release reads. Real pnpm, `.npmrc` +/// `lockfile=false`, the override in `pnpm-workspace.yaml` alone: 10.4.1 +/// and 10.5.0 install the registry release and exit 0, 10.5.1 and 10.28.0 +/// install the artifact, and 10.28.0 installs the registry release once +/// `package.json` declares an override of its own; a tree 10.28.0 +/// installed whose pin moves to 10.4.1 gets the registry release at the +/// next install. `vex` read every pnpm 10 as reading either file and +/// attested the registry rows. +#[test] +fn vendored_pnpm_pin_with_the_lock_off_needs_the_override_its_release_reads() { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path(); + let uuid = "55555555-5555-4555-8555-555555555555"; + let purl = "pkg:npm/foo@1.0.0"; + let rel = write_foo_ledger( + cwd, + uuid, + b"patched foo\n", + &[ + ("pnpm-workspace.yaml", "override"), + ("pnpm-lock.yaml", "lock"), + ], + ); + let manifest = |pnpm: &str, own: &str| { + std::fs::write( + cwd.join("package.json"), + format!( + r#"{{"name":"app","version":"0.1.0","packageManager":"pnpm@{pnpm}","dependencies":{{"foo":"1.0.0"}}{own}}}"# + ), + ) + .unwrap(); + }; + std::fs::write( + cwd.join("pnpm-lock.yaml"), + format!( + "lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n \ + excludeLinksFromLockfile: false\n\noverrides:\n foo@1.0.0: file:{rel}\n\n\ + importers:\n\n .:\n dependencies:\n foo:\n \ + specifier: file:{rel}\n version: file:{rel}\n\npackages:\n\n foo@file:{rel}:\n \ + resolution: {{integrity: sha512-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==, tarball: file:{rel}}}\n \ + version: 1.0.0\n\nsnapshots:\n\n foo@file:{rel}: {{}}\n" + ), + ) + .unwrap(); + std::fs::write( + cwd.join("pnpm-workspace.yaml"), + format!("packages:\n - '.'\noverrides:\n foo@1.0.0: file:{rel}\n"), + ) + .unwrap(); + std::fs::write(cwd.join(".npmrc"), "lockfile=false\n").unwrap(); + let not_read_because = |what: &str| { + assert_lock_not_read(cwd, purl); + let (_, env) = vex_json(cwd, &["--offline"]); + assert!(env.to_string().contains(what), "{what}: {env}"); + }; + + // The releases that read the workspace file. + for pnpm in ["10.5.1", "10.28.0"] { + manifest(pnpm, ""); + assert_vendored_attested(cwd, purl, pnpm); + } + // The ones that read package.json alone. + for pnpm in ["10.4.1", "10.5.0"] { + manifest(pnpm, ""); + not_read_because(&format!( + "(pnpm@{pnpm} (package.json packageManager) reads overrides from package.json alone)" + )); + } + // package.json's own overrides replace the workspace file's. + for own in [ + r#","pnpm":{"overrides":{"is-number":"7.0.0"}}"#, + r#","resolutions":{"is-number":"7.0.0"}"#, + ] { + manifest("10.28.0", own); + not_read_because( + "(pnpm@10.28.0 (package.json packageManager) reads package.json's overrides when it \ + declares any (`pnpm.overrides` or `resolutions`), and pnpm-workspace.yaml \ + `overrides` when it declares none)", + ); + } + // Declared where that pnpm reads it, it attests again. + manifest( + "10.28.0", + &format!(r#","pnpm":{{"overrides":{{"is-number":"7.0.0","foo@1.0.0":"file:{rel}"}}}}"#), + ); + assert_vendored_attested(cwd, purl, "package.json declares it beside its own"); + + // A tree pnpm 10.28.0 installed, whose pin then moves to 10.4.1: the + // next install switches to the pinned release, which reads + // package.json alone (real pnpm: it installs the registry release). + std::fs::create_dir_all(cwd.join("node_modules")).unwrap(); + std::fs::write( + cwd.join("node_modules/.modules.yaml"), + r#"{"packageManager":"pnpm@10.28.0"}"#, + ) + .unwrap(); + manifest("10.28.0", ""); + assert_vendored_attested(cwd, purl, "the record and the pin agree"); + manifest("10.4.1", ""); + not_read_because( + "pnpm@10.4.1 (package.json packageManager) reads overrides from package.json alone", + ); +} + /// A vendored pnpm lock entry with pnpm's lock turned off /// (`lockfile=false` in `.npmrc`): pnpm resolves without the lock, so the /// artifact installs only through an override (real pnpm 10.34.1: the diff --git a/crates/socket-patch-core/src/formats/pnpm/mod.rs b/crates/socket-patch-core/src/formats/pnpm/mod.rs index 98bda4544..483dfd4ea 100644 --- a/crates/socket-patch-core/src/formats/pnpm/mod.rs +++ b/crates/socket-patch-core/src/formats/pnpm/mod.rs @@ -34,7 +34,7 @@ pub(crate) mod registry_alias; mod version; pub(crate) mod workspace; -pub(crate) use version::range_admits; +pub(crate) use version::{governing_override_sources, range_admits}; pub use version::{ matches_file_id_build_keys, pinned_override_sources, registry_route_pins, root_only_workspace_breaks_add, routed_build_keys, OverrideSource, RegistryRoutePins, diff --git a/crates/socket-patch-core/src/formats/pnpm/version.rs b/crates/socket-patch-core/src/formats/pnpm/version.rs index e3fa7ce5e..a821c55af 100644 --- a/crates/socket-patch-core/src/formats/pnpm/version.rs +++ b/crates/socket-patch-core/src/formats/pnpm/version.rs @@ -260,6 +260,40 @@ pub fn pinned_override_sources(package_json: Option<&str>) -> Vec<(OverrideSourc stated } +/// Where each pnpm that governs a project's settings reads its overrides, +/// with its pin as prose: the release that installed the project +/// (`node_modules/.modules.yaml`) and the one package.json's +/// `packageManager` pins, the two the pnpm major is read from +/// (`pinned_pnpm_major`), here at the precision the override maps need. +/// Only one exact version names a release: pnpm writes nothing else into +/// its record, and it does not switch to a `packageManager` such as +/// `pnpm@10` ("not a valid version"; it installs with the pnpm that +/// runs). +/// +/// With the lock off nothing fails when an override is declared where a +/// pnpm does not read it: it installs the registry release and exits 0. +/// pnpm also switches to the `packageManager` release by itself, so a +/// record and a pin that differ are the pnpm that installed the tree and +/// the one that installs it next. Both are returned, for a caller that +/// asks every one of them to read the override, where +/// [`pinned_override_sources`] counts a declaration that any pnpm the +/// commit names reads. +pub(crate) fn governing_override_sources( + package_json: Option<&str>, + modules_yaml: Option<&str>, +) -> Vec<(OverrideSource, String)> { + const GOVERNING: [&str; 2] = ["node_modules/.modules.yaml", "package.json packageManager"]; + pnpm_pins(package_json, modules_yaml) + .into_iter() + .filter(|(source, _)| GOVERNING.contains(source)) + .filter_map(|(source, spec)| { + let (lo, hi) = version_bounds(&spec)?; + let reads = OverrideSource::of((lo, hi)).filter(|_| lo == hi)?; + Some((reads, format!("pnpm@{spec} ({source})"))) + }) + .collect() +} + /// The oldest pnpm hosted mode routes a patched package through a named /// registry for ([`registry_route_pins`]). pub const REGISTRY_ROUTE_FLOOR: (u64, u64) = (11, 20); @@ -660,6 +694,60 @@ mod tests { assert_eq!(pins("{\"packageManager\":\"pnpm@11.0.0\"}"), want); } + /// #2403: the pnpm releases that govern a project's settings are the + /// one that installed it and the `packageManager` pin, and where each + /// reads overrides follows its release. `engines` and `devEngines` + /// name what may install, not what does. + #[test] + fn the_governing_pnpm_releases_are_the_install_record_and_the_pin() { + use OverrideSource::{Manifest, ManifestElseWorkspace, Workspace}; + + let pm = |spec: &str| format!("{{\"packageManager\":\"pnpm@{spec}\"}}"); + let sources = |package_json: Option<&str>, modules_yaml: Option<&str>| { + governing_override_sources(package_json, modules_yaml) + .into_iter() + .map(|(source, _)| source) + .collect::>() + }; + for (spec, want) in [ + ("8.15.9", Manifest), + ("10.5.0", Manifest), + ("10.5.1", ManifestElseWorkspace), + ("10.28.0+sha512.abc", ManifestElseWorkspace), + ("11.0.0", Workspace), + ] { + assert_eq!(sources(Some(&pm(spec)), None), [want], "{spec}"); + assert_eq!(sources(None, Some(&pm(spec))), [want], "record {spec}"); + } + // Both are returned, the record first, each with its pin. + assert_eq!( + governing_override_sources(Some(&pm("10.4.1")), Some(&pm("10.28.0"))), + [ + ( + ManifestElseWorkspace, + "pnpm@10.28.0 (node_modules/.modules.yaml)".to_string() + ), + ( + Manifest, + "pnpm@10.4.1 (package.json packageManager)".to_string() + ), + ] + ); + // Not one exact version (pnpm does not switch to it), another + // tool's pin, a range of pnpm releases, or nothing. + for spec in ["10", "10.4", "^10.6.0", "~10.4.0", "next"] { + assert!(sources(Some(&pm(spec)), None).is_empty(), "{spec}"); + assert_eq!( + sources(Some(&pm(spec)), Some(&pm("10.28.0"))), + [ManifestElseWorkspace], + "{spec} beside a record" + ); + } + assert!(sources(Some(r#"{"packageManager":"yarn@4.5.0"}"#), Some("{}")).is_empty()); + assert!(sources(Some(r#"{"engines":{"pnpm":"10.4.1"}}"#), None).is_empty()); + assert!(sources(None, None).is_empty()); + } + #[test] fn file_id_build_keys_start_at_10_34_2_and_11_5_3() { let pm = |spec: &str| format!("{{\"packageManager\":\"pnpm@{spec}\"}}"); diff --git a/crates/socket-patch-core/src/utils/pnpm_workspace.rs b/crates/socket-patch-core/src/utils/pnpm_workspace.rs index bc3322949..25138738d 100644 --- a/crates/socket-patch-core/src/utils/pnpm_workspace.rs +++ b/crates/socket-patch-core/src/utils/pnpm_workspace.rs @@ -27,6 +27,7 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use crate::formats::pnpm::workspace::read_package_globs; +use crate::formats::pnpm::OverrideSource; use crate::utils::cargo_workspace::{ expand_glob_bounded, DirTree, DiskTree, MemoryTree, MAX_MANIFESTS, }; @@ -950,23 +951,56 @@ async fn lockfile_disabled_in( }) } -/// Which settings files turn pnpm's lock off for the project at `view`, -/// as `(pnpm-workspace.yaml, .npmrc)`, with the pnpm major that decides -/// which one counts ([`lockfile_disabled`]): the YAML file for pnpm 11 and -/// newer, `.npmrc` for pnpm 10 and older, either when no major is known. -/// The same majors read their override map from different places (pnpm 11 -/// from the YAML file alone), which is what VEX discovery asks this for. -pub(crate) async fn lockfile_off_sources(view: &ProjectView<'_>) -> (bool, bool, Option) { +/// Where each pnpm that installs the project at `view` with its lock off +/// reads the overrides it resolves with, each with the pin that names it +/// when one does. VEX discovery asks this: with the lock off, a vendored +/// package installs only through an override that every one of them +/// reads. +/// +/// The pnpm releases the project names come first +/// ([`governing_override_sources`]): the one that installed it and the +/// one `packageManager` switches the next install to. +/// +/// Then the settings file that turns the lock off, which follows the +/// pnpm major ([`lockfile_disabled`]): the YAML file for pnpm 11 and +/// newer, which read [`OverrideSource::Workspace`]; `.npmrc` for pnpm 10 +/// and older, either when no major is known. When no release named +/// above is a pnpm 10 or older, the override has to be in package.json +/// ([`OverrideSource::Manifest`]), where every such pnpm reads it: one +/// from 10.5.1 on reads package.json's overrides in place of the +/// workspace file's once it declares any. +/// +/// [`governing_override_sources`]: crate::formats::pnpm::governing_override_sources +pub(crate) async fn lockfile_off_override_sources( + view: &ProjectView<'_>, +) -> Vec<(OverrideSource, Option)> { let workspace = view.read_text(PNPM_WORKSPACE).await.ok(); let npmrc = view.read_text(".npmrc").await.ok(); let yaml = lockfile_off(|key, _| pnpm_setting(workspace.as_deref(), None, key, key)); let rc = lockfile_off(|_, key| pnpm_setting(None, npmrc.as_deref(), key, key)); - let major = pnpm_major(view).await; - ( - yaml.is_some() && major.is_none_or(|major| major >= 11), - rc.is_some() && major.is_none_or(|major| major <= 10), - major, - ) + let texts = read_texts(view, &[MODULES_YAML, "package.json", PNPM_LOCK]).await; + let major = pnpm_major_from(|rel| texts.get(rel).cloned()); + let mut readers: Vec<(OverrideSource, Option)> = Vec::new(); + let mut add = |source: OverrideSource, pin: Option| { + if readers.iter().all(|(known, _)| *known != source) { + readers.push((source, pin)); + } + }; + let named = crate::formats::pnpm::governing_override_sources( + texts.get("package.json").map(String::as_str), + texts.get(MODULES_YAML).map(String::as_str), + ); + for (source, pin) in named { + add(source, Some(pin)); + } + if yaml.is_some() && major.is_none_or(|major| major >= 11) { + add(OverrideSource::Workspace, None); + } + let pre_11 = |(source, _): &(OverrideSource, _)| *source != OverrideSource::Workspace; + if rc.is_some() && major.is_none_or(|major| major <= 10) && !readers.iter().any(pre_11) { + readers.push((OverrideSource::Manifest, None)); + } + readers } /// Where one settings source turns pnpm's lock off: its `lockfile` when diff --git a/crates/socket-patch-core/src/vex/discover/npm.rs b/crates/socket-patch-core/src/vex/discover/npm.rs index 104686142..9dd08b478 100644 --- a/crates/socket-patch-core/src/vex/discover/npm.rs +++ b/crates/socket-patch-core/src/vex/discover/npm.rs @@ -1434,20 +1434,21 @@ impl PnpmOverrideReader { /// vendored artifacts its override maps route packages to. pnpm applies /// `overrides` while it resolves, with or without a lock, so a vendored /// package still installs from its committed artifact exactly when the map -/// the governing pnpm major reads names it (measured: pnpm 10.34.1 reads -/// package.json `pnpm.overrides` and, with `lockfile=false` in `.npmrc`, -/// the workspace file's `overrides:` too; pnpm 11.27.0 reads the workspace -/// file alone and ignores both `.npmrc`'s `lockfile=false` and -/// `pnpm.overrides`). +/// the governing pnpm reads names it. Which map that is follows the pnpm +/// release, as it does with the lock on ([`OverrideSource`]; measured with +/// `lockfile=false` in `.npmrc` on pnpm 10.4.1, 10.5.0, 10.5.1 and +/// 10.28.0, #2403; pnpm 11.27.0 reads the workspace file alone and +/// ignores both `.npmrc`'s `lockfile=false` and `pnpm.overrides`). struct PnpmLockOff { source: String, maps: PnpmOverrideMaps, - /// The lock is off for pnpm 11+, which reads the workspace map alone. - needs_workspace: bool, - /// The lock is off for pnpm 10 and older, which read `pnpm.overrides`. - needs_manifest: bool, - /// The project pins pnpm 10, which reads the workspace map as well. - pnpm10: bool, + /// Where each pnpm that installs the project with its lock off reads + /// its overrides, with the pin that names it (`pnpm@10.4.1 + /// (package.json packageManager)`) when one does + /// ([`lockfile_off_override_sources`]). + /// + /// [`lockfile_off_override_sources`]: crate::utils::pnpm_workspace::lockfile_off_override_sources + readers: Vec<(OverrideSource, Option)>, } /// The vendored artifacts the two override maps of a pnpm project route @@ -1464,6 +1465,13 @@ struct PnpmOverrideMaps { /// package.json holds text that is not JSON, or overrides that are not /// a table: what it declares cannot be read. manifest_unreadable: bool, + /// pnpm reads package.json as declaring an override, or may: a table + /// with keys as pnpm counts them (a string's characters and an + /// array's items are keys too), or a file that cannot be read. + /// Measured on pnpm 10.28.0 with the lock off: `null`, `[]`, `""`, a + /// number and a boolean declare none, and the workspace file's + /// overrides are read; `"x"` and `["x"]` declare, and they are not. + manifest_may_declare: bool, /// package.json's text and document, for the readers of its pnpm pins /// and of what `vendor` would write. manifest_text: Option, @@ -1513,7 +1521,16 @@ impl PnpmOverrideMaps { .as_deref() .map(crate::vendor::pnpm_lock::override_section_entries) .unwrap_or_default(); + let keyed = |table: &&Value| match table { + Value::Object(entries) => !entries.is_empty(), + Value::String(text) => !text.is_empty(), + Value::Array(items) => !items.is_empty(), + _ => false, + }; PnpmOverrideMaps { + manifest_may_declare: manifest_read.is_err() + || matches!(doc, Some(Err(_))) + || tables.iter().any(keyed), manifest_table: !merged.is_empty(), manifest: vendored(merged.into_iter().collect()), manifest_unreadable: manifest_read.is_err() @@ -1557,14 +1574,10 @@ impl PnpmOverrideMaps { impl PnpmLockOff { async fn read(ctx: &DiscoverCtx<'_>, source: String) -> Self { - let (needs_workspace, needs_manifest, major) = - crate::utils::pnpm_workspace::lockfile_off_sources(&ctx.view).await; PnpmLockOff { source, maps: PnpmOverrideMaps::read(ctx).await, - needs_workspace, - needs_manifest, - pnpm10: major == Some(10), + readers: crate::utils::pnpm_workspace::lockfile_off_override_sources(&ctx.view).await, } } @@ -1585,21 +1598,60 @@ impl PnpmLockOff { }) }; let (manifest, workspace) = (routed(&self.maps.manifest), routed(&self.maps.workspace)); - (!self.needs_workspace || workspace) - && (!self.needs_manifest || manifest || (self.pnpm10 && workspace)) + self.readers + .iter() + .all(|(reader, _)| reader.reads(manifest, workspace, self.maps.manifest_may_declare)) } /// Completes "its pin is in ``, and …" for a ref no override - /// routes. + /// routes: the map that has to route it, and what each pnpm the + /// project names reads. fn unrouted(&self) -> String { - let map = match (self.needs_workspace, self.needs_manifest) { - (true, false) => "pnpm-workspace.yaml `overrides`", - (false, true) => "package.json `pnpm.overrides`", - _ => "package.json `pnpm.overrides` and pnpm-workspace.yaml `overrides`", + use OverrideSource::{Manifest, ManifestElseWorkspace, Unstated, Workspace}; + + let table = format!("{PNPM_MANIFEST} `pnpm.overrides`"); + let block = format!("{PNPM_WORKSPACE} `overrides`"); + let declares = self.maps.manifest_may_declare; + let reads = |source| self.readers.iter().any(|(reader, _)| *reader == source); + // Once package.json routes it, package.json declares an override, + // and a pnpm 10.5.1 through 10.x reads that one too. + let needs_manifest = reads(Manifest) || (declares && reads(ManifestElseWorkspace)); + let needs_workspace = reads(Workspace) || (!needs_manifest && reads(ManifestElseWorkspace)); + let unrouted = match (needs_manifest, needs_workspace) { + (true, true) => format!("{table} and {block} do not both route this package to it"), + (true, false) => format!("{table} does not route this package to it"), + (false, _) if !reads(Workspace) => { + format!("neither {table} nor {block} routes this package to it") + } + (false, _) => format!("{block} does not route this package to it"), + }; + let named: Vec = self + .readers + .iter() + .filter_map(|(reader, pin)| { + let pin = pin.as_deref()?; + Some(match reader { + Manifest => format!("{pin} reads overrides from {PNPM_MANIFEST} alone"), + ManifestElseWorkspace => format!( + "{pin} reads {PNPM_MANIFEST}'s overrides when it declares any \ + (`pnpm.overrides` or `resolutions`), and {block} when it declares none" + ), + Workspace => format!("{pin} reads overrides from {PNPM_WORKSPACE} alone"), + Unstated => return None, + }) + }) + .collect(); + let why = match named.as_slice() { + [] if needs_manifest && !needs_workspace => format!( + " (no install record or `packageManager` pin names a pnpm 10.5.1 through 10.x, \ + the releases that read {block})" + ), + [] => String::new(), + named => format!(" ({})", named.join("; ")), }; format!( "{}; without the lock pnpm installs a vendored artifact only through an override, \ - and {map} does not route this package to it", + and {unrouted}{why}", crate::utils::pnpm_workspace::describe_lockfile_disabled(&self.source) ) } @@ -4948,10 +5000,11 @@ mod tests { } /// With pnpm's lock off, a vendored entry of the unread lock installs - /// only through the override map the governing pnpm major reads - /// (measured: pnpm 10.34.1 applies `pnpm.overrides` or the workspace - /// file's `overrides:` with `lockfile=false`; pnpm 11.27.0 reads the - /// workspace file alone, and ignores `.npmrc`'s `lockfile=false`). An + /// only through the override map the governing pnpm reads (measured: + /// with `lockfile=false`, pnpm 10.34.1 applies `pnpm.overrides`, and + /// the workspace file's `overrides:` while package.json declares + /// none; pnpm 11.27.0 reads the workspace file alone, and ignores + /// `.npmrc`'s `lockfile=false`). An /// entry no such override routes to its artifact is what pnpm replaces /// with the registry release, so it is never attested. #[tokio::test] @@ -5031,7 +5084,8 @@ mod tests { ); assert!(!attested(&run(&p).await), "a dependent-scoped override"); - // A pinned pnpm 10 reads either map with `.npmrc`'s setting. + // A pinned pnpm 10.5.1 or newer reads the workspace map while + // package.json declares no override. let p = project(); p.write( "package.json", @@ -5043,6 +5097,164 @@ mod tests { assert!(attested(&run(&p).await), "pnpm 10, workspace override"); } + /// REGRESSION (#2403): with the lock off, the override has to be in + /// the map the governing pnpm reads, and that follows its release as + /// it does with the lock on ([`OverrideSource`]). Measured with + /// `lockfile=false` in `.npmrc` and the vendored override in + /// pnpm-workspace.yaml alone: pnpm 10.4.1 and 10.5.0 install the + /// registry release and exit 0, 10.5.1 and 10.28.0 install the + /// artifact, and 10.28.0 installs the registry release again once + /// package.json declares an override of its own (`pnpm.overrides` or + /// `resolutions`). Every pnpm 10 was read as reading either map, so + /// the upstream rows were attested. + #[tokio::test] + async fn pnpm_disabled_lockfile_reads_the_map_its_pnpm_10_release_reads() { + let rel = format!(".socket/vendor/npm/{UUID_B}/left-pad-1.3.0.tgz"); + let lock = format!( + "lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies:\n left-pad:\n \ + specifier: file:{rel}\n version: file:{rel}\n\npackages:\n\n \ + left-pad@file:{rel}:\n resolution: {{integrity: {SRI}, tarball: file:{rel}}}\n \ + version: 1.3.0\n" + ); + const PURL: &str = "pkg:npm/left-pad@1.3.0"; + let routed = format!(r#""left-pad@1.3.0":"file:{rel}""#); + let overridden = format!("packages:\n - '.'\noverrides:\n left-pad@1.3.0: file:{rel}\n"); + let (ws, bare) = (overridden.as_str(), "packages:\n - '.'\n"); + const OWN: &str = r#","pnpm":{"overrides":{"is-number":"7.0.0"}}"#; + const OWN_RES: &str = r#","resolutions":{"is-number":"7.0.0"}"#; + const EMPTY: &str = r#","pnpm":{"overrides":{}}"#; + let table = format!(r#","pnpm":{{"overrides":{{{routed}}}}}"#); + let table_own = format!(r#","pnpm":{{"overrides":{{"is-number":"7.0.0",{routed}}}}}"#); + let res = format!(r#","resolutions":{{{routed}}}"#); + const NULL_RES: &str = r#","resolutions":null"#; + const NO_RES: &str = r#","resolutions":[]"#; + const NULL_TABLE: &str = r#","pnpm":{"overrides":null}"#; + const TEXT_TABLE: &str = r#","pnpm":{"overrides":"x"}"#; + // `(packageManager, package.json's own keys, the workspace file, + // the install record, whether pnpm installs the artifact)`. + let rows: [(Option<&str>, &str, &str, Option<&str>, bool); 30] = [ + // pnpm older than 10.5.1 reads package.json alone. + (Some("9.15.9"), "", ws, None, false), + (Some("10.4.1"), "", ws, None, false), + (Some("10.5.0"), "", ws, None, false), + (Some("10.4.1"), &table, bare, None, true), + (Some("10.4.1"), &res, bare, None, true), + // From 10.5.1 the workspace file counts while package.json + // declares no override. + (Some("10.5.1"), "", ws, None, true), + (Some("10.28.0"), "", ws, None, true), + (Some("10.28.0"), EMPTY, ws, None, true), + // A table with no keys declares nothing; a string has keys. + (Some("10.28.0"), NULL_RES, ws, None, true), + (Some("10.28.0"), NO_RES, ws, None, true), + (Some("10.28.0"), NULL_TABLE, ws, None, true), + (Some("10.28.0"), TEXT_TABLE, ws, None, false), + (Some("10.28.0"), OWN, ws, None, false), + (Some("10.28.0"), OWN_RES, ws, None, false), + (Some("10.28.0"), &table_own, ws, None, true), + (Some("10.28.0"), &table, bare, None, true), + // With no pin, the pnpm that installed the checkout says. + (None, "", ws, Some("10.4.1"), false), + (None, "", ws, Some("10.28.0"), true), + (None, OWN, ws, Some("10.28.0"), false), + // A pin that differs from the install record is the pnpm the + // next install switches to: both have to read the override. + (Some("10.28.0"), "", ws, Some("10.4.1"), false), + (Some("10.4.1"), "", ws, Some("10.28.0"), false), + (Some("10.4.1"), &table, ws, Some("10.28.0"), true), + (Some("11.29.0"), &table, bare, Some("10.28.0"), false), + (Some("11.29.0"), &table, ws, Some("10.28.0"), true), + // No release named: the override has to be where every pnpm 10 + // and older reads it. pnpm does not switch to `pnpm@10` ("not a + // valid version"), so beside a record the record says. + (Some("10"), "", ws, None, false), + (Some("10"), &table, ws, None, true), + (Some("10"), "", ws, Some("10.28.0"), true), + (Some("10"), "", ws, Some("10.4.1"), false), + (None, "", ws, None, false), + (None, &table, bare, None, true), + ]; + let mut wrong = Vec::new(); + for (pin, own, workspace, installed, installs) in rows { + let p = Project::new(); + p.write("pnpm-lock.yaml", &lock); + p.write(".npmrc", "lockfile=false\n"); + p.write("pnpm-workspace.yaml", workspace); + let pin = pin.map_or(String::new(), |v| { + format!(r#""packageManager":"pnpm@{v}","#) + }); + p.write( + "package.json", + format!(r#"{{"name":"app",{pin}"dependencies":{{"left-pad":"1.3.0"}}{own}}}"#), + ); + if let Some(v) = installed { + p.write( + "node_modules/.modules.yaml", + format!(r#"{{"packageManager":"pnpm@{v}"}}"#), + ); + } + let out = run(&p).await; + assert_refs(&out, &[(PURL, UUID_B, WiringMode::Vendored)]); + let attested = marks(&out, PURL).is_empty(); + if attested != installs { + wrong.push(format!( + "{pin}{own} installed by {installed:?}, workspace override {}: attested \ + {attested}, pnpm installs the artifact {installs}", + workspace == ws + )); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + + // The detail names the map that pnpm reads. + let detail = |pin: &str, own: &str| { + let p = Project::new(); + p.write("pnpm-lock.yaml", &lock); + p.write(".npmrc", "lockfile=false\n"); + p.write("pnpm-workspace.yaml", ws); + p.write( + "package.json", + format!( + r#"{{"name":"app","packageManager":"pnpm@{pin}","dependencies":{{"left-pad":"1.3.0"}}{own}}}"# + ), + ); + async move { + let out = run(&p).await; + assert_eq!(marks(&out, PURL), [UnattestedKind::LockNotRead]); + out.unattested[0].detail.clone() + } + }; + let old = detail("10.4.1", "").await; + assert!( + old.contains("`lockfile=false` in .npmrc") + && old.contains( + "package.json `pnpm.overrides` does not route this package to it \ + (pnpm@10.4.1 (package.json packageManager) reads overrides from \ + package.json alone)" + ), + "{old}" + ); + let unnamed = detail("10", "").await; + assert!( + unnamed.contains( + "package.json `pnpm.overrides` does not route this package to it (no install \ + record or `packageManager` pin names a pnpm 10.5.1 through 10.x, the releases \ + that read pnpm-workspace.yaml `overrides`)" + ), + "{unnamed}" + ); + let shadowed = detail("10.28.0", OWN_RES).await; + assert!( + shadowed.contains( + "package.json `pnpm.overrides` does not route this package to it \ + (pnpm@10.28.0 (package.json packageManager) reads package.json's overrides \ + when it declares any (`pnpm.overrides` or `resolutions`), and \ + pnpm-workspace.yaml `overrides` when it declares none)" + ), + "{shadowed}" + ); + } + /// The vendored lock `vendor` writes for `left-pad@1.3.0` under /// [`UUID_B`]: the override it records, the importer and the rekeyed /// entry. `head` goes ahead of it (an env lockfile document). diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 5519a6f04..dcb6339c6 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -238,6 +238,13 @@ Each Legacy format has an upgrade path and an undo path. Both work in v5: which pnpm applies through `overrides` without a lock; `vex` attests such a vendored pin only while the override map that pnpm reads still routes the package to its artifact, and omits it otherwise (`vex_lock_not_read`). + Which map that is follows the pnpm release, as described next. Here the + releases are the one that installed the checkout + (`node_modules/.modules.yaml`) and the `packageManager` pin, which pnpm + switches to at the next install, and the override has to be where each + of them reads it: without a lock nothing fails when it sits elsewhere. + When `.npmrc` turns the lock off and neither names a release of pnpm 10 + or older, the override has to be in `package.json`. **A vendored override has to stay declared.** pnpm installs a lock only when the lock's `overrides:` equal the ones its settings declare: with a vendored override missing from the place pnpm reads, a frozen install