From 7e1149adefaef1725e7bb241d4c59698638d10e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 15:12:40 +0000 Subject: [PATCH 1/8] Start nuget-lock-pin Refs #2381. Assisted-by: Claude Code From 3d4f0aa96ce7d37ba9f6c3c93a1043732f04ac96 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 15:23:57 +0000 Subject: [PATCH 2/8] Omit a NuGet patch whose lock pins other bytes A vendored NuGet package keeps its id and version, so the `contentHash` in `packages.lock.json` is all that tells it from the upstream package in NuGet's global packages folder, which NuGet restores from before it asks any source. `vendor` pins that hash to the vendored nupkg. `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 then takes the upstream package, `--locked-mode` included. `vex` attested such a package `not_affected`: it read the pin for Bun's lock only. `nuget_feed::lock_pin_mismatch` reads it the way the writer's in-sync check does, over every lock a project under the root restores into, and `vex` omits the patch with `vendor_lock_pin_mismatch` when an entry of the patched version pins a hash that is not the committed nupkg's. Refs #2381. Assisted-by: Claude Code --- .../src/vendor/nuget_feed.rs | 183 ++++++++++++++++++ crates/socket-patch-core/src/vex/verify.rs | 19 +- 2 files changed, 197 insertions(+), 5 deletions(-) diff --git a/crates/socket-patch-core/src/vendor/nuget_feed.rs b/crates/socket-patch-core/src/vendor/nuget_feed.rs index a5fb4f554..e84d7d8df 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -2340,6 +2340,65 @@ 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 ([`nuget_prelude`]'s `lock_ok`), read the same way: +/// `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); + let artifact = entry.artifact.path.trim_start_matches("./"); + 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; + }; + let Ok(doc) = lock_value(&text) else { + continue; + }; + let pins: Vec<&str> = locked_at(&doc, &id, &version_norm) + .filter_map(|locked| locked.content_hash) + .collect(); + if pins.is_empty() { + continue; + } + // Read once, and only for a project that locks the package. + if expected.is_none() { + let bytes = read_zip_artifact(&project_root.join(artifact)).await?; + expected = Some(sha512_base64_of(&bytes)); + } + if pins.iter().any(|pin| Some(*pin) != 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 vendor` (or `socket-patch scan --mode vendored`) \ + to pin the lock again, then delete the directory of the package that its \ + warning names" + )); + } + } + None +} + /// 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. @@ -5737,6 +5796,130 @@ 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}"); + assert!(detail.contains("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); + + // 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); + } + + /// 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(()), } From 68f0e2b9d292a538f6070138b1969a6f643ac920 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 15:23:57 +0000 Subject: [PATCH 3/8] Fail vendor --check on a stale NuGet lock pin `vendor --check` reported "committed artifact and wiring verified" for a vendored NuGet package whose lock pins the upstream `contentHash` again: the config still maps the id to the vendored feed, and nothing compared the pin. It now fails that package, names the lock, and says how to pin it again. The CLI tests vendor the NuGet fixture, put the upstream pins back as `dotnet restore --force-evaluate` does, and run `vendor --check` and `vex`: both packages fail and none is attested, one stale entry fails its own package only, and a wet `vendor` pins the lock again, after which both commands pass. Refs #2381. Assisted-by: Claude Code --- .../socket-patch-cli/src/commands/vendor.rs | 5 + crates/socket-patch-cli/tests/vendor/main.rs | 3 + .../tests/vendor/vendor_nuget_lock_pin.rs | 130 ++++++++++++++++++ 3 files changed, 138 insertions(+) create mode 100644 crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index fa7cdac29..a6fc99268 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -1632,6 +1632,11 @@ async fn run_check(args: &VendorArgs) -> i32 { .await .err(); } + // A NuGet lock that pins other bytes restores those, whatever the + // config routes: the pin is read as the writer reads it. + if failure.is_none() && entry.ecosystem == "nuget" { + failure = vendor::nuget_feed::lock_pin_mismatch(entry, root).await; + } if let (None, Some(discovery), false) = ( &failure, &discovery, diff --git a/crates/socket-patch-cli/tests/vendor/main.rs b/crates/socket-patch-cli/tests/vendor/main.rs index 0325f0412..af5aa9ef3 100644 --- a/crates/socket-patch-cli/tests/vendor/main.rs +++ b/crates/socket-patch-cli/tests/vendor/main.rs @@ -22,10 +22,13 @@ 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; +#[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..55d1381ca --- /dev/null +++ b/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs @@ -0,0 +1,130 @@ +//! 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}")) +} + +/// The control: the lock `vendor` wrote is verified and attested. +#[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}"); +} + +/// 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}" + ); + + // The remedy the failure names: a wet run pins the lock again. + assert!(out.contains("re-run `socket-patch vendor`"), "{out}"); + let (code, stdout, stderr) = f.vendor(&[], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + 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}"); +} From 0c9a26e7060fe49f309dc7774f9b3239bd3dc822 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 15:27:27 +0000 Subject: [PATCH 4/8] Say a stale NuGet pin is what a re-vendor fixes Over a vendored NuGet package whose lock pins other bytes, `vendor --dry-run` said "already vendored; nothing to do" where the wet run pins the lock again, and the wet run explained itself with "the committed vendored nupkg was missing or stale", which it was not. The dry run counts such a package as one it would vendor: the ledger recording the patch is its tell for "in sync", and the lock pin is the one thing the ledger does not tell. The wet run's `vendor_artifact_rebuilt` warning says a lock pinned other bytes and was pinned again. Refs #2381. Assisted-by: Claude Code --- .../socket-patch-cli/src/commands/vendor.rs | 18 ++++++++--- .../tests/vendor/vendor_nuget_lock_pin.rs | 31 +++++++++++++++++-- .../src/vendor/nuget_feed.rs | 26 ++++++++++++---- 3 files changed, 63 insertions(+), 12 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index a6fc99268..e373cabe9 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -4967,10 +4967,20 @@ 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. - 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); + let recorded = lookup_entry(&state.entries, candidate) + .filter(|e| common.dry_run && e.uuid == record.uuid); + // One thing the ledger does not tell: a NuGet lock + // that pins other bytes, which the wet run pins again. + let pin_stale = match recorded { + Some(e) if e.ecosystem == "nuget" => { + vendor::nuget_feed::lock_pin_mismatch(e, &common.cwd) + .await + .is_some() + } + _ => false, + }; + let dry_previewed_in_sync = + event.action == PatchAction::Verified && recorded.is_some() && !pin_stale; if dry_previewed_in_sync { dry_in_sync += 1; } 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 index 55d1381ca..5d810972e 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs @@ -54,7 +54,17 @@ fn vex(f: &Fixture) -> (Vec, String) { (attested, format!("{stdout}\n{stderr}")) } -/// The control: the lock `vendor` wrote is verified and attested. +/// `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(); @@ -62,6 +72,8 @@ fn nuget_lock_pinned_to_the_vendored_nupkg_is_verified() { 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 @@ -90,10 +102,25 @@ fn nuget_lock_pinned_to_other_bytes_is_not_verified() { "{vex_out}" ); - // The remedy the failure names: a wet run pins the lock again. + // 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 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 + ); 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_eq!(std::fs::read_to_string(f.root.join(LOCK)).unwrap(), pinned); let (code, out) = check(&f); assert_eq!(code, 0, "{out}"); diff --git a/crates/socket-patch-core/src/vendor/nuget_feed.rs b/crates/socket-patch-core/src/vendor/nuget_feed.rs index e84d7d8df..dffbfafe7 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -194,6 +194,9 @@ 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: + /// what the re-vendor's warning then says was stale. + pin_stale: bool, } async fn nuget_prelude( @@ -387,7 +390,7 @@ 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; @@ -415,7 +418,9 @@ async fn nuget_prelude( } _ => false, }; - nupkg_ok && lock_ok + (nupkg_ok && lock_ok, nupkg_ok && !lock_ok) + } else { + (false, false) }; Ok(NugetPrelude { name: name.to_string(), @@ -436,6 +441,7 @@ async fn nuget_prelude( locks, config_wired, in_sync, + pin_stale, }) } @@ -637,6 +643,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, @@ -765,13 +772,20 @@ 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 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. From a15bd7a324cadbe2e2783ea69a06ccfa71f88f70 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 15:39:32 +0000 Subject: [PATCH 5/8] Name the stale global copy when a pin is redone The warning that NuGet's global packages folder holds the upstream copy of a vendored package (`vendor_nuget_stale_global_package`) was raised by the first vendor and by an in-sync re-run, and not by the run that rebuilds a wired package. That is the run which follows a `dotnet restore --force-evaluate`: it pinned the lock again and left the copy that made NuGet rewrite it unnamed, so the next restore failed NU1403 once more. The three paths raise the warning through one helper, `stale_global_package`. Refs #2381. Assisted-by: Claude Code --- .../tests/vendor/vendor_nuget_lock_pin.rs | 12 ++ .../src/vendor/nuget_feed.rs | 112 ++++++++++++++---- 2 files changed, 101 insertions(+), 23 deletions(-) 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 index 5d810972e..e4c00f188 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs @@ -114,6 +114,13 @@ fn nuget_lock_pinned_to_other_bytes_is_not_verified() { 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!( @@ -121,6 +128,11 @@ fn nuget_lock_pinned_to_other_bytes_is_not_verified() { && !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}"); diff --git a/crates/socket-patch-core/src/vendor/nuget_feed.rs b/crates/socket-patch-core/src/vendor/nuget_feed.rs index dffbfafe7..13f113619 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -669,21 +669,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 { @@ -786,6 +775,10 @@ pub async fn vendor_nuget( ), }; 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. @@ -985,14 +978,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); @@ -1083,6 +1069,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). @@ -3373,6 +3379,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 From 01383cecf93db3ca925aa75c2f6530af16a0a91a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 15:42:40 +0000 Subject: [PATCH 6/8] Call a vendored nupkg an artifact, not a tarball `vex` explains `vendor_lock_pin_mismatch` with one sentence, written when Bun's lock was the only one with a pin: "the lockfile pins the vendored tarball to a sha512". A NuGet lock now gets the same code, and its artifact is a nupkg. The sentence says "artifact". Refs #2381. Assisted-by: Claude Code --- crates/socket-patch-cli/src/commands/vex.rs | 2 +- crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) 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/vendor_nuget_lock_pin.rs b/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs index e4c00f188..55590e323 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs @@ -98,7 +98,9 @@ fn nuget_lock_pinned_to_other_bytes_is_not_verified() { ); } assert!( - vex_out.contains("(vendor_lock_pin_mismatch): Fx.Alpha@1.0.0, Fx.Beta@1.0.0"), + 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}" ); From ca76141edcaa95e1997b7af9462360a6ade5645f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 16:04:07 +0000 Subject: [PATCH 7/8] Take the review's findings on the NuGet lock pin - The remedy named `socket-patch vendor` first, which does nothing in a project with no manifest (what `scan --mode vendored` leaves). It now leads with `socket-patch scan --mode vendored`, which pins the lock again in both. - `vendor --check` ran the pin check before the liveness rule, so a package whose config and lock were both put back was reported with the pin's text where `vex` says `vendor_unwired`. The pin is judged after liveness, on a package that is wired. - The dry run's tally asked the pin check for every NuGet package. NuGet's backend reports an in-sync package as `already_vendored` on a dry run too, so a `verified` preview of one is never in sync, and the tally says so without reading the tree. That also covers a package whose config was put back. - `pin_stale` was "the nupkg is in sync and the lock is not", wider than a lock that pins other bytes. The prelude and the check now share one predicate, `pins_other_bytes`. - The check does not read an artifact path that leaves the root, and the dead `./` trim is gone. Refs #2381. Assisted-by: Claude Code --- .../socket-patch-cli/src/commands/vendor.rs | 33 ++--- crates/socket-patch-cli/tests/vendor/main.rs | 2 + .../tests/vendor/vendor_nuget_lock_pin.rs | 40 +++++- .../src/vendor/nuget_feed.rs | 121 ++++++++++++------ 4 files changed, 137 insertions(+), 59 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index e373cabe9..4c32e93d6 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -1632,11 +1632,6 @@ async fn run_check(args: &VendorArgs) -> i32 { .await .err(); } - // A NuGet lock that pins other bytes restores those, whatever the - // config routes: the pin is read as the writer reads it. - if failure.is_none() && entry.ecosystem == "nuget" { - failure = vendor::nuget_feed::lock_pin_mismatch(entry, root).await; - } if let (None, Some(discovery), false) = ( &failure, &discovery, @@ -1650,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). @@ -4967,20 +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. - let recorded = lookup_entry(&state.entries, candidate) - .filter(|e| common.dry_run && e.uuid == record.uuid); - // One thing the ledger does not tell: a NuGet lock - // that pins other bytes, which the wet run pins again. - let pin_stale = match recorded { - Some(e) if e.ecosystem == "nuget" => { - vendor::nuget_feed::lock_pin_mismatch(e, &common.cwd) - .await - .is_some() - } - _ => false, - }; - let dry_previewed_in_sync = - event.action == PatchAction::Verified && recorded.is_some() && !pin_stale; + // 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 && e.ecosystem != "nuget"); if dry_previewed_in_sync { dry_in_sync += 1; } diff --git a/crates/socket-patch-cli/tests/vendor/main.rs b/crates/socket-patch-cli/tests/vendor/main.rs index af5aa9ef3..1d41a19b8 100644 --- a/crates/socket-patch-cli/tests/vendor/main.rs +++ b/crates/socket-patch-cli/tests/vendor/main.rs @@ -27,6 +27,8 @@ 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"] 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 index 55590e323..d408f3738 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs @@ -106,7 +106,10 @@ fn nuget_lock_pinned_to_other_bytes_is_not_verified() { // 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 vendor`"), "{out}"); + 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"), @@ -169,3 +172,38 @@ fn nuget_lock_pin_is_judged_per_package() { 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 +/// as well as the lock, nothing routes the package to the vendored feed: +/// the check names the wiring that is gone, as `vex` does, and a dry run +/// would vendor both again. +#[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}"); + std::fs::write(f.root.join("nuget.config"), &config).unwrap(); + std::fs::write(f.root.join(LOCK), &lock).unwrap(); + + let (code, out) = check(&f); + assert_eq!(code, 1, "{out}"); + for purl in [ALPHA, BETA] { + assert!( + out.contains(&format!("{purl}: wiring missing")), + "the failure is the liveness rule's: {out}" + ); + } + assert!(!out.contains("contentHash"), "{out}"); + let (attested, out) = vex(&f); + assert!( + attested.is_empty() && out.contains("(vendor_unwired)"), + "{out}" + ); + let out = dry_run(&f); + assert!( + out.contains("Would vendor 2 packages") && !out.contains("nothing to do"), + "{out}" + ); +} diff --git a/crates/socket-patch-core/src/vendor/nuget_feed.rs b/crates/socket-patch-core/src/vendor/nuget_feed.rs index 13f113619..c95222846 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -194,8 +194,9 @@ 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: - /// what the re-vendor's warning then says was stale. + /// 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, } @@ -392,33 +393,34 @@ async fn nuget_prelude( } 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, nupkg_ok && !lock_ok) + } } else { (false, false) }; @@ -2373,15 +2375,20 @@ fn lock_pinned(text: &str, id: &str, version_norm: &str, expected_hash: &str) -> /// 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 ([`nuget_prelude`]'s `lock_ok`), read the same way: -/// `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). +/// 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); - let artifact = entry.artifact.path.trim_start_matches("./"); + // 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 @@ -2391,34 +2398,47 @@ pub async fn lock_pin_mismatch(entry: &VendorEntry, project_root: &Path) -> Opti let Ok(text) = read_regular_to_string(&project_root.join(&rel)).await else { continue; }; - let Ok(doc) = lock_value(&text) else { - continue; - }; - let pins: Vec<&str> = locked_at(&doc, &id, &version_norm) - .filter_map(|locked| locked.content_hash) - .collect(); - if pins.is_empty() { + if !pins_any_bytes(&text, &id, &version_norm) { continue; } - // Read once, and only for a project that locks the package. + // 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.iter().any(|pin| Some(*pin) != expected.as_deref()) { + 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 vendor` (or `socket-patch scan --mode vendored`) \ - to pin the lock again, then delete the directory of the package that its \ - warning names" + 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. @@ -5921,7 +5941,11 @@ mod tests { "{detail}" ); assert!(detail.contains(©_rel()), "{detail}"); - assert!(detail.contains("socket-patch vendor"), "{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); @@ -5961,6 +5985,25 @@ mod tests { 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); + + // An artifact path that leaves the root is not read. + tokio::fs::write(&lock, lock_json(&upstream)).await.unwrap(); + let mut outside = entry_with_wiring(UUID, Vec::new()); + outside.artifact.path = format!("../{}", copy_rel()); + assert_eq!(lock_pin_mismatch(&outside, root).await, None); + // A lock that is not JSON. tokio::fs::write(&lock, "<<<<<<< HEAD\n").await.unwrap(); assert_eq!(pin_mismatch(root).await, None); From 2e5af5779bee16164514a5a0a27518525fdb7e4d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 16:18:42 +0000 Subject: [PATCH 8/8] Make three NuGet pin tests fail for their reason A second review pass found the production change sound and three assertions that could not fail for the reason they named. - The row for an artifact path that leaves the root named a path with nothing at it, so it passed with or without the guard. It is a test of its own now, with a nupkg the lock does not pin at that path; with the guard removed it fails. - The unwired test put the config and the lock back together, a state the first dry-run rule already got right. It now checks the config put back alone, with the lock still pinned, and then both. - Nothing held the predicate the prelude's `pin_stale` goes by; `pins_other_bytes` has its rows. Refs #2381. Assisted-by: Claude Code --- .../tests/vendor/vendor_nuget_lock_pin.rs | 46 +++++++------- .../src/vendor/nuget_feed.rs | 61 +++++++++++++++++-- 2 files changed, 80 insertions(+), 27 deletions(-) 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 index d408f3738..1c248435c 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_nuget_lock_pin.rs @@ -174,9 +174,9 @@ fn nuget_lock_pin_is_judged_per_package() { } /// The pin is judged on a package that is wired. With the config put back -/// as well as the lock, nothing routes the package to the vendored feed: +/// 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. +/// 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"); @@ -184,26 +184,30 @@ fn nuget_package_with_no_wiring_left_is_reported_as_unwired() { 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}"); - std::fs::write(f.root.join("nuget.config"), &config).unwrap(); - std::fs::write(f.root.join(LOCK), &lock).unwrap(); - let (code, out) = check(&f); - assert_eq!(code, 1, "{out}"); - for purl in [ALPHA, BETA] { + 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!( - out.contains(&format!("{purl}: wiring missing")), - "the failure is the liveness rule's: {out}" + attested.is_empty() && out.contains("(vendor_unwired)"), + "{state}: {out}" ); - } - assert!(!out.contains("contentHash"), "{out}"); - let (attested, out) = vex(&f); - assert!( - attested.is_empty() && out.contains("(vendor_unwired)"), - "{out}" - ); - let out = dry_run(&f); - assert!( - out.contains("Would vendor 2 packages") && !out.contains("nothing to do"), - "{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 c95222846..de5c142a1 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -5998,12 +5998,6 @@ mod tests { tokio::fs::write(&lock, &beside).await.unwrap(); assert_eq!(pin_mismatch(root).await, None); - // An artifact path that leaves the root is not read. - tokio::fs::write(&lock, lock_json(&upstream)).await.unwrap(); - let mut outside = entry_with_wiring(UUID, Vec::new()); - outside.artifact.path = format!("../{}", copy_rel()); - assert_eq!(lock_pin_mismatch(&outside, root).await, None); - // A lock that is not JSON. tokio::fs::write(&lock, "<<<<<<< HEAD\n").await.unwrap(); assert_eq!(pin_mismatch(root).await, None); @@ -6014,6 +6008,61 @@ mod tests { 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]