diff --git a/crates/socket-patch-cli/tests/in_process_pnpm_registry_cleanup.rs b/crates/socket-patch-cli/tests/in_process_pnpm_registry_cleanup.rs index bfd865300..fb0479e4b 100644 --- a/crates/socket-patch-cli/tests/in_process_pnpm_registry_cleanup.rs +++ b/crates/socket-patch-cli/tests/in_process_pnpm_registry_cleanup.rs @@ -1930,3 +1930,195 @@ async fn the_removed_entries_are_listed_for_a_person() { ); assert_gone_cleaned(root, "removed"); } + +/// The patch record of [`KEPT`], for a `vex` that attests from the lock. +async fn mock_view(server: &MockServer) { + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{}", KEPT.uuid))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "uuid": KEPT.uuid, + "purl": KEPT.purl(), + "publishedAt": "2024-01-01T00:00:00Z", + "files": { + "package/index.js": { + "beforeHash": "a".repeat(64), + "afterHash": "b".repeat(64), + } + }, + "vulnerabilities": { + "GHSA-rout-pnpm-vexx": { + "cves": ["CVE-2024-9"], + "summary": "registry route vex fixture", + "severity": "high", + "description": "d" + } + }, + "description": "x", "license": "MIT", "tier": "free" + }))) + .mount(server) + .await; +} + +/// `vex` on a checkout with nothing installed: the number of +/// `not_affected` statements it wrote, and what it said. +fn vex_from_the_lock(root: &Path, server: &MockServer) -> (usize, String) { + let _ = std::fs::remove_dir_all(root.join("node_modules")); + let out = root.join("out.vex.json"); + let _ = std::fs::remove_file(&out); + let mut cmd = hermetic::binary_command(); + cmd.args(["vex", "--product", "pkg:npm/consumer@0.0.0", "--output"]) + .arg(&out) + .args(["--patch-server-url", HOST, "--cwd", root.to_str().unwrap()]) + .args([ + "--api-url", + &server.uri(), + "--org", + ORG, + "--api-token", + "fake", + ]); + let said = cmd.output().expect("run socket-patch vex"); + let attested = std::fs::read_to_string(&out) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()) + .and_then(|doc| doc["statements"].as_array().cloned()) + .unwrap_or_default() + .iter() + .filter(|statement| statement["status"] == "not_affected") + .count(); + (attested, String::from_utf8_lossy(&said.stderr).into_owned()) +} + +/// pnpm installs a routed lock only while pnpm-workspace.yaml declares the +/// registry and the override. With the override gone a frozen install +/// fails and a plain `pnpm install` takes the upstream release back; with +/// the registry gone, or the file left out of the commit, nothing +/// installs. `vex` attested the patch from the lock all the same (#2404). +/// The pin is still the project's: a hosted re-scan declares the route +/// again, and `rollback` still restores the upstream entry. +#[tokio::test] +async fn vex_attests_a_routed_pin_only_while_the_workspace_file_routes_it() { + let server = MockServer::start().await; + mock_api(&server, &[&KEPT], &[]).await; + mock_view(&server).await; + let routed_lock = lock(&[KEPT.recorded()], &[KEPT.routed()]); + let head = "packages:\n - '.'\n"; + let registry = format!("namedRegistries:\n {}: {}\n", KEPT.alias, KEPT.address()); + let route = format!( + "overrides:\n '{}': '{}:{}'\n", + KEPT.release(), + KEPT.alias, + KEPT.version + ); + + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project( + root, + &[KEPT.routed()], + Some(&created(&[&KEPT])), + &routed_lock, + ); + let (attested, said) = vex_from_the_lock(root, &server); + assert_eq!(attested, 1, "the route as a scan writes it:\n{said}"); + + for (case, workspace, names) in [ + ( + "the override gone", + Some(format!("{head}{registry}")), + "`overrides` does not declare", + ), + ( + "the registry gone", + Some(format!("{head}{route}")), + "`namedRegistries` does not declare", + ), + ( + "both gone", + Some(head.to_string()), + "`namedRegistries` does not declare", + ), + ("no workspace file", None, "there is no pnpm-workspace.yaml"), + ] { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root, &[KEPT.routed()], workspace.as_deref(), &routed_lock); + let (attested, said) = vex_from_the_lock(root, &server); + assert_eq!(attested, 0, "{case}: attested from the lock alone:\n{said}"); + for needle in [ + names, + "pnpm-lock.yaml: the lock routes pkg:npm/kept-pkg@1.0.0", + "socket-patch scan --mode hosted", + ] { + assert!(said.contains(needle), "{case}: no {needle:?} in:\n{said}"); + } + + // The remedy the message gives: the scan reads the pin as the + // project's own, declares the route again and changes no lock. + write_project(root, &[KEPT.routed()], workspace.as_deref(), &routed_lock); + let (code, doc) = scan_hosted(root, &server, &[]); + assert_eq!(code, Some(0), "{case}: {doc}"); + // The run put a reference of this patch back into the project's + // files, so it reports the pin as changed: the file it rewrote is + // one to commit. + let pin_changed: Vec<&Value> = doc["events"] + .as_array() + .unwrap() + .iter() + .filter(|event| event["purl"] == KEPT.purl().as_str()) + .map(|event| &event["details"]["pinChanged"]) + .collect(); + assert_eq!(pin_changed, [&json!(true)], "{case}: {doc}"); + let declared = read(root, "pnpm-workspace.yaml").unwrap_or_default(); + assert!( + declared.contains(®istry) && declared.contains(&route), + "{case}: the re-scan left the route undeclared:\n{declared}" + ); + assert_eq!( + read(root, "pnpm-lock.yaml").as_deref(), + Some(routed_lock.as_str()), + "{case}" + ); + let (attested, said) = vex_from_the_lock(root, &server); + assert_eq!(attested, 1, "{case}: after the re-scan:\n{said}"); + } + + // A member with a lock of its own, run on its own: the route is in + // the workspace file above it, which pnpm reads and this run does not. + let tmp = tempfile::tempdir().unwrap(); + let member = tmp.path().join("packages").join("a"); + std::fs::create_dir_all(&member).unwrap(); + std::fs::write( + tmp.path().join("pnpm-workspace.yaml"), + format!("packages:\n - 'packages/*'\nsharedWorkspaceLockfile: false\n{registry}{route}"), + ) + .unwrap(); + write_project(&member, &[KEPT.routed()], None, &routed_lock); + let (attested, said) = vex_from_the_lock(&member, &server); + assert_eq!(attested, 1, "a member run on its own:\n{said}"); + + // An unwind still finds the pin it has to restore. + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project( + root, + &[KEPT.routed()], + Some(&format!("{head}{registry}")), + &routed_lock, + ); + let mut cmd = hermetic::binary_command(); + cmd.env( + "SOCKET_NPM_REGISTRY", + format!("{}/npm-registry", server.uri()), + ) + .args(["rollback", "--yes", "--json", "--patch-server-url", HOST]) + .args(["--cwd", root.to_str().unwrap(), "--api-url", &server.uri()]) + .args(["--org", ORG, "--api-token", "fake"]); + let (code, doc) = run_json(&mut cmd); + assert_eq!(code, Some(0), "{doc}"); + let lock_text = read(root, "pnpm-lock.yaml").unwrap(); + assert!( + !lock_text.contains(KEPT.alias) && !lock_text.contains(HOST), + "rollback left the route in the lock:\n{lock_text}" + ); +} diff --git a/crates/socket-patch-core/src/formats/pnpm/named_registries.rs b/crates/socket-patch-core/src/formats/pnpm/named_registries.rs index 8474e6cd9..625895e3e 100644 --- a/crates/socket-patch-core/src/formats/pnpm/named_registries.rs +++ b/crates/socket-patch-core/src/formats/pnpm/named_registries.rs @@ -690,6 +690,47 @@ pub(crate) fn routes(text: &str, owned: &Owned) -> Vec<(HostedOverride, String)> .collect() } +/// Whether `text` (a pnpm-workspace.yaml) may route releases in a way this +/// reader cannot follow, so that a reader that finds no route there +/// cannot say the file declares none ([`routes`] and [`declared`] read +/// such a file as declaring nothing): +/// +/// - a document that is not a single block mapping (a flow-style root, +/// several documents), of which no key is read; +/// - a registry map or an override map set more than once, on one line +/// with entries, or with an entry that is not a one-line `key: value` +/// ([`locate`]); +/// - a `registries` map, pnpm 12's other spelling of the registry map. +/// +/// An empty inline mapping or a null (`overrides: {}`, `~`) declares +/// nothing, and is read as that. +pub(crate) fn routes_unreadable(text: &str) -> bool { + let lines: Vec = text.split('\n').map(str::to_string).collect(); + let values_of = |name: &str| -> Vec<&str> { + lines + .iter() + .filter_map(|line| top_level_key(line)) + .filter(|(key, _)| key.as_str() == name) + .map(|(_, value)| value) + .collect() + }; + let declares_nothing = |name: &str| match values_of(name).as_slice() { + [value] => { + let value: String = strip_comment(value).split_whitespace().collect(); + matches!(value.as_str(), "{}" | "~" | "null") + } + _ => false, + }; + block_insert_point(&lines).is_err() + || !values_of("registries").is_empty() + || [MapKind::Registry, MapKind::Override] + .into_iter() + .any(|kind| { + matches!(locate(&lines, kind.key()), Located::Unsupported(_)) + && !declares_nothing(kind.key()) + }) +} + /// Whether the file holds an entry of ours in any of the maps. pub(crate) fn holds_ours(text: &str, owned: &Owned) -> bool { MapKind::ALL.into_iter().any(|kind| { diff --git a/crates/socket-patch-core/src/vex/discover/mod.rs b/crates/socket-patch-core/src/vex/discover/mod.rs index 87cd922d5..5a8fb8716 100644 --- a/crates/socket-patch-core/src/vex/discover/mod.rs +++ b/crates/socket-patch-core/src/vex/discover/mod.rs @@ -2316,6 +2316,13 @@ impl<'a> DiscoverCtx<'a> { self.origin.hosted_uuid(url) } + /// Whether `origin` (`http(s)://host[:port]`) is a patch server's + /// under this run's origins: where a registry address has to be for + /// the registry to be hosted mode's. + pub(crate) fn on_patch_server(&self, origin: &str) -> bool { + crate::origin::on_patch_server_origin(origin, self.origin.origins()) + } + /// [`OriginPolicy::hosted_served_path`] under this run's origins. pub(crate) fn hosted_served_path(&self, url: &str) -> Option> { self.origin.hosted_served_path(url) diff --git a/crates/socket-patch-core/src/vex/discover/npm.rs b/crates/socket-patch-core/src/vex/discover/npm.rs index 0f3df4097..104686142 100644 --- a/crates/socket-patch-core/src/vex/discover/npm.rs +++ b/crates/socket-patch-core/src/vex/discover/npm.rs @@ -92,6 +92,11 @@ const PNPM_MANIFEST: &str = "package.json"; /// finds the diagnostic by it. pub(crate) const PNPM_OVERRIDE_UNDECLARED: &str = "the lock records the override"; +/// How the diagnostic of a hosted pnpm pin whose registry route the +/// workspace file does not declare starts, after the lock's name +/// ([`confirm_pnpm_routes`]). +pub(crate) const PNPM_ROUTE_UNDECLARED: &str = "the lock routes"; + pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { let mut locks: Vec = Vec::new(); let mut twin_present = false; @@ -1054,7 +1059,162 @@ async fn extract_pnpm_lock( } match off { Some(off) => out.unattest_vendored_not_read(file, &off.unrouted(), |r| off.routes(r)), - None => confirm_pnpm_overrides(ctx, file, &lock, out).await, + None => { + confirm_pnpm_overrides(ctx, file, &lock, out).await; + confirm_pnpm_routes(ctx, file, &lock, out).await; + } + } +} + +/// Unpin each hosted ref of the pnpm lock `file` that the lock routes +/// through a registry of hosted mode's while `pnpm-workspace.yaml` does +/// not declare that route (#2404). +/// +/// The registry route writes one patch into two files: a `namedRegistries` +/// entry and an `overrides` entry in the workspace file, and the lock in +/// the form pnpm writes for them (an `overrides:` record and the +/// `name@:version` keys, +/// [`crate::formats::pnpm::named_registries`]). pnpm installs that lock +/// only while the file declares both. Without the override a frozen +/// install stops with `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH`, and a plain +/// `pnpm install` resolves again, takes the package from the registry and +/// rewrites the lock without the patch. Without the registry no install +/// runs at all (`ERR_PNPM_MISSING_NAMED_REGISTRY`). So the lock alone no +/// longer says what installs: the ref keeps its place, since the pin is +/// still the project's and a hosted re-scan or an unwind completes it, but +/// it loses the lock's pin ([`PatchedRef::lockfile_basis_ok`]) and is +/// attested only from an installed tree whose every copy verifies, as the +/// pins of a lock pnpm does not read are +/// ([`Discovery::unpin_lock_not_read`]). +/// +/// The test is the writer's own of a route it keeps (`kept_route` in +/// [`crate::hosted::engine`]): the file routes the release to that +/// registry, at an address that serves the lock's tarball. Only a route +/// the lock itself records is asked for, as with a vendored override +/// ([`confirm_pnpm_overrides`]). A workspace file that cannot be read, or +/// that may route in a shape the reader does not follow +/// ([`routes_unreadable`]), may declare the route, so the ref then stands +/// as it did before this check; so does the ref of a workspace member run +/// on its own, whose settings are in the workspace file above it. A Rush +/// lock is installed with Rush's own settings. +/// +/// [`routes_unreadable`]: crate::formats::pnpm::named_registries::routes_unreadable +async fn confirm_pnpm_routes( + ctx: &DiscoverCtx<'_>, + file: &str, + lock: &PnpmLock<'_>, + out: &mut Discovery, +) { + use crate::formats::pnpm::named_registries::{ + declared, routes, routes_unreadable, Address, Owned, + }; + if crate::vendor::pnpm_lock::rush::is_lock_rel(file) { + return; + } + let pinned = |r: &PatchedRef| { + r.mode == WiringMode::Hosted + && r.source_file == Path::new(file) + && r.part == TreePart::File + && r.locked_integrity.is_some() + }; + if !out.refs.iter().any(pinned) { + return; + } + let Ok(workspace) = ctx.read_advisory_text_if_present(PNPM_WORKSPACE).await else { + return; + }; + // A member of a workspace declared above it: pnpm reads the settings + // of that file, which this run does not. + if workspace.is_none() + && ctx.disk_root().is_some_and(|root| { + crate::utils::pnpm_workspace::governing_workspace_file(root).is_some() + }) + { + return; + } + let workspace = workspace.as_deref().map(strip_bom); + if workspace.is_some_and(routes_unreadable) { + return; + } + let owned = Owned::of(workspace, &|origin| ctx.on_patch_server(origin)); + // The routes the lock records: its `overrides:` entries onto a + // registry named as hosted mode names one. The name is all a lock + // says, and whose registry the workspace file makes of that name + // (`owned`) is part of what is being asked. + let named = Owned::default(); + let recorded: Vec<_> = lock + .overrides() + .into_iter() + .filter_map(|(key, value)| named.route(&key, &value)) + .collect(); + if recorded.is_empty() { + return; + } + let kept = workspace + .map(|text| routes(text, &owned)) + .unwrap_or_default(); + let registries = workspace.map(declared).unwrap_or_default(); + // `(purl, why the file does not route it)` of each release the lock + // keys through a recorded route the file does not declare. + let mut unrouted: BTreeMap = BTreeMap::new(); + for package in lock.packages_of(PnpmDocument::Project) { + let key = crate::formats::pnpm::strip_pnpm_peer_suffix(package.key); + let Some(route) = named.build(key).filter(|route| recorded.contains(route)) else { + continue; + }; + let Some(tarball) = package.resolution.as_ref().and_then(|r| r.tarball()) else { + continue; + }; + let Some(purl) = npm_purl(&route.name, &route.version) else { + continue; + }; + if kept + .iter() + .any(|(declared, address)| *declared == route && Address::serves(address, tarball)) + { + continue; + } + let registry = registries + .iter() + .any(|(alias, address)| *alias == route.alias && Address::serves(address, tarball)); + let missing = match (workspace, registry) { + (None, _) => format!("there is no {PNPM_WORKSPACE}"), + (Some(_), true) => format!( + "{PNPM_WORKSPACE} `overrides` does not declare `'{}': '{}'`", + route.key(), + route.value() + ), + (Some(_), false) => format!( + "{PNPM_WORKSPACE} `namedRegistries` does not declare `{}` at the address the \ + lock's tarball is served from", + route.alias + ), + }; + unrouted.insert(purl, format!("`{}`, but {missing}", route.alias)); + } + for (purl, why) in unrouted { + let mut unpinned = false; + for r in out.refs.iter_mut().filter(|r| pinned(r) && r.purl == purl) { + r.locked_integrity = None; + unpinned = true; + } + if !unpinned { + continue; + } + out.diag( + DIAG_REF_INVALID, + file, + format!( + "{file}: {PNPM_ROUTE_UNDECLARED} {purl} through the registry {why}. pnpm \ + installs such a lock only while the file declares the registry and the \ + override: a frozen install fails (ERR_PNPM_LOCKFILE_CONFIG_MISMATCH, or \ + ERR_PNPM_MISSING_NAMED_REGISTRY without the registry) and a plain `pnpm \ + install` takes the package from the registry again. The pin is not attested \ + from the lock alone, only from an installed tree whose every copy verifies. \ + Run `socket-patch scan --mode hosted` to declare the route again, and commit \ + {PNPM_WORKSPACE}" + ), + ); } } @@ -6614,4 +6774,228 @@ packages: } assert!(out.diagnostics.is_empty(), "{:#?}", out.diagnostics); } + + /// The registry route (#2167) writes a patch as a `namedRegistries` + /// entry and an `overrides` entry in `pnpm-workspace.yaml`, and the + /// lock in the form pnpm writes for them. pnpm installs that lock only + /// while the workspace file still declares the override: without it a + /// frozen install fails and a plain one takes the upstream release + /// (#2404). + #[tokio::test] + async fn pnpm_registry_routed_pin_needs_the_override_the_lock_records() { + let url = hosted_url("npm", "leaf", "1.0.0", UUID_A, "leaf-1.0.0.tgz"); + let registry = url.strip_suffix("leaf-1.0.0.tgz").unwrap(); + let lock = format!( + "lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n \ + excludeLinksFromLockfile: false\n\noverrides:\n leaf@1.0.0: socket-7c8d9e0f:1.0.0\n\n\ + importers:\n\n .:\n dependencies:\n mid:\n specifier: 1.0.0\n \ + version: 1.0.0\n\npackages:\n\n leaf@socket-7c8d9e0f:1.0.0:\n resolution: \ + {{integrity: {SRI}, tarball: {url}}}\n\n mid@1.0.0:\n resolution: {{integrity: \ + {SRI}}}\n\nsnapshots:\n\n leaf@socket-7c8d9e0f:1.0.0: {{}}\n\n mid@1.0.0:\n \ + dependencies:\n leaf: socket-7c8d9e0f:1.0.0\n" + ); + const PURL: &str = "pkg:npm/leaf@1.0.0"; + let named = format!("namedRegistries:\n socket-7c8d9e0f: {registry}\n"); + let routed = "overrides:\n 'leaf@1.0.0': 'socket-7c8d9e0f:1.0.0'\n"; + let attested = |out: &Discovery| { + out.refs + .iter() + .any(|r| r.purl == PURL && r.lockfile_basis_ok()) + && marks(out, PURL).is_empty() + }; + let p = Project::new(); + p.write( + "package.json", + r#"{"name":"app","packageManager":"pnpm@11.29.0","dependencies":{"mid":"1.0.0"}}"#, + ); + p.write("pnpm-lock.yaml", &lock); + p.write( + "pnpm-workspace.yaml", + format!("packages:\n - '.'\n{named}{routed}"), + ); + assert!( + attested(&run(&p).await), + "control: the route as the scan writes it" + ); + + p.write( + "pnpm-workspace.yaml", + format!("packages:\n - '.'\n{named}"), + ); + let out = run(&p).await; + assert!( + !attested(&out), + "attested with the override gone from pnpm-workspace.yaml: {:#?}", + out.refs + ); + } + + /// The other rows of #2404, on the lock of + /// [`pnpm_registry_routed_pin_needs_the_override_the_lock_records`]: + /// what keeps the lock's pin, what loses it, and that a pin that loses + /// it is still the project's (a hosted re-scan and an unwind read it). + #[tokio::test] + async fn pnpm_registry_route_is_confirmed_by_the_workspace_file() { + let url = hosted_url("npm", "leaf", "1.0.0", UUID_A, "leaf-1.0.0.tgz"); + let registry = url.strip_suffix("leaf-1.0.0.tgz").unwrap(); + let lock_with = |overrides: &str| { + format!( + "lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n \ + excludeLinksFromLockfile: false\n\n{overrides}importers:\n\n .:\n \ + dependencies:\n mid:\n specifier: 1.0.0\n version: 1.0.0\n\n\ + packages:\n\n leaf@socket-7c8d9e0f:1.0.0:\n resolution: {{integrity: {SRI}, \ + tarball: {url}}}\n\n mid@1.0.0:\n resolution: {{integrity: {SRI}}}\n\n\ + snapshots:\n\n leaf@socket-7c8d9e0f:1.0.0: {{}}\n\n mid@1.0.0:\n \ + dependencies:\n leaf: socket-7c8d9e0f:1.0.0\n" + ) + }; + let lock = lock_with("overrides:\n leaf@1.0.0: socket-7c8d9e0f:1.0.0\n\n"); + const PURL: &str = "pkg:npm/leaf@1.0.0"; + let named = format!("namedRegistries:\n socket-7c8d9e0f: {registry}\n"); + let routed = "overrides:\n 'leaf@1.0.0': 'socket-7c8d9e0f:1.0.0'\n"; + let head = "packages:\n - '.'\n"; + let project = |lock: &str, workspace: Option| { + let p = Project::new(); + p.write( + "package.json", + r#"{"name":"app","packageManager":"pnpm@11.29.0","dependencies":{"mid":"1.0.0"}}"#, + ); + p.write("pnpm-lock.yaml", lock); + if let Some(workspace) = workspace { + p.write("pnpm-workspace.yaml", workspace); + } + p + }; + // `(pinned by the lock, the diagnostic)` of the one hosted ref. + let verdict = |out: &Discovery| { + let refs: Vec<&PatchedRef> = out.refs.iter().filter(|r| r.purl == PURL).collect(); + assert_eq!( + refs.len(), + 1, + "the pin is still the project's: {:#?}", + out.refs + ); + assert_eq!( + (refs[0].mode, refs[0].uuid.as_str()), + (WiringMode::Hosted, UUID_A) + ); + let diag: Vec<&str> = out + .diagnostics + .iter() + .filter(|d| d.detail.contains(super::PNPM_ROUTE_UNDECLARED)) + .map(|d| d.detail.as_str()) + .collect(); + assert!(diag.len() <= 1, "{diag:#?}"); + ( + refs[0].lockfile_basis_ok(), + diag.first().map(|d| d.to_string()), + ) + }; + + // What loses the pin, each with the part of the file it names. + let other = registry.replace(UUID_A, UUID_B); + for (case, workspace, names) in [ + ( + "no override", + Some(format!("{head}{named}")), + "`overrides` does not declare `'leaf@1.0.0': 'socket-7c8d9e0f:1.0.0'`", + ), + ( + "no registry", + Some(format!("{head}{routed}")), + "`namedRegistries` does not declare `socket-7c8d9e0f`", + ), + ( + "neither", + Some(head.to_string()), + "`namedRegistries` does not declare `socket-7c8d9e0f`", + ), + ("no file", None, "there is no pnpm-workspace.yaml"), + ( + "another version routed", + Some(format!( + "{head}{named}overrides:\n 'leaf@2.0.0': 'socket-7c8d9e0f:2.0.0'\n" + )), + "`overrides` does not declare", + ), + ( + "an emptied inline overrides map", + Some(format!("{head}{named}overrides: {{}}\n")), + "`overrides` does not declare", + ), + ( + "a null registry map", + Some(format!("{head}namedRegistries: ~\n{routed}")), + "`namedRegistries` does not declare `socket-7c8d9e0f`", + ), + ( + "the registry at another patch's address", + Some(format!( + "{head}namedRegistries:\n socket-7c8d9e0f: {other}\n{routed}" + )), + "`namedRegistries` does not declare `socket-7c8d9e0f` at the address", + ), + ] { + let out = run(&project(&lock, workspace)).await; + let (pinned, diag) = verdict(&out); + let diag = + diag.unwrap_or_else(|| panic!("{case}: no diagnostic: {:#?}", out.diagnostics)); + assert!(!pinned, "{case}: still pinned by the lock"); + for needle in [ + names, + PURL, + "pnpm-lock.yaml: ", + "socket-patch scan --mode hosted", + ] { + assert!(diag.contains(needle), "{case}: no {needle:?} in {diag}"); + } + } + + // What keeps it: the route declared (in any line ending, with the + // final `/` of the address left off), a map the reader cannot + // follow, and a lock that records no route of its own. + let crlf = format!("{head}{named}{routed}").replace('\n', "\r\n"); + let no_slash = format!( + "{head}namedRegistries:\n socket-7c8d9e0f: {}\n{routed}", + registry.trim_end_matches('/') + ); + for (case, lock, workspace) in [ + ("crlf", lock.clone(), crlf), + ("no final slash", lock.clone(), no_slash), + ( + "inline overrides", + lock.clone(), + format!("{head}{named}overrides: {{'leaf@1.0.0': 'socket-7c8d9e0f:1.0.0'}}\n"), + ), + ( + "inline registries", + lock.clone(), + format!("{head}namedRegistries: {{socket-7c8d9e0f: '{registry}'}}\n{routed}"), + ), + ( + "a flow-style document", + lock.clone(), + format!( + "{{packages: ['.'], namedRegistries: {{socket-7c8d9e0f: '{registry}'}}, \ + overrides: {{'leaf@1.0.0': 'socket-7c8d9e0f:1.0.0'}}}}\n" + ), + ), + ( + "pnpm 12's registries map", + lock.clone(), + format!( + "{head}registries:\n '{registry}':\n prefix: socket-7c8d9e0f\n{routed}" + ), + ), + ("no route recorded", lock_with(""), format!("{head}{named}")), + ] { + let out = run(&project(&lock, Some(workspace))).await; + assert_eq!( + verdict(&out), + (true, None), + "{case}: {:#?}", + out.diagnostics + ); + } + } }