diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index fa7cdac29..4c32e93d6 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -1645,6 +1645,12 @@ async fn run_check(args: &VendorArgs) -> i32 { failure = Some(unwired_check_failure(discovery, root, key, entry).await); } } + // Wired, and a NuGet lock pins other bytes: a restore takes those, + // whatever the config routes. The pin is read as the writer reads + // it, after the liveness rule, which names a wiring that is gone. + if failure.is_none() && entry.ecosystem == "nuget" { + failure = vendor::nuget_feed::lock_pin_mismatch(entry, root).await; + } // The committed copy and its `replace` can be intact while the // project no longer builds: vendor/modules.txt or the go.mod // requirements out of step with the `replace` (#343, #618). @@ -4962,10 +4968,14 @@ pub(crate) async fn vendor_records_reusing( // A dry run previews an in-sync package as `verified` // (the backends cannot tell without writing); the // ledger recording this exact patch is the tell. + // NuGet's backend can tell: it reports an in-sync + // package as `already_vendored` on a dry run too, lock + // pin included, so its `verified` preview is always a + // package the wet run writes. let dry_previewed_in_sync = common.dry_run && event.action == PatchAction::Verified && lookup_entry(&state.entries, candidate) - .is_some_and(|e| e.uuid == record.uuid); + .is_some_and(|e| e.uuid == record.uuid && e.ecosystem != "nuget"); if dry_previewed_in_sync { dry_in_sync += 1; } diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 6a8f0792d..9c68ae9e7 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -2875,7 +2875,7 @@ fn omission_phrase(reason: &str) -> &'static str { name, or a link), so what installs is not what was checked" } "vendor_lock_pin_mismatch" => { - "the lockfile pins the vendored tarball to a sha512 that is not that file's, so \ + "the lockfile pins the vendored artifact to a sha512 that is not that file's, so \ an install does not deliver it; re-run socket-patch scan --mode vendored" } "vendor_path_unsafe" => "the vendored artifact path is unsafe", diff --git a/crates/socket-patch-cli/tests/vendor/main.rs b/crates/socket-patch-cli/tests/vendor/main.rs index 0325f0412..1d41a19b8 100644 --- a/crates/socket-patch-cli/tests/vendor/main.rs +++ b/crates/socket-patch-cli/tests/vendor/main.rs @@ -22,10 +22,15 @@ mod redirect_npm_allow_remote; mod vendor_failure_paths; mod vendor_gem_docker_layer; mod vendor_gem_lockfile_only_e2e; +mod vendor_nuget_lock_pin; mod vendor_render; mod vendor_rerun_no_network_e2e; mod vendor_silent_errors; +// It loads `prebuilt_common` for itself. +#[allow(clippy::duplicate_mod)] +#[path = "../vendor_ecosystem_fixtures/mod.rs"] +mod fx; #[path = "../prebuilt_common/mod.rs"] mod prebuilt_common; #[path = "../vlt_hosted_common/mod.rs"] diff --git a/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs b/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs new file mode 100644 index 000000000..1c248435c --- /dev/null +++ b/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs @@ -0,0 +1,213 @@ +//! A vendored NuGet package keeps its id and version, so the lock's +//! `contentHash` is all that ties a restore to the vendored nupkg while the +//! global packages folder holds the upstream package: `vendor` pins it, and +//! `dotnet restore --force-evaluate` there (NuGet's remedy for the NU1403 +//! the pin raises) writes the upstream hash back and restores the upstream +//! package. `vendor --check`, `vex` and `vendor --dry-run` must read the pin +//! the way the writer does. + +use crate::fx::Fixture; + +const LOCK: &str = "packages.lock.json"; +const ALPHA: &str = "pkg:nuget/Fx.Alpha@1.0.0"; +const BETA: &str = "pkg:nuget/Fx.Beta@1.0.0"; + +/// The fixture, vendored, with the lock as it was before (every pin the +/// upstream nupkg's) and as `vendor` left it (every pin the vendored one's). +fn vendored() -> (Fixture, String, String) { + let f = Fixture::new("nuget"); + let upstream = std::fs::read_to_string(f.root.join(LOCK)).unwrap(); + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + let pinned = std::fs::read_to_string(f.root.join(LOCK)).unwrap(); + assert_ne!(pinned, upstream, "vendor pins the lock"); + (f, upstream, pinned) +} + +/// `vendor --check`: the exit code and both output streams. +fn check(f: &Fixture) -> (i32, String) { + let (code, stdout, stderr) = f.run(&["vendor", "--check"], &[]); + (code, format!("{stdout}\n{stderr}")) +} + +/// `vex`: the purls it attests `not_affected`, and both output streams. +fn vex(f: &Fixture) -> (Vec, String) { + let (_, stdout, stderr) = f.run(&["vex", "--product", "pkg:nuget/app@1.0.0"], &[]); + let attested = [ALPHA, BETA] + .into_iter() + .filter(|purl| { + serde_json::from_str::(&stdout) + .ok() + .and_then(|doc| doc["statements"].as_array().cloned()) + .unwrap_or_default() + .iter() + .any(|statement| { + statement["status"] == "not_affected" + && statement["products"] + .to_string() + .to_lowercase() + .contains(&purl.to_lowercase()) + }) + }) + .map(str::to_string) + .collect(); + (attested, format!("{stdout}\n{stderr}")) +} + +/// `vendor --dry-run`: both output streams. +fn dry_run(f: &Fixture) -> String { + let (code, stdout, stderr) = f.run(&["vendor", "--dry-run"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + format!("{stdout}\n{stderr}") +} + +const NOTHING_TO_DO: &str = "All 2 packages are already vendored; nothing to do."; + +/// The control: the lock `vendor` wrote is verified and attested, and a +/// dry run has nothing to do. +#[test] +fn nuget_lock_pinned_to_the_vendored_nupkg_is_verified() { + let (f, ..) = vendored(); + let (code, out) = check(&f); + assert_eq!(code, 0, "{out}"); + let (attested, out) = vex(&f); + assert_eq!(attested, [ALPHA, BETA], "{out}"); + let out = dry_run(&f); + assert!(out.contains(NOTHING_TO_DO), "{out}"); +} + +/// What `dotnet restore --force-evaluate` leaves over a global packages +/// folder that holds the upstream packages: the config still maps each id +/// to its vendored feed, and the lock pins the upstream `contentHash` again. +#[test] +fn nuget_lock_pinned_to_other_bytes_is_not_verified() { + let (f, upstream, pinned) = vendored(); + std::fs::write(f.root.join(LOCK), &upstream).unwrap(); + + let (code, out) = check(&f); + let (attested, vex_out) = vex(&f); + assert_eq!( + (code, attested.len()), + (1, 0), + "(vendor --check exit code, not_affected statements)\n{out}\n{vex_out}" + ); + for purl in [ALPHA, BETA] { + assert!( + out.contains(&format!("{purl}: {LOCK} pins ")), + "the failure names the lock: {out}" + ); + } + assert!( + vex_out.contains("(vendor_lock_pin_mismatch): Fx.Alpha@1.0.0, Fx.Beta@1.0.0") + && vex_out.contains("pins the vendored artifact to a sha512") + && !vex_out.contains("tarball"), + "{vex_out}" + ); + + // The remedy the failure names: a wet run pins the lock again. A dry + // run says so, and writes nothing. + assert!( + out.contains("re-run `socket-patch scan --mode vendored` (or `socket-patch vendor`"), + "{out}" + ); + let out = dry_run(&f); + assert!( + out.contains("Would vendor 2 packages") && !out.contains("nothing to do"), + "{out}" + ); + assert_eq!( + std::fs::read_to_string(f.root.join(LOCK)).unwrap(), + upstream + ); + // NuGet's record of the bytes it extracted the global copy from. + let global = f.store.join("nuget/fx.alpha/1.0.0"); + std::fs::write( + global.join(".nupkg.metadata"), + r#"{"version":2,"contentHash":"UPSTREAM=="}"#, + ) + .unwrap(); + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("a lock pinned Fx.Alpha@1.0.0 to other bytes") + && !stdout.contains("missing or stale"), + "the run says what was stale: {stdout}" + ); + assert!( + stdout.contains("vendor_nuget_stale_global_package") + && stdout.contains(&global.display().to_string()), + "the run names the copy a restore still takes: {stdout}" + ); + assert_eq!(std::fs::read_to_string(f.root.join(LOCK)).unwrap(), pinned); + let (code, out) = check(&f); + assert_eq!(code, 0, "{out}"); + let (attested, out) = vex(&f); + assert_eq!(attested, [ALPHA, BETA], "{out}"); +} + +/// One package's pin is not another's: only the package whose entry pins +/// other bytes fails the check and loses its statement. +#[test] +fn nuget_lock_pin_is_judged_per_package() { + let (f, upstream, pinned) = vendored(); + let upstream: serde_json::Value = serde_json::from_str(&upstream).unwrap(); + let mut lock: serde_json::Value = serde_json::from_str(&pinned).unwrap(); + let hash = + |doc: &serde_json::Value| doc["dependencies"]["net8.0"]["Fx.Alpha"]["contentHash"].clone(); + assert_ne!(hash(&lock), hash(&upstream)); + lock["dependencies"]["net8.0"]["Fx.Alpha"]["contentHash"] = hash(&upstream); + std::fs::write( + f.root.join(LOCK), + serde_json::to_string_pretty(&lock).unwrap(), + ) + .unwrap(); + + let (code, out) = check(&f); + assert_eq!(code, 1, "{out}"); + assert!(out.contains(&format!("{ALPHA}: {LOCK} pins ")), "{out}"); + assert!( + out.contains(&format!("{BETA}: committed artifact and wiring verified")), + "{out}" + ); + let (attested, out) = vex(&f); + assert_eq!(attested, [BETA], "{out}"); +} + +/// The pin is judged on a package that is wired. With the config put back +/// nothing routes the package to the vendored feed, whatever the lock pins: +/// the check names the wiring that is gone, as `vex` does, and a dry run +/// would vendor both again. The same once the lock is put back too. +#[test] +fn nuget_package_with_no_wiring_left_is_reported_as_unwired() { + let f = Fixture::new("nuget"); + let config = std::fs::read_to_string(f.root.join("nuget.config")).unwrap(); + let lock = std::fs::read_to_string(f.root.join(LOCK)).unwrap(); + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + + let unwired = |state: &str| { + let (code, out) = check(&f); + assert_eq!(code, 1, "{state}: {out}"); + for purl in [ALPHA, BETA] { + assert!( + out.contains(&format!("{purl}: wiring missing")), + "{state}: the failure is the liveness rule's: {out}" + ); + } + assert!(!out.contains("contentHash"), "{state}: {out}"); + let (attested, out) = vex(&f); + assert!( + attested.is_empty() && out.contains("(vendor_unwired)"), + "{state}: {out}" + ); + let out = dry_run(&f); + assert!( + out.contains("Would vendor 2 packages") && !out.contains("nothing to do"), + "{state}: {out}" + ); + }; + std::fs::write(f.root.join("nuget.config"), &config).unwrap(); + unwired("the config put back, the lock still pinned"); + std::fs::write(f.root.join(LOCK), &lock).unwrap(); + unwired("the config and the lock put back"); +} diff --git a/crates/socket-patch-core/src/vendor/nuget_feed.rs b/crates/socket-patch-core/src/vendor/nuget_feed.rs index a5fb4f554..de5c142a1 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -194,6 +194,10 @@ struct NugetPrelude { /// ...and the committed nupkg plus the lock pin are in sync (the hot /// path, which never asks the service). in_sync: bool, + /// Wired, the committed nupkg in sync, and a lock pins other bytes + /// ([`pins_other_bytes`]): what the re-vendor's warning then says was + /// stale. + pin_stale: bool, } async fn nuget_prelude( @@ -387,35 +391,38 @@ async fn nuget_prelude( } } } - let in_sync = config_wired && { + let (in_sync, pin_stale) = if config_wired { // One guarded read of the committed nupkg serves both the member-hash - // check and the lock's content-hash pin. - let nupkg_bytes = read_zip_artifact(&nupkg_path).await; - let nupkg_ok = nupkg_bytes - .as_deref() - .is_some_and(|bytes| zip_bytes_match_after_hashes(bytes, &record.files)); - // Only worth computing when the artifact itself is in sync (a stale - // nupkg rebuilds regardless of what the lock pins). - let lock_ok = match &nupkg_bytes { - _ if locks.is_empty() => true, - Some(bytes) if nupkg_ok => { - let expected = sha512_base64_of(bytes); + // check and the lock's content-hash pin, which is only worth + // computing when the artifact itself is in sync (a stale nupkg + // rebuilds regardless of what the lock pins). + let expected = read_zip_artifact(&nupkg_path) + .await + .filter(|bytes| zip_bytes_match_after_hashes(bytes, &record.files)) + .map(|bytes| sha512_base64_of(&bytes)); + match &expected { + None => (false, false), + Some(expected) => { // Pinned at our bytes, or no matching resolved entry at // all — the same absence `edit_lock` tolerates with a // warning on the first run. Treating absence as stale // would misreport "missing or stale; rebuilt" on every // rerun with nothing to actually pin. - locks.iter().all(|lock| { - lock_pinned(&lock.text, name, &version_norm, &expected) + let lock_ok = locks.iter().all(|lock| { + lock_pinned(&lock.text, name, &version_norm, expected) || matches!( - edit_lock(&lock.text, name, &version_norm, &expected), + edit_lock(&lock.text, name, &version_norm, expected), Ok(None) ) - }) + }); + let pin_stale = locks + .iter() + .any(|lock| pins_other_bytes(&lock.text, name, &version_norm, expected)); + (lock_ok, pin_stale) } - _ => false, - }; - nupkg_ok && lock_ok + } + } else { + (false, false) }; Ok(NugetPrelude { name: name.to_string(), @@ -436,6 +443,7 @@ async fn nuget_prelude( locks, config_wired, in_sync, + pin_stale, }) } @@ -637,6 +645,7 @@ pub async fn vendor_nuget( locks, config_wired, in_sync, + pin_stale, } = match nuget_prelude(purl, project_root, record).await { Ok(prelude) => prelude, Err(outcome) => return outcome, @@ -662,21 +671,10 @@ pub async fn vendor_nuget( // The warning keeps firing on re-runs until the stale copy is // gone (#352). let mut warnings: Vec = block.into_iter().collect(); - if let (Some(cached), Some(bytes)) = ( - extracted_content_hash(installed_dir).await, - read_zip_artifact(&nupkg_path).await, - ) { - if cached != sha512_base64_of(&bytes) { - warnings.push(VendorWarning::new( - "vendor_nuget_stale_global_package", - stale_global_package_detail( - name, - version, - installed_dir, - "the vendored feed", - ), - )); - } + if let Some(bytes) = read_zip_artifact(&nupkg_path).await { + let vendored = sha512_base64_of(&bytes); + warnings + .extend(stale_global_package(installed_dir, name, version, &vendored).await); } // A dir vendored before the re-include existed gains it now. if !dry_run { @@ -765,13 +763,24 @@ pub async fn vendor_nuget( } } } - warnings.push(VendorWarning::new( - "vendor_artifact_rebuilt", - format!( + // What was stale: the nupkg, or only a lock's pin of it (what + // `dotnet restore --force-evaluate` leaves over a global + // packages folder that holds the upstream package). + let detail = match pin_stale { + true => format!( + "a lock pinned {name}@{version} to other bytes than the committed vendored \ + nupkg's; rebuilt at {copy_rel} and pinned again (nuget.config untouched)" + ), + false => format!( "the committed vendored nupkg for {name}@{version} was missing or stale; \ rebuilt at {copy_rel} (nuget.config untouched)" ), - )); + }; + warnings.push(VendorWarning::new("vendor_artifact_rebuilt", detail)); + // The copy that a restore would still take, as on the first + // run and on an in-sync one (#352): after a `--force-evaluate` + // this is the run that has to name it. + warnings.extend(stale_global_package(installed_dir, name, version, &new_hash).await); // The rebuilt nupkg may differ byte-wise from the one the ledger // fingerprinted (a service ↔ local flip): hand back a refreshed // entry so the ledger sha256 and lock pin describe these bytes. @@ -971,14 +980,7 @@ pub async fn vendor_nuget( // A warm global packages folder shadows the vendored feed (#352): the // crawler found the package there, extracted from other bytes. - if let Some(cached) = extracted_content_hash(installed_dir).await { - if cached != new_hash { - warnings.push(VendorWarning::new( - "vendor_nuget_stale_global_package", - stale_global_package_detail(name, version, installed_dir, "the vendored feed"), - )); - } - } + warnings.extend(stale_global_package(installed_dir, name, version, &new_hash).await); // ── marker + ledger entry ──────────────────────────────────────────── let base_purl = build_nuget_purl(name, version); @@ -1069,6 +1071,26 @@ pub fn stale_global_package_detail(id: &str, version: &str, dir: &Path, how: &st ) } +/// The [`stale_global_package_detail`] warning of a vendored package, when +/// NuGet's global packages folder holds `installed_dir` extracted from +/// bytes other than the vendored nupkg's (`vendored_hash`, its +/// `contentHash`). Every wet path of [`vendor_nuget`] raises it, so the +/// warning keeps firing until the stale copy is gone. +async fn stale_global_package( + installed_dir: &Path, + id: &str, + version: &str, + vendored_hash: &str, +) -> Option { + let cached = extracted_content_hash(installed_dir).await?; + (cached != vendored_hash).then(|| { + VendorWarning::new( + "vendor_nuget_stale_global_package", + stale_global_package_detail(id, version, installed_dir, "the vendored feed"), + ) + }) +} + /// The ledger entry for a vendored nupkg: `wiring` is the config + lock /// records on a full vendor, only the re-pinned lock record on an /// artifact-only rebuild (see the hot path). @@ -2340,6 +2362,83 @@ fn lock_pinned(text: &str, id: &str, version_norm: &str, expected_hash: &str) -> matched } +/// Why the project's locks do not restore `entry`'s committed nupkg although +/// `nuget.config` routes the id to its feed: a lock that a project under the +/// root restores into locks the id at the patched version under a +/// `contentHash` that is not the nupkg's. A vendored package keeps its id +/// and version, so that hash is all that tells it from the upstream package +/// in NuGet's global packages folder, which NuGet restores from before it +/// asks any source. Vendoring pins it ([`edit_lock`]); `dotnet restore +/// --force-evaluate` over a folder that holds the upstream package (NuGet's +/// remedy for the NU1403 the pin raises there) writes the upstream hash +/// back. Every later restore, `--locked-mode` included, then takes the +/// upstream package and would fail on the vendored one, so `vendor --check` +/// reports it and `vex` does not attest the patch. +/// +/// The writer's rule, through the predicate its own re-run goes by +/// ([`pins_other_bytes`]): `None` when every such entry pins the nupkg, +/// when no lock locks the id at that version or the entry carries no hash +/// (the absence [`edit_lock`] tolerates), and when the locks or the nupkg +/// cannot be read (their own checks say so). +pub async fn lock_pin_mismatch(entry: &VendorEntry, project_root: &Path) -> Option { + let (id, version) = parse_nuget_purl(&entry.base_purl)?; + let version_norm = normalize_nuget_version(&version); + // The callers have checked the artifact; a path that is not one below + // the root is not read here either. + let artifact = entry.artifact.path.as_str(); + if !is_safe_multi_segment(artifact) { + return None; + } + let root = project_root.to_path_buf(); + let governed = run_blocking(move || super::nuget_config::governed_locks_on_disk(&root)) + .await + .ok()?; + let mut expected: Option = None; + for rel in governed.locks { + let Ok(text) = read_regular_to_string(&project_root.join(&rel)).await else { + continue; + }; + if !pins_any_bytes(&text, &id, &version_norm) { + continue; + } + // Read once, and only for a project that pins the package. + if expected.is_none() { + let bytes = read_zip_artifact(&project_root.join(artifact)).await?; + expected = Some(sha512_base64_of(&bytes)); + } + if pins_other_bytes(&text, &id, &version_norm, expected.as_deref()?) { + return Some(format!( + "{rel} pins {id} {version_norm} to a contentHash that is not the sha512 of \ + {artifact}, so `dotnet restore` does not restore the vendored package (it takes \ + a copy with the pinned hash from NuGet's global packages folder, or fails \ + NU1403); re-run `socket-patch scan --mode vendored` (or `socket-patch vendor`, \ + where the project has a .socket/manifest.json) to pin the lock again, then \ + delete the directory in the global packages folder that the run's warning names" + )); + } + } + None +} + +/// The `contentHash` of every entry of the lock `doc` that locks `id` at +/// `version_norm` and carries one. +fn pins<'a>(doc: &'a Value, id: &'a str, version_norm: &'a str) -> impl Iterator { + locked_at(doc, id, version_norm).filter_map(|locked| locked.content_hash) +} + +/// Whether the lock `text` pins `id` at `version_norm` at all. +fn pins_any_bytes(text: &str, id: &str, version_norm: &str) -> bool { + lock_value(text).is_ok_and(|doc| pins(&doc, id, version_norm).next().is_some()) +} + +/// Whether the lock `text` pins `id` at `version_norm` to a `contentHash` +/// other than `expected`: the one state in which NuGet restores other bytes +/// than the vendored nupkg's and accepts them. An entry with no hash pins +/// nothing, and neither does a lock that is not JSON. +fn pins_other_bytes(text: &str, id: &str, version_norm: &str, expected: &str) -> bool { + lock_value(text).is_ok_and(|doc| pins(&doc, id, version_norm).any(|pin| pin != expected)) +} + /// Restore a `nuget_lock_entry` record's original `contentHash`. `Ok(true)` = /// restored (or would be on dry run) / already restored; `Ok(false)` = drifted /// (neither our value nor the original is present); `Err` = I/O failure. @@ -3300,6 +3399,66 @@ mod tests { ); } + /// What `dotnet restore --force-evaluate` leaves over a global packages + /// folder that holds the upstream package: the lock on the upstream + /// hash again, the nupkg and the config as vendored. The re-run pins + /// the lock again, says that the pin was what was stale, and names the + /// copy a restore would still take. + #[tokio::test] + async fn stale_lock_pin_is_pinned_again_and_the_global_copy_named() { + let (dir, blobs, installed, record) = fixture(true, None).await; + let root = dir.path(); + let upstream = tokio::fs::read_to_string(root.join(PACKAGES_LOCK)) + .await + .unwrap(); + tokio::fs::write( + installed.join(".nupkg.metadata"), + "{\"version\":2,\"contentHash\":\"ORIGINALcachedhash==\"}", + ) + .await + .unwrap(); + let (result, ..) = unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + let pinned = tokio::fs::read_to_string(root.join(PACKAGES_LOCK)) + .await + .unwrap(); + assert_ne!(pinned, upstream); + + tokio::fs::write(root.join(PACKAGES_LOCK), &upstream) + .await + .unwrap(); + let entry = entry_with_wiring(UUID, Vec::new()); + assert!(lock_pin_mismatch(&entry, root).await.is_some()); + let (result, _entry, warnings) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + assert_eq!( + tokio::fs::read_to_string(root.join(PACKAGES_LOCK)) + .await + .unwrap(), + pinned + ); + assert_eq!(lock_pin_mismatch(&entry, root).await, None); + let rebuilt: Vec<&VendorWarning> = warnings + .iter() + .filter(|w| w.code == "vendor_artifact_rebuilt") + .collect(); + assert_eq!(rebuilt.len(), 1, "{warnings:?}"); + assert!( + rebuilt[0].detail.starts_with("a lock pinned") + && !rebuilt[0].detail.contains("missing or stale"), + "{}", + rebuilt[0].detail + ); + assert!( + warnings.iter().any(|w| { + w.code == "vendor_nuget_stale_global_package" + && w.detail.contains(&installed.display().to_string()) + }), + "{warnings:?}" + ); + } + /// #352: the crawler found the package in NuGet's global packages /// folder, extracted from the upstream bytes; NuGet would restore that /// copy before asking the vendored feed, so the run says so (first run @@ -5737,6 +5896,202 @@ mod tests { assert!(!lock_pinned(&lock, "Newtonsoft.Json", "12.0.0", "H==")); } + // ── lock_pin_mismatch: the verifiers' reading of the pin ─────────────── + + /// A project with the vendored nupkg committed. Returns its root and + /// the nupkg's `contentHash`. + async fn pinned_project() -> (tempfile::TempDir, String) { + let dir = tempfile::tempdir().unwrap(); + let nupkg = make_nupkg(PATCHED); + let path = dir.path().join(copy_rel()); + tokio::fs::create_dir_all(path.parent().unwrap()) + .await + .unwrap(); + tokio::fs::write(&path, &nupkg).await.unwrap(); + tokio::fs::write(dir.path().join("app.csproj"), "") + .await + .unwrap(); + (dir, sha512_base64_of(&nupkg)) + } + + async fn pin_mismatch(root: &Path) -> Option { + lock_pin_mismatch(&entry_with_wiring(UUID, Vec::new()), root).await + } + + #[tokio::test] + async fn lock_pin_mismatch_follows_the_writers_rule() { + let (dir, ours) = pinned_project().await; + let root = dir.path(); + let lock = root.join(PACKAGES_LOCK); + let upstream = sha512_base64_of(&make_nupkg(PRISTINE)); + + // No lock: nothing pins the package (the writer's `locks.is_empty()`). + assert_eq!(pin_mismatch(root).await, None); + + // Pinned at the vendored nupkg, in every framework. + tokio::fs::write(&lock, lock_json(&ours)).await.unwrap(); + assert_eq!(pin_mismatch(root).await, None); + + // What `dotnet restore --force-evaluate` writes over a global + // packages folder that holds the upstream package. + tokio::fs::write(&lock, lock_json(&upstream)).await.unwrap(); + let detail = pin_mismatch(root).await.expect("the upstream pin"); + assert!( + detail.starts_with("packages.lock.json pins Newtonsoft.Json 13.0.3 to a contentHash"), + "{detail}" + ); + assert!(detail.contains(©_rel()), "{detail}"); + // The remedy that works with and without a manifest comes first. + assert!( + detail.contains("re-run `socket-patch scan --mode vendored` (or `socket-patch vendor`"), + "{detail}" + ); + + // One framework repinned by hand, the other left: still not ours. + let mixed = lock_json(&ours).replacen(&ours, &upstream, 1); + tokio::fs::write(&lock, &mixed).await.unwrap(); + assert!(pin_mismatch(root).await.is_some()); + + // The id in another case and the version in another spelling are + // the same package to NuGet, and to the writer. + let respelled = lock_json(&upstream) + .replace("\"Newtonsoft.Json\"", "\"NEWTONSOFT.JSON\"") + .replace("\"resolved\": \"13.0.3\"", "\"resolved\": \"13.0.3.0\""); + tokio::fs::write(&lock, &respelled).await.unwrap(); + assert!(pin_mismatch(root).await.is_some()); + } + + /// What the writer tolerates is no mismatch: nothing there says which + /// bytes a restore takes, and the other checks have their own verdicts. + #[tokio::test] + async fn lock_pin_mismatch_is_silent_where_nothing_is_pinned() { + let (dir, _) = pinned_project().await; + let root = dir.path(); + let lock = root.join(PACKAGES_LOCK); + let upstream = sha512_base64_of(&make_nupkg(PRISTINE)); + + // Locked at another version: not this package's pin. + let other = + lock_json(&upstream).replace("\"resolved\": \"13.0.3\"", "\"resolved\": \"12.0.1\""); + tokio::fs::write(&lock, &other).await.unwrap(); + assert_eq!(pin_mismatch(root).await, None); + + // An entry with no contentHash (`edit_lock` has nothing to pin). + let hashless = serde_json::to_string(&json!({ + "version": 1, + "dependencies": { "net8.0": { "Newtonsoft.Json": { "resolved": "13.0.3" } } } + })) + .unwrap(); + tokio::fs::write(&lock, &hashless).await.unwrap(); + assert_eq!(pin_mismatch(root).await, None); + + // The same beside an entry pinned at the nupkg. + let ours = sha512_base64_of(&make_nupkg(PATCHED)); + let beside = serde_json::to_string(&json!({ + "version": 1, + "dependencies": { + "net6.0": { "Newtonsoft.Json": { "resolved": "13.0.3" } }, + "net8.0": { "Newtonsoft.Json": { "resolved": "13.0.3", "contentHash": ours } } + } + })) + .unwrap(); + tokio::fs::write(&lock, &beside).await.unwrap(); + assert_eq!(pin_mismatch(root).await, None); + + // A lock that is not JSON. + tokio::fs::write(&lock, "<<<<<<< HEAD\n").await.unwrap(); + assert_eq!(pin_mismatch(root).await, None); + + // The nupkg gone: the artifact check reports that. + tokio::fs::write(&lock, lock_json(&upstream)).await.unwrap(); + tokio::fs::remove_file(root.join(copy_rel())).await.unwrap(); + assert_eq!(pin_mismatch(root).await, None); + } + + /// An artifact path that leaves the root is not read, whatever lies + /// there: here a nupkg the lock does not pin, which would be a mismatch + /// if it were hashed. + #[tokio::test] + async fn lock_pin_mismatch_reads_no_artifact_outside_the_root() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("project"); + let outside = dir.path().join(copy_rel()); + tokio::fs::create_dir_all(outside.parent().unwrap()) + .await + .unwrap(); + tokio::fs::write(&outside, make_nupkg(PATCHED)) + .await + .unwrap(); + tokio::fs::create_dir_all(&root).await.unwrap(); + tokio::fs::write(root.join("app.csproj"), "") + .await + .unwrap(); + let upstream = sha512_base64_of(&make_nupkg(PRISTINE)); + tokio::fs::write(root.join(PACKAGES_LOCK), lock_json(&upstream)) + .await + .unwrap(); + let mut entry = entry_with_wiring(UUID, Vec::new()); + entry.artifact.path = format!("../{}", copy_rel()); + assert!(root.join(&entry.artifact.path).is_file()); + assert_eq!(lock_pin_mismatch(&entry, &root).await, None); + } + + /// The predicate the check and the writer's re-run share: only an + /// entry of the version that carries another hash pins other bytes. + #[test] + fn pins_other_bytes_needs_an_entry_with_another_hash() { + let other = |text: &str| pins_other_bytes(text, "Newtonsoft.Json", "13.0.3", "OURS=="); + assert!(!other(&lock_json("OURS=="))); + assert!(other(&lock_json("THEIRS=="))); + assert!(other( + &lock_json("OURS==").replacen("OURS==", "THEIRS==", 1) + )); + // An entry with no hash beside one pinned at ours: nothing else is + // pinned, so a re-run does not call the pin stale. + let beside = json!({ + "version": 1, + "dependencies": { + "net6.0": { "Newtonsoft.Json": { "resolved": "13.0.3" } }, + "net8.0": { "Newtonsoft.Json": { "resolved": "13.0.3", "contentHash": "OURS==" } } + } + }) + .to_string(); + assert!(!other(&beside) && pins_any_bytes(&beside, "Newtonsoft.Json", "13.0.3")); + assert!(!other( + &lock_json("THEIRS==").replace("13.0.3\"", "12.0.1\"") + )); + assert!(!other("<<<<<<< HEAD\n") && !pins_any_bytes("{}", "Newtonsoft.Json", "13.0.3")); + } + + /// Every lock a project under the root restores into is read, as every + /// one is pinned: the root config routes all of them. + #[tokio::test] + async fn lock_pin_mismatch_reads_every_governed_lock() { + let (dir, ours) = pinned_project().await; + let root = dir.path(); + let upstream = sha512_base64_of(&make_nupkg(PRISTINE)); + tokio::fs::write(root.join(PACKAGES_LOCK), lock_json(&ours)) + .await + .unwrap(); + tokio::fs::create_dir_all(root.join("lib")).await.unwrap(); + tokio::fs::write(root.join("lib/lib.csproj"), "") + .await + .unwrap(); + tokio::fs::write(root.join("lib").join(PACKAGES_LOCK), lock_json(&ours)) + .await + .unwrap(); + assert_eq!(pin_mismatch(root).await, None); + + tokio::fs::write(root.join("lib").join(PACKAGES_LOCK), lock_json(&upstream)) + .await + .unwrap(); + let detail = pin_mismatch(root).await.expect("the member's lock"); + assert!( + detail.starts_with("lib/packages.lock.json pins"), + "{detail}" + ); + } + // ── revert_lock_record pure edges ────────────────────────────────────── /// The package the fixture lock and config records belong to. diff --git a/crates/socket-patch-core/src/vex/verify.rs b/crates/socket-patch-core/src/vex/verify.rs index 3e50d378b..57dfcf26c 100644 --- a/crates/socket-patch-core/src/vex/verify.rs +++ b/crates/socket-patch-core/src/vex/verify.rs @@ -218,11 +218,20 @@ pub async fn applied_patches_with_copies( vendor.and_then(|ctx| lookup_entry(&ctx.entries, purl).map(|e| (ctx, e))); let result = if let Some((ctx, entry)) = vendor_entry { match verify_vendored_patch_record(&ctx.project_root, entry, record).await { - // The artifact holds the patch; the Bun lock must also be - // pinned to these very bytes for an install to deliver it. - Ok(()) if entry.flavor.as_deref() == Some("bun") => { - match crate::vendor::bun_lock::lock_pin_mismatch(entry, &ctx.project_root).await - { + // The artifact holds the patch; a lock that pins its + // content must also pin these very bytes for an install to + // deliver it: Bun's lock, and NuGet's, whose pin is all that + // tells the vendored package from the upstream one of the + // same id and version in the global packages folder. + Ok(()) => { + let mismatch = if entry.flavor.as_deref() == Some("bun") { + crate::vendor::bun_lock::lock_pin_mismatch(entry, &ctx.project_root).await + } else if entry.ecosystem == "nuget" { + crate::vendor::nuget_feed::lock_pin_mismatch(entry, &ctx.project_root).await + } else { + None + }; + match mismatch { Some(_) => Err("vendor_lock_pin_mismatch".to_string()), None => Ok(()), }