Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions crates/socket-patch-cli/src/commands/vendor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,9 @@ pub(crate) async fn dispatch_revert_one_opts(
/// * for PyPI, a project file still names the artifact although nothing
/// installs from it (a half-unwound uv pair, #1374): name it, and
/// re-lock before re-vendoring or reverting;
/// * a pnpm lock wires the artifact through an override the project's
/// settings do not declare, so pnpm does not install that lock (#2382):
/// the extractor's own diagnostic, which names the file and the remedy;
/// * otherwise a relock dropped the reference while the package stayed.
async fn unwired_check_failure(
discovery: &socket_patch_core::vex::discover::Discovery,
Expand Down Expand Up @@ -619,6 +622,12 @@ async fn unwired_check_failure(
registry release there (or remove that copy) to have it patched"
);
}
// A pnpm lock still wires the artifact, but pnpm installs that lock
// only with the override its settings no longer declare: say which
// file, and the remedy the diagnostic ends with (#2382).
if let Some(diag) = discovery.pnpm_override_undeclared(&entry.uuid) {
return format!("wiring incomplete: {}", diag.detail);
}
// Only the npm-family and Python extractors record every lock entry
// (`resolved_elsewhere`), so only there does "no lock resolves it"
// prove the dependency is gone rather than unreadable.
Expand Down
231 changes: 231 additions & 0 deletions crates/socket-patch-cli/tests/vendor_pnpm_override_e2e.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
//! pnpm installs a lock only when the lock's `overrides:` equal the ones
//! its settings declare, and each pnpm release reads those from its own
//! place: package.json before pnpm 10.5.1, package.json when it declares
//! overrides or else pnpm-workspace.yaml `overrides:` from 10.5.1 through
//! 10.x, the workspace file alone from pnpm 11 on. With a vendored override declared
//! where the project's pnpm does not read it, a frozen install fails
//! (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`) and a plain `pnpm install` puts
//! the registry release back (#2382; measured on pnpm 8.15.9, 9.15.9,
//! 10.2.0, 10.4.1, 10.5.0, 10.5.1, 10.28.0, 11.29.0 and 12.23.0).
//!
//! `vendor --check` and `vex` read the vendored reference from the lock
//! alone, so both called such a package patched. Each case vendors the pnpm
//! project of `vendor_ecosystem_fixtures` (`alpha`, `beta`) through the
//! built binary and takes the override out of one place.

#[path = "common/mod.rs"]
mod common;

#[path = "vendor_ecosystem_fixtures/mod.rs"]
mod fx;

use fx::Fixture;

const WORKSPACE: &str = "pnpm-workspace.yaml";
const MANIFEST: &str = "package.json";

/// The pnpm fixture, with `pin` as its `packageManager` when given.
fn project(pin: Option<&str>) -> Fixture {
let f = Fixture::new("pnpm");
if let Some(pin) = pin {
let text = std::fs::read_to_string(f.root.join(MANIFEST)).unwrap();
let pinned = text.replacen('{', &format!(r#"{{"packageManager":"pnpm@{pin}","#), 1);
std::fs::write(f.root.join(MANIFEST), pinned).unwrap();
}
f
}

/// `vendor --check`: the exit code and what it printed.
fn check(f: &Fixture) -> (i32, String) {
let (code, stdout, stderr) = f.run(&["vendor", "--check"], &[]);
(code, format!("{stdout}{stderr}"))
}

/// `vex`: the number of `not_affected` statements and the warnings.
fn vex(f: &Fixture) -> (usize, String) {
let (_, stdout, stderr) = f.run(&["vex", "--product", "pkg:npm/app@1.0.0"], &[]);
let attested = stdout.matches("\"status\": \"not_affected\"").count();
(attested, stderr)
}

/// Whether `rel` declares a vendored override.
fn declares(f: &Fixture, rel: &str) -> bool {
std::fs::read_to_string(f.root.join(rel)).is_ok_and(|text| text.contains(".socket/vendor/npm/"))
}

/// Take the vendored overrides out of package.json: its bytes before the
/// vendored run, which are `before`.
fn drop_manifest_override(f: &Fixture, before: &[u8]) {
std::fs::write(f.root.join(MANIFEST), before).unwrap();
}

/// The issue's case: the override is declared in no file. The lock still
/// names the artifact, so both verifiers passed.
#[test]
fn a_lock_whose_override_no_file_declares_is_not_verified() {
let f = project(None);
let before = std::fs::read(f.root.join(MANIFEST)).unwrap();
let (code, stdout, stderr) = f.vendor(&[], &[]);
assert_eq!(code, 0, "{stdout}\n{stderr}");
assert!(declares(&f, MANIFEST) && declares(&f, WORKSPACE));
assert_eq!((check(&f).0, vex(&f).0), (0, 1), "as vendored");

drop_manifest_override(&f, &before);
std::fs::remove_file(f.root.join(WORKSPACE)).unwrap();
assert!(declares(&f, "pnpm-lock.yaml"));
let tree = f.tree();

let (code, said) = check(&f);
let (attested, warned) = vex(&f);
assert_eq!(
(code, attested),
(1, 0),
"(vendor --check exit code, not_affected statements)\n{said}\n{warned}"
);
for (name, uuid) in [("alpha", "000000000001"), ("beta", "000000000002")] {
let line = said
.lines()
.find(|l| l.starts_with(&format!("pkg:npm/{name}@1.0.0: wiring incomplete: ")))
.unwrap_or_else(|| panic!("{name}: {said}"));
assert!(
line.contains(&format!("the override `{name}@1.0.0`"))
&& line.contains(&format!("-{uuid}/{name}-1.0.0.tgz"))
&& line.contains("neither package.json `pnpm.overrides` nor pnpm-workspace.yaml")
&& line.contains("ERR_PNPM_LOCKFILE_CONFIG_MISMATCH")
&& line.ends_with("Re-run `socket-patch vendor` to declare it again, and commit the files it changes"),
"{line}"
);
assert!(!line.contains("no lockfile or config references"), "{line}");
// `vex` folds the second package into the first one's warning.
assert!(warned.contains(&format!("{name}@1.0.0")), "{warned}");
}
assert!(
warned.contains("patched_ref_invalid: pnpm-lock.yaml: the lock records the override")
&& warned.contains("(vendor_unwired)"),
"{warned}"
);
assert_eq!(f.tree(), tree, "the two read-only commands wrote nothing");

// The remedy the message names puts both declarations back.
let (code, stdout, stderr) = f.vendor(&[], &[]);
assert_eq!(code, 0, "{stdout}\n{stderr}");
assert!(declares(&f, MANIFEST) && declares(&f, WORKSPACE));
assert_eq!((check(&f).0, vex(&f).0), (0, 1), "after the re-run");
}

/// The override is read where the project's pnpm reads it, so a file left
/// out of a commit (or a pnpm upgrade) is caught as soon as the checkout
/// says which pnpm it uses.
#[test]
fn the_override_counts_only_where_the_projects_pnpm_reads_it() {
// (the pnpm the project pins, the file the override is taken out of,
// whether pnpm still installs the lock).
for (pin, dropped, installs) in [
// No pin: either file.
(None, MANIFEST, true),
(None, WORKSPACE, true),
// pnpm 10.5.1 and newer 10.x read the workspace file when
// package.json has no table, and the table when it has one.
(Some("10.28.0"), MANIFEST, true),
(Some("10.28.0"), WORKSPACE, true),
// pnpm 11 and newer read the workspace file alone.
(Some("11.29.0"), MANIFEST, true),
(Some("11.29.0"), WORKSPACE, false),
(Some("12.23.0"), WORKSPACE, false),
// pnpm older than 10.5.1 reads package.json alone, and a project
// pinned to one with no workspace file gets none.
(Some("9.15.9"), MANIFEST, false),
(Some("10.4.1"), MANIFEST, false),
] {
let case = format!("pnpm {pin:?} without the override in {dropped}");
let f = project(pin);
let before = std::fs::read(f.root.join(MANIFEST)).unwrap();
let (code, stdout, stderr) = f.vendor(&[], &[]);
assert_eq!(code, 0, "{case}: {stdout}\n{stderr}");
assert_eq!(
declares(&f, WORKSPACE),
!matches!(pin, Some("9.15.9" | "10.4.1")),
"{case}: what vendor wrote"
);
assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: as vendored");
match dropped {
MANIFEST => drop_manifest_override(&f, &before),
_ => std::fs::remove_file(f.root.join(WORKSPACE)).unwrap(),
}

let (code, said) = check(&f);
let (attested, warned) = vex(&f);
let expected = if installs { (0, 1) } else { (1, 0) };
assert_eq!((code, attested), expected, "{case}\n{said}\n{warned}");
if installs {
continue;
}
let file = match dropped {
MANIFEST => "package.json `pnpm.overrides`",
_ => "pnpm-workspace.yaml `overrides`",
};
assert!(
said.contains(&format!(
"{file} does not declare it, and that is the only place this project's pnpm \
(pnpm@{} (package.json packageManager)) reads overrides from",
pin.unwrap()
)),
"{case}: {said}"
);
// Re-running vendor declares it where that pnpm reads it.
let (code, stdout, stderr) = f.vendor(&[], &[]);
assert_eq!(code, 0, "{case}: {stdout}\n{stderr}");
assert!(declares(&f, dropped), "{case}: the re-run wrote {dropped}");
assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: after the re-run");
}
}

/// pnpm 10.5.1 to 10.x read a `pnpm.overrides` table of package.json in
/// place of the workspace file's `overrides:` (measured on 10.28.0). A
/// project with a table of its own whose package.json loses the vendored
/// entries (a merge that took the other side) keeps them in the workspace
/// file, where that pnpm no longer looks.
#[test]
fn a_package_json_table_hides_the_workspace_override_on_pnpm_10() {
for (pin, installs) in [
(Some("10.28.0"), false),
// pnpm 11 ignores the table, and with no pin either map counts.
(Some("11.29.0"), true),
(None, true),
] {
let case = format!("pnpm {pin:?}");
let f = project(pin);
let text = std::fs::read_to_string(f.root.join(MANIFEST)).unwrap();
let own = text.replacen('{', r#"{"pnpm":{"overrides":{"gamma@1.0.0":"1.0.1"}},"#, 1);
std::fs::write(f.root.join(MANIFEST), &own).unwrap();
let (code, stdout, stderr) = f.vendor(&[], &[]);
assert_eq!(code, 0, "{case}: {stdout}\n{stderr}");
assert!(declares(&f, MANIFEST) && declares(&f, WORKSPACE), "{case}");
assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: as vendored");

drop_manifest_override(&f, own.as_bytes());
let (code, said) = check(&f);
let expected = if installs { (0, 1) } else { (1, 0) };
assert_eq!((code, vex(&f).0), expected, "{case}\n{said}");
if installs {
continue;
}
assert!(
said.contains(
"package.json declares overrides without it, and this project's pnpm \
(pnpm@10.28.0 (package.json packageManager)) reads those in place of \
pnpm-workspace.yaml `overrides`"
),
"{said}"
);
// The re-run adds the entries to the table that exists.
let (code, stdout, stderr) = f.vendor(&[], &[]);
assert_eq!(code, 0, "{case}: {stdout}\n{stderr}");
let after = std::fs::read_to_string(f.root.join(MANIFEST)).unwrap();
assert!(
after.contains("gamma@1.0.0") && declares(&f, MANIFEST),
"{after}"
);
assert_eq!((check(&f).0, vex(&f).0), (0, 1), "{case}: after the re-run");
}
}
20 changes: 18 additions & 2 deletions crates/socket-patch-core/src/formats/pnpm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ pub(crate) mod workspace;

pub(crate) use version::range_admits;
pub use version::{
matches_file_id_build_keys, registry_route_pins, root_only_workspace_breaks_add,
routed_build_keys, RegistryRoutePins, RoutedBuildKeys, REGISTRY_ROUTE_FLOOR,
matches_file_id_build_keys, pinned_override_sources, registry_route_pins,
root_only_workspace_breaks_add, routed_build_keys, OverrideSource, RegistryRoutePins,
RoutedBuildKeys, REGISTRY_ROUTE_FLOOR,
};

pub use grammar::PnpmDocument;
Expand Down Expand Up @@ -528,6 +529,21 @@ impl<'t> PnpmLock<'t> {
.any(|p| pnpm_registry_key(p.key) == Some((name, version)))
}

/// The `(key, value)` entries of the project documents' `overrides:`
/// sections: the overrides the lock was resolved with, which pnpm
/// compares with the ones its settings declare before it installs the
/// lock. The env lockfile document resolves pnpm's own dependencies and
/// is not read. Empty for a lock that records none.
pub(crate) fn overrides(&self) -> Vec<(String, String)> {
grammar::documents(self.text)
.into_iter()
.filter(|(_, kind)| *kind == PnpmDocument::Project)
.flat_map(|(span, _)| {
crate::vendor::pnpm_lock::override_section_entries(&self.text[span])
})
.collect()
}

/// Every packages entry whose flat resolution names a `tarball:`, in
/// lock order.
pub(crate) fn wired_refs(&self) -> impl Iterator<Item = PnpmTarballRef<'_>> {
Expand Down
95 changes: 94 additions & 1 deletion crates/socket-patch-core/src/formats/pnpm/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
//! 9.0.0, 9.7.1, 9.15.9, 10.0.0–10.4.1 failing and 10.5.0+ passing). Those
//! versions also read nothing the modes would write there: `trustLockfile`
//! is a pnpm >= 11 setting, and `overrides:` in pnpm-workspace.yaml is read
//! from 10.5 on (older ones read package.json `pnpm.overrides`).
//! from 10.5.1 on (older ones read package.json `pnpm.overrides`, see
//! [`OverrideSource`]).
//!
//! The evidence is read conservatively, because a wrong "skip" loses a
//! setting pnpm >= 11 needs: every present source must pin pnpm inside
Expand Down Expand Up @@ -167,6 +168,98 @@ pub fn root_only_workspace_breaks_add(
})
}

/// Where a pnpm release reads the overrides it resolves with. pnpm
/// installs a lock only when the lock's `overrides:` equal the ones it
/// reads here (`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` on a frozen install
/// otherwise, and a plain install resolves afresh and takes the registry
/// release), so this is where a vendored override has to be declared.
///
/// Measured with a vendored `left-pad` (#2382). pnpm 8.15.9, 9.15.9,
/// 10.2.0, 10.4.1 and 10.5.0 install the lock only with the override in
/// package.json. pnpm 10.5.1, 10.5.2, 10.6.0, 10.9.0, 10.13.1, 10.20.0 and
/// 10.28.0 also install it with the override in pnpm-workspace.yaml
/// `overrides:` alone, but 10.28.0 does not while package.json declares
/// overrides that lack it: those are read in place of the workspace
/// file's. pnpm 11.29.0 and 12.23.0 install it only with the override in
/// the workspace file.
///
/// package.json's overrides are `pnpm.overrides` over the top-level
/// `resolutions` (9.15.9 and 10.28.0 install the lock with the override
/// in `resolutions` alone, 11.29.0 does not), and declaring none is the
/// same as an empty table (10.5.1 and 10.28.0 read the workspace file
/// beside `"overrides": {}`, 10.28.0 does not beside a `resolutions`
/// entry of the project's own).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OverrideSource {
/// pnpm older than 10.5.1: package.json alone.
Manifest,
/// pnpm 10.5.1 through 10.x: package.json's overrides when it declares
/// any, else pnpm-workspace.yaml `overrides:`.
ManifestElseWorkspace,
/// pnpm 11 and newer: pnpm-workspace.yaml `overrides:` alone.
Workspace,
/// The project's files do not say which of those its pnpm is: either
/// map counts, the side that withholds no working wiring.
Unstated,
}

impl OverrideSource {
/// The source every release in `lo..=hi` reads; `None` when the span
/// crosses a boundary.
fn of((lo, hi): (Release, Release)) -> Option<Self> {
const WORKSPACE_READ: Release = (10, 5, 1);
const MANIFEST_IGNORED: Release = (11, 0, 0);
if hi < WORKSPACE_READ {
Some(OverrideSource::Manifest)
} else if lo >= MANIFEST_IGNORED {
Some(OverrideSource::Workspace)
} else if lo >= WORKSPACE_READ && hi < MANIFEST_IGNORED {
Some(OverrideSource::ManifestElseWorkspace)
} else {
None
}
}

/// Whether this pnpm reads an override that package.json declares
/// (`manifest`) or the workspace file declares (`workspace`);
/// `manifest_table` says package.json declares any override at all.
pub fn reads(self, manifest: bool, workspace: bool, manifest_table: bool) -> bool {
match self {
OverrideSource::Manifest => manifest,
OverrideSource::ManifestElseWorkspace if manifest_table => manifest,
OverrideSource::ManifestElseWorkspace | OverrideSource::Workspace => workspace,
OverrideSource::Unstated => manifest || workspace,
}
}
}

/// The [`OverrideSource`]s the pnpm pins package.json commits state
/// (`packageManager`, `devEngines.packageManager`, `engines.pnpm`), each
/// with its pin as prose (``pnpm@9.15.9 (package.json packageManager)``),
/// one entry per source; empty when no pin states one.
///
/// A pin states a source when every release it admits reads the same one
/// (an exact version, `~11.29.0`, `9.x`); a range that reaches across a
/// boundary (`>=9`, `^10.4.0`) or does not parse states none and is left
/// out. Pins that state different sources are all returned: a declaration
/// counts when a pnpm the project names reads it.
///
/// The install record (`node_modules/.modules.yaml`) is not read here. It
/// is not committed, so the same commit would verify on one machine and
/// fail on another, by whichever pnpm last installed there.
pub fn pinned_override_sources(package_json: Option<&str>) -> Vec<(OverrideSource, String)> {
let mut stated: Vec<(OverrideSource, String)> = Vec::new();
for (source, spec) in pnpm_pins(package_json, None) {
let Some(reads) = version_bounds(&spec).and_then(OverrideSource::of) else {
continue;
};
if stated.iter().all(|(known, _)| *known != reads) {
stated.push((reads, format!("pnpm@{spec} ({source})")));
}
}
stated
}

/// 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);
Expand Down
Loading
Loading