From 489824e4d83965e82f4d1380af7c73a6911fb3ec Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 18:31:03 -0500 Subject: [PATCH 001/120] Move a gem's platform builds together once one of them is patched MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A gem patch's reference now lists every platform gem of the gem's version (`registryOverride.identifiers.gemBuilds`): for each platform the sha256 the patch registry serves and, where there is a patched build, the patch it comes from. A platform with none is served as upstream's own gem, which the registry lists and hands on unchanged. The registry URL carries the snapshot the list was made at (`…//s/`); a later reference names a newer one. This replaces the list of patched platforms only (`gemPlatforms`), under which a lock moved only when every locked platform had a patched build, and one platform without one kept the whole gem unpatched. The gem rewriter: - moves every locked build to the registry together as soon as one of them is patched, each pinned to the sha256 the registry serves for it (a platform still on upstream's gem keeps the sha256 it had); - leaves the gem where it is, with no warning, while no locked build is patched: moving it would gain nothing (`gem_unpatched`); - still skips with `redirect_gem_platform_unsupported` when the registry does not list a locked platform, or the reference carries no list at all (a patch of the ruby gem alone, as before); - reports per locked build which patch is in place and whether this run put it there (`gem_builds`). A registry URL is recognised with any snapshot or none, under any grant token, by the manifest wiring, the lock rewrite and lockfile discovery, so a pair an earlier run wired is refreshed in place when the snapshot changes. A snapshot URL is written closed by a slash, as Bundler writes every remote. The pin of a gem stays one per package. `engine::pin_reports` turns the confirmed pins into what a run reports: a gem locked as platform builds once per locked build, each patched build under its own patch, each build on upstream's gem with none. `engine::gem_unpatched_skips` gives the quiet skip of a gem that was left alone. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/scan/hosted.rs | 4 +- crates/socket-patch-core/src/api/types.rs | 101 ++- crates/socket-patch-core/src/hosted/engine.rs | 210 +++++- .../src/patch/redirect/grant.rs | 34 +- .../src/patch/redirect/mod.rs | 643 +++++++++++++++--- .../socket-patch-core/src/vex/discover/gem.rs | 42 +- .../platform-prebuild-missing/overrides.json | 7 +- .../platform-prebuilds-rerun/input/Gemfile | 2 +- .../input/Gemfile.lock | 2 +- .../platform-prebuilds-rerun/overrides.json | 10 +- .../platform-prebuilds/expected-edits.json | 4 +- .../platform-prebuilds/expected/Gemfile | 2 +- .../platform-prebuilds/expected/Gemfile.lock | 2 +- .../bundler/platform-prebuilds/overrides.json | 10 +- .../vex-discover-golden/redirect-gem.json | 4 +- .../tests/upstream_restore_golden.rs | 16 +- 16 files changed, 904 insertions(+), 189 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 40a94ae948..72ef58b692 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -1032,7 +1032,7 @@ async fn refresh_stale_gems( .iter() .filter(|o| o.ecosystem == "gem" && o.name == name && o.version == version) .filter_map(|o| o.registry_override.as_ref()) - .flat_map(|ro| &ro.identifiers.gem_platforms) + .flat_map(|ro| ro.identifiers.gem_builds.iter().flatten()) .filter(|prebuild| Some(prebuild.platform.as_str()) == platform) .map(|prebuild| prebuild.gem_checksum_sha256.to_ascii_lowercase()) .collect(); @@ -2345,7 +2345,7 @@ async fn run_redirect_selected_untracked( let prebuilds = o .registry_override .iter() - .flat_map(|ro| &ro.identifiers.gem_platforms) + .flat_map(|ro| ro.identifiers.gem_builds.iter().flatten()) .map(|prebuild| prebuild.gem_checksum_sha256.clone()); for sha in sha.into_iter().chain(prebuilds) { gem_artifact_shas diff --git a/crates/socket-patch-core/src/api/types.rs b/crates/socket-patch-core/src/api/types.rs index cbb947141e..6a5a5289e8 100644 --- a/crates/socket-patch-core/src/api/types.rs +++ b/crates/socket-patch-core/src/api/types.rs @@ -762,13 +762,17 @@ mod tests { ); } - /// A gem patch with a built prebuild: the per-platform artifacts carry - /// `platform`, and the override lists each platform's sha256 under - /// `gemPlatforms`. Both are absent from a patch with no prebuild, which - /// reads as none. + /// A gem patch whose registry lists the version's platform gems: the + /// override names every one under `gemBuilds`, with the sha256 the + /// registry serves and the patch of a patched build (`patchUuid`, + /// `null` where the registry hands on upstream's gem), and the index + /// URL carries the snapshot. A reference with no `gemBuilds` reads as + /// no list, which is not an empty one. #[test] - fn package_vendor_result_reads_gem_prebuilds() { + fn package_vendor_result_reads_gem_builds() { let sha = "ab".repeat(32); + let upstream = "cd".repeat(32); + let built = "9f6b2c4e-1d3a-4f6b-8c2d-7e5a9b1c3d5f"; let json = serde_json::json!({ "status": "granted", "purl": "pkg:gem/nokogiri@1.18.10?platform=ruby", @@ -786,12 +790,15 @@ mod tests { ], "registryOverride": { "kind": "rubygems-compact-index", - "indexUrl": "https://patch.socket.dev/patch-registry/gem/t/u/", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/t/u/s/3", "identifiers": { "name": "nokogiri", "version": "1.18.10", "gemChecksumSha256": sha, - "gemPlatforms": [ - { "platform": "x86_64-linux-gnu", "gemChecksumSha256": sha } + "gemBuilds": [ + { "platform": "arm64-darwin", "gemChecksumSha256": upstream, + "patchUuid": null }, + { "platform": "x86_64-linux-gnu", "gemChecksumSha256": sha, + "patchUuid": built } ] } } @@ -810,32 +817,62 @@ mod tests { ("gem-platform-stub-gemspec", Some("x86_64-linux-gnu")), ] ); - let ids = result.registry_override.unwrap().identifiers; - assert_eq!(ids.gem_platforms.len(), 1); - assert_eq!(ids.gem_platforms[0].platform, "x86_64-linux-gnu"); - assert_eq!(ids.gem_platforms[0].gem_checksum_sha256, sha); + let registry = result.registry_override.unwrap(); + assert!(registry.index_url.ends_with("/u/s/3")); + let ids = registry.identifiers; + let builds = ids.gem_builds.as_deref().expect("the list"); + let read: Vec<_> = builds + .iter() + .map(|b| { + ( + b.platform.as_str(), + b.gem_checksum_sha256.as_str(), + b.patch_uuid.as_deref(), + ) + }) + .collect(); + assert_eq!( + read, + [ + ("arm64-darwin", upstream.as_str(), None), + ("x86_64-linux-gnu", sha.as_str(), Some(built)), + ] + ); + assert_eq!( + ids.gem_build("x86_64-linux-gnu") + .and_then(|b| b.patch_uuid.as_deref()), + Some(built) + ); + assert!(ids.gem_build("java").is_none()); - let mut bare = json; + let mut bare = json.clone(); bare["registryOverride"]["identifiers"] .as_object_mut() .unwrap() - .remove("gemPlatforms"); + .remove("gemBuilds"); let result: PackageVendorResult = serde_json::from_value(bare).unwrap(); assert!(result .registry_override .unwrap() .identifiers - .gem_platforms - .is_empty()); + .gem_builds + .is_none()); + // A list with nothing in it is a list: the version has no platform gem. + let mut empty = json; + empty["registryOverride"]["identifiers"]["gemBuilds"] = serde_json::json!([]); + let result: PackageVendorResult = serde_json::from_value(empty).unwrap(); + let ids = result.registry_override.unwrap().identifiers; + assert_eq!(ids.gem_builds.as_deref(), Some(&[][..])); } /// One reference response answers for every package of a batch. A - /// `gemPlatforms` the service sends as `null`, or with an entry that + /// `gemBuilds` the service sends as `null`, or with an entry that /// lacks its platform or its checksum, must not cost the other packages - /// (or the gem itself) their grants: `null` is no prebuild, and such an - /// entry is dropped, leaving that platform without one. + /// (or the gem itself) their grants: `null` is no list, and such an + /// entry is dropped, leaving that platform unlisted. A `patchUuid` that + /// is no string is no patch. #[test] - fn a_malformed_gem_platforms_field_never_fails_the_batch() { + fn a_malformed_gem_builds_field_never_fails_the_batch() { let sha = "ab".repeat(32); let gem = |platforms: serde_json::Value| { serde_json::json!({ @@ -853,7 +890,7 @@ mod tests { "identifiers": { "name": "nokogiri", "version": "1.18.10", "gemChecksumSha256": sha, - "gemPlatforms": platforms + "gemBuilds": platforms } } }) @@ -870,7 +907,8 @@ mod tests { { "platform": 3, "gemChecksumSha256": sha }, "x86_64-linux-gnu", null, - { "platform": "x86_64-linux-gnu", "gemChecksumSha256": sha } + { "platform": "x86_64-linux-gnu", "gemChecksumSha256": sha, + "patchUuid": 7 } ])), "npm": { "status": "granted", "url": "https://patch.socket.dev/x.tgz" } } @@ -882,16 +920,19 @@ mod tests { assert_eq!(result.status, "granted"); let ids = &result.registry_override.as_ref().unwrap().identifiers; assert_eq!(ids.gem_checksum_sha256.as_deref(), Some(sha.as_str())); - ids.gem_platforms - .iter() - .map(|p| (p.platform.clone(), p.gem_checksum_sha256.clone())) - .collect::>() + ids.gem_builds.as_ref().map(|builds| { + assert!(builds.iter().all(|b| b.patch_uuid.is_none())); + builds + .iter() + .map(|p| (p.platform.clone(), p.gem_checksum_sha256.clone())) + .collect::>() + }) }; - assert!(prebuilds("null-list").is_empty()); - assert!(prebuilds("no-list").is_empty()); + assert!(prebuilds("null-list").is_none()); + assert!(prebuilds("no-list").is_none()); assert_eq!( - prebuilds("holes"), - [("x86_64-linux-gnu".to_string(), sha.clone())], + prebuilds("holes").as_deref(), + Some(&[("x86_64-linux-gnu".to_string(), sha.clone())][..]), "only the entry that names a platform and a checksum is a prebuild" ); let artifacts = response.results["holes"].artifacts.as_deref().unwrap(); diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index c47082ffd8..08affff077 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -135,6 +135,100 @@ pub fn unconfirmed_candidates( .collect() } +/// Skip reason of a gem the Bundler lock names as precompiled platform +/// builds, left on its upstream registry because the patch registry has no +/// patched build yet for any platform the lock names: moving it would gain +/// nothing. Not a warning. The gem moves on a later run, once the patch +/// service lists a patched build for one of those platforms. +pub const GEM_NO_PATCHED_BUILD: &str = "redirect_gem_no_patched_build"; + +/// Code of the uncounted event of one locked platform build of a hosted +/// gem that the patch registry serves as upstream's own gem (no patched +/// build yet): that platform installs what it installed before, and is +/// neither counted nor attested as patched. +pub const GEM_UPSTREAM_BUILD_KEPT: &str = "gem_upstream_build_kept"; + +/// The skips of the gems a rewrite left on their upstream registry because +/// no locked build of them is patched yet +/// ([`RewriteResult::gem_unpatched`]), one per candidate, in candidate +/// order: a host adds them to its skips, so the gem is reported under +/// [`GEM_NO_PATCHED_BUILD`] and not as a patch nothing pins. +pub fn gem_unpatched_skips(candidates: &[Candidate], rewrite: &RewriteResult) -> Vec { + candidates + .iter() + .filter_map(|c| { + let platforms = rewrite.gem_unpatched.get(&c.dep.patch_uuid)?; + let detail = format!( + "{} {}: no patched build yet for {}; left on its upstream registry", + c.dep.name, + c.dep.version, + platforms.join(", ") + ); + Some(SkippedPatch { + detail: Some(detail), + ..SkippedPatch::new(&c.purl, &c.dep.patch_uuid, GEM_NO_PATCHED_BUILD) + }) + }) + .collect() +} + +/// One thing a hosted run reports for a confirmed pin: the pin itself, or, +/// for a gem the lock names as platform builds, one per locked build +/// ([`pin_reports`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PinReport { + /// What is reported: the pin's purl, or + /// `pkg:gem/@?platform=` for a platform gem. + pub purl: String, + /// The patch in place for it. `None` for a platform gem the patch + /// registry serves as upstream's own (no patched build yet): it is + /// reported ([`GEM_UPSTREAM_BUILD_KEPT`]) and never counted or + /// attested as patched. + pub uuid: Option, + /// For a build of a gem locked as platform builds: the gem patch's + /// uuid, the one pin all its builds go by. + pub gem_fix: Option, + /// For such a build: its platform (`None` for the ruby-platform gem). + pub platform: Option, + /// For such a build: whether this run put its patched build in place. + pub newly_patched: bool, +} + +/// What a hosted run reports for its confirmed pins (`(purl, uuid)`): each +/// pin once, except a gem the lock names as platform builds +/// ([`RewriteResult::gem_builds`]), which is reported per locked build: +/// each patched build under its own patch, each build that keeps +/// upstream's gem with no patch. The pins stay what every other step works +/// with (one per package); this is the one place they become per-build +/// outcomes, for the disk host and the in-memory engine alike. +pub fn pin_reports(confirmed: &[(String, String)], rewrite: &RewriteResult) -> Vec { + let mut reports = Vec::with_capacity(confirmed.len()); + for (purl, uuid) in confirmed { + let Some(builds) = rewrite.gem_builds.get(uuid) else { + reports.push(PinReport { + purl: purl.clone(), + uuid: Some(uuid.clone()), + gem_fix: None, + platform: None, + newly_patched: false, + }); + continue; + }; + let base = crate::utils::purl::strip_purl_qualifiers(purl); + reports.extend(builds.iter().map(|build| PinReport { + purl: match &build.platform { + Some(platform) => format!("{base}?platform={platform}"), + None => purl.clone(), + }, + uuid: build.patch_uuid.clone(), + gem_fix: Some(uuid.clone()), + platform: build.platform.clone(), + newly_patched: build.newly_patched, + })); + } + reports +} + /// A selected patch that was not redirected, and why (the `skipped[]` /// entries of the `redirect` block). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -7201,7 +7295,7 @@ mod tests { "identifiers": { "name": "nokogiri", "version": "1.18.10", "gemChecksumSha256": "a".repeat(64), - "gemPlatforms": [ + "gemBuilds": [ {"platform": "arm64-darwin", "gemChecksumSha256": "not-a-digest"} ] } @@ -12940,14 +13034,17 @@ snapshots: .as_mut() .unwrap() .identifiers - .gem_platforms = ["arm64-darwin", "x86_64-linux-gnu"] - .iter() - .zip(["a", "b"]) - .map(|(platform, digit)| GemPlatformChecksum { - platform: platform.to_string(), - gem_checksum_sha256: digit.repeat(64), - }) - .collect(); + .gem_builds = Some( + ["arm64-darwin", "x86_64-linux-gnu"] + .iter() + .zip(["a", "b"]) + .map(|(platform, digit)| GemPlatformChecksum { + platform: platform.to_string(), + gem_checksum_sha256: digit.repeat(64), + patch_uuid: Some(format!("77777777-7777-4777-8777-77777777777{digit}")), + }) + .collect(), + ); let lock = format!( "GEM\n remote: https://rubygems.org/\n specs:\n rails (7.0.0-arm64-darwin)\n rails \ (7.0.0-x86_64-linux-gnu)\n\nPLATFORMS\n arm64-darwin\n x86_64-linux-gnu\n\nDEPENDENCIES\n \ @@ -12965,6 +13062,32 @@ snapshots: done.confirmed, [("pkg:gem/rails@7.0.0".to_string(), FIXTURE_UUID.to_string())] ); + // The one pin is reported per locked build, each under its own + // patch, and both as newly patched. + let reported: Vec<(String, Option, bool)> = + pin_reports(&done.confirmed, &done.rewrite) + .into_iter() + .map(|report| { + assert_eq!(report.gem_fix.as_deref(), Some(FIXTURE_UUID)); + (report.purl, report.uuid, report.newly_patched) + }) + .collect(); + assert_eq!( + reported, + [ + ( + "pkg:gem/rails@7.0.0?platform=arm64-darwin".to_string(), + Some("77777777-7777-4777-8777-77777777777a".to_string()), + true + ), + ( + "pkg:gem/rails@7.0.0?platform=x86_64-linux-gnu".to_string(), + Some("77777777-7777-4777-8777-77777777777b".to_string()), + true + ), + ] + ); + assert!(gem_unpatched_skips(std::slice::from_ref(&candidate), &done.rewrite).is_empty()); let written = &done.rewrite.files["Gemfile.lock"]; assert!( written.contains( @@ -12986,10 +13109,77 @@ snapshots: for (rel, text) in &done.rewrite.files { p.insert_text(rel, text.as_str()); } - let (_, again) = gem_rewrite_of(&ProjectView::Memory(&p), vec![candidate]).await; + let (_, again) = gem_rewrite_of(&ProjectView::Memory(&p), vec![candidate.clone()]).await; assert!(again.rewrite.files.is_empty(), "{:?}", again.rewrite.edits); assert_eq!(again.confirmed, done.confirmed); assert!(again.unattributed.is_empty(), "{:?}", again.unattributed); + let again_reports = pin_reports(&again.confirmed, &again.rewrite); + assert_eq!(again_reports.len(), 2); + assert!(again_reports.iter().all(|report| !report.newly_patched)); + + // A pin of any other package is reported as it is. + let npm = [("pkg:npm/a@1.0.0".to_string(), "u".to_string())]; + let [plain] = pin_reports(&npm, &done.rewrite) + .try_into() + .expect("one report"); + assert_eq!( + (plain.purl.as_str(), plain.uuid.as_deref()), + ("pkg:npm/a@1.0.0", Some("u")) + ); + assert!(plain.gem_fix.is_none()); + + // A registry that serves upstream's gem for one platform: that + // build is reported with no patch. With none patched, the gem + // stays where it is, and is skipped under its own quiet code. + let listing = |patched: &[bool]| { + let mut candidate = candidate.clone(); + let ids = &mut candidate + .dep + .registry_override + .as_mut() + .unwrap() + .identifiers; + for (build, patched) in ids.gem_builds.as_mut().unwrap().iter_mut().zip(patched) { + if !patched { + build.patch_uuid = None; + } + } + candidate + }; + let mut fresh = MemoryProject::new(); + fresh.insert_text("Gemfile", GEMFILE); + fresh.insert_text("Gemfile.lock", lock.as_str()); + let one = listing(&[true, false]); + let (_, mixed) = gem_rewrite_of(&ProjectView::Memory(&fresh), vec![one]).await; + assert_eq!(mixed.confirmed, done.confirmed); + let patched: Vec = pin_reports(&mixed.confirmed, &mixed.rewrite) + .iter() + .map(|report| report.uuid.is_some()) + .collect(); + assert_eq!(patched, [true, false]); + let none = listing(&[false, false]); + let (_, left) = gem_rewrite_of(&ProjectView::Memory(&fresh), vec![none.clone()]).await; + assert!(left.rewrite.files.is_empty() && left.confirmed.is_empty()); + assert!( + left.rewrite.warnings.is_empty(), + "{:?}", + left.rewrite.warnings + ); + let [skip] = gem_unpatched_skips(std::slice::from_ref(&none), &left.rewrite) + .try_into() + .expect("one skip"); + assert_eq!(skip.reason, GEM_NO_PATCHED_BUILD); + assert_eq!( + skip.detail.as_deref(), + Some( + "rails 7.0.0: no patched build yet for arm64-darwin, x86_64-linux-gnu; left on \ + its upstream registry" + ) + ); + assert!( + unconfirmed_candidates(std::slice::from_ref(&none), &left.confirmed, &[skip]) + .is_empty() + ); } /// #390: `bundle config set --local gemfile Gemfile.next` makes bundler diff --git a/crates/socket-patch-core/src/patch/redirect/grant.rs b/crates/socket-patch-core/src/patch/redirect/grant.rs index 695f5152e3..b87f760c2d 100644 --- a/crates/socket-patch-core/src/patch/redirect/grant.rs +++ b/crates/socket-patch-core/src/patch/redirect/grant.rs @@ -267,11 +267,13 @@ fn check_registry_override(ov: &RegistryOverride, origins: &[String]) -> Result< return Err(bad(what, "64 hex digits")); } } - // A prebuild's platform and sha256 are spelled into `Gemfile.lock` + // A platform gem's platform and sha256 are spelled into `Gemfile.lock` // (`name (version-) sha256=`) and its platform into the // gem file name a refresh downloads. One entry per platform: two would - // leave which sha256 the lock pins to their order. - for (at, prebuild) in ids.gem_platforms.iter().enumerate() { + // leave which sha256 the lock pins to their order. The patch of a + // patched build is reported and attested by its uuid. + let gem_builds = ids.gem_builds.as_deref().unwrap_or_default(); + for (at, prebuild) in gem_builds.iter().enumerate() { let platform = prebuild.platform.as_str(); if !is_plain_gem_token(platform) || platform.len() > MAX_COORDINATE @@ -283,12 +285,16 @@ fn check_registry_override(ov: &RegistryOverride, origins: &[String]) -> Result< if !is_hex(&prebuild.gem_checksum_sha256, 64) { return Err(bad("gem platform checksum", "64 hex digits")); } - if ids.gem_platforms[..at] + if gem_builds[..at] .iter() .any(|earlier| earlier.platform == platform) { return Err(bad("gem platform list", "one entry per platform")); } + let patch = prebuild.patch_uuid.as_deref(); + if patch.is_some_and(|uuid| !crate::patch::path_safety::is_canonical_uuid(uuid)) { + return Err(bad("gem platform patch", "a patch uuid")); + } } for (what, digest) in [ ("Maven pom sha256", &ids.maven_pom_sha256), @@ -633,15 +639,17 @@ mod tests { .as_mut() .unwrap() .identifiers - .gem_platforms = list - .iter() - .map( - |(platform, sha)| crate::patch::redirect::GemPlatformChecksum { - platform: platform.to_string(), - gem_checksum_sha256: sha.clone(), - }, - ) - .collect(); + .gem_builds = Some( + list.iter() + .map( + |(platform, sha)| crate::patch::redirect::GemPlatformChecksum { + platform: platform.to_string(), + gem_checksum_sha256: sha.clone(), + patch_uuid: None, + }, + ) + .collect(), + ); match field { None => assert_eq!(check(&dep, &[]), Ok(())), Some(field) => { diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index ef0a182c64..4c263ff557 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -202,25 +202,31 @@ pub struct RegistryOverrideIdentifiers { /// sha256 hex of the patched ruby-platform gem (`-.gem`), /// the value Bundler records in the lock's `CHECKSUMS`. pub gem_checksum_sha256: Option, - /// The patch's built prebuilds: one entry per platform the patch - /// registry also serves a patched `--.gem` - /// for. Empty (or absent) when it serves the ruby gem alone. The gem - /// rewriter moves a lock's platform entries only when every one of - /// them is listed here. - #[serde(default, deserialize_with = "lenient_gem_platforms")] - #[cfg_attr(test, serde(skip_serializing_if = "Vec::is_empty"))] - pub gem_platforms: Vec, + /// Every platform gem of the gem's version, as the patch registry + /// serves it under `index_url`: a patched build where one exists + /// (`patch_uuid`), else upstream's own gem, which the registry lists + /// and hands on unchanged. The list is complete, so a lock's platform + /// entries can all take the registry as their one source, each pinned + /// to the sha256 listed for it. `None` when the reference carries no + /// list (the service does not know the version's platforms): the patch + /// is then of the ruby gem alone, and a lock that names platform + /// builds is left as it is. + #[serde(default, deserialize_with = "lenient_gem_builds")] + #[cfg_attr(test, serde(skip_serializing_if = "Option::is_none"))] + pub gem_builds: Option>, } -/// `gemPlatforms` as the patch API may send it, read so that the field can +/// `gemBuilds` as the patch API may send it, read so that the field can /// never fail the response it rides in: one reference response answers for /// every package of a batch, and a strict reading of this optional list /// would cost all of them their grant. `null`, or anything that is no list, -/// is no prebuild. An entry without a `platform` or a `gemChecksumSha256` -/// string (missing, `null`, empty, another type) is dropped: that platform -/// has no prebuild, so a lock that names it keeps the skip. What an entry -/// that IS two strings holds is checked later, per grant ([`grant::check`]). -fn lenient_gem_platforms<'de, D>(deserializer: D) -> Result, D::Error> +/// is no list. An entry without a `platform` or a `gemChecksumSha256` +/// string (missing, `null`, empty, another type) is dropped: the registry +/// is then not known to serve that platform, so a lock that names it is +/// left as it is. A `patchUuid` that is no string is no patch (the +/// platform is served as upstream's gem). What an entry that IS these +/// strings holds is checked later, per grant ([`grant::check`]). +fn lenient_gem_builds<'de, D>(deserializer: D) -> Result>, D::Error> where D: serde::Deserializer<'de>, { @@ -229,22 +235,41 @@ where let text = entry.get(key)?.as_str()?; (!text.is_empty()).then(|| text.to_string()) }; - Ok(value - .as_array() - .into_iter() - .flatten() - .filter_map(|entry| { - Some(GemPlatformChecksum { - platform: text(entry, "platform")?, - gem_checksum_sha256: text(entry, "gemChecksumSha256")?, + Ok(value.as_array().map(|list| { + list.iter() + .filter_map(|entry| { + Some(GemPlatformChecksum { + platform: text(entry, "platform")?, + gem_checksum_sha256: text(entry, "gemChecksumSha256")?, + patch_uuid: text(entry, "patchUuid"), + }) }) - }) - .collect()) + .collect() + })) } -/// One prebuild of a gem patch: a patched platform gem that is a drop-in -/// for the upstream one (same file name, same gemspec metadata, no -/// `extensions`). +/// One build a lock names of a gem that takes a patch registry as its +/// source ([`RewriteResult::gem_builds`]). +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(test, derive(Serialize))] +#[cfg_attr(test, serde(rename_all = "camelCase"))] +pub struct GemLockedBuild { + /// The build's platform as the lock spells it; `None` for the + /// ruby-platform gem. + pub platform: Option, + /// The patch of the build the registry serves: the gem's own patch for + /// the ruby-platform gem, the platform's for a patched platform gem. + /// `None` where the registry serves upstream's own gem (no patched + /// build yet): that platform is as it was. + pub patch_uuid: Option, + /// Whether this rewrite is what put the patched build in place: the + /// lock did not already pin it from the registry. + pub newly_patched: bool, +} + +/// One platform gem of a patched gem's version, as the patch registry +/// serves it: a patched build that is a drop-in for the upstream one (same +/// file name, same gemspec metadata, no `extensions`), or upstream's own. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[cfg_attr(test, derive(Serialize))] #[serde(rename_all = "camelCase")] @@ -252,8 +277,23 @@ pub struct GemPlatformChecksum { /// `Gem::Platform#to_s` as the gem's file name and `Gemfile.lock` spell /// it (`x86_64-linux-gnu`, `arm64-darwin`, `java`). Never `ruby`. pub platform: String, - /// sha256 hex of that platform's `.gem`. + /// sha256 hex of the `.gem` the registry serves for that platform. pub gem_checksum_sha256: String, + /// The patch of this platform's patched build. `None` for a platform + /// with no patched build: the registry lists upstream's own gem for it + /// and answers its file with a redirect to the upstream registry, so a + /// machine of that platform installs what it installed before. + #[cfg_attr(test, serde(skip_serializing_if = "Option::is_none"))] + pub patch_uuid: Option, +} + +impl RegistryOverrideIdentifiers { + /// What the registry serves for the platform gem `platform`, where it + /// lists it ([`Self::gem_builds`]). + pub fn gem_build(&self, platform: &str) -> Option<&GemPlatformChecksum> { + let builds = self.gem_builds.as_deref()?; + builds.iter().find(|build| build.platform == platform) + } } #[derive(Debug, Clone, Deserialize)] @@ -439,6 +479,29 @@ pub struct RewriteResult { serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") )] pub bundled_skipped_uuids: std::collections::BTreeSet, + /// gem: the builds the lock names of each gem it names as platform + /// builds and this rewrite pins (or found pinned) through the patch + /// registry, by the gem patch's uuid. The registry serves a patched + /// build for some platforms and upstream's own gem for the rest, so + /// the one pin of the gem stands for the patched builds only: a run + /// reports and attests each of those under its own patch, and none of + /// the others ([`GemLockedBuild`]). Absent for a gem locked as its + /// ruby-platform gem alone. Serialized only when non-empty. + #[cfg_attr( + test, + serde(skip_serializing_if = "std::collections::BTreeMap::is_empty") + )] + pub gem_builds: BTreeMap>, + /// gem: the gems the lock names as platform builds that were left on + /// their upstream registry because the patch registry has no patched + /// build for any platform the lock names yet, by the gem patch's uuid, + /// with those platforms. Not a defect: the gem moves once a later + /// reference lists one. Serialized only when non-empty. + #[cfg_attr( + test, + serde(skip_serializing_if = "std::collections::BTreeMap::is_empty") + )] + pub gem_unpatched: BTreeMap>, /// Patch uuid → the yarn.lock keys of the `npm:` alias entries of its /// package the rewriter left untouched (`redirect_yarn_classic_alias_skipped`, /// `redirect_yarn_berry_alias_skipped`): that copy keeps installing the @@ -985,6 +1048,8 @@ fn merge_group_delta(result: &mut RewriteResult, delta: RewriteResult) { confirmed_sbt_uuids, refused_sbt_uuids, confirmed_bazel_maven_uuids, + gem_builds, + gem_unpatched, } = delta; result.files.extend(files); result.binary_files.extend(binary_files); @@ -1032,6 +1097,8 @@ fn merge_group_delta(result: &mut RewriteResult, delta: RewriteResult) { .confirmed_maven_reactor_uuids .extend(confirmed_maven_reactor_uuids); result.bundled_skipped_uuids.extend(bundled_skipped_uuids); + result.gem_builds.extend(gem_builds); + result.gem_unpatched.extend(gem_unpatched); for (uuid, keys) in alias_skipped_entries { result .alias_skipped_entries @@ -8085,9 +8152,16 @@ pub fn grant_token_path_segment(url: &str, patch_uuid: &str) -> Option { /// the index URL itself as the segment immediately preceding the patch-uuid /// level, so the idempotency guard never silently degrades into the /// nesting-corruption failure mode when a caller forgets the token. +/// +/// A gem registry's URL may end in a snapshot level (`…//s/`: the +/// registry as it stood when the reference was made, which a later +/// reference replaces with a newer one). That level rotates too, and comes +/// and goes with the patch service knowing the version's platform gems, so +/// the pattern takes the URL with any snapshot or none. pub(crate) fn gem_index_url_pattern(dep: &DepOverride, index_url: &str) -> String { - let mut url_pat = regex::escape(index_url); - let derived_token = grant_token_path_segment(index_url, &dep.patch_uuid); + let (root, _) = split_gem_snapshot(index_url); + let mut url_pat = regex::escape(root); + let derived_token = grant_token_path_segment(root, &dep.patch_uuid); let rotating = [ Some(dep.token.as_str()), derived_token.as_deref(), @@ -8098,7 +8172,52 @@ pub(crate) fn gem_index_url_pattern(dep: &DepOverride, index_url: &str) -> Strin url_pat = url_pat.replace(®ex::escape(&format!("/{rotating}/")), "/[^/\"]+/"); } } - url_pat + // `root` ends in `/` whenever the URL had a snapshot level. + let level = if root.ends_with('/') { "" } else { "/" }; + format!("{url_pat}(?:{level}s/[0-9]+/?)?") +} + +/// A gem registry URL without its snapshot level, and that level's number: +/// `…//s/[/]` is `(…//, Some(n))`; a URL with none is itself +/// and `None`. The snapshot is a positive integer written in plain digits. +pub(crate) fn split_gem_snapshot(index_url: &str) -> (&str, Option) { + let trimmed = index_url.trim_end_matches('/'); + let Some((before, number)) = trimmed.rsplit_once('/') else { + return (index_url, None); + }; + let plain = !number.is_empty() + && number.len() <= 18 + && number.bytes().all(|b| b.is_ascii_digit()) + && !number.starts_with('0'); + match (before.strip_suffix("/s"), plain) { + (Some(root), true) => { + // Keep the slash that closes the patch uuid's level. + let root = &index_url[..root.len() + 1]; + (root, number.parse().ok()) + } + _ => (index_url, None), + } +} + +/// Whether `lock` already takes the gem `dep` patches from that patch's +/// registry (`index_url`), under any grant token and snapshot: a `GEM` +/// section that lists the gem at that version and whose remote is it. +fn gem_lock_on_registry( + lock: &crate::formats::gem::GemfileLock<'_>, + dep: &DepOverride, + index_url: &str, +) -> bool { + let Ok(registry) = regex::Regex::new(&format!("^{}$", gem_index_url_pattern(dep, index_url))) + else { + return false; + }; + lock.gem_sections().any(|section| { + let mut specs = section.specs.iter().filter_map(|line| line.parsed); + specs.any(|spec| spec.name == dep.name && spec.version == dep.version) + && section + .remote_bases() + .any(|remote| registry.is_match(remote) || registry.is_match(&format!("{remote}/"))) + }) } /// A gemfile spelling with the redirect's own footprint erased: the Socket @@ -8969,6 +9088,15 @@ fn rewrite_gem( }); continue; } + // A registry URL with a snapshot level may come without the slash + // that closes it; Bundler writes every remote with one, so the + // manifest and the lock take the URL in that form, and a later + // `bundle install` has nothing to respell. + let index_url: std::borrow::Cow<'_, str> = match split_gem_snapshot(&ov.index_url) { + (_, Some(_)) if !ov.index_url.ends_with('/') => format!("{}/", ov.index_url).into(), + _ => ov.index_url.as_str().into(), + }; + let index_url: &str = &index_url; let sha256 = ov .identifiers .gem_checksum_sha256 @@ -9032,51 +9160,44 @@ fn rewrite_gem( .collect(); // Platform-specific builds (`name (version-arm64-darwin)` among the // specs or the CHECKSUMS entries): bundler installs the build of - // the machine it runs on, so the redirect holds only when the patch - // registry serves a patched build ("prebuild") for EVERY platform - // the lock names. Each entry is then pinned to its own prebuild. - // With one missing, a machine of that platform would be sent to a - // registry that has no gem for it (or keep the upstream build under - // the ruby gem's sha256): skip the dep entirely. + // the machine it runs on, and takes a gem from one source. The + // patch registry lists every platform gem of the version: the + // patched build where there is one, upstream's own gem (handed on + // unchanged) where there is none yet. So every locked build moves + // to it together, each pinned to the sha256 the registry serves + // for it, as soon as one of them is patched. A platform the + // registry does not list would send that platform's machines to a + // registry with no gem for them: the dep is skipped entirely. if let Some(parsed) = &handed_in { let builds = parsed.locked_builds(&dep.name, &dep.version); if !builds.platforms.is_empty() { - let prebuilt = |platform: &str| { - ov.identifiers - .gem_platforms - .iter() - .find(|prebuild| prebuild.platform == platform) - }; // Every build the lock names, the ruby-platform one first. let ids = builds.ids(&dep.name, &dep.version); let entry = |id: &crate::patch::gem_source::GemId| { format!("`{} ({})`", id.name, id.token()) }; let platform_builds = || ids.iter().filter(|id| id.platform.is_some()); - let missing: Vec = platform_builds() - .filter(|id| id.platform.as_deref().and_then(prebuilt).is_none()) + let listed = |id: &&crate::patch::gem_source::GemId| { + let platform = id.platform.as_deref()?; + ov.identifiers.gem_build(platform) + }; + let unlisted: Vec = platform_builds() + .filter(|id| listed(id).is_none()) .map(entry) .collect(); // Bundler < 2.2 lists every source in one GEM section, where // only a ruby-platform entry has been proven to converge. let merged = matches!(layout, Some(LockLayout::Merged(_))); - if !missing.is_empty() || merged { - let why = if !missing.is_empty() { - let served: Vec<&str> = ov - .identifiers - .gem_platforms - .iter() - .map(|prebuild| prebuild.platform.as_str()) - .collect(); + if !unlisted.is_empty() || merged { + let why = if ov.identifiers.gem_builds.is_none() { + "the patch covers the ruby platform gem only (the patch registry does \ + not list the platform gems of this version)" + .to_string() + } else if !unlisted.is_empty() { format!( - "the patch has no patched build for {} (the patch registry serves \ - the ruby platform gem{})", - missing.join(", "), - if served.is_empty() { - " only".to_string() - } else { - format!(" and patched builds for {}", served.join(", ")) - } + "the patch registry does not list {} among the platform gems of \ + this version", + unlisted.join(", ") ) } else { "its bundler (< 2.2) lists every gem source in one GEM section, where \ @@ -9095,20 +9216,53 @@ fn rewrite_gem( }); continue; } - // Each build's entry takes its own archive's sha256. The - // ruby gem's is among them only where the lock has that - // entry beside the platform builds (the registry serves it - // too). - checksums = ids - .iter() - .filter_map(|id| { - let sha256 = match id.platform.as_deref() { - Some(platform) => prebuilt(platform)?.gem_checksum_sha256.clone(), - None => sha256.clone()?, - }; - Some((id.token(), sha256)) - }) - .collect(); + // Whether the lock already takes the gem from this patch's + // registry (under any grant token and snapshot). + let hosted = gem_lock_on_registry(parsed, dep, index_url); + // What each locked build is pinned to: its own archive's + // sha256. The ruby gem's is among them only where the lock + // has that entry beside the platform builds. + let mut pinned: Vec = Vec::with_capacity(ids.len()); + checksums = Vec::with_capacity(ids.len()); + for id in &ids { + let (patch_uuid, sha256) = match id.platform.as_deref() { + Some(_) => { + let Some(build) = listed(&id) else { continue }; + (build.patch_uuid.clone(), build.gem_checksum_sha256.clone()) + } + None => { + let Some(sha256) = sha256.clone() else { + continue; + }; + (Some(dep.patch_uuid.clone()), sha256) + } + }; + let token = id.token(); + // In place before this run: the lock was on the + // registry and already pinned exactly this archive (a + // lock with no CHECKSUMS says nothing either way). + let was = parsed.checksum(&dep.name, &token); + let in_place = + hosted && was.is_none_or(|was| was.eq_ignore_ascii_case(&sha256)); + pinned.push(GemLockedBuild { + platform: id.platform.clone(), + newly_patched: patch_uuid.is_some() && !in_place, + patch_uuid, + }); + checksums.push((token, sha256)); + } + // No locked build is patched yet: moving the gem would + // gain nothing, so it stays on its upstream registry until + // a later reference lists a patched build for a platform + // the lock names. + if pinned.iter().all(|build| build.patch_uuid.is_none()) { + result.gem_unpatched.insert( + dep.patch_uuid.clone(), + pinned.into_iter().filter_map(|b| b.platform).collect(), + ); + continue; + } + result.gem_builds.insert(dep.patch_uuid.clone(), pinned); } } @@ -9157,7 +9311,7 @@ fn rewrite_gem( match plan_gem_redirect( files, dep, - &ov.index_url, + index_url, &checksums, gemfile.as_deref(), lk, @@ -22982,20 +23136,46 @@ mod tests { ); } - /// [`gem_override`] with a prebuild (`(platform, sha256)`) per platform. + /// The uuid of the patch [`gem_override_prebuilt`] gives a patched + /// platform gem. + fn build_uuid(platform: &str) -> String { + let digits: String = platform.bytes().map(|b| (b % 10).to_string()).collect(); + format!("b0b0b0b0-0000-4000-8000-{:0>12.12}", digits) + } + + /// [`gem_override`] whose registry lists a patched build + /// (`(platform, sha256)`) per platform, each with a patch of its own. fn gem_override_prebuilt(name: &str, version: &str, prebuilds: &[(&str, &str)]) -> DepOverride { + let builds: Vec<(&str, &str, bool)> = prebuilds + .iter() + .map(|(platform, sha)| (*platform, *sha, true)) + .collect(); + gem_override_listing(name, version, &builds) + } + + /// [`gem_override`] whose registry lists `builds` + /// (`(platform, sha256, patched)`): a patched build with a patch of its + /// own, or upstream's gem handed on unchanged. + fn gem_override_listing( + name: &str, + version: &str, + builds: &[(&str, &str, bool)], + ) -> DepOverride { let mut dep = gem_override(name, version); dep.registry_override .as_mut() .expect("gem_override always carries a registry override") .identifiers - .gem_platforms = prebuilds - .iter() - .map(|(platform, sha)| GemPlatformChecksum { - platform: platform.to_string(), - gem_checksum_sha256: sha.to_string(), - }) - .collect(); + .gem_builds = Some( + builds + .iter() + .map(|(platform, sha, patched)| GemPlatformChecksum { + platform: platform.to_string(), + gem_checksum_sha256: sha.to_string(), + patch_uuid: patched.then(|| build_uuid(platform)), + }) + .collect(), + ); dep } @@ -23226,25 +23406,27 @@ mod tests { assert!(again.files.is_empty() && again.edits.is_empty()); } - /// One locked platform with no prebuild keeps the whole gem where it - /// is: a machine of that platform would be sent to a registry that has - /// no gem for it. The warning names the missing build and what the - /// registry does serve. + /// A locked platform the patch registry does not list keeps the whole + /// gem where it is: a machine of that platform would be sent to a + /// registry that has no gem for it. So does a patch whose reference + /// carries no list at all (a patch of the ruby gem alone). The warning + /// names the builds and which of the two it is. #[test] - fn gem_platform_without_a_prebuild_skips_the_gem_and_names_it() { + fn gem_platform_the_registry_does_not_list_skips_the_gem_and_names_it() { let lock = nokogiri_lock(&["arm64-darwin", "x86_64-linux-gnu"], false, true); - for (prebuilds, served) in [ + let arm = "a".repeat(64); + for (dep, why) in [ + ( + gem_override_prebuilt("nokogiri", "1.18.10", &[("arm64-darwin", &arm)]), + "the patch registry does not list `nokogiri (1.18.10-x86_64-linux-gnu)` among \ + the platform gems of this version; redirect skipped", + ), ( - vec![("arm64-darwin", "a".repeat(64))], - "the ruby platform gem and patched builds for arm64-darwin", + gem_override("nokogiri", "1.18.10"), + "the patch covers the ruby platform gem only (the patch registry does not list \ + the platform gems of this version); redirect skipped", ), - (vec![], "the ruby platform gem only"), ] { - let prebuilds: Vec<(&str, &str)> = prebuilds - .iter() - .map(|(platform, sha)| (*platform, sha.as_str())) - .collect(); - let dep = gem_override_prebuilt("nokogiri", "1.18.10", &prebuilds); let (gemfile, after, r) = gem_redirect(NOKOGIRI_GEMFILE, &lock, dep); assert!( r.files.is_empty() && r.edits.is_empty(), @@ -23259,16 +23441,265 @@ mod tests { panic!("one warning: {:?}", r.warnings); }; assert_eq!(warning.code, "redirect_gem_platform_unsupported"); - assert!(warning.detail.contains(served), "{}", warning.detail); - assert!( - warning - .detail - .contains("no patched build for `nokogiri (1.18.10-x86_64-linux-gnu)`") - == !prebuilds.is_empty(), - "{}", - warning.detail + assert!(warning.detail.ends_with(why), "{}", warning.detail); + assert!(r.gem_builds.is_empty() && r.gem_unpatched.is_empty()); + } + } + + /// What [`RewriteResult::gem_builds`] says of the one gem: per locked + /// build `(platform, patch uuid, newly patched)`. + fn builds_of(r: &RewriteResult) -> Vec<(Option<&str>, Option<&str>, bool)> { + let builds = r.gem_builds.get("uuid").map(Vec::as_slice); + builds + .unwrap_or_default() + .iter() + .map(|b| { + ( + b.platform.as_deref(), + b.patch_uuid.as_deref(), + b.newly_patched, + ) + }) + .collect() + } + + /// The registry lists every platform gem of the version: a patched + /// build for one platform, upstream's own gem for the other. One + /// patched build is enough to move the gem: every locked build goes to + /// the registry together, the patched one pinned to its patched gem + /// and the other to the gem it already had. Nothing is warned about; + /// the result says which build is which, and that this run is what + /// put the patched one in place. A second run changes nothing. + #[test] + fn gem_platforms_move_together_once_one_is_patched() { + let arm = "a".repeat(64); + let linux = upstream_sha("1.18.10-x86_64-linux-gnu"); + let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; + let dep = gem_override_listing( + "nokogiri", + "1.18.10", + &[ + ("arm64-darwin", &arm, true), + ("x86_64-linux-gnu", &linux, false), + ], + ); + let lock = nokogiri_lock(&platforms, false, true); + let (gemfile, moved, r) = gem_redirect(NOKOGIRI_GEMFILE, &lock, dep.clone()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!( + gemfile.contains(&format!("source: \"{GEM_TEST_URL}\"")), + "{gemfile}" + ); + assert_eq!( + moved, + nokogiri_lock_hosted( + &platforms, + false, + Some(&[ + ("1.18.10-arm64-darwin", &arm), + ("1.18.10-x86_64-linux-gnu", &linux) + ]) + ), + "the upstream build keeps the sha256 it had" + ); + let arm_patch = build_uuid("arm64-darwin"); + assert_eq!( + builds_of(&r), + [ + (Some("arm64-darwin"), Some(arm_patch.as_str()), true), + (Some("x86_64-linux-gnu"), None, false), + ] + ); + assert!(r.gem_unpatched.is_empty()); + + let (_, _, again) = gem_redirect(&gemfile, &moved, dep); + assert!(again.files.is_empty() && again.edits.is_empty()); + assert!(again.warnings.is_empty(), "{:?}", again.warnings); + assert_eq!( + builds_of(&again), + [ + (Some("arm64-darwin"), Some(arm_patch.as_str()), false), + (Some("x86_64-linux-gnu"), None, false), + ], + "in place: nothing is newly patched" + ); + } + + /// No locked build is patched yet: moving the gem would gain nothing, + /// so it stays on its upstream registry. Not a warning; the result + /// names the gem and the platforms that are waiting. + #[test] + fn gem_with_no_patched_locked_build_stays_upstream() { + let lock = nokogiri_lock(&["arm64-darwin", "x86_64-linux-gnu"], false, true); + let dep = gem_override_listing( + "nokogiri", + "1.18.10", + &[ + ("arm64-darwin", &upstream_sha("1.18.10-arm64-darwin"), false), + ("java", &"c".repeat(64), true), + ( + "x86_64-linux-gnu", + &upstream_sha("1.18.10-x86_64-linux-gnu"), + false, + ), + ], + ); + let (gemfile, after, r) = gem_redirect(NOKOGIRI_GEMFILE, &lock, dep); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.edits); + assert_eq!( + (gemfile.as_str(), after.as_str()), + (NOKOGIRI_GEMFILE, lock.as_str()) + ); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(r.gem_builds.is_empty()); + assert_eq!( + r.gem_unpatched.get("uuid").map(Vec::as_slice), + Some(&["arm64-darwin".to_string(), "x86_64-linux-gnu".to_string()][..]) + ); + } + + /// [`gem_override_listing`] with its registry at the snapshot `number` + /// (`…/uuid/s/`, as the patch service spells it: no closing + /// slash). + fn gem_override_at_snapshot(number: u32, builds: &[(&str, &str, bool)]) -> DepOverride { + let mut dep = gem_override_listing("nokogiri", "1.18.10", builds); + let ov = dep.registry_override.as_mut().expect("a gem registry"); + ov.index_url = format!("{GEM_TEST_URL}s/{number}"); + dep + } + + /// A registry URL carries the snapshot it was made at. The manifest + /// and the lock take it closed by a slash, as Bundler writes a remote. + /// A later reference names a newer snapshot, where a platform that had + /// upstream's gem has a patched build: the URL is refreshed in place + /// (never written twice), the one checksum that changed is rewritten, + /// and the result names the build that is newly patched. The same + /// snapshot again changes nothing. + #[test] + fn gem_newer_snapshot_refreshes_the_url_and_the_new_builds() { + let (arm, linux) = ("a".repeat(64), "b".repeat(64)); + let upstream = upstream_sha("1.18.10-x86_64-linux-gnu"); + let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; + let first = gem_override_at_snapshot( + 1, + &[ + ("arm64-darwin", &arm, true), + ("x86_64-linux-gnu", &upstream, false), + ], + ); + let lock = nokogiri_lock(&platforms, false, true); + let (gemfile, moved, r) = gem_redirect(NOKOGIRI_GEMFILE, &lock, first.clone()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let at_one = format!("{GEM_TEST_URL}s/1/"); + assert!( + gemfile.contains(&format!("source: \"{at_one}\"")), + "{gemfile}" + ); + assert!(moved.contains(&format!(" remote: {at_one}\n")), "{moved}"); + let (_, _, same) = gem_redirect(&gemfile, &moved, first); + assert!( + same.files.is_empty() && same.edits.is_empty(), + "{:?}", + same.edits + ); + + let second = gem_override_at_snapshot( + 2, + &[ + ("arm64-darwin", &arm, true), + ("x86_64-linux-gnu", &linux, true), + ], + ); + let (gemfile_two, lock_two, r) = gem_redirect(&gemfile, &moved, second.clone()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let at_two = format!("{GEM_TEST_URL}s/2/"); + assert_eq!(gemfile_two, gemfile.replace(&at_one, &at_two)); + assert_eq!( + lock_two, + moved + .replace(&at_one, &at_two) + .replace(&format!("sha256={upstream}"), &format!("sha256={linux}")) + ); + assert_eq!( + gemfile_two.matches("patch.test").count(), + 1, + "{gemfile_two}" + ); + let (arm_patch, linux_patch) = (build_uuid("arm64-darwin"), build_uuid("x86_64-linux-gnu")); + assert_eq!( + builds_of(&r), + [ + (Some("arm64-darwin"), Some(arm_patch.as_str()), false), + (Some("x86_64-linux-gnu"), Some(linux_patch.as_str()), true), + ] + ); + let (_, _, again) = gem_redirect(&gemfile_two, &lock_two, second); + assert!( + again.files.is_empty() && again.edits.is_empty(), + "{:?}", + again.edits + ); + assert!(builds_of(&again).iter().all(|(_, _, newly)| !newly)); + } + + /// The snapshot level of a registry URL is read off its end, and the + /// recogniser of a patch's registry URL takes any snapshot or none + /// under any grant token: a pair an earlier run wired is refreshed, + /// whichever form it was written in. + #[test] + fn gem_registry_url_is_recognised_with_any_snapshot_or_none() { + let plain = "https://patch.test/gem/tok/uuid/"; + assert_eq!(split_gem_snapshot(plain), (plain, None)); + assert_eq!( + split_gem_snapshot("https://patch.test/gem/tok/uuid"), + ("https://patch.test/gem/tok/uuid", None) + ); + for snapshot in [ + "https://patch.test/gem/tok/uuid/s/12", + "https://patch.test/gem/tok/uuid/s/12/", + ] { + assert_eq!( + split_gem_snapshot(snapshot), + (plain, Some(12)), + "{snapshot}" ); } + // Not a snapshot level: no number, a leading zero, another name. + for other in [ + "https://patch.test/gem/tok/uuid/s/", + "https://patch.test/gem/tok/uuid/s/012", + "https://patch.test/gem/tok/uuid/s/1a", + "https://patch.test/gem/tok/uuid/t/3", + ] { + assert_eq!(split_gem_snapshot(other).1, None, "{other}"); + } + let dep = gem_override("nokogiri", "1.18.10"); + for index_url in [ + plain, + "https://patch.test/gem/tok/uuid/s/3", + "https://patch.test/gem/tok/uuid/s/3/", + ] { + let registry = Regex::new(&format!("^{}$", gem_index_url_pattern(&dep, index_url))) + .expect("a pattern"); + for ours in [ + plain, + "https://patch.test/gem/an-older-grant/uuid/", + "https://patch.test/gem/tok/uuid/s/3", + "https://patch.test/gem/tok/uuid/s/3/", + "https://patch.test/gem/another-grant/uuid/s/41/", + ] { + assert!(registry.is_match(ours), "{index_url} takes {ours}"); + } + for other in [ + "https://rubygems.org/", + "https://patch.test/gem/tok/uuid/s/", + "https://patch.test/gem/tok/uuid/s/3/x", + "https://patch.test/gem/tok/uuid/info/nokogiri", + "https://evil.test/gem/tok/uuid/s/3/", + ] { + assert!(!registry.is_match(other), "{index_url} refuses {other}"); + } + } } /// A lock that names only platform builds needs no ruby-platform diff --git a/crates/socket-patch-core/src/vex/discover/gem.rs b/crates/socket-patch-core/src/vex/discover/gem.rs index 2f68ef949b..46efe24dd6 100644 --- a/crates/socket-patch-core/src/vex/discover/gem.rs +++ b/crates/socket-patch-core/src/vex/discover/gem.rs @@ -572,21 +572,24 @@ pub(crate) fn gemfile_source_block_pins(gemfile: &str, uuid: &str, gem_name: Opt } /// Whether hosted `remote` is the patch's compact-index root: -/// `…/patch-registry/gem//[/]`, `uuid` the LAST path level, -/// no query or fragment. +/// `…/patch-registry/gem//[/]`, `uuid` the LAST path level +/// but for a snapshot level (`…//s/[/]`), no query or fragment. fn is_patch_registry_index(remote: &str, uuid: &str) -> bool { patch_registry_uuid(remote).is_some_and(|u| u == uuid) } /// The patch uuid of a compact-index root /// `…/patch-registry/gem//[/]` (no query or fragment): its -/// last path level. +/// last path level, or the one before a snapshot level +/// (`…//s/[/]`: the registry as it stood when the patch service +/// made the reference). fn patch_registry_uuid(remote: &str) -> Option { let url = reqwest::Url::parse(remote).ok()?; if url.query().is_some() || url.fragment().is_some() { return None; } - let segments: Vec<&str> = url.path_segments()?.filter(|s| !s.is_empty()).collect(); + let (root, _) = crate::patch::redirect::split_gem_snapshot(url.path()); + let segments: Vec<&str> = root.split('/').filter(|s| !s.is_empty()).collect(); match segments.as_slice() { [.., "patch-registry", "gem", token, last] if !token.is_empty() => Some(last.to_string()), _ => None, @@ -1209,6 +1212,37 @@ mod tests { assert!(out.unlocked_pins.is_empty(), "{:#?}", out.unlocked_pins); } + /// A registry URL may end in a snapshot level (`…//s/`): the + /// patch is still the one its uuid level names. Anything else after + /// the uuid is no registry root. + #[test] + fn a_registry_url_with_a_snapshot_names_the_same_patch() { + let root = index(UUID_A); + for url in [ + root.clone(), + root.trim_end_matches('/').to_string(), + format!("{root}s/3"), + format!("{root}s/3/"), + format!("{root}s/41/"), + ] { + assert_eq!( + super::patch_registry_uuid(&url).as_deref(), + Some(UUID_A), + "{url}" + ); + assert!(super::is_patch_registry_index(&url, UUID_A), "{url}"); + } + for url in [ + format!("{root}s/"), + format!("{root}s/03/"), + format!("{root}s/3/info/rails"), + format!("{root}gems/rails-7.0.0.gem"), + format!("{root}s/3?x=1"), + ] { + assert!(!super::is_patch_registry_index(&url, UUID_A), "{url}"); + } + } + /// Only the shape the rewriter writes, in the manifest bundler loads. #[tokio::test] async fn manifest_source_pins_fail_closed() { diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/overrides.json index 293fadc614..6bce248357 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/overrides.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/overrides.json @@ -8,15 +8,16 @@ "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/gems/nokogiri-1.18.10.gem", "registryOverride": { "kind": "rubygems-compact-index", - "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4", "identifiers": { "name": "nokogiri", "version": "1.18.10", "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", - "gemPlatforms": [ + "gemBuilds": [ { "platform": "arm64-darwin", - "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "patchUuid": "77777777-7777-4777-8777-00000000000a" } ] } diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile index 9c7fb07659..8b333466e6 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile @@ -1,4 +1,4 @@ source "https://rubygems.org" -gem "nokogiri", "1.18.10", source: "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/" +gem "nokogiri", "1.18.10", source: "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/" gem "puma", "6.0.0" diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile.lock index 8f9165e97f..3673641ead 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile.lock +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile.lock @@ -1,5 +1,5 @@ GEM - remote: https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/ + remote: https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/ specs: nokogiri (1.18.10-arm64-darwin) racc (~> 1.4) diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/overrides.json index 1d3992b06b..016373e6cc 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/overrides.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/overrides.json @@ -8,19 +8,21 @@ "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/gems/nokogiri-1.18.10.gem", "registryOverride": { "kind": "rubygems-compact-index", - "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4", "identifiers": { "name": "nokogiri", "version": "1.18.10", "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", - "gemPlatforms": [ + "gemBuilds": [ { "platform": "arm64-darwin", - "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "patchUuid": "77777777-7777-4777-8777-00000000000a" }, { "platform": "x86_64-linux-gnu", - "gemChecksumSha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + "gemChecksumSha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "patchUuid": "77777777-7777-4777-8777-00000000000b" } ] } diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-edits.json index db56359064..c5a4642e8d 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-edits.json @@ -5,7 +5,7 @@ "action": "added", "key": "nokogiri", "original": "gem \"nokogiri\", \"1.18.10\"", - "new": "gem \"nokogiri\", \"1.18.10\", source: \"https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/\"" + "new": "gem \"nokogiri\", \"1.18.10\", source: \"https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/\"" }, { "path": "Gemfile.lock", @@ -37,6 +37,6 @@ "action": "rewritten", "key": "nokogiri", "original": "https://rubygems.org/", - "new": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/" + "new": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/" } ] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile index 9c7fb07659..8b333466e6 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile @@ -1,4 +1,4 @@ source "https://rubygems.org" -gem "nokogiri", "1.18.10", source: "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/" +gem "nokogiri", "1.18.10", source: "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/" gem "puma", "6.0.0" diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile.lock index 8f9165e97f..3673641ead 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile.lock +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile.lock @@ -1,5 +1,5 @@ GEM - remote: https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/ + remote: https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/ specs: nokogiri (1.18.10-arm64-darwin) racc (~> 1.4) diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/overrides.json index 1d3992b06b..016373e6cc 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/overrides.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/overrides.json @@ -8,19 +8,21 @@ "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/gems/nokogiri-1.18.10.gem", "registryOverride": { "kind": "rubygems-compact-index", - "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4", "identifiers": { "name": "nokogiri", "version": "1.18.10", "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", - "gemPlatforms": [ + "gemBuilds": [ { "platform": "arm64-darwin", - "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "patchUuid": "77777777-7777-4777-8777-00000000000a" }, { "platform": "x86_64-linux-gnu", - "gemChecksumSha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + "gemChecksumSha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "patchUuid": "77777777-7777-4777-8777-00000000000b" } ] } diff --git a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json index c843d7a11f..162c703fc1 100644 --- a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json +++ b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json @@ -62,7 +62,7 @@ "artifact_rel": null, "locked_integrity": "Sha256Hex(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", "integrity_required": true, - "url": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", + "url": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/", "lockfile_basis_ok": true } ], @@ -107,7 +107,7 @@ "artifact_rel": null, "locked_integrity": "Sha256Hex(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", "integrity_required": true, - "url": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", + "url": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/", "lockfile_basis_ok": true } ], diff --git a/crates/socket-patch-core/tests/upstream_restore_golden.rs b/crates/socket-patch-core/tests/upstream_restore_golden.rs index 7feddd7e69..655680d3da 100644 --- a/crates/socket-patch-core/tests/upstream_restore_golden.rs +++ b/crates/socket-patch-core/tests/upstream_restore_golden.rs @@ -609,14 +609,20 @@ async fn gem_edge_shapes_round_trip() { } } -/// [`gem_override`] with a prebuild for each of `platforms`: the patch -/// registry serves a patched platform gem for it too. +/// [`gem_override`] with a patched build for each of `platforms`: the +/// patch registry lists a patched platform gem for it, with a patch of its +/// own. fn gem_override_prebuilt(name: &str, version: &str, platforms: &[&str]) -> serde_json::Value { let mut overrides = gem_override(name, version); - overrides[0]["registryOverride"]["identifiers"]["gemPlatforms"] = platforms + overrides[0]["registryOverride"]["identifiers"]["gemBuilds"] = platforms .iter() - .map(|platform| { - serde_json::json!({"platform": platform, "gemChecksumSha256": "ab".repeat(32)}) + .enumerate() + .map(|(at, platform)| { + serde_json::json!({ + "platform": platform, + "gemChecksumSha256": "ab".repeat(32), + "patchUuid": format!("77777777-7777-4777-8777-00000000000{at}"), + }) }) .collect(); overrides From 377026094093c147db7aa8f8823712a3d19e7dc7 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 19:12:41 -0500 Subject: [PATCH 002/120] Report a gem locked as platform builds per locked build in hosted mode A gem patch's registry lists every platform gem of the gem's version: a patched build for some platforms, upstream's own gem for the rest. A lock that names platform builds moves to it as one pin, so a run that reported that pin once said the gem was patched where one locked platform still installs upstream's gem, and it named the gem's patch where each patched build has a patch of its own. Both hosted engines report such a gem per locked build, from the one expansion of the confirmed pins they share (`engine::pin_reports`): - `scan --mode hosted` and `get --mode hosted` record one `applied` (`verified` on a dry run) event per patched build, under that build's own patch, with `details.gemFix` (the gem's patch), `details.platform` and, when the run put the build in place, `details.newlyPatched`. A build the registry serves as upstream's gem is one `skipped` event with no `uuid` (`errorCode: gem_upstream_build_kept`), which `summary` does not count. A person gets one plain line per gem on stdout, such as `nokogiri 1.19.3: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. On a terminal it breaks after a clause, not in the middle of a word. - The in-memory engine's `redirect.patches[]` holds the same rows (`pinned` per patched build, `upstream_kept` for the others), its `redirected[]` lists the patched builds with `gemFix`, `platform` and `newlyPatched`, and the new `upstreamBuilds[]` lists the rest. A gem left on its upstream registry because no locked build is patched yet is skipped under `redirect_gem_no_patched_build` in both engines, before the unpinned patches are worked out. It is no warning and never `redirect_unconfirmed`, and a person reads one plain line of it instead of the "No patches could be switched" block. Everything else keeps working on the pins, one per package: the package counts of the human summary, the rollout budget and the severity floor, the takeover, the stale-install probes, VEX and telemetry. The gem mock of the stale-install suite serves `gemBuilds`, with a patch per patched build, under a snapshot URL. The parity suite covers a build on upstream's gem and a gem with no patched build, from the new `platform-pass-through` fixture. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/scan/hosted.rs | 479 ++++++++++- .../tests/e2e_redirect_gem_platform_builds.rs | 806 ++++++++++++++++++ .../tests/e2e_redirect_gem_stale_install.rs | 135 ++- .../tests/hosted_memory_common/mod.rs | 24 +- .../tests/hosted_memory_parity.rs | 116 ++- crates/socket-patch-core/src/hosted/engine.rs | 7 + .../src/hosted/memory/mod.rs | 33 +- .../src/hosted/memory/stages.rs | 3 + .../src/hosted/memory/types.rs | 34 + crates/socket-patch-core/src/hosted/render.rs | 131 ++- .../platform-pass-through/expected-edits.json | 34 + .../expected-warnings.json | 1 + .../platform-pass-through/expected/Gemfile | 4 + .../expected/Gemfile.lock | 30 + .../platform-pass-through/input/Gemfile | 4 + .../platform-pass-through/input/Gemfile.lock | 26 + .../platform-pass-through/overrides.json | 34 + .../vex-discover-golden/redirect-gem.json | 45 + crates/socket-patch-node/npm/index.d.ts | 3 +- 19 files changed, 1879 insertions(+), 70 deletions(-) create mode 100644 crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected-edits.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected-warnings.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected/Gemfile create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected/Gemfile.lock create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/input/Gemfile create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/input/Gemfile.lock create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/overrides.json diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 72ef58b692..1b01fd6f56 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -355,35 +355,98 @@ pub(super) const VEX_HOSTED_UNVERIFIED: &str = "vex_hosted_unverified"; /// uuid: `applied` (`verified` on a dry run) for each confirmed pin, `skipped` /// with the skip's code, and `skipped` / `redirect_unconfirmed` for each /// granted patch no lockfile entry pins. None of them change status or exit. +/// +/// `reports` are the confirmed pins as the run reports them +/// ([`engine::pin_reports`]): a gem the lock names as platform builds has +/// one event per locked build, whose `details` name the gem patch +/// (`gemFix`) and the build's `platform` (none for the ruby-platform gem). +/// A patched build is `applied` under its own patch, with `newlyPatched: +/// true` when this run put it in place. A build the patch registry serves +/// as upstream's own gem is an advisory `skipped` event with no `uuid` +/// ([`engine::GEM_UPSTREAM_BUILD_KEPT`]), which `summary` does not count: +/// nothing was skipped, that platform is as it was. +/// +/// [`engine::pin_reports`]: socket_patch_core::hosted::engine::pin_reports +/// [`engine::GEM_UPSTREAM_BUILD_KEPT`]: socket_patch_core::hosted::engine::GEM_UPSTREAM_BUILD_KEPT pub(super) fn record_hosted_events( env: &mut Envelope, - confirmed: &[(String, String)], + reports: &[socket_patch_core::hosted::engine::PinReport], unconfirmed: &[(String, String)], skipped: &[socket_patch_core::hosted::engine::SkippedPatch], dry_run: bool, ) { - for event in hosted_events(confirmed, unconfirmed, skipped, dry_run) { - env.record(event); + use socket_patch_core::hosted::engine::GEM_UPSTREAM_BUILD_KEPT; + for event in hosted_events(reports, unconfirmed, skipped, dry_run) { + if event.error_code.as_deref() == Some(GEM_UPSTREAM_BUILD_KEPT) { + env.events.push(event); + } else { + env.record(event); + } } } +/// Each pin of `confirmed` as its own report: what a run's telemetry +/// names, one patch per package, where the envelope reports a gem locked +/// as platform builds per build. +fn pin_reports_by_package( + confirmed: &[(String, String)], +) -> Vec { + confirmed + .iter() + .map( + |(purl, uuid)| socket_patch_core::hosted::engine::PinReport { + purl: purl.clone(), + uuid: Some(uuid.clone()), + gem_fix: None, + platform: None, + newly_patched: false, + }, + ) + .collect() +} + /// A hosted run's per-patch outcomes as events, tagged `mode: "hosted"` /// (see [`record_hosted_events`]): what the envelope records and what the -/// run's telemetry names. +/// run's telemetry names. Only the advisory event of a gem build left on +/// upstream's gem has no `uuid`. fn hosted_events( - confirmed: &[(String, String)], + reports: &[socket_patch_core::hosted::engine::PinReport], unconfirmed: &[(String, String)], skipped: &[socket_patch_core::hosted::engine::SkippedPatch], dry_run: bool, ) -> Vec { + use socket_patch_core::hosted::engine::{ + gem_upstream_build_kept_detail, GEM_UPSTREAM_BUILD_KEPT, + }; let pinned = if dry_run { PatchAction::Verified } else { PatchAction::Applied }; - let mut events: Vec = confirmed + let mut events: Vec = reports .iter() - .map(|(purl, uuid)| PatchEvent::new(pinned, purl.as_str()).with_uuid(uuid.as_str())) + .map(|report| { + let mut event = match &report.uuid { + Some(uuid) => { + PatchEvent::new(pinned, report.purl.as_str()).with_uuid(uuid.as_str()) + } + None => PatchEvent::new(PatchAction::Skipped, report.purl.as_str()).with_reason( + GEM_UPSTREAM_BUILD_KEPT, + gem_upstream_build_kept_detail(report.platform.as_deref().unwrap_or_default()), + ), + }; + if let Some(gem_fix) = &report.gem_fix { + let mut details = serde_json::json!({ "gemFix": gem_fix }); + if let Some(platform) = &report.platform { + details["platform"] = serde_json::json!(platform); + } + if report.newly_patched { + details["newlyPatched"] = serde_json::json!(true); + } + event.details = Some(details); + } + event + }) .chain(skipped.iter().map(|s| { let mut event = PatchEvent::new(PatchAction::Skipped, s.purl.as_str()).with_uuid(s.uuid.as_str()); @@ -2179,6 +2242,11 @@ async fn run_redirect_selected_untracked( // Candidates the rewrite left out because discovery would not attribute // their pin (`engine::rewrite`). skipped.extend(done.unattributed.iter().cloned()); + // A gem the lock names as platform builds, left on its upstream + // registry because none of them has a patched build yet: skipped under + // its own code, which is no warning, so it is never reported as a + // granted patch that nothing pins. + skipped.extend(engine::gem_unpatched_skips(&candidates, &done.rewrite)); grant_warnings.extend(mirror_pins_not_moved( &mirror_sources, &candidates, @@ -2662,6 +2730,10 @@ async fn run_redirect_selected_untracked( &confirmed, &skipped, ); + // The pins as the run reports them: a gem the lock names as platform + // builds once per locked build. Everything else above and below works + // on the pins themselves, one per package. + let reports = engine::pin_reports(&confirmed, rewrite); // Sent before the result prints: a consumer that closes stdout early // (SIGPIPE on the first write) must not lose it. if !selected.is_empty() { @@ -2671,7 +2743,12 @@ async fn run_redirect_selected_untracked( done.rewritten.len(), common.dry_run, &crate::telemetry_outcomes::patch_outcomes_of( - &hosted_events(&confirmed, &unconfirmed, &skipped, common.dry_run), + &hosted_events( + &pin_reports_by_package(&confirmed), + &unconfirmed, + &skipped, + common.dry_run, + ), socket_patch_core::telemetry::MODE_HOSTED, ), &telemetry.auth, @@ -2685,7 +2762,7 @@ async fn run_redirect_selected_untracked( // tagged `details.mode: "hosted"`, the `redirect` payload, and the // engine's warnings hoisted to the top-level `warnings`. let mut env = scan_result.take().unwrap_or_else(|| scan_envelope(common)); - record_hosted_events(&mut env, &confirmed, &unconfirmed, &skipped, common.dry_run); + record_hosted_events(&mut env, &reports, &unconfirmed, &skipped, common.dry_run); record_registry_cleanup( &mut env, ®istry_removed, @@ -2794,6 +2871,13 @@ async fn run_redirect_selected_untracked( for line in format_gem_manifest_edits(&rewrite.edits, common.dry_run) { println!("{line}"); } + // And, for a gem the lock names as platform builds, which of + // them are patched. + let stdout_width = + crate::ui::attended(crate::ui::Stream::Stdout).then(crate::ui::stdout_width); + for line in format_gem_build_lines(&reports, &skipped, common.dry_run) { + println!("{}", wrap_line(&line, stdout_width)); + } // And what it took out of a pnpm registry route nothing uses. for line in crate::commands::registry_gc::lines(®istry_removed, common.dry_run) { println!("{line}"); @@ -2827,6 +2911,8 @@ async fn run_redirect_selected_untracked( let skipped_pairs: Vec<(String, String)> = skipped .iter() .filter(|s| s.reason != super::rollout::ROLLOUT_DEFERRED) + // Said above, as one plain line per gem: nothing failed. + .filter(|s| s.reason != engine::GEM_NO_PATCHED_BUILD) .map(|s| (s.purl.clone(), s.reason.clone())) .collect(); let unconfirmed_purls: Vec = @@ -3376,6 +3462,124 @@ fn format_gem_manifest_edits( .collect() } +/// Which builds are patched of each gem the Bundler lock names as +/// precompiled platform builds, one line per gem. Such a gem takes its +/// patch registry as the one source of every locked build, and the +/// registry serves a patched build for some platforms and upstream's own +/// gem for the rest, so the summary's "1 package" does not say which +/// machines run patched code. Not a warning: nothing here needs doing. +/// +/// - `nokogiri 1.19.3: patched for arm64-darwin, x86_64-linux-gnu` +/// - a platform with no patched build yet: `…: patched for +/// x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched +/// build yet)` +/// - a patched build that this run found for a platform of a lock already +/// on the registry: `…: now also patched for arm64-darwin; already +/// patched for x86_64-linux-gnu` +/// - no locked platform has a patched build yet, so the gem was left +/// where it is (the skip's own sentence): `…: no patched build yet for +/// arm64-darwin, x86_64-linux-gnu; left on its upstream registry` +/// +/// The ruby-platform gem, where the lock names it beside the platform +/// builds, is the platform `ruby`. A dry run says `would be patched for` +/// (`would also be patched for`) of the builds a wet run would put in +/// place. `reports` are the run's pins per locked build +/// (`engine::pin_reports`), `skipped` its skips. +fn format_gem_build_lines( + reports: &[socket_patch_core::hosted::engine::PinReport], + skipped: &[socket_patch_core::hosted::engine::SkippedPatch], + dry_run: bool, +) -> Vec { + use socket_patch_core::hosted::engine::{PinReport, GEM_NO_PATCHED_BUILD}; + // Per gem patch, in report order: its locked builds. + let mut gems: Vec<(&str, Vec<&PinReport>)> = Vec::new(); + for report in reports { + let Some(gem_fix) = report.gem_fix.as_deref() else { + continue; + }; + match gems.iter_mut().find(|(fix, _)| *fix == gem_fix) { + Some((_, builds)) => builds.push(report), + None => gems.push((gem_fix, vec![report])), + } + } + let mut lines: Vec = Vec::new(); + for (_, builds) in gems { + let Some((_, name, version)) = builds.first().and_then(|build| purl_parts(&build.purl)) + else { + continue; + }; + let platforms = |keep: &dyn Fn(&PinReport) -> bool| -> String { + let named: Vec<&str> = builds + .iter() + .filter(|build| keep(build)) + .map(|build| build.platform.as_deref().unwrap_or("ruby")) + .collect(); + named.join(", ") + }; + let now = platforms(&|build| build.uuid.is_some() && build.newly_patched); + let before = platforms(&|build| build.uuid.is_some() && !build.newly_patched); + let kept = platforms(&|build| build.uuid.is_none()); + let (first, also) = if dry_run { + ("would be patched for", "would also be patched for") + } else { + ("patched for", "now also patched for") + }; + let mut parts: Vec = Vec::new(); + match (now.is_empty(), before.is_empty()) { + (false, true) => parts.push(format!("{first} {now}")), + (false, false) => { + parts.push(format!("{also} {now}")); + parts.push(format!("already patched for {before}")); + } + (true, false) => parts.push(format!("patched for {before}")), + // A pin stands for at least one patched build. + (true, true) => {} + } + if !kept.is_empty() { + parts.push(format!( + "upstream gem kept for {kept} (no patched build yet)" + )); + } + lines.push(format!("{name} {version}: {}", parts.join("; "))); + } + lines.extend( + skipped + .iter() + .filter(|skip| skip.reason == GEM_NO_PATCHED_BUILD) + .filter_map(|skip| skip.detail.clone()), + ); + lines +} + +/// `line` as it prints on stdout. With `width` (stdout is a terminal with +/// a person at it) a line that does not fit breaks after a clause (`; `) +/// under a two-space hanging indent, so no clause is cut in two unless it +/// is itself wider than the terminal, where it wraps at a word. Without +/// it the line is as it is, so a pipe or a log keeps one line. +fn wrap_line(line: &str, width: Option) -> String { + const INDENT: &str = " "; + let Some(width) = width else { + return line.to_string(); + }; + let mut rows: Vec = Vec::new(); + for clause in line.split_inclusive("; ") { + let clause = clause.trim_end(); + let room = if rows.len() > 1 { INDENT.len() } else { 0 }; + match rows.last_mut() { + Some(row) if room + row.chars().count() + 1 + clause.chars().count() <= width => { + row.push(' '); + row.push_str(clause); + } + _ => rows.push(clause.to_string()), + } + } + rows.iter() + .enumerate() + .flat_map(|(at, row)| wrap_words(row, width, if at == 0 { "" } else { INDENT }, INDENT)) + .collect::>() + .join("\n") +} + /// What wiring a gem to its patch source costs the project's update /// workflow, said once per run under [`format_gem_manifest_edits`]' lines. /// @@ -4342,9 +4546,13 @@ mod tests { {"purl": "pkg:npm/b@1.0.0", "uuid": "ub", "reason": "not_found"} ])) .unwrap(); + let pinned = super::pin_reports_by_package(&[( + "pkg:npm/minimist@1.2.2".to_string(), + "abc-123".to_string(), + )]); record_hosted_events( &mut env, - &[("pkg:npm/minimist@1.2.2".to_string(), "abc-123".to_string())], + &pinned, &[("pkg:npm/a@1.0.0".to_string(), "ua".to_string())], &skipped, false, @@ -4386,17 +4594,254 @@ mod tests { // A dry run previews the pin as `verified`. let mut env = Envelope::new(Command::Scan); - record_hosted_events( - &mut env, - &[("pkg:npm/minimist@1.2.2".to_string(), "abc-123".to_string())], - &[], - &[], - true, - ); + record_hosted_events(&mut env, &pinned, &[], &[], true); assert_eq!(env.summary.verified, 1); assert_eq!(env.summary.applied, 0); } + const BUILD_FIX: &str = "77777777-7777-4777-8777-777777777777"; + const BUILD_LINUX: &str = "77777777-7777-4777-8777-00000000000b"; + + /// One locked build of the gem `pkg:gem/nokogiri@1.19.3` as a run + /// reports it: `patch` is the patch of its patched build (`None`: the + /// registry serves upstream's gem), `newly` whether this run put it in + /// place. + fn build_report( + platform: Option<&str>, + patch: Option<&str>, + newly: bool, + ) -> socket_patch_core::hosted::engine::PinReport { + socket_patch_core::hosted::engine::PinReport { + purl: match platform { + Some(platform) => format!("pkg:gem/nokogiri@1.19.3?platform={platform}"), + None => "pkg:gem/nokogiri@1.19.3".to_string(), + }, + uuid: patch.map(str::to_string), + gem_fix: Some(BUILD_FIX.to_string()), + platform: platform.map(str::to_string), + newly_patched: newly, + } + } + + /// A gem the lock names as platform builds is recorded per locked + /// build. A patched build is a counted `applied` event under its own + /// patch, whose `details` name the gem patch and the platform, and say + /// when this run put the build in place. A build the registry serves as + /// upstream's gem is an event with no `uuid` that no `summary` count + /// moves for. The quiet skip of a gem with no patched build is an + /// ordinary counted skip, and never a warning. + #[test] + fn hosted_events_report_a_platform_locked_gem_per_build() { + use crate::json_envelope::{Command, Envelope}; + use socket_patch_core::hosted::engine::{ + SkippedPatch, GEM_NO_PATCHED_BUILD, GEM_UPSTREAM_BUILD_KEPT, + }; + let reports = [ + build_report(None, Some(BUILD_FIX), false), + build_report(Some("arm64-darwin"), None, false), + build_report(Some("x86_64-linux-gnu"), Some(BUILD_LINUX), true), + ]; + let skipped = [SkippedPatch { + detail: Some( + "rack 3.1.8: no patched build yet for java; left on its upstream registry".into(), + ), + ..SkippedPatch::new("pkg:gem/rack@3.1.8", "ur", GEM_NO_PATCHED_BUILD) + }]; + let mut env = Envelope::new(Command::Scan); + record_hosted_events(&mut env, &reports, &[], &skipped, false); + let v = env.to_value(); + assert_eq!( + v["events"], + serde_json::json!([ + { + "action": "applied", "purl": "pkg:gem/nokogiri@1.19.3", "uuid": BUILD_FIX, + "details": {"gemFix": BUILD_FIX, "mode": "hosted"}, + }, + { + "action": "skipped", + "purl": "pkg:gem/nokogiri@1.19.3?platform=arm64-darwin", + "errorCode": GEM_UPSTREAM_BUILD_KEPT, + "reason": "the patch registry serves upstream's own gem for arm64-darwin: \ + no patched build yet", + "details": {"gemFix": BUILD_FIX, "platform": "arm64-darwin", "mode": "hosted"}, + }, + { + "action": "applied", + "purl": "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu", + "uuid": BUILD_LINUX, + "details": { + "gemFix": BUILD_FIX, "platform": "x86_64-linux-gnu", + "newlyPatched": true, "mode": "hosted", + }, + }, + { + "action": "skipped", "purl": "pkg:gem/rack@3.1.8", "uuid": "ur", + "errorCode": GEM_NO_PATCHED_BUILD, + "reason": "rack 3.1.8: no patched build yet for java; left on its upstream \ + registry", + "details": {"mode": "hosted"}, + }, + ]) + ); + assert_eq!(v["summary"]["applied"], 2, "the patched builds"); + assert_eq!( + v["summary"]["skipped"], 1, + "the gem left alone, not the build" + ); + assert_eq!(v["summary"]["failed"], 0); + assert_eq!(v["status"], "success"); + assert!(v["warnings"].as_array().is_none_or(Vec::is_empty), "{v}"); + + // A dry run previews each patched build as `verified`; the build + // left on upstream's gem is reported the same way. + let mut env = Envelope::new(Command::Scan); + record_hosted_events(&mut env, &reports, &[], &[], true); + assert_eq!((env.summary.verified, env.summary.applied), (2, 0)); + assert_eq!(env.summary.skipped, 0); + assert_eq!(env.events.len(), 3); + + // Telemetry names one patch per package: the pin's. + let pins = [("pkg:gem/nokogiri@1.19.3".to_string(), BUILD_FIX.to_string())]; + let outcomes = crate::telemetry_outcomes::patch_outcomes_of( + &super::hosted_events(&super::pin_reports_by_package(&pins), &[], &skipped, false), + socket_patch_core::telemetry::MODE_HOSTED, + ); + let named: Vec<(&str, &str, Option<&str>)> = outcomes + .iter() + .map(|o| (o.uuid.as_str(), o.outcome, o.code.as_deref())) + .collect(); + assert_eq!( + named, + [ + (BUILD_FIX, "applied", None), + ("ur", "skipped", Some(GEM_NO_PATCHED_BUILD)), + ] + ); + } + + /// The human line of a gem locked as platform builds: which builds are + /// patched, which keep upstream's gem, which this run found patched on + /// a lock that was already on the registry, and what a dry run would + /// do. A package that is no such gem has no line. A gem left on its + /// upstream registry prints its skip's own sentence. + #[test] + fn gem_build_lines_say_which_builds_are_patched() { + use socket_patch_core::hosted::engine::{SkippedPatch, GEM_NO_PATCHED_BUILD}; + let line = |reports: &[socket_patch_core::hosted::engine::PinReport], dry_run| { + let lines = super::format_gem_build_lines(reports, &[], dry_run); + assert_eq!(lines.len(), 1, "{lines:?}"); + lines.into_iter().next().unwrap() + }; + let arm = |patch, newly| build_report(Some("arm64-darwin"), patch, newly); + let linux = |patch, newly| build_report(Some("x86_64-linux-gnu"), patch, newly); + let (a, b) = (Some("ua"), Some(BUILD_LINUX)); + + // Every locked build patched by this run, then found in place. + assert_eq!( + line(&[arm(a, true), linux(b, true)], false), + "nokogiri 1.19.3: patched for arm64-darwin, x86_64-linux-gnu" + ); + assert_eq!( + line(&[arm(a, false), linux(b, false)], false), + "nokogiri 1.19.3: patched for arm64-darwin, x86_64-linux-gnu" + ); + // One platform has no patched build yet. + assert_eq!( + line(&[arm(None, false), linux(b, true)], false), + "nokogiri 1.19.3: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin \ + (no patched build yet)" + ); + // A later run finds that platform patched. + assert_eq!( + line(&[arm(a, true), linux(b, false)], false), + "nokogiri 1.19.3: now also patched for arm64-darwin; already patched for \ + x86_64-linux-gnu" + ); + // The ruby-platform gem beside the platform builds. + assert_eq!( + line( + &[ + build_report(None, Some(BUILD_FIX), true), + arm(None, false), + linux(b, true) + ], + false + ), + "nokogiri 1.19.3: patched for ruby, x86_64-linux-gnu; upstream gem kept for \ + arm64-darwin (no patched build yet)" + ); + // A dry run says what the wet run would put in place. + assert_eq!( + line(&[arm(None, false), linux(b, true)], true), + "nokogiri 1.19.3: would be patched for x86_64-linux-gnu; upstream gem kept for \ + arm64-darwin (no patched build yet)" + ); + assert_eq!( + line(&[arm(a, true), linux(b, false)], true), + "nokogiri 1.19.3: would also be patched for arm64-darwin; already patched for \ + x86_64-linux-gnu" + ); + + // Any other pin has no line; a gem left alone has its skip's. + let plain = super::pin_reports_by_package(&[ + ("pkg:npm/a@1.0.0".to_string(), "u".to_string()), + ("pkg:gem/rack@3.1.8".to_string(), "v".to_string()), + ]); + assert!(super::format_gem_build_lines(&plain, &[], false).is_empty()); + let left = "rack 3.1.8: no patched build yet for java; left on its upstream registry"; + let skipped = [ + SkippedPatch::new("pkg:npm/b@1.0.0", "ub", "not_found"), + SkippedPatch { + detail: Some(left.to_string()), + ..SkippedPatch::new("pkg:gem/rack@3.1.8", "ur", GEM_NO_PATCHED_BUILD) + }, + ]; + assert_eq!( + super::format_gem_build_lines(&[arm(a, true), linux(b, true)], &skipped, false), + [ + "nokogiri 1.19.3: patched for arm64-darwin, x86_64-linux-gnu", + left + ] + ); + + // On a terminal a line that does not fit breaks after a clause, + // under a hanging indent; one that fits, and any line in a pipe, + // stays whole. + let long = line(&[arm(None, false), linux(b, true)], false); + assert_eq!(super::wrap_line(&long, None), long); + assert_eq!(super::wrap_line(&long, Some(120)), long); + for width in [80, 100] { + assert_eq!( + super::wrap_line(&long, Some(width)), + "nokogiri 1.19.3: patched for x86_64-linux-gnu;\n upstream gem kept for \ + arm64-darwin (no patched build yet)" + ); + } + // A clause wider than the terminal wraps at a word. + let platforms = [ + "aarch64-linux-gnu", + "aarch64-linux-musl", + "arm-linux-gnu", + "arm-linux-musl", + "arm64-darwin", + "x86_64-darwin", + "x86_64-linux-gnu", + "x86_64-linux-musl", + ]; + let many: Vec<_> = platforms + .iter() + .map(|platform| build_report(Some(platform), Some("u"), true)) + .collect(); + let wrapped = super::wrap_line(&line(&many, false), Some(80)); + assert_eq!( + wrapped, + "nokogiri 1.19.3: patched for aarch64-linux-gnu, aarch64-linux-musl,\n \ + arm-linux-gnu, arm-linux-musl, arm64-darwin, x86_64-darwin, x86_64-linux-gnu,\n \ + x86_64-linux-musl" + ); + assert!(wrapped.lines().all(|row| row.chars().count() <= 80)); + } + use std::path::PathBuf; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs new file mode 100644 index 0000000000..eb8a36b525 --- /dev/null +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs @@ -0,0 +1,806 @@ +//! Hosted mode over a gem the Bundler lock names as precompiled platform +//! builds (`nokogiri (1.19.3-x86_64-linux-gnu)`), against a wiremock patch +//! API (real binary, no Ruby or Bundler: nothing is installed here). +//! +//! The gem's fix is one patch, the ruby-platform gem's. Its reference lists +//! every platform gem of the version (`gemBuilds`): the sha256 the patch +//! registry serves and, where there is a patched build, the patch it comes +//! from. A platform with none is served as upstream's own gem. So: +//! +//! * every locked build moves to the registry together as soon as one of +//! them is patched, each pinned to the sha256 listed for it, with no +//! warning; +//! * the run reports the gem per locked build: an `applied` event under +//! the build's own patch, an uncounted `gem_upstream_build_kept` event +//! for a build that stays upstream's gem, and one plain line for people; +//! * a gem with no patched build for any locked platform is left where it +//! is, under a quiet skip; +//! * a later run on the same registry snapshot changes nothing, and one on +//! a newer snapshot refreshes the URL and says which builds it found +//! patched; +//! * a platform the registry does not list, or a reference with no list at +//! all, leaves the gem alone under `redirect_gem_platform_unsupported`. + +use std::path::Path; + +use serde_json::{json, Value}; +use wiremock::matchers::{method, path, path_regex}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +#[path = "common/mod.rs"] +mod common; + +const ORG: &str = "test-org"; +const DEP: &str = "platform-probe"; +const DEP_VERSION: &str = "1.19.3"; +const PURL: &str = "pkg:gem/platform-probe@1.19.3"; +/// The gem's patch: the one fix, selected as for any gem. +const UUID: &str = "7b1e4f3a-2c5d-4e6f-8a9b-0c1d2e3f4a5b"; +/// The patches of its patched platform builds. +const ARM_UUID: &str = "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d"; +const LINUX_UUID: &str = "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e"; +const TOKEN: &str = "66666666-6666-4666-8666-666666666666"; +const GHSA: &str = "GHSA-plat-form-gems"; +/// Shaped like a Socket API token, so no run warns about the token itself. +const API_TOKEN: &str = "sktsec_00000000000000000000000000000000000000000000_api"; + +const ARM: &str = "arm64-darwin"; +const LINUX: &str = "x86_64-linux-gnu"; + +/// The sha256 a lock pins before any run: upstream's own platform gems. +const ARM_UPSTREAM: &str = "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0"; +const LINUX_UPSTREAM: &str = "b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0"; +/// The sha256 of the patched gems. +const RUBY_PATCHED: &str = "c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1"; +const ARM_PATCHED: &str = "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1"; +const LINUX_PATCHED: &str = "b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1"; +const RACC: &str = "5555555555555555555555555555555555555555555555555555555555555555"; + +/// One platform gem as a reference lists it (`gemBuilds`): its platform, +/// the sha256 the registry serves, and the patch of its patched build +/// (`None`: the registry serves upstream's own gem). +type Listed = (&'static str, &'static str, Option<&'static str>); + +/// `arm64-darwin` on upstream's gem, `x86_64-linux-gnu` patched. +const ONE_PATCHED: [Listed; 2] = [ + (ARM, ARM_UPSTREAM, None), + (LINUX, LINUX_PATCHED, Some(LINUX_UUID)), +]; +const BOTH_PATCHED: [Listed; 2] = [ + (ARM, ARM_PATCHED, Some(ARM_UUID)), + (LINUX, LINUX_PATCHED, Some(LINUX_UUID)), +]; +const NONE_PATCHED: [Listed; 2] = [(ARM, ARM_UPSTREAM, None), (LINUX, LINUX_UPSTREAM, None)]; + +/// The registry URL a reference names: with the snapshot level when it +/// lists platform gems, plain when it does not. +fn index_url(api: &str, snapshot: Option) -> String { + let root = format!("{api}/patch-registry/gem/{TOKEN}/{UUID}/"); + match snapshot { + Some(snapshot) => format!("{root}s/{snapshot}"), + None => root, + } +} + +/// Mount the patch API of the one gem patch. `listing` is the reference's +/// `gemBuilds` and the snapshot its registry URL names; `None` is a +/// reference with no list (a patch of the ruby gem alone). +async fn mount_api(server: &MockServer, listing: Option<(&[Listed], u32)>) { + let mut identifiers = json!({ + "name": DEP, "version": DEP_VERSION, "gemChecksumSha256": RUBY_PATCHED, + }); + if let Some((builds, _)) = listing { + identifiers["gemBuilds"] = builds + .iter() + .map(|(platform, sha, patch)| { + json!({ "platform": platform, "gemChecksumSha256": sha, "patchUuid": patch }) + }) + .collect(); + } + let api = server.uri(); + let artifact = + format!("{api}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{UUID}/{DEP}-{DEP_VERSION}.gem"); + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "packages": [{ "purl": PURL, "patches": [{ + "uuid": UUID, "purl": PURL, "tier": "free", "cveIds": [], + "ghsaIds": [GHSA], "severity": "high", "title": "platform gem fixture", + }]}], + "canAccessPaidPatches": false, + }))) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path_regex(format!( + "^/v0/orgs/{ORG}/patches/by-package/.+$" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "patches": [{ + "uuid": UUID, "purl": PURL, "publishedAt": "2026-01-01T00:00:00Z", + "description": "x", "license": "MIT", "tier": "free", + "vulnerabilities": { GHSA: { + "cves": ["CVE-2026-5555"], "summary": "s", "severity": "high", + "description": "d", + }}, + }], + "canAccessPaidPatches": false, + }))) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "results": { UUID: { + "status": "granted", + "url": artifact, + "purl": PURL, + "artifacts": [{ + "kind": "tarball", "url": artifact, + "integrity": { "sha256": RUBY_PATCHED }, + }], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": index_url(&api, listing.map(|(_, snapshot)| snapshot)), + "identifiers": identifiers, + }, + }} + }))) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{UUID}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "uuid": UUID, "purl": PURL, "publishedAt": "2026-01-01T00:00:00Z", + "files": { "lib/platform_probe.rb": { + "beforeHash": "a".repeat(64), "afterHash": "b".repeat(64), + }}, + "vulnerabilities": { GHSA: { + "cves": ["CVE-2026-5555"], "summary": "s", "severity": "high", + "description": "d", + }}, + "description": "x", "license": "MIT", "tier": "free", + }))) + .mount(server) + .await; +} + +const GEMFILE: &str = + "source \"https://rubygems.org\"\n\ngem \"platform-probe\", \"1.19.3\"\ngem \"racc\", \"1.8.1\"\n"; + +/// A lock that names the gem as its two platform builds, each pinned to +/// upstream's archive, beside a plain gem. `checksums: false` is the lock +/// of a Bundler that writes no `CHECKSUMS` section. +fn lock(checksums: bool) -> String { + let mut lock = format!( + "GEM\n remote: https://rubygems.org/\n specs:\n {DEP} ({DEP_VERSION}-{ARM})\n {DEP} \ + ({DEP_VERSION}-{LINUX})\n racc (1.8.1)\n\nPLATFORMS\n {ARM}\n {LINUX}\n\nDEPENDENCIES\n \ + {DEP} (= {DEP_VERSION})\n racc (= 1.8.1)\n\n" + ); + if checksums { + lock.push_str(&format!( + "CHECKSUMS\n {DEP} ({DEP_VERSION}-{ARM}) sha256={ARM_UPSTREAM}\n {DEP} \ + ({DEP_VERSION}-{LINUX}) sha256={LINUX_UPSTREAM}\n racc (1.8.1) sha256={RACC}\n\n" + )); + } + lock.push_str("BUNDLED WITH\n 4.0.15\n"); + lock +} + +/// [`lock`] as a hosted run leaves it: the gem's builds under the patch +/// registry `index` (with its closing slash), pinned to `arm` and `linux`. +fn hosted_lock(index: &str, arm: &str, linux: &str) -> String { + format!( + "GEM\n remote: {index}\n specs:\n {DEP} ({DEP_VERSION}-{ARM})\n {DEP} \ + ({DEP_VERSION}-{LINUX})\n\nGEM\n remote: https://rubygems.org/\n specs:\n racc \ + (1.8.1)\n\nPLATFORMS\n {ARM}\n {LINUX}\n\nDEPENDENCIES\n {DEP} (= {DEP_VERSION})!\n racc (= \ + 1.8.1)\n\nCHECKSUMS\n {DEP} ({DEP_VERSION}-{ARM}) sha256={arm}\n {DEP} \ + ({DEP_VERSION}-{LINUX}) sha256={linux}\n racc (1.8.1) sha256={RACC}\n\nBUNDLED WITH\n 4.0.15\n" + ) +} + +/// [`GEMFILE`] as a hosted run leaves it. +fn hosted_gemfile(index: &str) -> String { + GEMFILE.replace( + "gem \"platform-probe\", \"1.19.3\"\n", + &format!("gem \"platform-probe\", \"1.19.3\", source: \"{index}\"\n"), + ) +} + +/// A project with [`GEMFILE`] and `lock`, in a new temp dir. +fn project(lock: &str) -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("Gemfile"), GEMFILE).unwrap(); + std::fs::write(dir.path().join("Gemfile.lock"), lock).unwrap(); + dir +} + +fn read(proj: &Path, rel: &str) -> String { + std::fs::read_to_string(proj.join(rel)).unwrap() +} + +/// `socket-patch --mode hosted` over `proj` against `api`, with +/// `extra` arguments. +fn hosted(proj: &Path, api: &str, command: &[&str], extra: &[&str]) -> (i32, String, String) { + let mut args: Vec<&str> = command.to_vec(); + args.extend_from_slice(&[ + "--mode", + "hosted", + "--yes", + "--cwd", + proj.to_str().expect("utf8 temp path"), + "--api-url", + api, + "--org", + ORG, + "--api-token", + API_TOKEN, + ]); + args.extend_from_slice(extra); + common::run_with_env(proj, &args, &[]) +} + +/// A `--json` hosted scan: exit code and envelope. +fn scan_json(proj: &Path, api: &str, extra: &[&str]) -> (i32, Value) { + let mut args = vec!["--json"]; + args.extend_from_slice(extra); + let (code, stdout, stderr) = hosted(proj, api, &["scan"], &args); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + (code, env) +} + +/// The run's hosted events (`details.mode: "hosted"`), in envelope order. +fn hosted_events(env: &Value) -> Vec { + env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|event| event["details"]["mode"] == "hosted") + .cloned() + .collect() +} + +fn warning_codes(env: &Value) -> Vec { + env["warnings"] + .as_array() + .into_iter() + .flatten() + .map(|w| w["code"].as_str().unwrap_or_default().to_string()) + .collect() +} + +/// The event of a patched build: `applied` (`verified` on a dry run) under +/// the build's own patch. +fn patched_event(action: &str, platform: &str, patch: &str, newly: bool) -> Value { + let mut details = json!({ "gemFix": UUID, "platform": platform, "mode": "hosted" }); + if newly { + details["newlyPatched"] = json!(true); + } + json!({ + "action": action, "purl": format!("{PURL}?platform={platform}"), "uuid": patch, + "details": details, + }) +} + +/// The uncounted event of a build that stays upstream's gem. +fn upstream_event(platform: &str) -> Value { + json!({ + "action": "skipped", + "purl": format!("{PURL}?platform={platform}"), + "errorCode": "gem_upstream_build_kept", + "reason": format!( + "the patch registry serves upstream's own gem for {platform}: no patched build yet" + ), + "details": { "gemFix": UUID, "platform": platform, "mode": "hosted" }, + }) +} + +/// The uuids each reference request of the run asked about, one list per +/// request, and the paths of every request that was no patch API call. +async fn requests(server: &MockServer) -> (Vec>, Vec) { + let mut references = Vec::new(); + let mut other = Vec::new(); + for request in server.received_requests().await.unwrap_or_default() { + let route = request.url.path().to_string(); + if route == format!("/v0/orgs/{ORG}/patches/package") { + let body: Value = serde_json::from_slice(&request.body).unwrap_or_default(); + references.push( + body["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|uuid| uuid.as_str().map(str::to_string)) + .collect(), + ); + } else if !route.starts_with(&format!("/v0/orgs/{ORG}/patches/")) { + other.push(route); + } + } + (references, other) +} + +/// Two locked platforms, one with a patched build and one without: the +/// gem moves, the platform without one keeps the sha256 it had, and the +/// run says so without a warning. One reference request, for the gem's +/// own patch, and no request to the registry. +#[tokio::test(flavor = "multi_thread")] +async fn a_gem_moves_as_soon_as_one_locked_build_is_patched() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&index, ARM_UPSTREAM, LINUX_PATCHED) + ); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&index)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + (&json!(1), &json!(0), &json!(0)), + "the build on upstream's gem is counted nowhere: {env}" + ); + assert_eq!( + env["redirect"]["rewrittenFiles"], + json!(["Gemfile", "Gemfile.lock"]) + ); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); + + // For a person: one plain line on stdout, and nothing that warns. + let proj = project(&lock(true)); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("Switched 1 package to hosted patches; rewrote 2 files.\n"), + "one package, whatever its builds:\n{stdout}" + ); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {LINUX}; upstream gem kept for {ARM} (no patched \ + build yet)\n" + )), + "{stdout}" + ); + assert!( + !stderr.contains("Warning") + && !stderr.contains("Skipped") + && !stderr.contains("Not hosted"), + "{stderr}" + ); + // `--silent` says nothing of it. + let proj = project(&lock(true)); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &["--silent"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + !stdout.contains(DEP) && !stderr.contains(DEP), + "{stdout}\n{stderr}" + ); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&index, ARM_UPSTREAM, LINUX_PATCHED) + ); + + // A dry run previews the same outcome and writes nothing. + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &["--dry-run"]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("verified", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + let (code, stdout, _) = hosted(proj.path(), &api, &["scan"], &["--dry-run"]); + assert_eq!(code, 0, "{stdout}"); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: would be patched for {LINUX}; upstream gem kept for {ARM} (no \ + patched build yet)\n" + )), + "{stdout}" + ); +} + +/// Every locked build has a patched build: one `applied` event per build, +/// each under its own patch, all naming the gem's patch as their fix. +#[tokio::test(flavor = "multi_thread")] +async fn every_patched_build_is_reported_under_its_own_patch() { + let server = MockServer::start().await; + mount_api(&server, Some((&BOTH_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&index, ARM_PATCHED, LINUX_PATCHED) + ); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, true), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + assert_eq!(env["summary"]["applied"], 2, "{env}"); + assert_eq!(env["summary"]["skipped"], 0, "{env}"); + + let proj = project(&lock(true)); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("Switched 1 package to hosted patches; rewrote 2 files.\n"), + "{stdout}" + ); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {ARM}, {LINUX}\n" + )), + "{stdout}" + ); + assert!(!stderr.contains("Warning"), "{stderr}"); +} + +/// No locked build has a patched build yet: moving the gem would gain +/// nothing, so both files stay as they are. Exit 0, no warning, one +/// skipped event under the quiet code, and one plain line for a person +/// instead of the "No patches could be switched" block. +#[tokio::test(flavor = "multi_thread")] +async fn a_gem_with_no_patched_build_is_left_alone_quietly() { + let server = MockServer::start().await; + mount_api(&server, Some((&NONE_PATCHED[..], 4))).await; + let api = server.uri(); + let left = format!( + "{DEP} {DEP_VERSION}: no patched build yet for {ARM}, {LINUX}; left on its upstream \ + registry" + ); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); + assert_eq!(read(proj.path(), "Gemfile"), GEMFILE); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [json!({ + "action": "skipped", "purl": PURL, "uuid": UUID, + "errorCode": "redirect_gem_no_patched_build", "reason": left, + "details": { "mode": "hosted" }, + })], + "{env}" + ); + assert_eq!(env["summary"]["skipped"], 1, "{env}"); + assert_eq!(env["summary"]["applied"], 0, "{env}"); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([])); + + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&format!("\n{left}\n")), "{stdout}"); + assert!( + !stderr.contains("No patches could be switched") + && !stderr.contains("Warning") + && !stderr.contains(DEP), + "nothing on stderr names it:\n{stderr}" + ); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); +} + +/// Later runs. On the same snapshot nothing is written and no build is +/// reported as newly patched. A newer snapshot that lists one more patched +/// build refreshes the registry URL in both files, re-pins that build's +/// sha256 alone, and the run names it. A platform the lock gains afterwards +/// is reported with the others. +#[tokio::test(flavor = "multi_thread")] +async fn later_runs_report_what_changed_since() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + let first_lock = read(proj.path(), "Gemfile.lock"); + assert_eq!(first_lock, hosted_lock(&index, ARM_UPSTREAM, LINUX_PATCHED)); + + // The same snapshot again. + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), first_lock); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&index)); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([]), "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, false) + ], + "in place, not newly patched: {env}" + ); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already on hosted patches; nothing to rewrite.\n"), + "{stdout}" + ); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {LINUX}; upstream gem kept for {ARM} (no patched \ + build yet)\n" + )), + "{stdout}" + ); + + // A newer snapshot: arm64-darwin has a patched build too. + server.reset().await; + mount_api(&server, Some((&BOTH_PATCHED[..], 5))).await; + let newer = format!("{}/", index_url(&api, Some(5))); + let hosted_pair = (first_lock.clone(), hosted_gemfile(&index)); + let human = project(&hosted_pair.0); + std::fs::write(human.path().join("Gemfile"), &hosted_pair.1).unwrap(); + + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&newer, ARM_PATCHED, LINUX_PATCHED), + "the URL and the one checksum that changed" + ); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&newer)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, true), + patched_event("applied", LINUX, LINUX_UUID, false) + ], + "{env}" + ); + let (code, stdout, stderr) = hosted(human.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: now also patched for {ARM}; already patched for {LINUX}\n" + )), + "{stdout}" + ); + assert!(!stderr.contains("Warning"), "{stderr}"); + assert_eq!( + read(human.path(), "Gemfile.lock"), + hosted_lock(&newer, ARM_PATCHED, LINUX_PATCHED) + ); + + // The lock gains a platform (`bundle lock --add-platform`), which the + // registry serves as upstream's gem: it is reported with the others, + // and nothing is rewritten for it. + const MUSL: &str = "x86_64-linux-musl"; + let musl_sha = "d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0"; + let mut listing: Vec = BOTH_PATCHED.to_vec(); + listing.push((MUSL, musl_sha, None)); + server.reset().await; + mount_api(&server, Some((&listing[..], 5))).await; + let gained = read(proj.path(), "Gemfile.lock") + .replace( + &format!(" {DEP} ({DEP_VERSION}-{LINUX})\n"), + &format!(" {DEP} ({DEP_VERSION}-{LINUX})\n {DEP} ({DEP_VERSION}-{MUSL})\n"), + ) + .replace( + &format!("PLATFORMS\n {ARM}\n {LINUX}\n"), + &format!("PLATFORMS\n {ARM}\n {LINUX}\n {MUSL}\n"), + ) + .replace( + &format!(" {DEP} ({DEP_VERSION}-{LINUX}) sha256={LINUX_PATCHED}\n"), + &format!( + " {DEP} ({DEP_VERSION}-{LINUX}) sha256={LINUX_PATCHED}\n {DEP} \ + ({DEP_VERSION}-{MUSL}) sha256={musl_sha}\n" + ), + ); + std::fs::write(proj.path().join("Gemfile.lock"), &gained).unwrap(); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), gained); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, false), + patched_event("applied", LINUX, LINUX_UUID, false), + upstream_event(MUSL), + ], + "{env}" + ); +} + +/// A lock with no `CHECKSUMS` section (Bundler before 2.6): the gem still +/// moves, pinned by source alone, and is reported per build. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_without_checksums_still_moves() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + + let proj = project(&lock(false)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + let after = read(proj.path(), "Gemfile.lock"); + assert!( + after.starts_with(&format!( + "GEM\n remote: {index}\n specs:\n {DEP} ({DEP_VERSION}-{ARM})\n {DEP} \ + ({DEP_VERSION}-{LINUX})\n\nGEM\n remote: https://rubygems.org/\n" + )), + "{after}" + ); + assert!(!after.contains("CHECKSUMS"), "{after}"); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&index)); + assert_eq!( + warning_codes(&env), + ["redirect_gem_no_checksums_section"], + "the lock's own caveat, and nothing about platforms: {env}" + ); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); +} + +/// A locked platform the registry does not list, and a reference with no +/// list at all: machines of that platform would be sent to a registry with +/// no gem for them, so nothing is written and the run says why. +#[tokio::test(flavor = "multi_thread")] +async fn an_unlisted_platform_leaves_the_gem_alone_with_a_warning() { + let linux_only: [Listed; 1] = [(LINUX, LINUX_PATCHED, Some(LINUX_UUID))]; + let cases: [(Option<(&[Listed], u32)>, String); 2] = [ + ( + Some((&linux_only[..], 4)), + format!( + "the patch registry does not list `{DEP} ({DEP_VERSION}-{ARM})` among the \ + platform gems of this version" + ), + ), + ( + None, + "the patch covers the ruby platform gem only (the patch registry does not list the \ + platform gems of this version)" + .to_string(), + ), + ]; + for (listing, why) in cases { + let server = MockServer::start().await; + mount_api(&server, listing).await; + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &server.uri(), &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); + assert_eq!(read(proj.path(), "Gemfile"), GEMFILE); + assert_eq!( + warning_codes(&env), + ["redirect_gem_platform_unsupported"], + "{env}" + ); + let detail = env["warnings"][0]["detail"].as_str().unwrap(); + assert!(detail.contains(&why), "{detail}"); + assert_eq!( + hosted_events(&env), + [json!({ + "action": "skipped", "purl": PURL, "uuid": UUID, + "errorCode": "redirect_unconfirmed", + "reason": "no lockfile entry pinning it could be rewritten", + "details": { "mode": "hosted" }, + })], + "{env}" + ); + } +} + +/// `get --mode hosted` writes what `scan` writes and +/// reports the gem per build the same way. +#[tokio::test(flavor = "multi_thread")] +async fn get_reports_the_gem_as_scan_does() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + + let proj = project(&lock(true)); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["get", UUID], &["--json"]); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&index, ARM_UPSTREAM, LINUX_PATCHED) + ); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&index)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); + + let proj = project(&lock(true)); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["get", UUID], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {LINUX}; upstream gem kept for {ARM} (no patched \ + build yet)\n" + )), + "{stdout}" + ); + assert!(!stderr.contains("Warning"), "{stderr}"); +} + +/// The gem is one package to the rollout budget and to the severity floor, +/// however many of its builds are patched: a budget of one new patch admits +/// it whole, and a floor above its severity leaves it out whole. +#[tokio::test(flavor = "multi_thread")] +async fn rollout_and_the_severity_floor_count_the_gem_once() { + let server = MockServer::start().await; + mount_api(&server, Some((&BOTH_PATCHED[..], 4))).await; + let api = server.uri(); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &["--max-new-patches", "1"]); + assert_eq!(code, 0, "{env}"); + assert_eq!( + env["rollout"]["counts"], + json!({ "new": 1, "deferred": 0, "upgrade": 0, "already": 0 }), + "{env}" + ); + assert_eq!(env["rollout"]["deferred"], json!([]), "{env}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, true), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &["--min-severity", "critical"]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); + assert_eq!(env["policy"]["counts"]["filtered"], 1, "{env}"); + assert_eq!(hosted_events(&env), Vec::::new(), "{env}"); +} diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index c7e7065370..ab6f3f6cb0 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -101,14 +101,28 @@ async fn mount_api_for(server: &MockServer, view_budget: Option, patched_sh mount_api_with(server, view_budget, patched_sha, &[]).await; } -/// [`mount_api_for`] with the grant also listing `prebuilds`, the patch's -/// patched platform gems as `(platform, sha256)` (`gemPlatforms`; absent -/// from a grant that has none, as the service sends it). +/// One platform gem of the fixture gem's version as the grant lists it +/// (`gemBuilds`): its platform, the sha256 the patch registry serves for +/// it, and the patch of its patched build (`None`: the registry serves +/// upstream's own gem for that platform). +type ListedBuild<'a> = (&'a str, String, Option<&'a str>); + +/// The snapshot the registry URL of a grant that lists platform gems names. +const SNAPSHOT: u32 = 4; + +/// The patches of the fixture gem's patched platform builds. +const ARM_UUID: &str = "a1b2c3d4-0000-4000-8000-00000000000a"; +const LINUX_UUID: &str = "a1b2c3d4-0000-4000-8000-00000000000b"; + +/// [`mount_api_for`] with the grant also listing `builds`, every platform +/// gem of the version (`gemBuilds`; absent from a grant with none, as the +/// service sends a patch of the ruby gem alone), under a registry URL that +/// names [`SNAPSHOT`]. async fn mount_api_with( server: &MockServer, view_budget: Option, patched_sha: &str, - prebuilds: &[(&str, String)], + builds: &[ListedBuild<'_>], ) { mount_patch_api_with( server, @@ -116,11 +130,18 @@ async fn mount_api_with( PATCHED_LIB, view_budget, patched_sha, - prebuilds, + builds, + SNAPSHOT, ) .await; } +/// The path of the patch registry of the fixture gem's patch as a grant +/// that lists platform gems names it (no trailing slash). +fn snapshot_registry_path() -> String { + format!("/patch-registry/gem/{TOKEN}/{UUID}/s/{SNAPSHOT}") +} + /// [`mount_api_for`] for the patch `uuid`, whose patched lib is /// `patched_lib`. async fn mount_patch_api( @@ -130,37 +151,42 @@ async fn mount_patch_api( view_budget: Option, patched_sha: &str, ) { - mount_patch_api_with(server, uuid, patched_lib, view_budget, patched_sha, &[]).await; + mount_patch_api_with(server, uuid, patched_lib, view_budget, patched_sha, &[], 0).await; } /// The API of the patch `uuid`, whose patched lib is `patched_lib` and -/// whose grant lists `prebuilds`. +/// whose grant lists `builds` under the registry snapshot `snapshot` (a +/// grant with no list names the registry without one). async fn mount_patch_api_with( server: &MockServer, uuid: &str, patched_lib: &str, view_budget: Option, patched_sha: &str, - prebuilds: &[(&str, String)], + builds: &[ListedBuild<'_>], + snapshot: u32, ) { let mut identifiers = serde_json::json!({ "name": DEP, "version": DEP_VERSION, "gemChecksumSha256": patched_sha, }); - if !prebuilds.is_empty() { - identifiers["gemPlatforms"] = prebuilds - .iter() - .map(|(platform, sha)| { - serde_json::json!({ "platform": platform, "gemChecksumSha256": sha }) - }) - .collect(); - } let hosted_url = format!( "{}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{uuid}/{DEP}-{DEP_VERSION}.gem", server.uri() ); - let index_url = format!("{}/patch-registry/gem/{TOKEN}/{uuid}/", server.uri()); + let mut index_url = format!("{}/patch-registry/gem/{TOKEN}/{uuid}/", server.uri()); + if !builds.is_empty() { + identifiers["gemBuilds"] = builds + .iter() + .map(|(platform, sha, patch)| { + serde_json::json!({ + "platform": platform, "gemChecksumSha256": sha, "patchUuid": patch, + }) + }) + .collect(); + index_url = format!("{index_url}s/{snapshot}"); + } Mock::given(method("POST")) .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ @@ -351,6 +377,23 @@ fn hosted_pinned(env: &serde_json::Value) -> u64 { .count() as u64 } +/// `(purl, uuid)` of each hosted pin the run reports, in event order. +fn hosted_pins(env: &serde_json::Value) -> Vec<(String, String)> { + env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| { + e["details"]["mode"] == "hosted" + && (e["action"] == "applied" || e["action"] == "verified") + }) + .map(|e| { + let text = |key: &str| e[key].as_str().unwrap_or_default().to_string(); + (text("purl"), text("uuid")) + }) + .collect() +} + fn stale_warnings(env: &serde_json::Value) -> Vec { env["warnings"] .as_array() @@ -2576,8 +2619,8 @@ async fn refresh_replaces_a_stale_platform_install_with_its_prebuild() { None, &sha256_of(&real_gem(PATCHED_LIB)), &[ - (PLATFORM, sha256_of(&prebuilt)), - (OTHER_PLATFORM, sha256_of(&other_prebuilt)), + (PLATFORM, sha256_of(&prebuilt), Some(ARM_UUID)), + (OTHER_PLATFORM, sha256_of(&other_prebuilt), Some(LINUX_UUID)), ], ) .await; @@ -2585,7 +2628,8 @@ async fn refresh_replaces_a_stale_platform_install_with_its_prebuild() { // The patch registry serves the prebuild under the platform gem's name. Mock::given(method("GET")) .and(path(format!( - "/patch-registry/gem/{TOKEN}/{UUID}/gems/{leaf}.gem" + "{}/gems/{leaf}.gem", + snapshot_registry_path() ))) .respond_with( ResponseTemplate::new(200).set_body_raw(prebuilt.clone(), "application/octet-stream"), @@ -2647,7 +2691,18 @@ async fn refresh_replaces_a_stale_platform_install_with_its_prebuild() { let (code, stdout, stderr) = common::run_with_env(&proj, &args, &[]); let env = common::parse_json_envelope(&stdout); assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); - assert_eq!(hosted_pinned(&env), 1, "{env}"); + // One pin, reported per locked build, each under its own patch. + assert_eq!( + hosted_pins(&env), + [ + (format!("{PURL}?platform={PLATFORM}"), ARM_UUID.to_string()), + ( + format!("{PURL}?platform={OTHER_PLATFORM}"), + LINUX_UUID.to_string() + ), + ], + "{env}" + ); assert!( !stdout.contains("redirect_gem_platform_unsupported"), "every locked platform has a prebuild: {env}" @@ -2655,7 +2710,7 @@ async fn refresh_replaces_a_stale_platform_install_with_its_prebuild() { // The lock: both builds under the patch registry, each on its own // prebuild's sha256. - let index = format!("{uri}/patch-registry/gem/{TOKEN}/{UUID}/"); + let index = format!("{uri}{}/", snapshot_registry_path()); let hosted_lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); assert!( hosted_lock.contains(&format!( @@ -2800,15 +2855,15 @@ async fn stale_guard_follows_the_builds_the_lock_names_in_a_home_with_both() { None, &sha256_of(&real_gem(PATCHED_LIB)), &[ - (PLATFORM, sha256_of(&prebuilt)), - (OTHER_PLATFORM, sha256_of(&other_prebuilt)), + (PLATFORM, sha256_of(&prebuilt), Some(ARM_UUID)), + (OTHER_PLATFORM, sha256_of(&other_prebuilt), Some(LINUX_UUID)), ], ) .await; let leaf = format!("{DEP}-{DEP_VERSION}-{PLATFORM}"); for (route, body) in [ ( - format!("/patch-registry/gem/{TOKEN}/{UUID}/gems/{leaf}.gem"), + format!("{}/gems/{leaf}.gem", snapshot_registry_path()), prebuilt.clone(), ), (format!("/upstream/gems/{leaf}.gem"), upstream.clone()), @@ -2866,7 +2921,7 @@ async fn stale_guard_follows_the_builds_the_lock_names_in_a_home_with_both() { common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &path_env); let env = common::parse_json_envelope(&stdout); assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); - assert_eq!(hosted_pinned(&env), 1, "{env}"); + assert_eq!(hosted_pinned(&env), 2, "both locked builds: {env}"); let stale = stale_warnings(&env); assert_eq!(stale.len(), 1, "one stale copy, the platform build: {env}"); assert!( @@ -2964,11 +3019,11 @@ async fn gem_hosted_scan_pins_platform_builds_from_the_lock_alone() { ); for complete in [true, false] { let server = MockServer::start().await; - let mut prebuilds = vec![(PLATFORM, arm_sha.clone())]; + let mut builds = vec![(PLATFORM, arm_sha.clone(), Some(ARM_UUID))]; if complete { - prebuilds.push((OTHER_PLATFORM, linux_sha.clone())); + builds.push((OTHER_PLATFORM, linux_sha.clone(), Some(LINUX_UUID))); } - mount_api_with(&server, None, &ruby_sha, &prebuilds).await; + mount_api_with(&server, None, &ruby_sha, &builds).await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); std::fs::create_dir_all(&proj).unwrap(); @@ -2984,12 +3039,13 @@ async fn gem_hosted_scan_pins_platform_builds_from_the_lock_alone() { let after = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); let skipped = warnings_with_code(&env, "redirect_gem_platform_unsupported"); if complete { - assert_eq!(hosted_pinned(&env), 1, "{env}"); + assert_eq!(hosted_pinned(&env), 2, "one per locked build: {env}"); assert!(skipped.is_empty(), "{env}"); assert!( after.contains(&format!( - "/patch-registry/gem/{TOKEN}/{UUID}/\n specs:\n {DEP} \ - ({DEP_VERSION}-{PLATFORM})\n {DEP} ({DEP_VERSION}-{OTHER_PLATFORM})\n" + "{}/\n specs:\n {DEP} ({DEP_VERSION}-{PLATFORM})\n {DEP} \ + ({DEP_VERSION}-{OTHER_PLATFORM})\n", + snapshot_registry_path() )), "{after}" ); @@ -3011,8 +3067,9 @@ async fn gem_hosted_scan_pins_platform_builds_from_the_lock_alone() { }; assert!( detail.contains(&format!( - "no patched build for `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})`" - )) && detail.contains(&format!("patched builds for {PLATFORM}")), + "the patch registry does not list `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})` \ + among the platform gems of this version" + )), "{detail}" ); assert_eq!(after, lock, "the lock is untouched"); @@ -3026,7 +3083,7 @@ async fn gem_hosted_scan_pins_platform_builds_from_the_lock_alone() { } /// A lock that names the gem only as platform builds, beside a plain -/// gem, and a patch without a patched build for every locked platform: +/// gem, and a patch whose registry does not list every locked platform: /// the run refuses the gem. The lock still resolves it, so the closing /// totals count its advisory as left to patch, in hosted mode (which /// reads the gem from the lock alone) and in vendored mode (which reads @@ -3071,7 +3128,7 @@ async fn refused_platform_gem_is_counted_as_left_to_patch() { &server, None, &sha256_of(&real_gem(PATCHED_LIB)), - &[(PLATFORM, arm_sha.clone())], + &[(PLATFORM, arm_sha.clone(), Some(ARM_UUID))], ) .await; let tmp = tempfile::tempdir().unwrap(); @@ -3123,9 +3180,11 @@ async fn refused_platform_gem_is_counted_as_left_to_patch() { ); assert_eq!(code, 0, "{mode}\nstdout:\n{stdout}\nstderr:\n{stderr}"); // The premise: the run refused the gem for a platform the patch - // has no build for. + // registry does not serve. let refusal = match mode { - "hosted" => format!("no patched build for `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})`"), + "hosted" => { + format!("the patch registry does not list `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})`") + } _ => format!("the patch service has no prebuilt platform gem of `{DEP}`"), }; assert!( diff --git a/crates/socket-patch-cli/tests/hosted_memory_common/mod.rs b/crates/socket-patch-cli/tests/hosted_memory_common/mod.rs index 8429d58d9e..7f6c781c13 100644 --- a/crates/socket-patch-cli/tests/hosted_memory_common/mod.rs +++ b/crates/socket-patch-cli/tests/hosted_memory_common/mod.rs @@ -532,7 +532,19 @@ pub fn legacy_redirect(envelope: &Value) -> Value { Some("applied") | Some("verified") => { redirected += 1; let action = if dry_run { "would_pin" } else { "pinned" }; - patches.push(serde_json::json!({"purl": purl, "uuid": uuid, "action": action})); + let mut row = serde_json::json!({"purl": purl, "uuid": uuid, "action": action}); + build_keys(e, &mut row); + patches.push(row); + } + // A locked platform build of a hosted gem that stays upstream's + // own gem: reported, never counted, and no skip. + Some("skipped") if e["errorCode"] == "gem_upstream_build_kept" => { + let mut row = serde_json::json!({ + "purl": purl, "action": "upstream_kept", + "errorCode": "gem_upstream_build_kept", "error": e["reason"], + }); + build_keys(e, &mut row); + patches.push(row); } Some("skipped") if e["errorCode"] == "redirect_unconfirmed" => { patches.push(serde_json::json!({ @@ -580,6 +592,16 @@ pub fn legacy_redirect(envelope: &Value) -> Value { })) } +/// Copy what an event's `details` say of a gem's locked build (`gemFix`, +/// `platform`, `newlyPatched`) onto its `redirect.patches[]` row. +fn build_keys(event: &Value, row: &mut Value) { + for key in ["gemFix", "platform", "newlyPatched"] { + if let Some(value) = event["details"].get(key) { + row[key] = value.clone(); + } + } +} + /// An engine `redirect` block with `skipped[]` sorted by purl then uuid /// (the envelope's events are purl-sorted; the engine keeps its own order). pub fn sorted_redirect(redirect: &Value) -> Value { diff --git a/crates/socket-patch-cli/tests/hosted_memory_parity.rs b/crates/socket-patch-cli/tests/hosted_memory_parity.rs index a896e5cb24..327efb821f 100644 --- a/crates/socket-patch-cli/tests/hosted_memory_parity.rs +++ b/crates/socket-patch-cli/tests/hosted_memory_parity.rs @@ -35,6 +35,9 @@ struct Case { /// to match: a yarn classic pin reads the served tarball (#558, #591), /// which the fixtures' placeholder hashes could never verify. serve_npm_tarballs: bool, + /// Change the patches the fake API serves, for a case that differs from + /// its fixture only in what the patch service answers. + edit_patches: Option, } fn case(fixture: &'static str) -> Case { @@ -44,6 +47,7 @@ fn case(fixture: &'static str) -> Case { expect_redirect: true, dry_run: false, serve_npm_tarballs: false, + edit_patches: None, } } @@ -89,12 +93,20 @@ async fn serve_npm_tarballs(server: &MockServer, patches: &mut [common::Patch]) /// Returns the (shared) `redirect` block so a case can assert on it too. async fn assert_parity(case: Case) -> Value { + assert_parity_run(case).await.0 +} + +/// [`assert_parity`], also returning the engine's result for the one root. +async fn assert_parity_run(case: Case) -> (Value, socket_patch_cli::hosted_memory::ProjectResult) { let dir = fixtures_root().join("redirect").join(case.fixture); let server = MockServer::start().await; let mut patches = patches_from_overrides(&dir.join("overrides.json"), Some(&server.uri())); if case.serve_npm_tarballs { serve_npm_tarballs(&server, &mut patches).await; } + if let Some(edit) = case.edit_patches { + edit(&mut patches); + } mount_api(&server, &patches).await; let mut files = fixture_files(&dir.join("input")); for (rel, bytes) in &case.extra { @@ -168,7 +180,7 @@ async fn assert_parity(case: Case) -> Value { "{}", case.fixture ); - disk_redirect + (disk_redirect, project.clone()) } #[tokio::test] @@ -306,6 +318,108 @@ async fn parity_gemfile_platform_prebuilds() { assert_parity(case("gem/bundler/platform-prebuilds")).await; } +/// A lock of platform builds where the patch registry has a patched build +/// for one platform and serves upstream's own gem for the other. Both +/// engines move the gem, pin each build to what the registry serves, and +/// report it per locked build: the patched build under its own patch, the +/// other as kept on upstream's gem, counted by neither. +#[tokio::test] +async fn parity_gemfile_platform_pass_through() { + use socket_patch_cli::hosted_memory::{RedirectedPatch, UpstreamBuild}; + const FIX: &str = "77777777-7777-7777-7777-777777777777"; + const LINUX: &str = "77777777-7777-4777-8777-00000000000b"; + let (redirect, project) = assert_parity_run(case("gem/bundler/platform-pass-through")).await; + assert_eq!(redirect["redirected"], 1, "{redirect:#}"); + assert_eq!(redirect["warnings"], serde_json::json!([]), "{redirect:#}"); + assert_eq!(redirect["skipped"], serde_json::json!([]), "{redirect:#}"); + assert_eq!( + redirect["patches"], + serde_json::json!([ + { + "purl": "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin", + "action": "upstream_kept", + "errorCode": "gem_upstream_build_kept", + "error": "the patch registry serves upstream's own gem for arm64-darwin: no \ + patched build yet", + "gemFix": FIX, + "platform": "arm64-darwin", + }, + { + "purl": "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + "uuid": LINUX, + "action": "pinned", + "gemFix": FIX, + "platform": "x86_64-linux-gnu", + "newlyPatched": true, + }, + ]), + "{redirect:#}" + ); + assert_eq!( + project.redirected, + [RedirectedPatch { + purl: "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu".into(), + uuid: LINUX.into(), + gem_fix: Some(FIX.into()), + platform: Some("x86_64-linux-gnu".into()), + newly_patched: true, + }] + ); + assert_eq!( + project.upstream_builds, + [UpstreamBuild { + purl: "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin".into(), + gem_fix: FIX.into(), + platform: "arm64-darwin".into(), + }] + ); + assert!(project.skipped.is_empty(), "{:?}", project.skipped); +} + +/// The same lock where no locked platform has a patched build yet: both +/// engines leave the gem on its upstream registry, write nothing, warn of +/// nothing, and report one skip under the quiet code, never an unpinned +/// patch. +#[tokio::test] +async fn parity_gemfile_platform_no_patched_build() { + fn none_patched(patches: &mut [common::Patch]) { + for patch in patches { + let builds = &mut patch.reference["registryOverride"]["identifiers"]["gemBuilds"]; + for build in builds.as_array_mut().expect("the fixture lists builds") { + build["patchUuid"] = Value::Null; + } + } + } + let (redirect, project) = assert_parity_run(Case { + expect_redirect: false, + edit_patches: Some(none_patched), + ..case("gem/bundler/platform-pass-through") + }) + .await; + let detail = "nokogiri 1.18.10: no patched build yet for arm64-darwin, x86_64-linux-gnu; left \ + on its upstream registry"; + assert_eq!(redirect["redirected"], 0, "{redirect:#}"); + assert_eq!(redirect["rewrittenFiles"], serde_json::json!([])); + assert_eq!(redirect["warnings"], serde_json::json!([]), "{redirect:#}"); + assert_eq!( + redirect["patches"], + serde_json::json!([{ + "purl": "pkg:gem/nokogiri@1.18.10", + "uuid": "77777777-7777-7777-7777-777777777777", + "action": "skipped", + "errorCode": "redirect_gem_no_patched_build", + "error": detail, + }]), + "{redirect:#}" + ); + assert!(project.redirected.is_empty() && project.upstream_builds.is_empty()); + let [skip] = project.skipped.as_slice() else { + panic!("one skip: {:?}", project.skipped); + }; + assert_eq!(skip.reason, "redirect_gem_no_patched_build"); + assert_eq!(skip.detail.as_deref(), Some(detail)); +} + /// The gem fixture as the root of a Bazel workspace whose rules_ruby hub /// reads the lock and names the patched gem in `gem_checksums`. With the /// sha256 of the upstream archive there, the checkout and the engine write diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index 08affff077..7f2bf69bbb 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -148,6 +148,13 @@ pub const GEM_NO_PATCHED_BUILD: &str = "redirect_gem_no_patched_build"; /// neither counted nor attested as patched. pub const GEM_UPSTREAM_BUILD_KEPT: &str = "gem_upstream_build_kept"; +/// What a host says beside [`GEM_UPSTREAM_BUILD_KEPT`] for the locked +/// build of `platform`: the one wording of the disk host's event and the +/// in-memory engine's row. +pub fn gem_upstream_build_kept_detail(platform: &str) -> String { + format!("the patch registry serves upstream's own gem for {platform}: no patched build yet") +} + /// The skips of the gems a rewrite left on their upstream registry because /// no locked build of them is patched yet /// ([`RewriteResult::gem_unpatched`]), one per candidate, in candidate diff --git a/crates/socket-patch-core/src/hosted/memory/mod.rs b/crates/socket-patch-core/src/hosted/memory/mod.rs index 979102f8cf..6f490b21e2 100644 --- a/crates/socket-patch-core/src/hosted/memory/mod.rs +++ b/crates/socket-patch-core/src/hosted/memory/mod.rs @@ -1297,6 +1297,7 @@ async fn engine( redirect, summary: state.summary.clone(), redirected: Vec::new(), + upstream_builds: Vec::new(), skipped, deferred: state.deferred.clone(), error: state.error.clone(), @@ -1533,6 +1534,7 @@ fn finish_root( redirect: serde_json::json!({ "mode": "hosted" }), summary: state.summary.clone(), redirected: Vec::new(), + upstream_builds: Vec::new(), skipped, deferred: state.deferred.clone(), error: Some(ProjectError { @@ -1562,22 +1564,43 @@ fn finish_root( warnings.extend(npm_warnings); warnings.extend(pre_warnings); let redirect_warnings = crate::hosted::render::rewrite_warnings_json(&warnings); + // The pins as the run reports them: a gem the lock names as platform + // builds once per locked build. + let reports = crate::hosted::engine::pin_reports(&confirmed, &rewrite); let redirect = crate::hosted::render::redirect_json_block( - &confirmed, + &reports, &unconfirmed, rewritten, &skipped, redirect_warnings, dry_run, ); + let mut redirected = Vec::with_capacity(reports.len()); + let mut upstream_builds = Vec::new(); + for report in reports { + match (report.uuid, report.gem_fix, report.platform) { + (Some(uuid), gem_fix, platform) => redirected.push(RedirectedPatch { + purl: report.purl, + uuid, + gem_fix, + platform, + newly_patched: report.newly_patched, + }), + (None, Some(gem_fix), Some(platform)) => upstream_builds.push(UpstreamBuild { + purl: report.purl, + gem_fix, + platform, + }), + // Only a platform build of a gem is ever served as upstream's. + (None, _, _) => {} + } + } ProjectResult { root, redirect, summary: state.summary.clone(), - redirected: confirmed - .into_iter() - .map(|(purl, uuid)| RedirectedPatch { purl, uuid }) - .collect(), + redirected, + upstream_builds, skipped, deferred: state.deferred.clone(), error: None, diff --git a/crates/socket-patch-core/src/hosted/memory/stages.rs b/crates/socket-patch-core/src/hosted/memory/stages.rs index 79a99af090..2cbac564ba 100644 --- a/crates/socket-patch-core/src/hosted/memory/stages.rs +++ b/crates/socket-patch-core/src/hosted/memory/stages.rs @@ -395,6 +395,9 @@ pub(crate) async fn rewrite( }); } skipped.extend(done.unattributed.iter().cloned()); + // A gem left on its upstream registry because no build the lock names + // is patched yet is skipped under its own code, never unpinned. + skipped.extend(engine::gem_unpatched_skips(&candidates, &done.rewrite)); let unconfirmed = engine::unconfirmed_candidates(&candidates, &done.confirmed, &skipped); Ok(Rewritten { project, diff --git a/crates/socket-patch-core/src/hosted/memory/types.rs b/crates/socket-patch-core/src/hosted/memory/types.rs index fa81876e81..d36dec8114 100644 --- a/crates/socket-patch-core/src/hosted/memory/types.rs +++ b/crates/socket-patch-core/src/hosted/memory/types.rs @@ -272,11 +272,41 @@ pub struct ProjectSummary { pub can_access_paid_patches: bool, } +/// One patch a project's files pin. A gem the Bundler lock names as +/// platform builds is listed once per locked build that has a patched +/// build, under that build's own patch +/// ([`pin_reports`](crate::hosted::engine::pin_reports)); every other +/// package once, with `purl` and `uuid` alone. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RedirectedPatch { + /// `pkg:gem/@?platform=` for a platform gem. pub purl: String, pub uuid: String, + /// For a build of a gem locked as platform builds: the gem patch's + /// uuid, the one selected patch all its builds go by. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub gem_fix: Option, + /// For such a build: its platform (absent on the ruby-platform gem). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub platform: Option, + /// For such a build: this run put its patched build in place. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub newly_patched: bool, +} + +/// One locked platform build of a redirected gem that the patch registry +/// serves as upstream's own gem (no patched build yet): machines of that +/// platform install what they installed before, so it is no entry of +/// `redirected`. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UpstreamBuild { + /// `pkg:gem/@?platform=`. + pub purl: String, + /// The gem patch's uuid, as [`RedirectedPatch::gem_fix`]. + pub gem_fix: String, + pub platform: String, } pub use crate::hosted::engine::SkippedPatch; @@ -307,6 +337,10 @@ pub struct ProjectResult { pub redirect: serde_json::Value, pub summary: ProjectSummary, pub redirected: Vec, + /// The platform builds of the redirected gems that stay upstream's own + /// gem; absent when there are none. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub upstream_builds: Vec, pub skipped: Vec, /// NEW patches over the run-wide `maxNewPatches` budget, in rank order /// (also in `skipped[]` as `rollout_deferred`). diff --git a/crates/socket-patch-core/src/hosted/render.rs b/crates/socket-patch-core/src/hosted/render.rs index 5131ec0e29..398dfc1d5b 100644 --- a/crates/socket-patch-core/src/hosted/render.rs +++ b/crates/socket-patch-core/src/hosted/render.rs @@ -3,7 +3,9 @@ //! ([`RewriteWarning`], [`SkippedPatch`]); only this adapter spells them as //! JSON, so the disk and memory paths cannot drift in key names. -use super::engine::SkippedPatch; +use super::engine::{ + gem_upstream_build_kept_detail, PinReport, SkippedPatch, GEM_UPSTREAM_BUILD_KEPT, +}; use crate::patch::redirect::RewriteWarning; /// A `skipped[]` entry (`{purl, uuid, reason[, detail]}`). @@ -29,12 +31,21 @@ pub fn rewrite_warnings_json(warnings: &[RewriteWarning]) -> Vec, skipped: &[SkippedPatch], @@ -42,9 +53,33 @@ pub fn redirect_json_block( dry_run: bool, ) -> serde_json::Value { let pinned = if dry_run { "would_pin" } else { "pinned" }; - let mut patches: Vec = confirmed + let mut patches: Vec = reports .iter() - .map(|(purl, uuid)| serde_json::json!({ "purl": purl, "uuid": uuid, "action": pinned })) + .map(|report| { + let mut row = match &report.uuid { + Some(uuid) => { + serde_json::json!({ "purl": report.purl, "uuid": uuid, "action": pinned }) + } + None => serde_json::json!({ + "purl": report.purl, + "action": UPSTREAM_KEPT, + "errorCode": GEM_UPSTREAM_BUILD_KEPT, + "error": gem_upstream_build_kept_detail( + report.platform.as_deref().unwrap_or_default(), + ), + }), + }; + if let Some(gem_fix) = &report.gem_fix { + row["gemFix"] = serde_json::json!(gem_fix); + } + if let Some(platform) = &report.platform { + row["platform"] = serde_json::json!(platform); + } + if report.newly_patched { + row["newlyPatched"] = serde_json::json!(true); + } + row + }) .chain(skipped.iter().map(|s| { let mut row = serde_json::json!({ "purl": s.purl, "uuid": s.uuid, "action": "skipped", "errorCode": s.reason, @@ -67,7 +102,7 @@ pub fn redirect_json_block( }); serde_json::json!({ "mode": "hosted", - "redirected": confirmed.len(), + "redirected": reports.iter().filter(|report| report.uuid.is_some()).count(), "rewrittenFiles": rewritten, "skipped": skipped.iter().map(skipped_json).collect::>(), "patches": patches, @@ -79,3 +114,85 @@ pub fn redirect_json_block( /// The `errorCode` of an `unpinned` `redirect.patches[]` row: the patch was /// granted, but no lockfile entry pinning it could be rewritten. pub const REDIRECT_UNCONFIRMED: &str = "redirect_unconfirmed"; + +/// The `action` of the `redirect.patches[]` row of a locked platform build +/// of a hosted gem that the patch registry serves as upstream's own gem: +/// that build is as it was, and is neither pinned to a patch nor skipped. +pub const UPSTREAM_KEPT: &str = "upstream_kept"; + +#[cfg(test)] +mod tests { + use super::*; + + /// A pin of any package is one `pinned` row with `purl` and `uuid` + /// alone. A gem the lock names as platform builds is one row per + /// locked build: `pinned` under the build's own patch, or + /// `upstream_kept` with no `uuid` for a build that stays upstream's + /// gem, which `redirected` does not count and `skipped[]` does not + /// list. A dry run previews a pin as `would_pin`. + #[test] + fn the_redirect_block_reports_a_platform_locked_gem_per_build() { + const FIX: &str = "77777777-7777-4777-8777-777777777777"; + let build = |platform: Option<&str>, uuid: Option<&str>, newly: bool| PinReport { + purl: match platform { + Some(platform) => format!("pkg:gem/nokogiri@1.19.3?platform={platform}"), + None => "pkg:gem/nokogiri@1.19.3".to_string(), + }, + uuid: uuid.map(str::to_string), + gem_fix: Some(FIX.to_string()), + platform: platform.map(str::to_string), + newly_patched: newly, + }; + let reports = [ + PinReport { + purl: "pkg:npm/a@1.0.0".into(), + uuid: Some("ua".into()), + gem_fix: None, + platform: None, + newly_patched: false, + }, + build(None, Some(FIX), false), + build(Some("arm64-darwin"), None, false), + build(Some("x86_64-linux-gnu"), Some("ul"), true), + ]; + let block = redirect_json_block(&reports, &[], Vec::new(), &[], Vec::new(), false); + assert_eq!(block["redirected"], 3); + assert_eq!(block["skipped"], serde_json::json!([])); + assert_eq!( + block["patches"], + serde_json::json!([ + { + "purl": "pkg:gem/nokogiri@1.19.3", "uuid": FIX, "action": "pinned", + "gemFix": FIX, + }, + { + "purl": "pkg:gem/nokogiri@1.19.3?platform=arm64-darwin", + "action": "upstream_kept", + "errorCode": "gem_upstream_build_kept", + "error": "the patch registry serves upstream's own gem for arm64-darwin: no \ + patched build yet", + "gemFix": FIX, + "platform": "arm64-darwin", + }, + { + "purl": "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu", "uuid": "ul", + "action": "pinned", "gemFix": FIX, "platform": "x86_64-linux-gnu", + "newlyPatched": true, + }, + { "purl": "pkg:npm/a@1.0.0", "uuid": "ua", "action": "pinned" }, + ]) + ); + let dry = redirect_json_block(&reports, &[], Vec::new(), &[], Vec::new(), true); + let actions: Vec<&str> = dry["patches"] + .as_array() + .unwrap() + .iter() + .map(|row| row["action"].as_str().unwrap()) + .collect(); + assert_eq!( + actions, + ["would_pin", "upstream_kept", "would_pin", "would_pin"] + ); + assert_eq!(dry["redirected"], 3); + } +} diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected-edits.json new file mode 100644 index 0000000000..9686e371e1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected-edits.json @@ -0,0 +1,34 @@ +[ + { + "path": "Gemfile", + "kind": "redirect_gemfile_source_option", + "action": "added", + "key": "nokogiri", + "original": "gem \"nokogiri\", \"1.18.10\"", + "new": "gem \"nokogiri\", \"1.18.10\", source: \"https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/\"" + }, + { + "path": "Gemfile.lock", + "kind": "redirect_gemfile_lock_checksum", + "action": "rewritten", + "key": "nokogiri", + "original": "nokogiri (1.18.10-x86_64-linux-gnu) sha256=4444444444444444444444444444444444444444444444444444444444444444", + "new": "nokogiri (1.18.10-x86_64-linux-gnu) sha256=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + }, + { + "path": "Gemfile.lock", + "kind": "redirect_gemfile_lock_dependency_pin", + "action": "rewritten", + "key": "nokogiri", + "original": "nokogiri (= 1.18.10)", + "new": "nokogiri (= 1.18.10)!" + }, + { + "path": "Gemfile.lock", + "kind": "redirect_gemfile_lock_gem_source", + "action": "rewritten", + "key": "nokogiri", + "original": "https://rubygems.org/", + "new": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected-warnings.json new file mode 100644 index 0000000000..fe51488c70 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected-warnings.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected/Gemfile b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected/Gemfile new file mode 100644 index 0000000000..8b333466e6 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected/Gemfile @@ -0,0 +1,4 @@ +source "https://rubygems.org" + +gem "nokogiri", "1.18.10", source: "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/" +gem "puma", "6.0.0" diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected/Gemfile.lock new file mode 100644 index 0000000000..2f2aa48059 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/expected/Gemfile.lock @@ -0,0 +1,30 @@ +GEM + remote: https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/ + specs: + nokogiri (1.18.10-arm64-darwin) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-linux-gnu) + racc (~> 1.4) + +GEM + remote: https://rubygems.org/ + specs: + puma (6.0.0) + racc (1.8.1) + +PLATFORMS + arm64-darwin + x86_64-linux-gnu + +DEPENDENCIES + nokogiri (= 1.18.10)! + puma (= 6.0.0) + +CHECKSUMS + nokogiri (1.18.10-arm64-darwin) sha256=3333333333333333333333333333333333333333333333333333333333333333 + nokogiri (1.18.10-x86_64-linux-gnu) sha256=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + puma (6.0.0) sha256=1111111111111111111111111111111111111111111111111111111111111111 + racc (1.8.1) sha256=5555555555555555555555555555555555555555555555555555555555555555 + +BUNDLED WITH + 4.0.15 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/input/Gemfile b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/input/Gemfile new file mode 100644 index 0000000000..bbbe99128f --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/input/Gemfile @@ -0,0 +1,4 @@ +source "https://rubygems.org" + +gem "nokogiri", "1.18.10" +gem "puma", "6.0.0" diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/input/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/input/Gemfile.lock new file mode 100644 index 0000000000..7064b964be --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/input/Gemfile.lock @@ -0,0 +1,26 @@ +GEM + remote: https://rubygems.org/ + specs: + nokogiri (1.18.10-arm64-darwin) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-linux-gnu) + racc (~> 1.4) + puma (6.0.0) + racc (1.8.1) + +PLATFORMS + arm64-darwin + x86_64-linux-gnu + +DEPENDENCIES + nokogiri (= 1.18.10) + puma (= 6.0.0) + +CHECKSUMS + nokogiri (1.18.10-arm64-darwin) sha256=3333333333333333333333333333333333333333333333333333333333333333 + nokogiri (1.18.10-x86_64-linux-gnu) sha256=4444444444444444444444444444444444444444444444444444444444444444 + puma (6.0.0) sha256=1111111111111111111111111111111111111111111111111111111111111111 + racc (1.8.1) sha256=5555555555555555555555555555555555555555555555555555555555555555 + +BUNDLED WITH + 4.0.15 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/overrides.json new file mode 100644 index 0000000000..18363808c3 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-pass-through/overrides.json @@ -0,0 +1,34 @@ +[ + { + "ecosystem": "gem", + "name": "nokogiri", + "version": "1.18.10", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/gems/nokogiri-1.18.10.gem", + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", + "gemBuilds": [ + { + "platform": "arm64-darwin", + "gemChecksumSha256": "3333333333333333333333333333333333333333333333333333333333333333", + "patchUuid": null + }, + { + "platform": "x86_64-linux-gnu", + "gemChecksumSha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "patchUuid": "77777777-7777-4777-8777-00000000000b" + } + ] + } + }, + "integrity": { + "sha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json index 162c703fc1..f865f322de 100644 --- a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json +++ b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json @@ -44,6 +44,51 @@ "elsewhere": [], "live_claims": [] }, + "redirect/gem/bundler/platform-pass-through/expected": { + "refs": [ + { + "purl": "pkg:gem/nokogiri@1.18.10", + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "source_file": "Gemfile.lock", + "artifact_rel": null, + "locked_integrity": "Sha256Hex(\"3333333333333333333333333333333333333333333333333333333333333333\")", + "integrity_required": true, + "url": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/s/4/", + "lockfile_basis_ok": true + } + ], + "diagnostics": [], + "recognized": [ + { + "uuid": "11111111-1111-1111-1111-111111111111", + "mode": "hosted", + "file": "Gemfile.lock" + }, + { + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "file": "Gemfile.lock" + } + ], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [ + { + "mode": "hosted", + "uuid": "77777777-7777-7777-7777-777777777777", + "purl": "pkg:gem/nokogiri@1.18.10" + } + ] + }, + "redirect/gem/bundler/platform-pass-through/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, "redirect/gem/bundler/platform-prebuild-missing/input": { "refs": [], "diagnostics": [], diff --git a/crates/socket-patch-node/npm/index.d.ts b/crates/socket-patch-node/npm/index.d.ts index a12cf2db0b..b65ca49bf2 100644 --- a/crates/socket-patch-node/npm/index.d.ts +++ b/crates/socket-patch-node/npm/index.d.ts @@ -76,7 +76,8 @@ export interface ProjectResult { root: string redirect: Record // same shape as CLI `--json` `redirect` block summary: { scannedPackages: number; packagesWithPatches: number; totalPatches: number; freePatches: number; paidPatches: number; canAccessPaidPatches: boolean } - redirected: { purl: string; uuid: string }[] + redirected: { purl: string; uuid: string; gemFix?: string; platform?: string; newlyPatched?: boolean }[] // a gem the lock names as platform builds: one entry per locked build that has a patched build, under that build's own patch (gemFix = the gem's selected patch; newlyPatched = this run put the build in place) + upstreamBuilds?: { purl: string; gemFix: string; platform: string }[] // locked platform builds of redirected gems that the patch registry serves as upstream's own gem (no patched build yet); never in `redirected` skipped: { purl: string; uuid: string; reason: string; detail?: string }[] // reasons include the policy_* codes; deferred rows appear as `rollout_deferred` deferred: DeferredPatch[] // NEW patches over the maxNewPatches budget, rank order error?: { code: string; message: string } // project-level failure (e.g. corrupt_ledger, patch_lookup_failed) From e66aa1b8cc1d0238b2f25268fe16e773042ea997 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 19:12:54 -0500 Subject: [PATCH 003/120] Leave a gem build on upstream's gem out of the stale-install guard A hosted gem locked as platform builds keeps upstream's own gem for a platform with no patched build: its lock entry pins upstream's sha256, and a machine of that platform holds the right copy. The guard judged that copy like any other. Its cached archive passed only because the sha256 of upstream's gem was counted among the patched artifacts. With the archive pruned, the patch's file hashes called upstream's files stale, and the run downloaded upstream's gem from the registry to replace the install with the bytes it already held, and reported a refresh. Such a build is not judged at all, installed or committed to the cache dir: nothing is reported, nothing is refreshed, no gem is downloaded and no patch record is fetched for it. The patched artifacts are those of the patched builds alone. A platform with a patched build is handled as before. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/scan/hosted.rs | 154 +++++++++++++++++- .../tests/e2e_redirect_gem_stale_install.rs | 137 +++++++++++++++- 2 files changed, 280 insertions(+), 11 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 1b01fd6f56..b5ac0095b4 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -687,7 +687,12 @@ fn stale_cache_gem(purl: &str, cache_path: &Path) -> StaleGem { /// * A gem locked as precompiled platform builds is installed as /// `--`, and cached under that name: each is /// judged the same way, against the patched artifacts of the gem, which -/// include its prebuilds. +/// include its patched platform builds. +/// * A platform build the patch registry serves as upstream's own gem (no +/// patched build yet; `gem_upstream_leaves` names it by leaf) is not +/// judged at all, installed or committed to the cache dir: its lock +/// entry pins upstream's gem, so a machine of that platform holds the +/// right copy, and there is nothing to report or to refresh. /// * Which copies are judged is the lock's to say: every build of the gem /// the project's lock names is looked for under its own leaf, in every /// gem home. A gem home can hold several builds of one version (the @@ -696,6 +701,7 @@ fn stale_cache_gem(purl: &str, cache_path: &Path) -> StaleGem { /// platform build Bundler loads, or replace a build that is not this /// project's. Only where no lock names the gem (a global scan) is the /// first installed copy judged, as before. +#[allow(clippy::too_many_arguments)] async fn gem_stale_install_warnings( cwd: &Path, global: bool, @@ -709,6 +715,7 @@ async fn gem_stale_install_warnings( (String, String), std::collections::BTreeSet, >, + gem_upstream_leaves: &std::collections::BTreeSet, views: &mut ViewFallback<'_>, ) -> StaleInstallOutcome { use socket_patch_core::crawlers::types::CrawlerOptions; @@ -832,6 +839,10 @@ async fn gem_stale_install_warnings( let Some(leaf) = dir.file_name().and_then(|n| n.to_str()) else { continue; }; + // Upstream's own gem is what the lock pins for this build. + if gem_upstream_leaves.contains(leaf) { + continue; + } let entry = dir_state.entry(dir.clone()).or_insert_with(|| DirJudgment { purl: (*purl).to_string(), leaf: leaf.to_string(), @@ -968,6 +979,7 @@ async fn gem_stale_install_warnings( }; for cache_path in builds .iter() + .filter(|build| !gem_upstream_leaves.contains(&build.leaf)) .map(|build| app_cache.join(format!("{}.gem", build.leaf))) { if cache_covered.contains(&cache_path) || !cache_path.is_file() { @@ -1053,6 +1065,7 @@ async fn refresh_stale_gems( (String, String), std::collections::BTreeSet, >, + gem_upstream_leaves: &std::collections::BTreeSet, overrides: &[DepOverride], mirror_sources: &socket_patch_core::hosted::engine::MirrorSources, views: &mut ViewFallback<'_>, @@ -1066,6 +1079,7 @@ async fn refresh_stale_gems( confirmed, local_records, gem_artifact_shas, + gem_upstream_leaves, views, ) .await; @@ -1084,9 +1098,9 @@ async fn refresh_stale_gems( // The patched archive: what bundler itself would download from the // patch registry (`/gems/.gem`), else the grant's own // artifact, verified against the sha256 the lock pins. A platform - // build (`--`) is the patch's prebuild for - // that platform, pinned by its own sha256; a platform gem declares no - // extensions, so replacing one builds nothing. + // build (`--`) is the patched build the + // registry serves for that platform, pinned by its own sha256; a + // platform gem declares no extensions, so replacing one builds nothing. let wanted = |gem: &StaleGem| { let (name, version) = gem_sha_key(&gem.purl); let build = GemBuild::of_leaf(&gem.purl, &gem.leaf); @@ -1097,6 +1111,7 @@ async fn refresh_stale_gems( .filter_map(|o| o.registry_override.as_ref()) .flat_map(|ro| ro.identifiers.gem_builds.iter().flatten()) .filter(|prebuild| Some(prebuild.platform.as_str()) == platform) + .filter(|prebuild| prebuild.patch_uuid.is_some()) .map(|prebuild| prebuild.gem_checksum_sha256.to_ascii_lowercase()) .collect(); let sha256 = if prebuilt.is_empty() { @@ -1148,6 +1163,7 @@ async fn refresh_stale_gems( confirmed, local_records, gem_artifact_shas, + gem_upstream_leaves, views, ) .await @@ -2397,25 +2413,39 @@ async fn run_redirect_selected_untracked( // // purl-coordinate → every PATCHED .gem artifact's sha256 (registry // override identifier, tarball integrity fallback; one per platform - // variant, and one per prebuild: the patched platform gem a lock that + // variant, and one per patched platform build: the gem a lock that // names platform builds is pinned to) — judges the installed and // committed archives, and verifies the archive a refresh installs. let mut gem_artifact_shas: std::collections::BTreeMap< (String, String), std::collections::BTreeSet, > = std::collections::BTreeMap::new(); + // The platform builds the patch registry serves as upstream's own gem + // (no patched build yet), by leaf: a machine of such a platform holds + // upstream's gem, which is what its lock entry pins. + let mut gem_upstream_leaves: std::collections::BTreeSet = + std::collections::BTreeSet::new(); for o in done.overrides.iter().filter(|o| o.ecosystem == "gem") { let sha = o .registry_override .as_ref() .and_then(|ro| ro.identifiers.gem_checksum_sha256.clone()) .or_else(|| o.integrity.sha256.clone()); - let prebuilds = o + let mut patched_builds = Vec::new(); + for build in o .registry_override .iter() .flat_map(|ro| ro.identifiers.gem_builds.iter().flatten()) - .map(|prebuild| prebuild.gem_checksum_sha256.clone()); - for sha in sha.into_iter().chain(prebuilds) { + { + match build.patch_uuid { + Some(_) => patched_builds.push(build.gem_checksum_sha256.clone()), + None => { + gem_upstream_leaves + .insert(format!("{}-{}-{}", o.name, o.version, build.platform)); + } + } + } + for sha in sha.into_iter().chain(patched_builds) { gem_artifact_shas .entry((o.name.clone(), o.version.clone())) .or_default() @@ -2431,6 +2461,7 @@ async fn run_redirect_selected_untracked( &confirmed, &local_records, &gem_artifact_shas, + &gem_upstream_leaves, &done.overrides, &mirror_sources, &mut views, @@ -4935,6 +4966,7 @@ mod tests { confirmed, records, &std::collections::BTreeMap::new(), + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await @@ -5214,6 +5246,7 @@ mod tests { &one_confirmed, &none, &shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5231,6 +5264,7 @@ mod tests { &one_confirmed, &none, &shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5244,6 +5278,7 @@ mod tests { &one_confirmed, &none, &shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5279,6 +5314,7 @@ mod tests { &confirmed, &std::collections::BTreeMap::new(), &shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5374,6 +5410,7 @@ mod tests { &one_confirmed(), &none, &shas, + &std::collections::BTreeSet::new(), &mut views, ) .await; @@ -5394,6 +5431,7 @@ mod tests { &one_confirmed(), &none, &shas, + &std::collections::BTreeSet::new(), &mut views, ) .await; @@ -5424,6 +5462,7 @@ mod tests { &one_confirmed(), &none, &std::collections::BTreeMap::new(), + &std::collections::BTreeSet::new(), &mut views, ) .await; @@ -5461,6 +5500,7 @@ mod tests { &one_confirmed(), &std::collections::BTreeMap::new(), &shas, + &std::collections::BTreeSet::new(), &mut views, ) .await; @@ -5576,6 +5616,7 @@ mod tests { &one_confirmed(), &one_record(), &std::collections::BTreeMap::new(), + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5649,6 +5690,7 @@ mod tests { &confirmed, &records, &shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await @@ -5694,6 +5736,7 @@ mod tests { &confirmed, &records, &upper, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5740,6 +5783,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5783,6 +5827,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5811,6 +5856,7 @@ mod tests { &one_confirmed(), &one_record(), &patched_shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5834,6 +5880,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5876,6 +5923,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5901,6 +5949,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5928,6 +5977,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -6017,6 +6067,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeSet::new(), &mut super::ViewFallback::offline(), ) .await; @@ -6036,6 +6087,93 @@ mod tests { } } + /// A lock that names two platform builds, on a machine of the platform + /// the patch registry serves as upstream's own gem: the installed copy + /// and the committed cache-dir archive are upstream's gem, which is + /// what that lock entry pins. Neither is judged, whatever evidence + /// there is: nothing is stale, nothing is unjudged, and so nothing is + /// handed to the refresh. The same copies of a platform that has a + /// patched build are stale. + #[tokio::test] + async fn gem_stale_probe_leaves_a_build_on_upstreams_gem_alone() { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path(); + std::fs::write( + cwd.join("Gemfile"), + "source \"https://rubygems.org\"\ngem \"stale-unit\", \"1.0.0\"\n", + ) + .unwrap(); + std::fs::write( + cwd.join("Gemfile.lock"), + "GEM\n remote: https://rubygems.org/\n specs:\n stale-unit \ + (1.0.0-arm64-darwin)\n stale-unit (1.0.0-x86_64-linux-gnu)\n\nPLATFORMS\n \ + arm64-darwin\n x86_64-linux-gnu\n\nDEPENDENCIES\n stale-unit (= 1.0.0)\n\n\ + BUNDLED WITH\n 2.5.0\n", + ) + .unwrap(); + let leaf = format!("{GEM_LEAF}-arm64-darwin"); + let home = gem_home(cwd); + let gem_dir = home.join("gems").join(&leaf); + std::fs::create_dir_all(gem_dir.join("lib")).unwrap(); + std::fs::write(gem_dir.join("lib").join("stale_unit.rb"), GEM_UPSTREAM).unwrap(); + let archive = home.join("cache").join(format!("{leaf}.gem")); + std::fs::create_dir_all(archive.parent().unwrap()).unwrap(); + std::fs::write(&archive, b"upstream platform .gem").unwrap(); + let committed = cwd.join("vendor").join("cache").join(format!("{leaf}.gem")); + std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); + std::fs::write(&committed, b"upstream platform .gem").unwrap(); + + /// The probe of the one confirmed gem, whose patched artifacts are + /// the ruby gem and the other platform's build. + async fn judge( + cwd: &std::path::Path, + upstream_leaves: &std::collections::BTreeSet, + ) -> super::StaleInstallOutcome { + let shas = std::collections::BTreeMap::from([( + ("stale-unit".to_string(), "1.0.0".to_string()), + std::collections::BTreeSet::from(["0".repeat(64), "1".repeat(64)]), + )]); + gem_stale_install_warnings( + cwd, + false, + None, + &one_confirmed(), + &std::collections::BTreeMap::new(), + &shas, + upstream_leaves, + &mut super::ViewFallback::offline(), + ) + .await + } + let upstream = std::collections::BTreeSet::from([leaf.clone()]); + let patched_platform = std::collections::BTreeSet::new(); + + let out = judge(cwd, &upstream).await; + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert!(out.gems.is_empty(), "nothing to refresh"); + assert!(out.stale_purls.is_empty() && out.unjudged_purls.is_empty()); + let out = judge(cwd, &patched_platform).await; + assert_eq!(out.warnings.len(), 1, "{:?}", out.warnings); + assert_eq!(out.gems.len(), 1); + assert_eq!( + out.gems[0].cache_archive.as_deref(), + Some(committed.as_path()), + "the committed archive is stale with it" + ); + + // With no archive beside the install there is nothing to judge it + // by: unjudged for a patched platform, still nothing for this one. + std::fs::remove_file(&archive).unwrap(); + std::fs::remove_file(&committed).unwrap(); + let out = judge(cwd, &upstream).await; + assert!(out.warnings.is_empty() && out.unjudged_purls.is_empty()); + let out = judge(cwd, &patched_platform).await; + assert_eq!( + out.unjudged_purls, + std::collections::BTreeSet::from([GEM_PURL.to_string()]) + ); + } + /// The standalone cache-flavor warning's load-bearing wording. #[test] fn gem_stale_cache_warning_names_archive_and_remedy() { diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index ab6f3f6cb0..588685ab03 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -3005,11 +3005,142 @@ async fn stale_guard_follows_the_builds_the_lock_names_in_a_home_with_both() { ruby_copy_untouched(); } +/// A lock of two platform builds where the patch registry has a patched +/// build for the other platform only: this machine's platform is served +/// as upstream's own gem, and its lock entry keeps upstream's sha256. The +/// copy this machine installed and the committed `bundle cache` archive +/// are upstream's gem, which is right. The scan moves the gem, reports no +/// stale install, refreshes nothing and downloads no gem: with the gem +/// home's cached archive beside the install, and with it pruned, where +/// only the patch's file hashes could judge the copy (they would call +/// upstream's files stale). +#[tokio::test(flavor = "multi_thread")] +async fn a_platform_served_as_upstreams_gem_is_no_stale_install() { + let upstream = real_gem_for(UPSTREAM_LIB, PLATFORM); + let other_upstream = real_gem_for(UPSTREAM_LIB, OTHER_PLATFORM); + let other_patched = real_gem_for(PATCHED_LIB, OTHER_PLATFORM); + let leaf = format!("{DEP}-{DEP_VERSION}-{PLATFORM}"); + for cached in [true, false] { + let server = MockServer::start().await; + mount_api_with( + &server, + None, + &sha256_of(&real_gem(PATCHED_LIB)), + &[ + (PLATFORM, sha256_of(&upstream), None), + (OTHER_PLATFORM, sha256_of(&other_patched), Some(LINUX_UUID)), + ], + ) + .await; + // The registry hands this platform's gem on unchanged: a refresh + // that asked for it would be served, and would show below. + let gem_route = format!("{}/gems/{leaf}.gem", snapshot_registry_path()); + Mock::given(method("GET")) + .and(path(gem_route.clone())) + .respond_with( + ResponseTemplate::new(200) + .set_body_raw(upstream.clone(), "application/octet-stream"), + ) + .mount(&server) + .await; + + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"), + ) + .unwrap(); + let lock = platform_lock(&sha256_of(&upstream), &sha256_of(&other_upstream)); + std::fs::write(proj.join("Gemfile.lock"), &lock).unwrap(); + let home = project_home(&proj); + let gem_dir = install_real_gem_for(&home, UPSTREAM_LIB, PLATFORM); + let home_archive = home.join("cache").join(format!("{leaf}.gem")); + if !cached { + std::fs::remove_file(&home_archive).unwrap(); + } + let committed = proj + .join("vendor") + .join("cache") + .join(format!("{leaf}.gem")); + std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); + std::fs::write(&committed, &upstream).unwrap(); + + let uri = server.uri(); + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "cached={cached}: {env}\nstderr:\n{stderr}"); + // The gem moved: the other platform is patched, this one is not. + assert_eq!( + hosted_pins(&env), + [( + format!("{PURL}?platform={OTHER_PLATFORM}"), + LINUX_UUID.to_string() + )], + "cached={cached}: {env}" + ); + let hosted_lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + assert!( + hosted_lock.contains(&format!( + "CHECKSUMS\n {DEP} ({DEP_VERSION}-{PLATFORM}) sha256={}\n {DEP} \ + ({DEP_VERSION}-{OTHER_PLATFORM}) sha256={}\n", + sha256_of(&upstream), + sha256_of(&other_patched) + )), + "cached={cached}: this platform keeps upstream's sha256:\n{hosted_lock}" + ); + + // Nothing about this machine's copy: it is the gem the lock pins. + assert!( + stale_warnings(&env).is_empty() + && warnings_with_code(&env, "redirect_gem_install_refreshed").is_empty(), + "cached={cached}: {env}" + ); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "cached={cached}"); + assert_eq!(std::fs::read(&committed).unwrap(), upstream); + match cached { + true => assert_eq!(std::fs::read(&home_archive).unwrap(), upstream), + false => assert!(!home_archive.exists(), "no archive is added"), + } + let asked: Vec = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .map(|request| request.url.path().to_string()) + .filter(|route| route.contains("/gems/") || route.contains("/patches/view/")) + .collect(); + assert_eq!( + asked, + Vec::::new(), + "cached={cached}: no gem is downloaded, no record is fetched to judge the copy" + ); + + // For a person: the one line about the gem's builds, and no warning. + let (code, stdout, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &[]); + assert_eq!(code, 0, "cached={cached}:\n{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "{DEP} {DEP_VERSION}: patched for {OTHER_PLATFORM}; upstream gem kept for \ + {PLATFORM} (no patched build yet)\n" + )), + "cached={cached}:\n{stdout}" + ); + assert!( + !stderr.contains("stale") && !stderr.contains("unpatched install"), + "cached={cached}:\n{stderr}" + ); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "cached={cached}"); + } +} + /// A fresh checkout: nothing is installed, and the lock names the gem only /// as platform builds. The hosted scan reads the gem from the lock alone -/// and pins every build to its prebuild. With a prebuild missing for one -/// locked platform it pins nothing, says which, and leaves both files as -/// they were. +/// and pins every build to its patched build. Where the patch registry +/// does not list one locked platform it pins nothing, says which, and +/// leaves both files as they were. #[tokio::test(flavor = "multi_thread")] async fn gem_hosted_scan_pins_platform_builds_from_the_lock_alone() { let ruby_sha = sha256_of(&real_gem(PATCHED_LIB)); From 8def61c5c8c5ed226ecb633bd10ff848324a9e33 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 19:33:51 -0500 Subject: [PATCH 004/120] Ask for the list of a gem's builds, and wait quietly for a missing one Four refinements of how a gem patch's registry is read. The list is asked for. The patch service answers a reference request as it always has unless the request carries `gemBuilds: true`, so that a release that knows no list keeps getting the ruby gem's registry alone. Every package reference request now carries it: the hosted lookup, the vendored one, and the public-proxy route. The list names the ruby gem too (`platform: "ruby"`, the patch itself). The entry was refused as a malformed platform, which cost the gem its grant. It is accepted, and the ruby gem's checksum is read from it where it is there, so every locked build is pinned from the one list. A platform can be missing from the list for a while: the service leaves it out while its patched build is being made. A lock that names such a platform was skipped with a warning, as if the registry were wrong. The gem is now left as it is with no warning (`gem_unlisted`, skip reason `redirect_gem_build_pending`) and moves on a later run. The warning `redirect_gem_platform_unsupported` remains for a patch with no list at all and for the merged lock of Bundler < 2.2. The snapshot level of a registry URL is an opaque key of lowercase hex digits, not a number. It is recognised and never read for a meaning. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/scan/hosted.rs | 6 +- .../tests/e2e_redirect_gem_platform_builds.rs | 120 ++++--- .../tests/e2e_redirect_gem_stale_install.rs | 39 ++- crates/socket-patch-core/src/api/client.rs | 25 +- crates/socket-patch-core/src/api/types.rs | 19 ++ crates/socket-patch-core/src/hosted/engine.rs | 76 ++++- .../src/patch/redirect/grant.rs | 3 +- .../src/patch/redirect/mod.rs | 292 ++++++++++++------ .../socket-patch-core/src/vex/discover/gem.rs | 10 +- 9 files changed, 397 insertions(+), 193 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index b5ac0095b4..74967a8bee 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -2943,7 +2943,7 @@ async fn run_redirect_selected_untracked( .iter() .filter(|s| s.reason != super::rollout::ROLLOUT_DEFERRED) // Said above, as one plain line per gem: nothing failed. - .filter(|s| s.reason != engine::GEM_NO_PATCHED_BUILD) + .filter(|s| !engine::is_quiet_gem_skip(&s.reason)) .map(|s| (s.purl.clone(), s.reason.clone())) .collect(); let unconfirmed_purls: Vec = @@ -3521,7 +3521,7 @@ fn format_gem_build_lines( skipped: &[socket_patch_core::hosted::engine::SkippedPatch], dry_run: bool, ) -> Vec { - use socket_patch_core::hosted::engine::{PinReport, GEM_NO_PATCHED_BUILD}; + use socket_patch_core::hosted::engine::{is_quiet_gem_skip, PinReport}; // Per gem patch, in report order: its locked builds. let mut gems: Vec<(&str, Vec<&PinReport>)> = Vec::new(); for report in reports { @@ -3576,7 +3576,7 @@ fn format_gem_build_lines( lines.extend( skipped .iter() - .filter(|skip| skip.reason == GEM_NO_PATCHED_BUILD) + .filter(|skip| is_quiet_gem_skip(&skip.reason)) .filter_map(|skip| skip.detail.clone()), ); lines diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs index eb8a36b525..4cd66780e3 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs @@ -676,53 +676,87 @@ async fn a_lock_without_checksums_still_moves() { ); } -/// A locked platform the registry does not list, and a reference with no -/// list at all: machines of that platform would be sent to a registry with -/// no gem for them, so nothing is written and the run says why. +/// A reference with no list at all is a patch of the ruby gem alone: +/// nothing is written and the run says why. #[tokio::test(flavor = "multi_thread")] -async fn an_unlisted_platform_leaves_the_gem_alone_with_a_warning() { - let linux_only: [Listed; 1] = [(LINUX, LINUX_PATCHED, Some(LINUX_UUID))]; - let cases: [(Option<(&[Listed], u32)>, String); 2] = [ - ( - Some((&linux_only[..], 4)), - format!( - "the patch registry does not list `{DEP} ({DEP_VERSION}-{ARM})` among the \ - platform gems of this version" - ), - ), - ( - None, +async fn a_patch_with_no_list_leaves_the_gem_alone_with_a_warning() { + let server = MockServer::start().await; + mount_api(&server, None).await; + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &server.uri(), &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); + assert_eq!(read(proj.path(), "Gemfile"), GEMFILE); + assert_eq!( + warning_codes(&env), + ["redirect_gem_platform_unsupported"], + "{env}" + ); + let detail = env["warnings"][0]["detail"].as_str().unwrap(); + assert!( + detail.contains( "the patch covers the ruby platform gem only (the patch registry does not list the \ platform gems of this version)" - .to_string(), ), - ]; - for (listing, why) in cases { - let server = MockServer::start().await; - mount_api(&server, listing).await; - let proj = project(&lock(true)); - let (code, env) = scan_json(proj.path(), &server.uri(), &[]); - assert_eq!(code, 0, "{env}"); - assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); - assert_eq!(read(proj.path(), "Gemfile"), GEMFILE); - assert_eq!( - warning_codes(&env), - ["redirect_gem_platform_unsupported"], - "{env}" - ); - let detail = env["warnings"][0]["detail"].as_str().unwrap(); - assert!(detail.contains(&why), "{detail}"); - assert_eq!( - hosted_events(&env), - [json!({ - "action": "skipped", "purl": PURL, "uuid": UUID, - "errorCode": "redirect_unconfirmed", - "reason": "no lockfile entry pinning it could be rewritten", - "details": { "mode": "hosted" }, - })], - "{env}" - ); - } + "{detail}" + ); + assert_eq!( + hosted_events(&env), + [json!({ + "action": "skipped", "purl": PURL, "uuid": UUID, + "errorCode": "redirect_unconfirmed", + "reason": "no lockfile entry pinning it could be rewritten", + "details": { "mode": "hosted" }, + })], + "{env}" + ); +} + +/// A locked platform the list leaves out is one whose patched build is +/// still being made: a machine of that platform would be sent to a +/// registry with no gem for it, so the gem is left as it is, with no +/// warning and one plain line, and a later run over a list that has the +/// platform moves it. +#[tokio::test(flavor = "multi_thread")] +async fn a_platform_missing_from_the_list_is_waited_for_quietly() { + let linux_only: [Listed; 1] = [(LINUX, LINUX_PATCHED, Some(LINUX_UUID))]; + let server = MockServer::start().await; + mount_api(&server, Some((&linux_only[..], 4))).await; + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &server.uri(), &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); + assert_eq!(read(proj.path(), "Gemfile"), GEMFILE); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + let waiting = format!( + "{DEP} {DEP_VERSION}: the patch registry does not list {ARM} yet (a patched build is \ + still being made); left as it is until it does" + ); + assert_eq!( + hosted_events(&env), + [json!({ + "action": "skipped", "purl": PURL, "uuid": UUID, + "errorCode": "redirect_gem_build_pending", + "reason": waiting, + "details": { "mode": "hosted" }, + })], + "{env}" + ); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + + let (code, stdout, stderr) = hosted(proj.path(), &server.uri(), &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&waiting), "{stdout}"); + assert!(!stderr.contains("Warning"), "{stderr}"); + + // The build is there: the list names the platform, and the gem moves. + let later = MockServer::start().await; + mount_api(&later, Some((&ONE_PATCHED[..], 5))).await; + let (code, env) = scan_json(proj.path(), &later.uri(), &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + assert_ne!(read(proj.path(), "Gemfile.lock"), lock(true)); } /// `get --mode hosted` writes what `scan` writes and diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index 588685ab03..930b2c7ba1 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -3193,13 +3193,22 @@ async fn gem_hosted_scan_pins_platform_builds_from_the_lock_alone() { ); } else { assert_eq!(hosted_pinned(&env), 0, "{env}"); - let [detail] = skipped.as_slice() else { - panic!("one platform skip: {env}"); + // A platform the list leaves out is still being built: the + // gem waits for a later run, and nothing is warned about. + assert!(skipped.is_empty(), "{env}"); + let waiting: Vec<&str> = env["events"] + .as_array() + .unwrap() + .iter() + .filter(|event| event["errorCode"] == "redirect_gem_build_pending") + .filter_map(|event| event["reason"].as_str()) + .collect(); + let [detail] = waiting.as_slice() else { + panic!("one quiet skip: {env}"); }; assert!( detail.contains(&format!( - "the patch registry does not list `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})` \ - among the platform gems of this version" + "the patch registry does not list {OTHER_PLATFORM} yet" )), "{detail}" ); @@ -3310,17 +3319,21 @@ async fn refused_platform_gem_is_counted_as_left_to_patch() { &[], ); assert_eq!(code, 0, "{mode}\nstdout:\n{stdout}\nstderr:\n{stderr}"); - // The premise: the run refused the gem for a platform the patch - // registry does not serve. - let refusal = match mode { - "hosted" => { - format!("the patch registry does not list `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})`") - } - _ => format!("the patch service has no prebuilt platform gem of `{DEP}`"), + // The premise: the run left the gem alone for a platform the + // patch registry does not serve. + let (refusal, said) = match mode { + "hosted" => ( + format!("the patch registry does not list {OTHER_PLATFORM} yet"), + &stdout, + ), + _ => ( + format!("the patch service has no prebuilt platform gem of `{DEP}`"), + &stderr, + ), }; assert!( - stderr.contains(&refusal), - "{mode}: the run refuses the gem\nstdout:\n{stdout}\nstderr:\n{stderr}" + said.contains(&refusal), + "{mode}: the run leaves the gem alone\nstdout:\n{stdout}\nstderr:\n{stderr}" ); assert_eq!( std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index fb137ea93f..c5f93481e0 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -1260,10 +1260,7 @@ impl ApiClient { let path = self.patches_path("package"); let mut results = std::collections::HashMap::new(); for chunk in uuids.chunks(MAX_REFERENCE_BATCH) { - let body = PackageVendorRequest { - uuids: chunk.to_vec(), - free_only: None, - }; + let body = PackageVendorRequest::new(chunk, false); let resp = self .post_json::(&path, &body) .await?; @@ -1976,12 +1973,7 @@ impl ApiClient { free_only: bool, vendor_url: Option<&str>, ) -> Result, VendorAttemptError> { - let body = PackageVendorRequest { - uuids: uuids.to_vec(), - // Only send freeOnly when forcing it (the public-proxy contract); - // the authenticated endpoint defaults to false. - free_only: free_only.then_some(true), - }; + let body = PackageVendorRequest::new(uuids, free_only); let (url, use_auth) = self.vendor_package_url(vendor_url); debug_log(&format!("POST {url}")); @@ -5041,7 +5033,9 @@ mod vendor_package_tests { let serve_url = format!("{}{SERVE_PATH}", server.uri()); Mock::given(method("POST")) .and(path("/v0/orgs/acme/patches/package")) - .and(body_partial_json(json!({ "uuids": [UUID] }))) + .and(body_partial_json( + json!({ "uuids": [UUID], "gemBuilds": true }), + )) .respond_with( ResponseTemplate::new(200) .set_body_json(granted_body(&serve_url, "sha512-ABC123==")), @@ -5078,7 +5072,7 @@ mod vendor_package_tests { .and(path("/patch/package")) .and(NoAuthorizationHeader) .and(body_partial_json( - json!({ "uuids": [UUID], "freeOnly": true }), + json!({ "uuids": [UUID], "freeOnly": true, "gemBuilds": true }), )) .respond_with( ResponseTemplate::new(200).set_body_json(granted_body(&serve_url, "sha512-ZZ==")), @@ -5349,7 +5343,12 @@ mod vendor_package_tests { .and(path("/patch/package")) .and(NoAuthorizationHeader) .and(BodyLacksFreeOnlyKey) - .and(body_partial_json(json!({ "uuids": [UUID] }))) + // Every reference request asks for the complete list of a + // gem's builds: the service answers one without the flag as + // a release that knows no such list expects. + .and(body_partial_json( + json!({ "uuids": [UUID], "gemBuilds": true }), + )) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "results": { UUID: { "status": "granted", "url": null, "artifacts": [] } } }))) diff --git a/crates/socket-patch-core/src/api/types.rs b/crates/socket-patch-core/src/api/types.rs index 6a5a5289e8..b6462a5d80 100644 --- a/crates/socket-patch-core/src/api/types.rs +++ b/crates/socket-patch-core/src/api/types.rs @@ -272,6 +272,25 @@ pub(crate) struct PackageVendorRequest { pub uuids: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub free_only: Option, + /// Asks for a gem patch's registry as the complete list of the + /// version's gems (`registryOverride.identifiers.gemBuilds`, under a + /// snapshot URL). The service answers a request without it as it + /// always has, with the ruby gem's registry alone, so every reference + /// request of this CLI carries it: [`Self::new`]. + pub gem_builds: bool, +} + +impl PackageVendorRequest { + /// The request for `uuids`, with `freeOnly` only when it is forced + /// (the public-proxy contract; the authenticated endpoint defaults to + /// false). + pub(crate) fn new(uuids: &[String], free_only: bool) -> Self { + PackageVendorRequest { + uuids: uuids.to_vec(), + free_only: free_only.then_some(true), + gem_builds: true, + } + } } /// Response from the package-vendor endpoint: one result per requested UUID, diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index 7f2bf69bbb..cc7a6f2d20 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -155,25 +155,50 @@ pub fn gem_upstream_build_kept_detail(platform: &str) -> String { format!("the patch registry serves upstream's own gem for {platform}: no patched build yet") } -/// The skips of the gems a rewrite left on their upstream registry because -/// no locked build of them is patched yet -/// ([`RewriteResult::gem_unpatched`]), one per candidate, in candidate -/// order: a host adds them to its skips, so the gem is reported under -/// [`GEM_NO_PATCHED_BUILD`] and not as a patch nothing pins. +/// Skip reason of a gem the Bundler lock names as precompiled platform +/// builds, left as it is because the patch registry does not list a +/// platform the lock names: the patch service leaves a platform out while +/// its patched build is being made. Not a warning. The gem moves on a +/// later run, once the list has that platform. +pub const GEM_BUILD_PENDING: &str = "redirect_gem_build_pending"; + +/// Whether `reason` is one of the two quiet skips of a gem locked as +/// platform builds ([`GEM_NO_PATCHED_BUILD`], [`GEM_BUILD_PENDING`]): the +/// only cases where a gem with a fix is not moved, both of which pass by +/// themselves and are said in one plain line, never as a failure. +pub fn is_quiet_gem_skip(reason: &str) -> bool { + reason == GEM_NO_PATCHED_BUILD || reason == GEM_BUILD_PENDING +} + +/// The skips of the gems a rewrite left where they are for now: no locked +/// build of them is patched yet ([`RewriteResult::gem_unpatched`]), or +/// the registry does not list a locked platform yet +/// ([`RewriteResult::gem_unlisted`]). One per candidate, in candidate +/// order: a host adds them to its skips, so the gem is reported under its +/// own quiet code and not as a patch nothing pins. pub fn gem_unpatched_skips(candidates: &[Candidate], rewrite: &RewriteResult) -> Vec { candidates .iter() .filter_map(|c| { - let platforms = rewrite.gem_unpatched.get(&c.dep.patch_uuid)?; - let detail = format!( - "{} {}: no patched build yet for {}; left on its upstream registry", - c.dep.name, - c.dep.version, - platforms.join(", ") - ); + let (name, version, uuid) = (&c.dep.name, &c.dep.version, &c.dep.patch_uuid); + let (reason, detail) = if let Some(platforms) = rewrite.gem_unlisted.get(uuid) { + let detail = format!( + "{name} {version}: the patch registry does not list {} yet (a patched build \ + is still being made); left as it is until it does", + platforms.join(", ") + ); + (GEM_BUILD_PENDING, detail) + } else { + let platforms = rewrite.gem_unpatched.get(uuid)?; + let detail = format!( + "{name} {version}: no patched build yet for {}; left on its upstream registry", + platforms.join(", ") + ); + (GEM_NO_PATCHED_BUILD, detail) + }; Some(SkippedPatch { detail: Some(detail), - ..SkippedPatch::new(&c.purl, &c.dep.patch_uuid, GEM_NO_PATCHED_BUILD) + ..SkippedPatch::new(&c.purl, uuid, reason) }) }) .collect() @@ -13187,6 +13212,31 @@ snapshots: unconfirmed_candidates(std::slice::from_ref(&none), &left.confirmed, &[skip]) .is_empty() ); + + // A locked platform the list leaves out (its build is being made): + // the gem waits, under the other quiet code. + let mut pending = candidate.clone(); + let ids = &mut pending.dep.registry_override.as_mut().unwrap().identifiers; + ids.gem_builds.as_mut().unwrap().pop(); + let (_, waits) = gem_rewrite_of(&ProjectView::Memory(&fresh), vec![pending.clone()]).await; + assert!(waits.rewrite.files.is_empty() && waits.confirmed.is_empty()); + assert!( + waits.rewrite.warnings.is_empty(), + "{:?}", + waits.rewrite.warnings + ); + let [skip] = gem_unpatched_skips(std::slice::from_ref(&pending), &waits.rewrite) + .try_into() + .expect("one skip"); + assert_eq!(skip.reason, GEM_BUILD_PENDING); + assert!(is_quiet_gem_skip(&skip.reason) && !is_quiet_gem_skip("redirect_unconfirmed")); + assert_eq!( + skip.detail.as_deref(), + Some( + "rails 7.0.0: the patch registry does not list x86_64-linux-gnu yet (a patched \ + build is still being made); left as it is until it does" + ) + ); } /// #390: `bundle config set --local gemfile Gemfile.next` makes bundler diff --git a/crates/socket-patch-core/src/patch/redirect/grant.rs b/crates/socket-patch-core/src/patch/redirect/grant.rs index b87f760c2d..5eb4ea1b0b 100644 --- a/crates/socket-patch-core/src/patch/redirect/grant.rs +++ b/crates/socket-patch-core/src/patch/redirect/grant.rs @@ -278,7 +278,6 @@ fn check_registry_override(ov: &RegistryOverride, origins: &[String]) -> Result< if !is_plain_gem_token(platform) || platform.len() > MAX_COORDINATE || !platform.starts_with(|c: char| c.is_ascii_alphabetic()) - || platform == "ruby" { return Err(bad("gem platform", "a plain platform name")); } @@ -618,7 +617,7 @@ mod tests { None, vec![("x86_64-linux-gnu", sha.clone()), ("java", sha.clone())], ), - (Some("gem platform "), vec![("ruby", sha.clone())]), + (None, vec![("ruby", sha.clone())]), ( Some("gem platform "), vec![("arm64-darwin)\n evil (1.0", sha.clone())], diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 4c263ff557..c05695483c 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -202,15 +202,17 @@ pub struct RegistryOverrideIdentifiers { /// sha256 hex of the patched ruby-platform gem (`-.gem`), /// the value Bundler records in the lock's `CHECKSUMS`. pub gem_checksum_sha256: Option, - /// Every platform gem of the gem's version, as the patch registry - /// serves it under `index_url`: a patched build where one exists - /// (`patch_uuid`), else upstream's own gem, which the registry lists - /// and hands on unchanged. The list is complete, so a lock's platform - /// entries can all take the registry as their one source, each pinned - /// to the sha256 listed for it. `None` when the reference carries no - /// list (the service does not know the version's platforms): the patch - /// is then of the ruby gem alone, and a lock that names platform - /// builds is left as it is. + /// Every gem of the gem's version, as the patch registry serves it + /// under `index_url`: the ruby gem (`platform: "ruby"`, the patch + /// itself) and each platform gem, as a patched build where one exists + /// (`patch_uuid`), else as upstream's own gem, which the registry + /// lists and hands on unchanged. So a lock's entries can all take the + /// registry as their one source, each pinned to the sha256 listed for + /// it. A platform whose patched build is still being made is left out + /// until it is there. `None` when the reference carries no list (the + /// service does not know the version's platforms, or the gem has no + /// platform gem): the patch is then of the ruby gem alone, and a lock + /// that names platform builds is left as it is. #[serde(default, deserialize_with = "lenient_gem_builds")] #[cfg_attr(test, serde(skip_serializing_if = "Option::is_none"))] pub gem_builds: Option>, @@ -255,7 +257,7 @@ where #[cfg_attr(test, serde(rename_all = "camelCase"))] pub struct GemLockedBuild { /// The build's platform as the lock spells it; `None` for the - /// ruby-platform gem. + /// ruby-platform gem (which the list names `ruby`). pub platform: Option, /// The patch of the build the registry serves: the gem's own patch for /// the ruby-platform gem, the platform's for a patched platform gem. @@ -275,7 +277,8 @@ pub struct GemLockedBuild { #[serde(rename_all = "camelCase")] pub struct GemPlatformChecksum { /// `Gem::Platform#to_s` as the gem's file name and `Gemfile.lock` spell - /// it (`x86_64-linux-gnu`, `arm64-darwin`, `java`). Never `ruby`. + /// it (`x86_64-linux-gnu`, `arm64-darwin`, `java`), or `ruby` for the + /// ruby-platform gem. pub platform: String, /// sha256 hex of the `.gem` the registry serves for that platform. pub gem_checksum_sha256: String, @@ -502,6 +505,17 @@ pub struct RewriteResult { serde(skip_serializing_if = "std::collections::BTreeMap::is_empty") )] pub gem_unpatched: BTreeMap>, + /// gem: the gems the lock names as platform builds that were left as + /// they are because the patch registry does not list a platform the + /// lock names, by the gem patch's uuid, with those platforms. The + /// patch service leaves a platform out while its patched build is + /// being made, so this passes by itself: a later run moves the gem. + /// Serialized only when non-empty. + #[cfg_attr( + test, + serde(skip_serializing_if = "std::collections::BTreeMap::is_empty") + )] + pub gem_unlisted: BTreeMap>, /// Patch uuid → the yarn.lock keys of the `npm:` alias entries of its /// package the rewriter left untouched (`redirect_yarn_classic_alias_skipped`, /// `redirect_yarn_berry_alias_skipped`): that copy keeps installing the @@ -1050,6 +1064,7 @@ fn merge_group_delta(result: &mut RewriteResult, delta: RewriteResult) { confirmed_bazel_maven_uuids, gem_builds, gem_unpatched, + gem_unlisted, } = delta; result.files.extend(files); result.binary_files.extend(binary_files); @@ -1099,6 +1114,7 @@ fn merge_group_delta(result: &mut RewriteResult, delta: RewriteResult) { result.bundled_skipped_uuids.extend(bundled_skipped_uuids); result.gem_builds.extend(gem_builds); result.gem_unpatched.extend(gem_unpatched); + result.gem_unlisted.extend(gem_unlisted); for (uuid, keys) in alias_skipped_entries { result .alias_skipped_entries @@ -8153,11 +8169,12 @@ pub fn grant_token_path_segment(url: &str, patch_uuid: &str) -> Option { /// level, so the idempotency guard never silently degrades into the /// nesting-corruption failure mode when a caller forgets the token. /// -/// A gem registry's URL may end in a snapshot level (`…//s/`: the -/// registry as it stood when the reference was made, which a later -/// reference replaces with a newer one). That level rotates too, and comes -/// and goes with the patch service knowing the version's platform gems, so -/// the pattern takes the URL with any snapshot or none. +/// A gem registry's URL may end in a snapshot level (`…//s/`: +/// the registry as it stood when the reference was made, which a later +/// reference replaces with another once what it lists changes). That level +/// rotates too, and comes and goes with the patch service knowing the +/// version's platform gems, so the pattern takes the URL with any snapshot +/// or none. pub(crate) fn gem_index_url_pattern(dep: &DepOverride, index_url: &str) -> String { let (root, _) = split_gem_snapshot(index_url); let mut url_pat = regex::escape(root); @@ -8174,26 +8191,30 @@ pub(crate) fn gem_index_url_pattern(dep: &DepOverride, index_url: &str) -> Strin } // `root` ends in `/` whenever the URL had a snapshot level. let level = if root.ends_with('/') { "" } else { "/" }; - format!("{url_pat}(?:{level}s/[0-9]+/?)?") + format!("{url_pat}(?:{level}s/[0-9a-f]+/?)?") } -/// A gem registry URL without its snapshot level, and that level's number: -/// `…//s/[/]` is `(…//, Some(n))`; a URL with none is itself -/// and `None`. The snapshot is a positive integer written in plain digits. -pub(crate) fn split_gem_snapshot(index_url: &str) -> (&str, Option) { +/// A gem registry URL without its snapshot level, and that level's key: +/// `…//s/[/]` is `(…//, Some(key))`; a URL with none is +/// itself and `None`. The key is the patch service's to choose (a short +/// string of lowercase hex digits): it is never read for a meaning, only +/// recognised, so that a URL with another key is known as the same +/// registry at another moment. +pub(crate) fn split_gem_snapshot(index_url: &str) -> (&str, Option<&str>) { let trimmed = index_url.trim_end_matches('/'); - let Some((before, number)) = trimmed.rsplit_once('/') else { + let Some((before, key)) = trimmed.rsplit_once('/') else { return (index_url, None); }; - let plain = !number.is_empty() - && number.len() <= 18 - && number.bytes().all(|b| b.is_ascii_digit()) - && !number.starts_with('0'); - match (before.strip_suffix("/s"), plain) { + let hex = !key.is_empty() + && key.len() <= 64 + && key + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); + match (before.strip_suffix("/s"), hex) { (Some(root), true) => { // Keep the slash that closes the patch uuid's level. let root = &index_url[..root.len() + 1]; - (root, number.parse().ok()) + (root, Some(key)) } _ => (index_url, None), } @@ -9097,10 +9118,13 @@ fn rewrite_gem( _ => ov.index_url.as_str().into(), }; let index_url: &str = &index_url; - let sha256 = ov - .identifiers - .gem_checksum_sha256 - .clone() + // The ruby gem's sha256: the entry the list of the version's gems + // has for it (`ruby`), else the reference's own checksum, which is + // the same archive's. + let ruby_listed = ov.identifiers.gem_build("ruby"); + let sha256 = ruby_listed + .map(|build| build.gem_checksum_sha256.clone()) + .or_else(|| ov.identifiers.gem_checksum_sha256.clone()) .or_else(|| dep.integrity.sha256.clone()); // A lock that names only platform builds pins no ruby-platform gem: // its prebuilds' sha256 (checked below) are all the redirect needs. @@ -9166,8 +9190,10 @@ fn rewrite_gem( // unchanged) where there is none yet. So every locked build moves // to it together, each pinned to the sha256 the registry serves // for it, as soon as one of them is patched. A platform the - // registry does not list would send that platform's machines to a - // registry with no gem for them: the dep is skipped entirely. + // registry does not list (its patched build is still being made) + // would send that platform's machines to a registry with no gem + // for them: the gem is left as it is until a later reference + // lists it. if let Some(parsed) = &handed_in { let builds = parsed.locked_builds(&dep.name, &dep.version); if !builds.platforms.is_empty() { @@ -9183,26 +9209,19 @@ fn rewrite_gem( }; let unlisted: Vec = platform_builds() .filter(|id| listed(id).is_none()) - .map(entry) + .filter_map(|id| id.platform.clone()) .collect(); // Bundler < 2.2 lists every source in one GEM section, where // only a ruby-platform entry has been proven to converge. let merged = matches!(layout, Some(LockLayout::Merged(_))); - if !unlisted.is_empty() || merged { - let why = if ov.identifiers.gem_builds.is_none() { + let no_list = ov.identifiers.gem_builds.is_none(); + if no_list || merged { + let why = if no_list { "the patch covers the ruby platform gem only (the patch registry does \ not list the platform gems of this version)" - .to_string() - } else if !unlisted.is_empty() { - format!( - "the patch registry does not list {} among the platform gems of \ - this version", - unlisted.join(", ") - ) } else { "its bundler (< 2.2) lists every gem source in one GEM section, where \ socket-patch redirects only a ruby platform gem" - .to_string() }; result.warnings.push(RewriteWarning { code: "redirect_gem_platform_unsupported".into(), @@ -9216,6 +9235,14 @@ fn rewrite_gem( }); continue; } + // A locked platform the list leaves out: its patched build + // is still being made, and the patch service names it only + // once it is there. Nothing to warn about; a later run + // moves the gem. + if !unlisted.is_empty() { + result.gem_unlisted.insert(dep.patch_uuid.clone(), unlisted); + continue; + } // Whether the lock already takes the gem from this patch's // registry (under any grant token and snapshot). let hosted = gem_lock_on_registry(parsed, dep, index_url); @@ -23406,44 +23433,102 @@ mod tests { assert!(again.files.is_empty() && again.edits.is_empty()); } - /// A locked platform the patch registry does not list keeps the whole - /// gem where it is: a machine of that platform would be sent to a - /// registry that has no gem for it. So does a patch whose reference - /// carries no list at all (a patch of the ruby gem alone). The warning - /// names the builds and which of the two it is. + /// A patch whose reference carries no list of the version's gems is a + /// patch of the ruby gem alone: a lock that names platform builds is + /// left as it is, and the warning says so. #[test] - fn gem_platform_the_registry_does_not_list_skips_the_gem_and_names_it() { + fn gem_platforms_with_no_list_skip_the_gem_and_say_why() { let lock = nokogiri_lock(&["arm64-darwin", "x86_64-linux-gnu"], false, true); - let arm = "a".repeat(64); - for (dep, why) in [ - ( - gem_override_prebuilt("nokogiri", "1.18.10", &[("arm64-darwin", &arm)]), - "the patch registry does not list `nokogiri (1.18.10-x86_64-linux-gnu)` among \ - the platform gems of this version; redirect skipped", - ), - ( - gem_override("nokogiri", "1.18.10"), + let dep = gem_override("nokogiri", "1.18.10"); + let (gemfile, after, r) = gem_redirect(NOKOGIRI_GEMFILE, &lock, dep); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.edits); + assert_eq!( + (gemfile.as_str(), after.as_str()), + (NOKOGIRI_GEMFILE, lock.as_str()) + ); + let [warning] = r.warnings.as_slice() else { + panic!("one warning: {:?}", r.warnings); + }; + assert_eq!(warning.code, "redirect_gem_platform_unsupported"); + assert!( + warning.detail.ends_with( "the patch covers the ruby platform gem only (the patch registry does not list \ - the platform gems of this version); redirect skipped", + the platform gems of this version); redirect skipped" ), - ] { - let (gemfile, after, r) = gem_redirect(NOKOGIRI_GEMFILE, &lock, dep); - assert!( - r.files.is_empty() && r.edits.is_empty(), - "nothing is written: {:?}", - r.edits - ); - assert_eq!( - (gemfile.as_str(), after.as_str()), - (NOKOGIRI_GEMFILE, lock.as_str()) - ); - let [warning] = r.warnings.as_slice() else { - panic!("one warning: {:?}", r.warnings); - }; - assert_eq!(warning.code, "redirect_gem_platform_unsupported"); - assert!(warning.detail.ends_with(why), "{}", warning.detail); - assert!(r.gem_builds.is_empty() && r.gem_unpatched.is_empty()); - } + "{}", + warning.detail + ); + assert!(r.gem_builds.is_empty() && r.gem_unpatched.is_empty() && r.gem_unlisted.is_empty()); + } + + /// A locked platform the list leaves out (its patched build is still + /// being made) keeps the whole gem where it is: a machine of that + /// platform would be sent to a registry that has no gem for it. Not a + /// warning: the result names the platform that is waited for, and a + /// run over a list that has it moves the gem. + #[test] + fn gem_platform_missing_from_the_list_leaves_the_gem_for_a_later_run() { + let lock = nokogiri_lock(&["arm64-darwin", "x86_64-linux-gnu"], false, true); + let (arm, linux) = ("a".repeat(64), "b".repeat(64)); + let dep = gem_override_prebuilt("nokogiri", "1.18.10", &[("arm64-darwin", &arm)]); + let (gemfile, after, r) = gem_redirect(NOKOGIRI_GEMFILE, &lock, dep); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.edits); + assert_eq!( + (gemfile.as_str(), after.as_str()), + (NOKOGIRI_GEMFILE, lock.as_str()) + ); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert_eq!( + r.gem_unlisted.get("uuid").map(Vec::as_slice), + Some(&["x86_64-linux-gnu".to_string()][..]) + ); + assert!(r.gem_builds.is_empty() && r.gem_unpatched.is_empty()); + + let dep = gem_override_prebuilt( + "nokogiri", + "1.18.10", + &[("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)], + ); + let (_, _, later) = gem_redirect(NOKOGIRI_GEMFILE, &lock, dep); + assert!(!later.files.is_empty() && later.gem_unlisted.is_empty()); + assert_eq!(builds_of(&later).len(), 2); + } + + /// The list names the ruby gem too (`platform: "ruby"`, the patch + /// itself), so a lock with the plain entry beside its platform builds + /// reads every pin from the one list. + #[test] + fn gem_ruby_entry_is_pinned_from_the_list() { + let (ruby, arm) = ("e".repeat(64), "a".repeat(64)); + let mut dep = gem_override_listing( + "nokogiri", + "1.18.10", + &[("arm64-darwin", &arm, true), ("ruby", &ruby, true)], + ); + let ids = &mut dep.registry_override.as_mut().unwrap().identifiers; + ids.gem_builds.as_mut().unwrap()[1].patch_uuid = Some("uuid".into()); + // The reference's own checksum agrees with the entry; the entry is + // what is read. + ids.gem_checksum_sha256 = None; + let lock = nokogiri_lock(&["arm64-darwin"], true, true); + let (_, moved, r) = gem_redirect(NOKOGIRI_GEMFILE, &lock, dep); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!( + moved.contains(&format!(" nokogiri (1.18.10) sha256={ruby}\n")), + "{moved}" + ); + assert!( + moved.contains(&format!(" nokogiri (1.18.10-arm64-darwin) sha256={arm}\n")), + "{moved}" + ); + let arm_patch = build_uuid("arm64-darwin"); + assert_eq!( + builds_of(&r), + [ + (None, Some("uuid"), true), + (Some("arm64-darwin"), Some(arm_patch.as_str()), true), + ] + ); } /// What [`RewriteResult::gem_builds`] says of the one gem: per locked @@ -23558,19 +23643,19 @@ mod tests { ); } - /// [`gem_override_listing`] with its registry at the snapshot `number` - /// (`…/uuid/s/`, as the patch service spells it: no closing + /// [`gem_override_listing`] with its registry at the snapshot `key` + /// (`…/uuid/s/`, as the patch service spells it: no closing /// slash). - fn gem_override_at_snapshot(number: u32, builds: &[(&str, &str, bool)]) -> DepOverride { + fn gem_override_at_snapshot(key: &str, builds: &[(&str, &str, bool)]) -> DepOverride { let mut dep = gem_override_listing("nokogiri", "1.18.10", builds); let ov = dep.registry_override.as_mut().expect("a gem registry"); - ov.index_url = format!("{GEM_TEST_URL}s/{number}"); + ov.index_url = format!("{GEM_TEST_URL}s/{key}"); dep } /// A registry URL carries the snapshot it was made at. The manifest /// and the lock take it closed by a slash, as Bundler writes a remote. - /// A later reference names a newer snapshot, where a platform that had + /// A later reference names another snapshot, where a platform that had /// upstream's gem has a patched build: the URL is refreshed in place /// (never written twice), the one checksum that changed is rewritten, /// and the result names the build that is newly patched. The same @@ -23581,7 +23666,7 @@ mod tests { let upstream = upstream_sha("1.18.10-x86_64-linux-gnu"); let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; let first = gem_override_at_snapshot( - 1, + "9f3c01", &[ ("arm64-darwin", &arm, true), ("x86_64-linux-gnu", &upstream, false), @@ -23590,7 +23675,7 @@ mod tests { let lock = nokogiri_lock(&platforms, false, true); let (gemfile, moved, r) = gem_redirect(NOKOGIRI_GEMFILE, &lock, first.clone()); assert!(r.warnings.is_empty(), "{:?}", r.warnings); - let at_one = format!("{GEM_TEST_URL}s/1/"); + let at_one = format!("{GEM_TEST_URL}s/9f3c01/"); assert!( gemfile.contains(&format!("source: \"{at_one}\"")), "{gemfile}" @@ -23604,7 +23689,7 @@ mod tests { ); let second = gem_override_at_snapshot( - 2, + "07ab2e", &[ ("arm64-darwin", &arm, true), ("x86_64-linux-gnu", &linux, true), @@ -23612,7 +23697,7 @@ mod tests { ); let (gemfile_two, lock_two, r) = gem_redirect(&gemfile, &moved, second.clone()); assert!(r.warnings.is_empty(), "{:?}", r.warnings); - let at_two = format!("{GEM_TEST_URL}s/2/"); + let at_two = format!("{GEM_TEST_URL}s/07ab2e/"); assert_eq!(gemfile_two, gemfile.replace(&at_one, &at_two)); assert_eq!( lock_two, @@ -23642,10 +23727,11 @@ mod tests { assert!(builds_of(&again).iter().all(|(_, _, newly)| !newly)); } - /// The snapshot level of a registry URL is read off its end, and the - /// recogniser of a patch's registry URL takes any snapshot or none - /// under any grant token: a pair an earlier run wired is refreshed, - /// whichever form it was written in. + /// The snapshot level of a registry URL is read off its end (an + /// opaque key of lowercase hex digits), and the recogniser of a + /// patch's registry URL takes any snapshot or none under any grant + /// token: a pair an earlier run wired is refreshed, whichever form it + /// was written in. #[test] fn gem_registry_url_is_recognised_with_any_snapshot_or_none() { let plain = "https://patch.test/gem/tok/uuid/"; @@ -23654,21 +23740,24 @@ mod tests { split_gem_snapshot("https://patch.test/gem/tok/uuid"), ("https://patch.test/gem/tok/uuid", None) ); - for snapshot in [ - "https://patch.test/gem/tok/uuid/s/12", - "https://patch.test/gem/tok/uuid/s/12/", + for (snapshot, key) in [ + ("https://patch.test/gem/tok/uuid/s/12", "12"), + ("https://patch.test/gem/tok/uuid/s/12/", "12"), + ("https://patch.test/gem/tok/uuid/s/07ab2e9f", "07ab2e9f"), ] { assert_eq!( split_gem_snapshot(snapshot), - (plain, Some(12)), + (plain, Some(key)), "{snapshot}" ); } - // Not a snapshot level: no number, a leading zero, another name. + // Not a snapshot level: no key, a key that is not lowercase hex, + // another level name. for other in [ "https://patch.test/gem/tok/uuid/s/", - "https://patch.test/gem/tok/uuid/s/012", - "https://patch.test/gem/tok/uuid/s/1a", + "https://patch.test/gem/tok/uuid/s/1G", + "https://patch.test/gem/tok/uuid/s/AB12", + "https://patch.test/gem/tok/uuid/s/a-1", "https://patch.test/gem/tok/uuid/t/3", ] { assert_eq!(split_gem_snapshot(other).1, None, "{other}"); @@ -23677,7 +23766,7 @@ mod tests { for index_url in [ plain, "https://patch.test/gem/tok/uuid/s/3", - "https://patch.test/gem/tok/uuid/s/3/", + "https://patch.test/gem/tok/uuid/s/9f3c01/", ] { let registry = Regex::new(&format!("^{}$", gem_index_url_pattern(&dep, index_url))) .expect("a pattern"); @@ -23686,7 +23775,7 @@ mod tests { "https://patch.test/gem/an-older-grant/uuid/", "https://patch.test/gem/tok/uuid/s/3", "https://patch.test/gem/tok/uuid/s/3/", - "https://patch.test/gem/another-grant/uuid/s/41/", + "https://patch.test/gem/another-grant/uuid/s/07ab2e/", ] { assert!(registry.is_match(ours), "{index_url} takes {ours}"); } @@ -23694,6 +23783,7 @@ mod tests { "https://rubygems.org/", "https://patch.test/gem/tok/uuid/s/", "https://patch.test/gem/tok/uuid/s/3/x", + "https://patch.test/gem/tok/uuid/s/3G/", "https://patch.test/gem/tok/uuid/info/nokogiri", "https://evil.test/gem/tok/uuid/s/3/", ] { diff --git a/crates/socket-patch-core/src/vex/discover/gem.rs b/crates/socket-patch-core/src/vex/discover/gem.rs index 46efe24dd6..677327957d 100644 --- a/crates/socket-patch-core/src/vex/discover/gem.rs +++ b/crates/socket-patch-core/src/vex/discover/gem.rs @@ -573,7 +573,7 @@ pub(crate) fn gemfile_source_block_pins(gemfile: &str, uuid: &str, gem_name: Opt /// Whether hosted `remote` is the patch's compact-index root: /// `…/patch-registry/gem//[/]`, `uuid` the LAST path level -/// but for a snapshot level (`…//s/[/]`), no query or fragment. +/// but for a snapshot level (`…//s/[/]`), no query or fragment. fn is_patch_registry_index(remote: &str, uuid: &str) -> bool { patch_registry_uuid(remote).is_some_and(|u| u == uuid) } @@ -581,7 +581,7 @@ fn is_patch_registry_index(remote: &str, uuid: &str) -> bool { /// The patch uuid of a compact-index root /// `…/patch-registry/gem//[/]` (no query or fragment): its /// last path level, or the one before a snapshot level -/// (`…//s/[/]`: the registry as it stood when the patch service +/// (`…//s/[/]`: the registry as it stood when the patch service /// made the reference). fn patch_registry_uuid(remote: &str) -> Option { let url = reqwest::Url::parse(remote).ok()?; @@ -1212,7 +1212,7 @@ mod tests { assert!(out.unlocked_pins.is_empty(), "{:#?}", out.unlocked_pins); } - /// A registry URL may end in a snapshot level (`…//s/`): the + /// A registry URL may end in a snapshot level (`…//s/`): the /// patch is still the one its uuid level names. Anything else after /// the uuid is no registry root. #[test] @@ -1223,7 +1223,7 @@ mod tests { root.trim_end_matches('/').to_string(), format!("{root}s/3"), format!("{root}s/3/"), - format!("{root}s/41/"), + format!("{root}s/07ab2e9f/"), ] { assert_eq!( super::patch_registry_uuid(&url).as_deref(), @@ -1234,7 +1234,7 @@ mod tests { } for url in [ format!("{root}s/"), - format!("{root}s/03/"), + format!("{root}s/3G/"), format!("{root}s/3/info/rails"), format!("{root}gems/rails-7.0.0.gem"), format!("{root}s/3?x=1"), From b7a065b3dd454b40fff1ae682780c91d5a7f39dd Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 19:20:30 -0500 Subject: [PATCH 005/120] Vendor each platform tree of a gem from that platform's own patch A gem the Bundler lock names as precompiled platform gems is vendored as one unpacked patched platform gem per locked platform. Those gems are no artifacts of the gem's patch: each patched platform gem has a patch of its own, and the gem patch's package reference lists every platform gem of the version (`registryOverride.identifiers.gemBuilds`), with the sha256 its registry serves and, where there is a patched build, the patch it comes from. The per-platform artifact kinds `gem-platform` and `gem-platform-stub-gemspec`, and the `platform` field of an artifact, are not served, so they are no longer read. Vendoring such a gem: - asks for the gem patch's reference once, to learn the patch of each locked platform's build, and for the references of those patches in ONE request (`ApiClient::fetch_vendor_references`); - downloads each platform's gem (its patch's `tarball`) and stub gemspec (`gem-stub-gemspec`), a few at a time, and verifies each against the digest its own reference states and the gem also against the sha256 the gem patch's registry lists for that platform. A mismatch refuses with `vendor_prebuilt_integrity_mismatch`, names the platform, and leaves an existing copy as it was; - keeps verifying the trees against the gem patch's record for the patched files they ship. No record of a platform's patch is fetched; - records per tree which patch it came from and the digests its downloads passed (`VendorEntry::gem_builds`, `gemBuilds` in the ledger). A restore fetches each tree again by its recorded patch, in one reference request, and checks the downloads against the recorded digests. While a locked platform has no patched build (the registry serves upstream's own gem for it, does not list it, or the reference carries no list) the gem is not vendored: nothing is downloaded or written, and the skip (`vendor_prebuilt_platform_pending`, as before) is one line that names the platforms. A gem already vendored stays in force as it is when the lock gains such a platform; a copy that is damaged and cannot be rebuilt is still the `vendor_prebuilt_required` failure. An entry that names only the platforms of its copy (`gemPlatforms`, written by builds before this one) still reads, verifies and reverts. It is no longer written: the next vendor run rebuilds the copy from each platform's patch and records them. A restore of such an entry says to vendor again, since nothing names a patch to fetch its trees by. `gems_locked_as_platform_gems` tells a caller which gems the lock resolves that way. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/api/client.rs | 300 +++- crates/socket-patch-core/src/api/types.rs | 97 +- crates/socket-patch-core/src/vendor/gem.rs | 1569 +++++++++++++---- crates/socket-patch-core/src/vendor/mod.rs | 19 +- .../src/vendor/redownload.rs | 27 +- .../src/vendor/service_fetch.rs | 107 +- crates/socket-patch-core/src/vendor/state.rs | 159 +- crates/socket-patch-core/src/vendor/verify.rs | 8 +- 8 files changed, 1771 insertions(+), 515 deletions(-) diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index c5f93481e0..3d56a9d419 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -1680,19 +1680,19 @@ impl ApiClient { } /// Step 1 of [`Self::fetch_vendor_package`] on its own: what the - /// service lists for the patch besides its archive (the per-platform - /// gem prebuilds and their stub gemspecs), each with its host-rewritten - /// URL and sha512, and NO archive download. A backend that takes only - /// those artifacts learns here which exist. Same grant, statuses, retry - /// ladder and circuit breaker as the full fetch; a uuid the attached - /// plan names is answered from its reference batch. + /// service's package reference says of the patch (its artifacts, each + /// with its host-rewritten URL and sha512, and the platform gems its + /// registry lists), with NO download. A backend that downloads the + /// artifacts itself learns here which exist. Same grant, statuses, + /// retry ladder and circuit breaker as the full fetch; a uuid the + /// attached plan names is answered from its reference batch. pub(crate) async fn fetch_vendor_reference( &self, uuid: &str, free_only: bool, vendor_url: Option<&str>, patch_server_url: Option<&str>, - ) -> VendorServiceOutcome> { + ) -> VendorServiceOutcome { if let Some(refused) = self.vendor_request_refused(uuid) { return VendorServiceOutcome::Failed(refused); } @@ -1700,21 +1700,58 @@ impl ApiClient { .request_vendor_package(uuid, free_only, vendor_url) .await { - Ok(result) => ( - reference_miss(&result.status).unwrap_or_else(|| { - VendorServiceOutcome::Ready(served_secondary_artifacts( - &result, - patch_server_url, - )) - }), - false, - ), + Ok(result) => (vendor_reference(&result, patch_server_url), false), Err((e, retryable)) => (VendorServiceOutcome::Failed(e), retryable), }; self.note_vendor_outcome(&outcome, retryable_failure); outcome } + /// [`Self::fetch_vendor_reference`] for several patches in ONE request + /// (per [`MAX_REFERENCE_BATCH`] uuids): the outcome of each of `uuids`, + /// in their order. `Err` when no answer was had at all (a refused or + /// failed request), which the circuit breaker counts once. + pub(crate) async fn fetch_vendor_references( + &self, + uuids: &[String], + free_only: bool, + vendor_url: Option<&str>, + patch_server_url: Option<&str>, + ) -> Result>, ApiError> { + if let Some(refused) = uuids + .iter() + .find_map(|uuid| self.vendor_request_refused(uuid)) + { + return Err(refused); + } + let mut results = std::collections::HashMap::new(); + for chunk in uuids.chunks(MAX_REFERENCE_BATCH) { + match self + .request_vendor_references(chunk, free_only, vendor_url) + .await + { + Ok(answered) => results.extend(answered), + // As `note_vendor_outcome` counts one failed request. + Err((e, retryable)) => { + if retryable { + self.vendor_outage.fetch_add(1, Ordering::Relaxed); + } + return Err(e); + } + } + } + self.vendor_outage.store(0, Ordering::Relaxed); + Ok(uuids + .iter() + .map(|uuid| match results.get(uuid) { + Some(result) => vendor_reference(result, patch_server_url), + None => VendorServiceOutcome::Failed(ApiError::Other(format!( + "package response missing a result for {uuid}" + ))), + }) + .collect()) + } + /// Attach a download plan: `uuids` are the packages the vendor loop is /// expected to download from the service, in loop order, with these /// request parameters. Until the guard drops, the loop's @@ -2397,14 +2434,11 @@ pub(crate) struct FetchedVendorPackage { pub prestaged: crate::vendor::prestage::Prestaged, } -/// A non-tarball served artifact reference (e.g. `gem-stub-gemspec`): its kind, -/// final download URL, and sha512 SRI. Bytes are fetched + verified on demand. +/// A served artifact reference (e.g. `gem-stub-gemspec`): its kind, final +/// download URL, and sha512 SRI. Bytes are fetched + verified on demand. #[derive(Debug, Clone)] pub(crate) struct SecondaryArtifact { pub kind: String, - /// The gem platform a `gem-platform` / `gem-platform-stub-gemspec` - /// artifact is for; `None` on every other kind. - pub platform: Option, pub url: String, /// Normalized `sha512-` of the artifact bytes. pub integrity_sri: String, @@ -2469,8 +2503,23 @@ impl std::fmt::Debug for PrefetchedSecondary { } } -/// Outcome of [`ApiClient::fetch_vendor_package`], and, with the served -/// artifact list in place of the archive, of +/// What a granted package reference says of its patch, with nothing +/// downloaded ([`ApiClient::fetch_vendor_reference`]). +#[derive(Debug)] +pub(crate) struct VendorReference { + /// The archive (`kind: "tarball"`), when the reference gives it a url + /// and a sha512. + pub archive: Option, + /// The other served artifacts (see [`served_secondary_artifacts`]). + pub secondary: Vec, + /// gem: the platform gems of the gem's version as the patch's registry + /// serves them (`registryOverride.identifiers.gemBuilds`); `None` when + /// the reference carries no list. + pub gem_builds: Option>, +} + +/// Outcome of [`ApiClient::fetch_vendor_package`], and, with the +/// [`VendorReference`] in place of the archive, of /// [`ApiClient::fetch_vendor_reference`]. /// /// The vendor backends map these onto the `auto`/`service`/`build` policy: @@ -2508,21 +2557,55 @@ fn reference_miss(status: &str) -> Option> { } } +/// What `result` settles for [`ApiClient::fetch_vendor_reference`]: the +/// miss its status names, else its [`VendorReference`]. +fn vendor_reference( + result: &PackageVendorResult, + patch_server_url: Option<&str>, +) -> VendorServiceOutcome { + if let Some(miss) = reference_miss(&result.status) { + return miss; + } + let gem_builds = result + .registry_override + .as_ref() + .and_then(|registry| registry.identifiers.gem_builds.clone()); + VendorServiceOutcome::Ready(VendorReference { + archive: served_artifacts(result, patch_server_url, true).pop(), + secondary: served_secondary_artifacts(result, patch_server_url), + gem_builds, + }) +} + /// The served artifacts of a granted reference OTHER than the archive (the -/// gem path-source stub gemspec, the per-platform gem prebuilds, …) — their -/// host-rewritten URL + normalized sha512 — so a backend that needs one can -/// download + verify it lazily. Each is skipped unless it carries both a -/// url and a sha512. +/// gem path-source stub gemspec, …) — their host-rewritten URL + normalized +/// sha512 — so a backend that needs one can download + verify it lazily. +/// Each is skipped unless it carries both a url and a sha512. fn served_secondary_artifacts( result: &PackageVendorResult, patch_server_url: Option<&str>, ) -> Vec { - let mut secondary_artifacts: Vec = Vec::new(); + served_artifacts(result, patch_server_url, false) +} + +/// The served artifacts of a granted reference that carry a url and a +/// sha512, the url host-rewritten: the archive alone (`archive`; its own +/// url, else the reference's top-level one), or every other artifact. +fn served_artifacts( + result: &PackageVendorResult, + patch_server_url: Option<&str>, + archive: bool, +) -> Vec { + let mut served: Vec = Vec::new(); for a in result.artifacts.iter().flatten() { - if a.kind == "tarball" { + if (a.kind == "tarball") != archive { continue; } - let (Some(url), Some(sha512)) = (a.url.as_deref(), a.integrity.sha512.as_deref()) else { + let url = a + .url + .as_deref() + .or(result.url.as_deref().filter(|_| archive)); + let (Some(url), Some(sha512)) = (url, a.integrity.sha512.as_deref()) else { continue; }; let url = match patch_server_url { @@ -2532,15 +2615,17 @@ fn served_secondary_artifacts( }, None => url.to_string(), }; - secondary_artifacts.push(SecondaryArtifact { + served.push(SecondaryArtifact { kind: a.kind.clone(), - platform: a.platform.clone(), url, integrity_sri: normalize_sha512_sri(sha512), prefetched: None, }); + if archive { + break; + } } - secondary_artifacts + served } /// A serve GET's answer short of a failure. @@ -5305,6 +5390,155 @@ mod vendor_package_tests { )); } + // ── fetch_vendor_reference(s) (a gem's platform builds) ──────────── + + /// A gem patch's reference read without a download: its archive and + /// stub as artifacts to fetch later, and the platform gems its + /// registry lists, each with the patch of its patched build. + #[tokio::test] + async fn vendor_reference_reads_the_artifacts_and_the_gem_builds() { + const BUILD: &str = "22222222-2222-4222-8222-222222222222"; + let server = MockServer::start().await; + let gem_url = format!("{}/patch/gem/a.gem", server.uri()); + Mock::given(method("POST")) + .and(path("/v0/orgs/acme/patches/package")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "results": { UUID: { + "status": "granted", + "url": gem_url, + "artifacts": [ + { "kind": "tarball", "integrity": { "sha512": "sha512-GEM==" } }, + { "kind": "gem-stub-gemspec", "url": "https://x/a.gemspec", + "integrity": { "sha512": "STUB==" } }, + { "kind": "gem-stub-gemspec", "url": null, + "integrity": { "sha512": "sha512-NOURL==" } } + ], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://x/patch-registry/gem/t/u/s/2", + "identifiers": { + "name": "a", "version": "1.0.0", + "gemBuilds": [ + { "platform": "arm64-darwin", + "gemChecksumSha256": "ab".repeat(32), "patchUuid": null }, + { "platform": "x86_64-linux-gnu", + "gemChecksumSha256": "cd".repeat(32), "patchUuid": BUILD } + ] + } + } + }} + }))) + .expect(1) + .mount(&server) + .await; + let outcome = auth_client(server.uri()) + .fetch_vendor_reference(UUID, false, None, None) + .await; + let VendorServiceOutcome::Ready(reference) = outcome else { + panic!("expected Ready, got {outcome:?}"); + }; + // The archive takes the reference's top-level url when it has none + // of its own; an artifact with no url is not listed. + let archive = reference.archive.expect("the archive"); + assert_eq!( + (archive.url.as_str(), archive.integrity_sri.as_str()), + (gem_url.as_str(), "sha512-GEM==") + ); + let secondary: Vec<_> = reference + .secondary + .iter() + .map(|a| (a.kind.as_str(), a.url.as_str(), a.integrity_sri.as_str())) + .collect(); + assert_eq!( + secondary, + [("gem-stub-gemspec", "https://x/a.gemspec", "sha512-STUB==")] + ); + let builds: Vec<_> = reference + .gem_builds + .as_deref() + .expect("the list") + .iter() + .map(|b| (b.platform.as_str(), b.patch_uuid.as_deref())) + .collect(); + assert_eq!( + builds, + [("arm64-darwin", None), ("x86_64-linux-gnu", Some(BUILD))] + ); + } + + /// The references of several patches come from ONE request and are + /// answered in the order asked, each by its own status; a uuid the + /// response leaves out is a failure of that uuid alone. A request that + /// fails is `Err`: nothing is known of any of them. A malformed uuid + /// is refused before any request. + #[tokio::test] + async fn vendor_references_are_asked_for_in_one_request() { + const A: &str = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + const B: &str = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + const C: &str = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v0/orgs/acme/patches/package")) + .and(body_partial_json(json!({ "uuids": [B, A, C] }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "results": { + A: { "status": "granted", "url": "https://x/a.gem", + "artifacts": [{ "kind": "tarball", "url": "https://x/a.gem", + "integrity": { "sha512": "sha512-A==" } }] }, + B: { "status": "pending_build", "url": null, "artifacts": [] } + } + }))) + .expect(1) + .mount(&server) + .await; + let client = auth_client(server.uri()); + let uuids = [B.to_string(), A.to_string(), C.to_string()]; + let outcomes = client + .fetch_vendor_references(&uuids, false, None, None) + .await + .expect("one answer for all three"); + assert_eq!(outcomes.len(), 3); + assert!(matches!(outcomes[0], VendorServiceOutcome::Pending)); + match &outcomes[1] { + VendorServiceOutcome::Ready(reference) => { + let archive = reference.archive.as_ref().expect("the archive"); + assert_eq!(archive.url, "https://x/a.gem"); + assert!(reference.gem_builds.is_none()); + } + other => panic!("expected Ready, got {other:?}"), + } + match &outcomes[2] { + VendorServiceOutcome::Failed(ApiError::Other(msg)) => { + assert!(msg.contains(C), "{msg}") + } + other => panic!("expected Failed, got {other:?}"), + } + + let refused = client + .fetch_vendor_references(&[A.to_string(), "not-a-uuid".into()], false, None, None) + .await; + assert!( + matches!(refused, Err(ApiError::InvalidHash(_))), + "{refused:?}" + ); + + let down = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(503)) + .mount(&down) + .await; + let down_client = auth_client(down.uri()).with_vendor_retry(VendorRetryPolicy::none()); + let failed = down_client + .fetch_vendor_references(&uuids, false, None, None) + .await; + assert!(failed.is_err(), "{failed:?}"); + assert_eq!( + down_client.vendor_outage.load(Ordering::Relaxed), + 1, + "the circuit breaker counts the failed request once" + ); + } + // ── fetch_registry_references (hosted-mode scan resolution) ──────── /// `fetch_registry_references` with no UUIDs must return an empty map diff --git a/crates/socket-patch-core/src/api/types.rs b/crates/socket-patch-core/src/api/types.rs index b6462a5d80..16b3edd548 100644 --- a/crates/socket-patch-core/src/api/types.rs +++ b/crates/socket-patch-core/src/api/types.rs @@ -333,26 +333,18 @@ pub struct PackageVendorResult { } /// One served artifact: the native tarball (`kind: "tarball"`), or a -/// second artifact — npm's yarn-berry cache zip (`kind: "yarn-berry-zip"`), -/// gem's path-source stub gemspec (`kind: "gem-stub-gemspec"`), or, per -/// platform a gem patch has a prebuild for, the patched platform gem -/// (`kind: "gem-platform"`) and its stub gemspec -/// (`kind: "gem-platform-stub-gemspec"`). `url` is null only when the -/// artifact isn't stored yet (e.g. an unbuilt berry zip). +/// second artifact — npm's yarn-berry cache zip (`kind: "yarn-berry-zip"`) +/// or gem's path-source stub gemspec (`kind: "gem-stub-gemspec"`). The +/// patch of a platform gem serves the same two as the patch of the ruby +/// gem: the patched platform `.gem` as its `tarball`, and that gem's stub +/// gemspec. `url` is null only when the artifact isn't stored yet (e.g. an +/// unbuilt berry zip). #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PackageVendorArtifact { pub kind: String, #[serde(default)] pub url: Option, - /// The gem platform the artifact is for (`x86_64-linux-gnu`, - /// `arm64-darwin`, `java`: `Gem::Platform#to_s` as `Gemfile.lock` - /// spells it, never `ruby`). Present exactly on the two `gem-platform*` - /// kinds; a patch with no prebuild serves neither. A value that is no - /// string reads as absent instead of failing the whole response: that - /// artifact is then the prebuild of no platform. - #[serde(default, deserialize_with = "lenient_string")] - pub platform: Option, /// Every ecosystem's tarball populates `sha512` (npm SRI form /// `sha512-`) + `sha1` + `md5`; golang additionally `dirhash_h1` /// (`h1:`); the npm yarn-berry zip carries only `yarn_berry10c0` @@ -364,16 +356,6 @@ pub struct PackageVendorArtifact { pub integrity: Integrity, } -/// An optional string field that never fails its response: anything that -/// is no string reads as absent. -fn lenient_string<'de, D>(deserializer: D) -> Result, D::Error> -where - D: serde::Deserializer<'de>, -{ - let value = serde_json::Value::deserialize(deserializer)?; - Ok(value.as_str().map(str::to_string)) -} - #[cfg(test)] mod tests { use super::*; @@ -599,23 +581,24 @@ mod tests { ); } - /// A gem patch with prebuilds serves, beside the ruby gem's `tarball` - /// and stub, one `gem-platform` gem and stub per built platform; the - /// artifacts every patch served before carry no `platform`. + /// The patch of a platform gem serves what the patch of a ruby gem + /// serves: the patched platform `.gem` as its `tarball`, and that gem's + /// stub gemspec. A field this build does not read on an artifact (a + /// `platform`, whatever its type) is ignored and never fails the + /// response. #[test] - fn package_vendor_result_reads_the_gem_platform_artifacts() { + fn package_vendor_result_reads_a_platform_gems_own_artifacts() { let json = r#"{ "status": "granted", - "purl": "pkg:gem/nokogiri@1.18.10?platform=ruby", - "url": "https://patch.example/nokogiri-1.18.10.gem", + "purl": "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + "url": "https://patch.example/nokogiri-1.18.10-x86_64-linux-gnu.gem", "artifacts": [ - { "kind": "tarball", "url": "https://patch.example/nokogiri-1.18.10.gem", - "integrity": { "sha512": "sha512-ruby" } }, - { "kind": "gem-platform", "platform": "x86_64-linux-gnu", + { "kind": "tarball", "url": "https://patch.example/nokogiri-1.18.10-x86_64-linux-gnu.gem", "contentType": "application/octet-stream", "sizeBytes": 4000000, - "integrity": { "sha512": "sha512-prebuild" } }, - { "kind": "gem-platform-stub-gemspec", "platform": "x86_64-linux-gnu", + "platform": 7, + "integrity": { "sha512": "sha512-build" } }, + { "kind": "gem-stub-gemspec", "platform": "x86_64-linux-gnu", "url": "https://patch.example/nokogiri-1.18.10-x86_64-linux-gnu.gemspec", "integrity": { "sha512": "sha512-stub" } } ] @@ -624,20 +607,15 @@ mod tests { let artifacts = result.artifacts.unwrap(); let seen: Vec<(&str, Option<&str>)> = artifacts .iter() - .map(|a| (a.kind.as_str(), a.platform.as_deref())) + .map(|a| (a.kind.as_str(), a.integrity.sha512.as_deref())) .collect(); assert_eq!( seen, [ - ("tarball", None), - ("gem-platform", Some("x86_64-linux-gnu")), - ("gem-platform-stub-gemspec", Some("x86_64-linux-gnu")), + ("tarball", Some("sha512-build")), + ("gem-stub-gemspec", Some("sha512-stub")), ] ); - assert_eq!( - artifacts[1].integrity.sha512.as_deref(), - Some("sha512-prebuild") - ); } #[test] @@ -799,12 +777,7 @@ mod tests { "artifacts": [ { "kind": "tarball", "url": "https://patch.socket.dev/a.gem", "integrity": { "sha256": sha } }, - { "kind": "gem-platform", "platform": "x86_64-linux-gnu", - "url": "https://patch.socket.dev/a-x86_64-linux-gnu.gem", - "contentType": "application/octet-stream", "sizeBytes": 4000000, - "integrity": { "sha256": sha } }, - { "kind": "gem-platform-stub-gemspec", "platform": "x86_64-linux-gnu", - "url": "https://patch.socket.dev/a-x86_64-linux-gnu.gemspec", + { "kind": "gem-stub-gemspec", "url": "https://patch.socket.dev/a.gemspec", "integrity": {} } ], "registryOverride": { @@ -823,19 +796,11 @@ mod tests { } }); let result: PackageVendorResult = serde_json::from_value(json.clone()).unwrap(); + // The platform gems are not artifacts of this reference: each + // patched one is the `tarball` of its own patch. let artifacts = result.artifacts.as_deref().unwrap(); - let platforms: Vec<_> = artifacts - .iter() - .map(|a| (a.kind.as_str(), a.platform.as_deref())) - .collect(); - assert_eq!( - platforms, - [ - ("tarball", None), - ("gem-platform", Some("x86_64-linux-gnu")), - ("gem-platform-stub-gemspec", Some("x86_64-linux-gnu")), - ] - ); + let kinds: Vec<_> = artifacts.iter().map(|a| a.kind.as_str()).collect(); + assert_eq!(kinds, ["tarball", "gem-stub-gemspec"]); let registry = result.registry_override.unwrap(); assert!(registry.index_url.ends_with("/u/s/3")); let ids = registry.identifiers; @@ -900,8 +865,8 @@ mod tests { "artifacts": [ { "kind": "tarball", "url": "https://patch.socket.dev/a.gem", "integrity": { "sha256": sha } }, - { "kind": "gem-platform", "platform": null, "url": null }, - { "kind": "gem-platform", "platform": 7 } + { "kind": "gem-stub-gemspec", "platform": null, "url": null }, + { "kind": "gem-stub-gemspec", "platform": 7 } ], "registryOverride": { "kind": "rubygems-compact-index", @@ -955,6 +920,10 @@ mod tests { "only the entry that names a platform and a checksum is a prebuild" ); let artifacts = response.results["holes"].artifacts.as_deref().unwrap(); - assert!(artifacts.iter().all(|a| a.platform.is_none())); + assert_eq!( + artifacts.len(), + 3, + "an artifact field of any type is read past" + ); } } diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index bf81f0a35a..78819408e8 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -59,12 +59,16 @@ //! (`nokogiri (1.18.10-x86_64-linux-gnu)`, `nokogiri (1.18.10-arm64-darwin)`) //! and usually no plain `nokogiri (1.18.10)`. Such a gem cannot be vendored //! as its ruby-platform tree (the extensions would never be built), so it is -//! vendored as the patch service's PREBUILDS — the patched platform gems — -//! one unpacked tree per locked platform, each with the stub gemspec the -//! service serves for it (verified against real bundler 4.0.15): +//! vendored as the patch service's PATCHED PLATFORM GEMS, one unpacked tree +//! per locked platform, each with the stub gemspec the service serves for +//! it (verified against real bundler 4.0.15). The gem's fix is the patch +//! of its ruby gem (`` below, whatever the platforms); each patched +//! platform gem has a patch of its own, which the fix's package reference +//! names (`gemBuilds[].patchUuid`) and whose `tarball` and stub gemspec +//! the tree is unpacked from: //! //! ```text -//! .socket/vendor/gem//-//… # the unpacked prebuild +//! .socket/vendor/gem//-//… # the unpacked platform gem //! .socket/vendor/gem//-//.gemspec //! //! PATH @@ -88,18 +92,26 @@ //! `.gitignore` (`!*`) and `.gitattributes` every backend that commits //! binaries writes: they re-include the trees and keep a project filter //! (a Git LFS rule, EOL conversion) off their bytes. A `.gitignore` a -//! prebuild ships inside its own tree would override that, so it is +//! platform gem ships inside its own tree would override that, so it is //! emptied in the copy. A tree git would still not commit in full is //! refused: wired without its binary, the gem would install everywhere //! and fail to load; -//! * every locked platform needs a prebuild. While the service lists none -//! for one of them the gem is left as it is and reported as a skip -//! ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]): a prebuild is listed -//! only once built, so the next run may find it. A plain +//! * every locked platform needs a patched build. While the fix's +//! reference names none for one of them (the patch registry serves +//! upstream's own gem for it, does not list it, or lists no platform gem +//! at all) the gem is left as it is and reported as a skip +//! ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]): a build is named only +//! once published, so the next run may find it. A plain //! ` ()` entry beside the platform ones (the ruby platform, //! which no prebuilt tree serves) is refused with nothing written, and so //! is a lock written by a bundler older than the layout was run against -//! (`PLATFORM_LAYOUT_MIN_BUNDLER`). +//! (`PLATFORM_LAYOUT_MIN_BUNDLER`); +//! * the ledger entry records each tree's platform, patch and the digests +//! its downloads were verified against +//! ([`VendorEntry::gem_builds`]), which is what a restore fetches the +//! tree again by. The trees are verified against the FIX's record for +//! the patched files they ship; a platform patch's own record is never +//! read here. use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -115,6 +127,8 @@ use crate::patch::redirect::gem_line_tail_blocks_edit; use crate::utils::fs::{atomic_write_bytes_preserving_mode, read_regular_to_string}; use crate::utils::line_endings::{self, to_lf, LineEndings}; use crate::utils::purl::{build_gem_purl, parse_gem_purl, purl_qualifier}; +use crate::vendor::lock_inventory::LockIntegrity; +use crate::vendor::registry_fetch::artifact_matches_integrity; use super::common::{ already_patched_result, cleanup_failed_stage, copy_matches_after_hashes, done, failed_result, @@ -125,13 +139,14 @@ use super::path::{parse_vendor_path, vendor_uuid_dir_rel}; use super::registry_fetch::{extract_gem_data, extract_on_blocking_pool}; use super::revert::{self, KeepPolicy}; use super::service_fetch::{ - claim_prestaged, downloaded_warning, fetch_served_artifacts, fetch_verified_archive, - fetch_verified_platform_secondary, fetch_verified_secondary, SecondaryArtifactResult, - ServedArtifacts, ServicePolicy, + claim_prestaged, downloaded_warning, fetch_served_reference, fetch_served_references, + fetch_verified_archive, fetch_verified_artifact, fetch_verified_secondary, + SecondaryArtifactResult, ServicePolicy, }; use super::source::PackageSource; use super::state::{ - write_marker_or_warn, VendorArtifact, VendorEntry, VendorMarker, WiringAction, WiringRecord, + write_marker_or_warn, GemBuildEntry, VendorArtifact, VendorEntry, VendorMarker, WiringAction, + WiringRecord, }; use super::{RevertOpts, RevertOutcome, VendorOutcome, VendorServiceConfig, VendorWarning}; use crate::formats::gem::{ @@ -216,9 +231,15 @@ struct GemPrelude { copy_ok: bool, /// The platforms the lock pins the gem for, in lock order, when it /// locks it as precompiled platform gems (see the module docs): the - /// copy is then one prebuild tree per platform. Empty for the plain - /// `name (version)` entry, vendored as the gem's own tree. + /// copy is then one patched platform gem's tree per platform. Empty + /// for the plain `name (version)` entry, vendored as the gem's own + /// tree. platforms: Vec, + /// The wired copy's trees are intact, and its ledger entry names no + /// patch for them ([`VendorEntry::gem_platforms`]): `copy_ok` is then + /// `false`, so the run rebuilds the copy from each platform's own + /// patch and records them. + unattributed: bool, } /// What `Gemfile.lock` resolves `name`@`version` to, read from every source @@ -372,6 +393,34 @@ pub async fn gem_lock_refusals( .collect() } +/// The gem purls of `purls`, as given, that `Gemfile.lock` resolves as +/// precompiled platform gems (see the module docs), in any source section +/// (a lock already vendored holds them in our `PATH` section). What is +/// vendored for such a gem is the lock's to say: an installed copy is one +/// platform's gem at most, and its files say nothing of the patch's. +/// Read-only; none when bundler loads another manifest or the lock cannot +/// be read. +pub async fn gems_locked_as_platform_gems(project_root: &Path, purls: &[&str]) -> Vec { + let gems: Vec<(&str, String, String)> = purls + .iter() + .filter_map(|purl| { + let (name, version) = parse_gem_purl(purl)?; + Some((*purl, name.to_string(), version.to_string())) + }) + .collect(); + if gems.is_empty() || gem_manifest_refusal(project_root).await.is_some() { + return Vec::new(); + } + let Ok(lock_text) = read_regular_to_string(&project_root.join(GEMFILE_LOCK)).await else { + return Vec::new(); + }; + let lock = crate::formats::gem::parse(&lock_text); + gems.into_iter() + .filter(|(_, name, version)| !locked_gem(&lock, name, version).platforms.is_empty()) + .map(|(purl, ..)| purl.to_string()) + .collect() +} + /// The [`GEM_VERSION_NOT_LOCKED`] refusals of [`gem_lock_refusals`]. pub async fn gem_version_not_locked_refusals( project_root: &Path, @@ -515,7 +564,7 @@ async fn gem_prelude( // purl, so a `?platform=ruby` lookup can still land on a native // install dir). Whether that is vendorable is the lock's to say, // below: a lock that pins the gem as platform gems is vendored from - // the patch service's prebuilds for EVERY platform it pins (the + // the patch service's patched gem of EVERY platform it pins (the // installed dir is one of them, and is not read). // // Gating on the platform (not only the staging dir name) lets @@ -615,9 +664,9 @@ async fn gem_prelude( // ── a gem the lock pins as precompiled platform gems ───────────────── // The lock decides what is vendored: the gem's own tree for the plain - // `name (version)` entry, the patch service's prebuilds for - // platform-suffixed ones (see the module docs). Decided here, before - // the patch service is asked for anything. + // `name (version)` entry, the patch service's patched platform gems + // for platform-suffixed ones (see the module docs). Decided here, + // before the patch service is asked for anything. let locked = locked_gem(&crate::formats::gem::parse(&lock_text), name, version); if locked.platforms.is_empty() { // Locked for the ruby platform alone: the copy to vendor is the @@ -647,9 +696,10 @@ async fn gem_prelude( // Only the local stub is checked here (when present); the service stub is // re-checked in `gem_service_copy`, and a native gem emits no service stub // at all (the converter refuses it), so the service path also misses. - // A gem locked as platform gems is vendored from prebuilds, which have - // nothing to build: an installed ruby-platform copy of it (compiled on - // this machine, beside the lock's platform gems) says nothing of them. + // A gem locked as platform gems is vendored from patched platform + // gems, which have nothing to build: an installed ruby-platform copy of + // it (compiled on this machine, beside the lock's platform gems) says + // nothing of them. if let Some(text) = local_stub.as_ref().filter(|_| locked.platforms.is_empty()) { if gemspec_declares_extensions(text) { return Err(refused( @@ -670,6 +720,7 @@ async fn gem_prelude( let lock_wired = lock_text.split('\n').any(|l| l == remote_line) && gemfile_text.contains(©_rel); let mut copy_ok = false; + let mut unattributed = false; if lock_wired { if lock_checksum_in_sync(&lock_text, name, version, &locked.platforms) { // Probe the copy only once the lock is known to be wired (the @@ -686,15 +737,18 @@ async fn gem_prelude( && stub_gemspec_valid(©_dir, name).await } platforms => { - let inventory = recorded_inventory(project_root, &record.uuid, ©_rel).await; - platform_copy_intact( - ©_dir, - name, - platforms, - &record.files, - inventory.as_ref(), - ) - .await + let recorded = recorded_copy(project_root, &record.uuid, ©_rel).await; + let inventory = recorded + .as_ref() + .and_then(|entry| entry.artifact.file_inventory.as_ref()); + let intact = + platform_copy_intact(©_dir, name, platforms, &record.files, inventory) + .await; + unattributed = intact + && recorded.is_some_and(|entry| { + entry.gem_builds.is_empty() && !entry.gem_platforms.is_empty() + }); + intact && !unattributed } }; } else { @@ -746,6 +800,7 @@ async fn gem_prelude( lock_wired, copy_ok, platforms: locked.platforms, + unattributed, }) } @@ -757,8 +812,8 @@ async fn gem_prelude( /// running platform is not known, so its lock is left alone. const PLATFORM_LAYOUT_MIN_BUNDLER: (u32, u32) = (2, 3); -/// Why a gem the lock pins as platform gems cannot be vendored from -/// prebuilds, when the lock alone says so: it also locks the plain +/// Why a gem the lock pins as platform gems cannot be vendored as patched +/// platform gems, when the lock alone says so: it also locks the plain /// `name (version)` entry — the ruby platform, which no prebuilt tree /// serves and whose extensions bundler never builds for a `path:` gem — /// one of its platforms is no directory name, or the bundler that wrote @@ -837,18 +892,14 @@ async fn stub_gemspec_valid(tree: &Path, name: &str) -> bool { } } -/// The file inventory the vendor ledger records for the copy at -/// `copy_rel` of the patch `uuid`: what vouches for the bytes of its -/// prebuild trees once they are vendored (see [`verify_platform_tree`]). -/// `None` when the ledger has no entry for that copy, records no inventory -/// for it, or cannot be read. +/// The vendor ledger's entry for the copy at `copy_rel` of the patch +/// `uuid`: its file inventory is what vouches for the bytes of the +/// platform trees once they are vendored (see [`verify_platform_tree`]), +/// and it names the patch each tree came from. `None` when the ledger has +/// no entry for that copy or cannot be read. /// /// [`verify_platform_tree`]: super::verify::verify_platform_tree -async fn recorded_inventory( - project_root: &Path, - uuid: &str, - copy_rel: &str, -) -> Option> { +async fn recorded_copy(project_root: &Path, uuid: &str, copy_rel: &str) -> Option { let state = super::state::load_state_shared(project_root).await.ok()?; state .entries @@ -856,7 +907,38 @@ async fn recorded_inventory( .find(|e| { e.ecosystem == "gem" && e.uuid == uuid && e.artifact.path.replace('\\', "/") == copy_rel }) - .and_then(|e| e.artifact.file_inventory.clone()) + .cloned() +} + +/// Whether the copy the ledger records at `copy_rel` for the patch `uuid` +/// is intact as recorded: every tree the entry names passes +/// [`platform_copy_intact`]. What a run that cannot bring the copy up to +/// date asks before it leaves it in force. +async fn recorded_copy_stands( + project_root: &Path, + record: &PatchRecord, + copy_rel: &str, + copy_dir: &Path, + name: &str, +) -> bool { + let Some(entry) = recorded_copy(project_root, &record.uuid, copy_rel).await else { + return false; + }; + let platforms: Vec = entry + .gem_tree_platforms() + .into_iter() + .map(str::to_string) + .collect(); + !platforms.is_empty() + && platforms.iter().all(|p| is_platform_dir_name(p)) + && platform_copy_intact( + copy_dir, + name, + &platforms, + &record.files, + entry.artifact.file_inventory.as_ref(), + ) + .await } /// The in-sync test of a copy vendored as platform gems: the tree of every @@ -952,8 +1034,8 @@ fn gem_edits( let lock_edit = edit_lock(&prelude.lock_text, name, version, &prelude.copy_rel).and_then( |edit| match edit.platforms == prelude.platforms { true => Ok(edit), - // The copy holds one prebuild per platform the lock resolves - // the gem for, and the edit moves the entries of one section: + // The copy holds one tree per platform the lock resolves the + // gem for, and the edit moves the entries of one section: // an entry it leaves behind (in a GIT or foreign PATH section) // would have a tree and no spec in the vendored section. false => Err(format!( @@ -984,8 +1066,8 @@ fn gem_edits( /// path. The vendor loop's download plan consults this; the `.gem`'s /// `gem-stub-gemspec` secondary rides the same planned download. `None` /// for a gem the lock pins as platform gems: it is vendored from the -/// prebuilds the service's package reference lists -/// ([`stage_platform_prebuilds`]), and the ruby gem is never downloaded. +/// patches the service's package reference names for its platforms +/// ([`stage_platform_builds`]), and the ruby gem is never downloaded. pub(crate) async fn service_preflight( purl: &str, installed_path: &Path, @@ -1061,11 +1143,19 @@ pub async fn vendor_gem<'a>( lock_wired, copy_ok, platforms, + unattributed, } = &prelude; let (name, version) = (name.as_str(), version.as_str()); let (copy_rel, uuid_dir, copy_dir) = (copy_rel.as_str(), uuid_dir.as_path(), copy_dir.as_path()); - let (lock_wired, copy_ok) = (*lock_wired, *copy_ok); + let (lock_wired, copy_ok, unattributed) = (*lock_wired, *copy_ok, *unattributed); + // What is vendored for each locked platform, once the service names it. + let label = format!("{name}@{version}"); + let locked = |standing: Standing| PlatformTrees { + gem: &label, + from: BuildsFrom::Locked(platforms), + standing, + }; // ── idempotent hot path ────────────────────────────────────────────── // Copy (incl. the gemspec) already carries every afterHash and both files @@ -1110,12 +1200,12 @@ pub async fn vendor_gem<'a>( return refusal; } let mut warnings: Vec = Vec::new(); - let result = match materialise_patched_copy( + let (result, builds) = match materialise_patched_copy( purl, copy_dir, uuid_dir, name, - platforms, + &locked(Standing::Wired), record, false, // live-wired: never unwind the uuid dir on failure service, @@ -1123,17 +1213,23 @@ pub async fn vendor_gem<'a>( ) .await { - Ok(result) => result, - Err(outcome) => return rebuild_needs_every_prebuild(*outcome), + Ok(materialised) => materialised, + Err(outcome) => { + return wired_copy_not_rebuilt(*outcome, project_root, record, &prelude).await + } }; if !result.success { return done(result, None, warnings); } + let why = match unattributed { + true => "was recorded with no patch named for its platform gems", + false => "was missing or stale", + }; warnings.push(VendorWarning::new( "vendor_artifact_rebuilt", format!( - "the committed vendored copy for {name}@{version} was missing or \ - stale; rebuilt at {copy_rel} (Gemfile and Gemfile.lock untouched)" + "the committed vendored copy for {name}@{version} {why}; rebuilt at \ + {copy_rel} (Gemfile and Gemfile.lock untouched)" ), )); // The rebuilt tree may differ from the one the ledger @@ -1147,7 +1243,7 @@ pub async fn vendor_gem<'a>( build_gem_purl(name, version), record, copy_rel.to_string(), - platforms, + builds, file_inventory, Vec::new(), ); @@ -1160,18 +1256,20 @@ pub async fn vendor_gem<'a>( // An unwired gem previews the Gemfile and lock edit refusals the wet // run raises (a declaration inside a `group` block, #1761), so a // takeover or eject preview over the restored text refuses too. + let mut standing = Standing::Wired; if !lock_wired { - if let Err(outcome) = gem_edits(purl, &prelude) { - return *outcome; + match gem_edits(purl, &prelude) { + Ok((plan, _)) => standing = plan.standing(), + Err(outcome) => return *outcome, } } let previewed = match platforms.as_slice() { [] => super::service_fetch::preview_service(service, record, extract_gem_data).await, - platforms => preview_platform_prebuilds(service, record, name, platforms).await, + _ => preview_platform_builds(service, record, name, &locked(standing)).await, }; if let Err(outcome) = previewed { return match lock_wired { - true => rebuild_needs_every_prebuild(*outcome), + true => wired_copy_not_rebuilt(*outcome, project_root, record, &prelude).await, false => *outcome, }; } @@ -1196,12 +1294,12 @@ pub async fn vendor_gem<'a>( if let Some(refusal) = service_offline_conflict(service) { return refusal; } - let mut result = match materialise_patched_copy( + let (mut result, builds) = match materialise_patched_copy( purl, copy_dir, uuid_dir, name, - platforms, + &locked(plan.standing()), record, true, // fresh vendor: nothing pre-existing worth keeping service, @@ -1209,7 +1307,7 @@ pub async fn vendor_gem<'a>( ) .await { - Ok(result) => result, + Ok(materialised) => materialised, Err(outcome) => return *outcome, }; if !result.success { @@ -1388,7 +1486,7 @@ pub async fn vendor_gem<'a>( base_purl, record, copy_rel.to_string(), - platforms, + builds, file_inventory, wiring, ); @@ -1396,18 +1494,45 @@ pub async fn vendor_gem<'a>( done(result, Some(entry), warnings) } -/// The outcome of rebuilding a copy the lock is ALREADY wired to when the -/// service lists no prebuild for one of its platforms. For a gem that is -/// not vendored yet that is a skip -/// ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]): nothing depends on the -/// copy. Here the lock names a tree that is missing or damaged, and no -/// older patch stands in for it, so it is the plain miss, a failure. -fn rebuild_needs_every_prebuild(outcome: VendorOutcome) -> VendorOutcome { +/// The outcome of a copy the lock is ALREADY wired to that this run could +/// not rebuild because a locked platform has no patched build +/// ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]). While the copy the +/// ledger records is intact (the lock gained a platform since, or the +/// entry names no patch for its trees) it stays in force as it is, and +/// the outcome stays that skip. Otherwise the lock names a tree that is +/// missing or damaged and no older patch stands in for it: the plain +/// miss, a failure. +async fn wired_copy_not_rebuilt( + outcome: VendorOutcome, + project_root: &Path, + record: &PatchRecord, + prelude: &GemPrelude, +) -> VendorOutcome { match outcome { VendorOutcome::Refused { code, detail } if code == super::VENDOR_PREBUILT_PLATFORM_PENDING => { - refused(super::VENDOR_PREBUILT_REQUIRED, detail) + let stands = recorded_copy_stands( + project_root, + record, + &prelude.copy_rel, + &prelude.copy_dir, + &prelude.name, + ) + .await; + match stands { + true => refused( + code, + format!("{detail}; its vendored copy stays in force as it is."), + ), + false => refused( + super::VENDOR_PREBUILT_REQUIRED, + format!( + "{detail}; its vendored copy is missing or damaged and cannot be \ + rebuilt until then." + ), + ), + } } other => other, } @@ -1415,18 +1540,18 @@ fn rebuild_needs_every_prebuild(outcome: VendorOutcome) -> VendorOutcome { /// The ledger entry for a vendored gem copy: `wiring` is the Gemfile + lock /// records on a full vendor, empty on an artifact-only rebuild (see the hot -/// path). `platforms` are the platform trees of a copy vendored as platform +/// path). `builds` are the platform trees of a copy vendored as platform /// gems (empty for the gem's own tree). fn gem_entry( base_purl: String, record: &PatchRecord, copy_rel: String, - platforms: &[String], + builds: Vec, file_inventory: Option>, wiring: Vec, ) -> VendorEntry { VendorEntry { - gem_platforms: platforms.to_vec(), + gem_builds: builds, ..VendorEntry::new( "gem".to_string(), base_purl, @@ -1610,40 +1735,188 @@ fn refuse_unusable_stub( Ok(()) } -/// The patched platform gem the patch service built for one platform of a -/// gem (a "prebuild": a drop-in for the upstream platform gem, with the -/// patch's files replaced and the extension rebuilt), and the stub gemspec -/// it serves for it — the per-platform twins of the `tarball` and -/// [`GEM_STUB_ARTIFACT_KIND`] artifacts. Each names its platform, and a -/// platform with no prebuild built has neither. -pub(crate) const GEM_PLATFORM_ARTIFACT_KIND: &str = "gem-platform"; -pub(crate) const GEM_PLATFORM_STUB_ARTIFACT_KIND: &str = "gem-platform-stub-gemspec"; - -/// How many platforms' prebuilds (a platform gem and its stub gemspec +/// How many platforms' gems (a patched platform gem and its stub gemspec /// each) are downloaded at once. const PREBUILD_DOWNLOADS_AT_ONCE: usize = 4; -/// Download and verify the prebuild of each of `platforms` and its stub -/// gemspec, and unpack them into `stage`: `//` holds the -/// platform gem's files and `.gemspec` (see the module docs). -/// -/// Which prebuilds exist is read off the service's package reference -/// alone; the ruby gem that reference also names is never downloaded -/// (bundler would have to build its extensions). While the service lists -/// no prebuild, or no stub, for one of `platforms`, nothing is downloaded -/// and the gem is skipped ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]). A -/// later failure leaves a partial `stage` for the caller to remove. -/// Returns the run's advisories: the download, and the ignore files that -/// were emptied. -async fn stage_platform_prebuilds( +/// Which patches the trees of a copy vendored as platform gems come from. +pub(super) enum BuildsFrom<'a> { + /// The platforms the lock names, in lock order, each from the patch + /// the gem patch's package reference names for it + /// (`gemBuilds[].patchUuid`). + Locked(&'a [String]), + /// The trees a ledger entry records, each from its recorded patch: a + /// restore of that copy. + Recorded(&'a [GemBuildEntry]), +} + +/// What a gem has in place of the patch being vendored, should a locked +/// platform turn out to have no patched build: how that skip is worded. +#[derive(Clone, Copy, PartialEq)] +pub(super) enum Standing { + /// Nothing: the gem is not vendored. + NotVendored, + /// The lock is wired to this patch's copy. + Wired, + /// The Gemfile is wired to the copy of another patch of the gem. + EarlierPatch, +} + +/// The platform trees one call stages, and how a miss is worded. +pub(super) struct PlatformTrees<'a> { + /// `@`, for messages. + pub(super) gem: &'a str, + pub(super) from: BuildsFrom<'a>, + pub(super) standing: Standing, +} + +/// One platform tree to stage: the patch it is unpacked from, and what its +/// downloads must match beyond the digests that patch's own reference +/// states for them. +struct BuildSource { + platform: String, + uuid: String, + pinned: BuildPin, +} + +enum BuildPin { + /// sha256 (hex) of the `.gem` the gem patch's registry lists for the + /// platform (`gemBuilds[].gemChecksumSha256`). + Registry(String), + /// sha512 (SRI) of the `.gem` and of the stub gemspec the ledger + /// recorded when the tree was vendored. An empty one pins nothing. + Ledger { gem: String, gemspec: String }, +} + +/// `a`, `a and b`, `a, b and c`. +fn listed(items: &[&str]) -> String { + match items { + [] => String::new(), + [one] => (*one).to_string(), + [head @ .., last] => format!("{} and {last}", head.join(", ")), + } +} + +/// How the line of a gem that is not vendored +/// ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]) ends when some of its +/// locked platforms do have a patched build: hosted mode patches those. +/// A caller that knows the gem is hosted already says so in its place. +pub const HOSTED_CAN_PATCH: &str = "; `scan --mode hosted` can patch the others now."; + +/// The one line for a gem left as it is because `missing` (locked +/// platforms) have no patched build, while `patched` (the other locked +/// platforms) have one. For a lock already wired to this patch's copy +/// ([`Standing::Wired`]) the caller ends the line with what became of +/// that copy ([`wired_copy_not_rebuilt`]); otherwise it is the whole +/// line. +fn no_patched_build_detail( + gem: &str, + missing: &[&str], + patched: &[&str], + standing: Standing, +) -> String { + let lead = match standing { + Standing::NotVendored => "is not vendored", + Standing::Wired | Standing::EarlierPatch => "was not brought up to date", + }; + let have = match patched { + [] => String::new(), + [one] => format!(" ({one} has one)"), + patched => format!(" ({} have one)", listed(patched)), + }; + let tail = match (standing, patched.is_empty()) { + (Standing::Wired, _) => "", + (Standing::EarlierPatch, _) => { + "; its vendored copy of an earlier patch stays in force as it is." + } + (Standing::NotVendored, true) => ".", + (Standing::NotVendored, false) => HOSTED_CAN_PATCH, + }; + format!( + "{gem} {lead}: no patched build yet for {}{have}. Vendored mode needs every locked \ + platform{tail}", + listed(missing) + ) +} + +/// The patch of each of `platforms`' patched build, as the package +/// reference of `record` (the gem's fix) names them, with the sha256 its +/// registry lists for that platform gem: ONE request, and nothing +/// downloaded. While a locked platform has no patched build (the registry +/// serves upstream's own gem for it, does not list it, or lists no +/// platform gem at all) the gem is skipped +/// ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]). +async fn locked_build_sources( cfg: &VendorServiceConfig, record: &PatchRecord, name: &str, + trees: &PlatformTrees<'_>, platforms: &[String], +) -> Result, Box> { + let policy = ServicePolicy::Refused; + let reference = fetch_served_reference(cfg, &record.uuid).await; + let served = policy.settle( + reference, + "platform gem", + &format!("platform gems for {name}"), + )?; + let builds = served.gem_builds.as_deref().unwrap_or_default(); + let mut sources: Vec = Vec::with_capacity(platforms.len()); + let mut missing: Vec<&str> = Vec::new(); + for platform in platforms { + let build = builds.iter().find(|build| build.platform == *platform); + match build.and_then(|build| Some((build, build.patch_uuid.as_deref()?))) { + Some((build, uuid)) => sources.push(BuildSource { + platform: platform.clone(), + uuid: uuid.to_string(), + pinned: BuildPin::Registry(build.gem_checksum_sha256.clone()), + }), + None => missing.push(platform), + } + } + if missing.is_empty() { + return Ok(sources); + } + // Not a failure: a platform's patched build is named only once it is + // published, so this is as likely "not yet" as "never", and nothing + // was touched. + let patched: Vec<&str> = sources.iter().map(|s| s.platform.as_str()).collect(); + Err(Box::new(refused( + super::VENDOR_PREBUILT_PLATFORM_PENDING, + no_patched_build_detail(trees.gem, &missing, &patched, trees.standing), + ))) +} + +/// Download and verify the patched gem of each platform of `trees` and its +/// stub gemspec, and unpack them into `stage`: `//` holds +/// the platform gem's files and `.gemspec` (see the module docs). +/// Each platform's gem is the `tarball` of that platform's own patch, and +/// its stub that patch's [`GEM_STUB_ARTIFACT_KIND`]; `record` is the gem's +/// fix, whose files the trees are verified against. The ruby gem of the +/// fix is never downloaded (bundler would have to build its extensions). +/// +/// The patches are named by the fix's package reference (one request, +/// [`locked_build_sources`]) or by the ledger entry being restored, and +/// their own references are asked for in ONE request more. Every download +/// is verified against the digest its patch's reference states, and the +/// gem also against the sha256 the fix's registry lists for that platform +/// (or, on a restore, both against what the ledger recorded). A failure +/// leaves a partial `stage` for the caller to remove. Returns the run's +/// advisories (the download, and the ignore files that were emptied) and +/// what the ledger records of each tree. +async fn stage_platform_builds( + cfg: &VendorServiceConfig, + record: &PatchRecord, + name: &str, + trees: &PlatformTrees<'_>, stage: &Path, -) -> Result, Box> { +) -> Result<(Vec, Vec), Box> { use futures_util::StreamExt as _; let policy = ServicePolicy::Refused; + let platforms: Vec<&str> = match &trees.from { + BuildsFrom::Locked(platforms) => platforms.iter().map(String::as_str).collect(), + BuildsFrom::Recorded(builds) => builds.iter().map(|b| b.platform.as_str()).collect(), + }; // SECURITY: a platform names a directory under the stage, and the // ledger a restore reads them from is committed, tamper-able data. if let Some(platform) = platforms.iter().find(|p| !is_platform_dir_name(p)) { @@ -1652,83 +1925,70 @@ async fn stage_platform_prebuilds( format!("unsafe gem platform `{platform}` for `{name}`"), )); } - let listed = fetch_served_artifacts(cfg, &record.uuid).await; - let served = policy.settle(listed, "platform gem", &format!("platform gems for {name}"))?; + let sources: Vec = match &trees.from { + BuildsFrom::Locked(platforms) => { + locked_build_sources(cfg, record, name, trees, platforms).await? + } + BuildsFrom::Recorded(builds) => builds + .iter() + .map(|built| BuildSource { + platform: built.platform.clone(), + uuid: built.uuid.clone(), + pinned: BuildPin::Ledger { + gem: built.gem_integrity.clone(), + gemspec: built.gemspec_integrity.clone(), + }, + }) + .collect(), + }; - let missing: Vec<&str> = platforms - .iter() - .map(String::as_str) - .filter(|platform| { - served - .platform(GEM_PLATFORM_ARTIFACT_KIND, platform) - .is_none() - || served - .platform(GEM_PLATFORM_STUB_ARTIFACT_KIND, platform) - .is_none() - }) - .collect(); - if !missing.is_empty() { - let quoted = |platforms: &[&str]| { - platforms - .iter() - .map(|platform| format!("`{platform}`")) - .collect::>() - .join(", ") + // What each platform's patch serves, asked together and before any + // download. + let uuids: Vec = sources.iter().map(|source| source.uuid.clone()).collect(); + let references = fetch_served_references(cfg, &uuids) + .await + .map_err(|reason| policy.miss(format!("patch service request failed ({reason})")))?; + let mut builds = Vec::with_capacity(sources.len()); + for (source, reference) in sources.iter().zip(references) { + let subject = format!("{name} ({})", source.platform); + let served = policy.settle( + reference, + "platform gem", + &format!("platform gem for {subject}"), + )?; + let Some(gem) = served.archive.clone() else { + return Err(policy.miss(format!( + "the patch service served no patched platform gem for {subject}" + ))); }; - let built: Vec<&str> = platforms - .iter() - .map(String::as_str) - .filter(|platform| !missing.contains(platform)) - .collect(); - let built = match built.as_slice() { - [] => "it has none of the locked platforms".to_string(), - built => format!("it has {}", quoted(built)), + let Some(stub) = served.secondary(GEM_STUB_ARTIFACT_KIND).cloned() else { + return Err(policy.miss(format!( + "the patch service served no stub gemspec for {subject}" + ))); }; - // Not a failure: a prebuild is listed only once it is built, so - // this is as likely "not yet" as "never", and nothing was touched. - return Err(Box::new(refused( - super::VENDOR_PREBUILT_PLATFORM_PENDING, - format!( - "the patch service has no prebuilt platform gem of `{name}` for {} yet \ - ({built}); {GEMFILE_LOCK} locks {name} as precompiled platform gems and bundler \ - never builds a `path:` gem's extensions, so the patch is not vendored until \ - every locked platform has one", - quoted(&missing) - ), - ))); + builds.push((source, subject, gem, stub)); } - // The prebuilds, a few platforms at a time and taken in lock order. - let served = &served; - let mut downloads = std::pin::pin!(futures_util::stream::iter(platforms) - .map(|platform| async move { - let subject = format!("{name} ({platform})"); - let gem = platform_artifact( - cfg, - served, - GEM_PLATFORM_ARTIFACT_KIND, - platform, - "platform gem", - &subject, - ) - .await?; - let stub = platform_artifact( - cfg, - served, - GEM_PLATFORM_STUB_ARTIFACT_KIND, - platform, - "stub gemspec", - &subject, - ) - .await?; - Ok::<_, Box>((platform, subject, gem, stub)) + // The gems, a few platforms at a time and taken in lock order. + let mut downloads = std::pin::pin!(futures_util::stream::iter(&builds) + .map(|(source, subject, gem, stub)| async move { + let gem_bytes = build_artifact(cfg, gem, "patched platform gem", subject).await?; + source.pinned.check_gem(&gem_bytes, subject)?; + let stub_bytes = build_artifact(cfg, stub, "stub gemspec", subject).await?; + source.pinned.check_stub(&stub_bytes, subject)?; + Ok::<_, Box>((gem_bytes, stub_bytes)) }) .buffered(PREBUILD_DOWNLOADS_AT_ONCE)); let mut emptied: Vec = Vec::new(); - while let Some(downloaded) = downloads.next().await { - let (platform, subject, gem, stub) = downloaded?; - refuse_unusable_stub(policy, name, &subject, &String::from_utf8_lossy(&stub))?; + let mut built: Vec = Vec::with_capacity(builds.len()); + for (source, subject, gem, stub) in &builds { + let Some(downloaded) = downloads.next().await else { + break; + }; + let (gem_bytes, stub_bytes) = downloaded?; + let platform = source.platform.as_str(); + refuse_unusable_stub(policy, name, subject, &String::from_utf8_lossy(&stub_bytes))?; let tree = stage.join(platform); if let Err(e) = tokio::fs::create_dir_all(&tree).await { @@ -1737,10 +1997,10 @@ async fn stage_platform_prebuilds( format!("cannot create {}: {e}", tree.display()), )); } - if let Err(e) = extract_on_blocking_pool(gem, &tree, extract_gem_data).await { + if let Err(e) = extract_on_blocking_pool(gem_bytes, &tree, extract_gem_data).await { return Err(policy.hard( "vendor_prebuilt_extract_failed", - format!("cannot extract the prebuilt platform gem for {subject}: {e}"), + format!("cannot extract the patched platform gem for {subject}: {e}"), )); } match empty_shipped_gitignores(&tree, &record.files).await { @@ -1748,56 +2008,113 @@ async fn stage_platform_prebuilds( Err(e) => { return Err(policy.hard( "vendor_prebuilt_write_failed", - format!("cannot empty a `.gitignore` the prebuilt platform gem for {subject} ships: {e}"), + format!("cannot empty a `.gitignore` the patched platform gem for {subject} ships: {e}"), )); } } - if let Err(e) = tokio::fs::write(tree.join(format!("{name}.gemspec")), &stub).await { + if let Err(e) = tokio::fs::write(tree.join(format!("{name}.gemspec")), &stub_bytes).await { return Err(policy.hard( "vendor_prebuilt_write_failed", format!("cannot write the stub gemspec for {subject} into the vendored dir: {e}"), )); } - // `gem` passed the service's digest for this platform above - // (`platform_artifact`), which is what vouches for a tree that - // ships none of the patched files: only one it does ship can - // contradict the patch. + // The gem passed the digests stated for this platform above, which + // is what vouches for a tree that ships none of the patched files: + // only one it does ship can contradict the patch. let verified = super::verify::TreeVoucher::VerifiedDownload; if super::verify::verify_platform_tree(&tree, &record.files, verified) .await .is_err() { return Err(policy.miss(format!( - "prebuilt platform gem for {subject} does not carry the patch (a patched \ + "patched platform gem for {subject} does not carry the patch (a patched \ file it ships is not the patched one)" ))); } + built.push(GemBuildEntry { + platform: platform.to_string(), + uuid: source.uuid.clone(), + gem_integrity: gem.integrity_sri.clone(), + gemspec_integrity: stub.integrity_sri.clone(), + }); } - let source_url = platforms + let source_url = builds .first() - .and_then(|platform| served.platform(GEM_PLATFORM_ARTIFACT_KIND, platform)) - .map(|artifact| artifact.url.as_str()) + .map(|(_, _, gem, _)| gem.url.as_str()) .unwrap_or_default(); let mut warnings = vec![downloaded_warning( - format_args!( - "{name} as prebuilt platform gems ({})", - platforms.join(", ") - ), + format_args!("{name} as patched platform gems ({})", platforms.join(", ")), source_url, )]; if !emptied.is_empty() { warnings.push(VendorWarning::new( GITIGNORE_NEUTRALIZED, format!( - "{name}: the prebuilt platform gems ship their own `.gitignore` ({}), whose \ + "{name}: the patched platform gems ship their own `.gitignore` ({}), whose \ rules would keep git from committing files of the vendored trees; emptied in \ the vendored copy (commit it)", super::npm_dir::summarize_rules(&emptied) ), )); } - Ok(warnings) + Ok((warnings, built)) +} + +impl BuildPin { + /// Whether the downloaded platform gem is the one this tree is pinned + /// to; a mismatch is never vendored. + fn check_gem(&self, gem: &[u8], subject: &str) -> Result<(), Box> { + let mismatch = |why: String| { + ServicePolicy::Refused.hard( + "vendor_prebuilt_integrity_mismatch", + format!("patched platform gem for {subject} {why}; refusing to vendor it"), + ) + }; + match self { + Self::Registry(listed) => { + let sha256 = crate::utils::digest::sha256_hex_of(gem); + match sha256.eq_ignore_ascii_case(listed) { + true => Ok(()), + false => Err(mismatch(format!( + "is not the gem the patch registry lists for that platform (sha256 \ + {sha256}, listed {listed})" + ))), + } + } + Self::Ledger { gem: recorded, .. } => { + Self::check_recorded(gem, recorded).map_err(|why| { + mismatch(format!( + "is not the gem this copy was vendored from ({why})" + )) + }) + } + } + } + + /// [`Self::check_gem`] for the stub gemspec, which only the ledger pins. + fn check_stub(&self, stub: &[u8], subject: &str) -> Result<(), Box> { + let Self::Ledger { gemspec, .. } = self else { + return Ok(()); + }; + Self::check_recorded(stub, gemspec).map_err(|why| { + ServicePolicy::Refused.hard( + "vendor_prebuilt_integrity_mismatch", + format!( + "stub gemspec for {subject} is not the one this copy was vendored with \ + ({why}); refusing to vendor it" + ), + ) + }) + } + + fn check_recorded(bytes: &[u8], recorded: &str) -> Result<(), String> { + if recorded.is_empty() { + return Ok(()); + } + // The Sri verifier never reads the name arg. + artifact_matches_integrity(bytes, "", &LockIntegrity::Sri(recorded.to_string())) + } } /// The advisory of [`empty_shipped_gitignores`]: the vendored trees differ @@ -1857,22 +2174,20 @@ async fn empty_shipped_gitignores( Ok(emptied) } -/// One per-platform artifact of `kind` (`what`, for messages about +/// One artifact of a platform's patch (`what`, for messages about /// `subject`), downloaded and verified against its served integrity like /// the ruby gem's stub: a mismatch is never vendored. The check is not /// optional: an artifact the service states no digest for is not listed -/// at all, and for a prebuild that ships none of the patched files it is -/// the only evidence that the tree is the patched build. -async fn platform_artifact( +/// at all, and for a platform gem that ships none of the patched files it +/// is the only evidence that the tree is the patched build. +async fn build_artifact( cfg: &VendorServiceConfig, - served: &ServedArtifacts, - kind: &str, - platform: &str, + artifact: &crate::api::client::SecondaryArtifact, what: &str, subject: &str, ) -> Result, Box> { let policy = ServicePolicy::Refused; - match fetch_verified_platform_secondary(cfg, served, kind, platform).await { + match fetch_verified_artifact(cfg, Some(artifact)).await { SecondaryArtifactResult::Ready(bytes) => Ok(bytes), SecondaryArtifactResult::Absent => { Err(policy.miss(format!("the patch service served no {what} for {subject}"))) @@ -1880,7 +2195,7 @@ async fn platform_artifact( SecondaryArtifactResult::IntegrityMismatch(reason) => Err(policy.hard( "vendor_prebuilt_integrity_mismatch", format!( - "prebuilt {what} for {subject} failed integrity verification ({reason}); \ + "{what} for {subject} failed integrity verification ({reason}); \ refusing to vendor tampered bytes" ), )), @@ -1891,28 +2206,29 @@ async fn platform_artifact( } /// [`gem_service_copy`] for a gem the lock pins as platform gems: the copy -/// is the verified prebuild of each of `platforms`, staged in full and then -/// swapped into place, so a failure leaves any pre-existing (possibly -/// live-wired) copy untouched and no husk behind. The uuid dir's git -/// metadata is the caller's to write ([`restore_uuid_metadata`]): -/// `copy_dir` may itself sit in a stage (`repair`'s restore). +/// is the verified patched gem of each platform of `trees`, each from its +/// own patch, staged in full and then swapped into place, so a failure +/// leaves any pre-existing (possibly live-wired) copy untouched and no +/// husk behind. The uuid dir's git metadata is the caller's to write +/// ([`restore_uuid_metadata`]): `copy_dir` may itself sit in a stage +/// (`repair`'s restore). Returns what the ledger records of each tree. #[allow(clippy::too_many_arguments)] pub(super) async fn gem_platform_service_copy( service: Option<&VendorServiceConfig>, record: &PatchRecord, name: &str, - platforms: &[String], + trees: &PlatformTrees<'_>, copy_dir: &Path, uuid_dir: &Path, unwind_uuid_dir: bool, warnings: &mut Vec, -) -> Result<(), Box> { +) -> Result, Box> { let cfg = service .filter(|cfg| cfg.service_enabled()) .ok_or_else(|| Box::new(super::service_fetch::required()))?; let stage = stage_dir_for(copy_dir); let _ = remove_tree(&stage).await; - let staged = match stage_platform_prebuilds(cfg, record, name, platforms, &stage).await { + let (staged, built) = match stage_platform_builds(cfg, record, name, trees, &stage).await { Ok(staged) => staged, Err(outcome) => { cleanup_failed_stage(&stage, uuid_dir, unwind_uuid_dir).await; @@ -1927,9 +2243,16 @@ pub(super) async fn gem_platform_service_copy( )); } warnings.extend(staged); - Ok(()) + Ok(built) } +/// Why a copy vendored as platform gems cannot be restored from its ledger +/// entry alone: the entry names its platforms and no patch for their trees +/// ([`VendorEntry::gem_platforms`]), so there is nothing to fetch them by. +pub(super) const UNATTRIBUTED_TREES: &str = "the ledger names no patch for the platform gems of \ + this copy; run `socket-patch scan --mode vendored` to vendor it again (or restore the \ + committed directory from version control)"; + /// `/.gitignore` of a gem vendored as platform gems: re-includes /// everything under the uuid dir against the project's own ignore rules. /// A prebuild's tree holds the compiled extension (`*.so`, `*.bundle`, @@ -1990,11 +2313,11 @@ async fn keep_platform_trees_committable( /// A dry run's check of a gem the lock pins as platform gems: the whole /// download, verification and unpacking of [`gem_platform_service_copy`], /// into a scratch directory. -async fn preview_platform_prebuilds( +async fn preview_platform_builds( service: Option<&VendorServiceConfig>, record: &PatchRecord, name: &str, - platforms: &[String], + trees: &PlatformTrees<'_>, ) -> Result<(), Box> { if let Some(outcome) = service_offline_conflict(service) { return Err(Box::new(outcome)); @@ -2004,29 +2327,31 @@ async fn preview_platform_prebuilds( .ok_or_else(|| Box::new(super::service_fetch::required()))?; let scratch = tempfile::tempdir() .map_err(|e| Box::new(refused("vendor_prebuilt_extract_failed", e.to_string())))?; - stage_platform_prebuilds(cfg, record, name, platforms, scratch.path()) + stage_platform_builds(cfg, record, name, trees, scratch.path()) .await .map(|_| ()) } /// Acquire a verified service copy without replacing the prior copy on -/// failure: the gem's own tree, or one prebuild tree per platform in -/// `platforms` when the lock pins the gem as platform gems (with the uuid -/// dir's git metadata, see [`restore_uuid_metadata`]). +/// failure: the gem's own tree, or one patched platform gem's tree per +/// platform of `trees` when the lock pins the gem as platform gems (with +/// the uuid dir's git metadata, see [`restore_uuid_metadata`]). Returns +/// what the ledger records of each such tree, with the result. #[allow(clippy::too_many_arguments)] async fn materialise_patched_copy( purl: &str, copy_dir: &Path, uuid_dir: &Path, name: &str, - platforms: &[String], + trees: &PlatformTrees<'_>, record: &PatchRecord, unwind_uuid_dir: bool, service: Option<&VendorServiceConfig>, warnings: &mut Vec, -) -> Result> { - match platforms { - [] => { +) -> Result<(ApplyResult, Vec), Box> { + let mut builds = Vec::new(); + match &trees.from { + BuildsFrom::Locked([]) => { gem_service_copy( service, record, @@ -2038,12 +2363,12 @@ async fn materialise_patched_copy( ) .await? } - platforms => { - gem_platform_service_copy( + _ => { + builds = gem_platform_service_copy( service, record, name, - platforms, + trees, copy_dir, uuid_dir, unwind_uuid_dir, @@ -2065,7 +2390,10 @@ async fn materialise_patched_copy( } } } - Ok(already_patched_result(purl, copy_dir, &record.files)) + Ok(( + already_patched_result(purl, copy_dir, &record.files), + builds, + )) } /// Revert a gem vendor entry: restore the Gemfile line / delete the managed @@ -2259,6 +2587,16 @@ enum GemfilePlan { Append { block: String }, } +impl GemfilePlan { + /// What the gem has in place of the patch this plan wires. + fn standing(&self) -> Standing { + match self { + Self::RewireOurs { .. } => Standing::EarlierPatch, + Self::Rewrite { .. } | Self::Append { .. } => Standing::NotVendored, + } + } +} + /// The way out of a native-extension refusal (#2091): the modes that /// compile the extension ("Ruby gems: native extensions" in /// `docs/ecosystems.md`). Worded as hosted mode words its own refusals @@ -11895,102 +12233,227 @@ mod tests { .into_bytes() } - /// What the patch service lists for one platform: its prebuild and - /// the stub gemspec (`None` leaves that artifact out of the answer), - /// and the sha512 it advertises for the prebuild when not its own. + /// How the gem patch's registry lists one platform gem of the + /// version (`gemBuilds`). + #[derive(Clone, Copy, PartialEq)] + enum Listed { + /// With the patch of its patched build. + Patched, + /// As upstream's own gem: no patched build (`patchUuid: null`). + PassThrough, + /// Not at all. + Unlisted, + } + + /// What the patch service has for one platform gem: how the gem + /// patch's registry lists it, and what the platform's own patch + /// serves: the patched platform gem (its `tarball`) and the stub + /// gemspec (`None` leaves that artifact out of the patch's + /// reference), the sha512 that reference states for the gem when + /// not its own, and the sha256 the registry lists for it when not + /// its own. struct Served { platform: &'static str, + listed: Listed, gem: Option>, stub: Option>, gem_sha512: Option, + listed_sha256: Option, } - /// `platform`'s prebuild: the patched Ruby file and the platform's - /// own binary, with its stub. + /// `platform`'s patched build: the patched Ruby file and the + /// platform's own binary, with its stub. fn served(platform: &'static str) -> Served { Served { platform, + listed: Listed::Patched, gem: Some(make_gem(&[(RB, RB_PATCHED), (SO, platform.as_bytes())])), stub: Some(stub(platform)), gem_sha512: None, + listed_sha256: None, } } - /// A patch service answering for `uuid` with the patched ruby gem - /// and `prebuilds`, in the shape of the wire contract. - async fn service( + /// The patch of `platform`'s patched build of the fix `uuid`. + fn build_uuid(uuid: &str, platform: &str) -> String { + let tag = &crate::utils::digest::sha256_hex_of(platform.as_bytes())[..8]; + format!("{tag}{}", &uuid[8..]) + } + + /// A patch service answering for the gem patch `uuid` and for the + /// patch of each patched build of `builds`, in the shape of the + /// wire contract: the gem patch's reference lists `builds` under + /// `gemBuilds` (`list: false` leaves the list out, a patch of the + /// ruby gem alone), and each platform's own patch serves that + /// platform's gem and stub. A reference request is answered for + /// the uuids it names. + async fn serve( uuid: &str, - prebuilds: &[Served], + builds: &[Served], + list: bool, ) -> (wiremock::MockServer, VendorServiceConfig) { use wiremock::matchers::{method, path}; use wiremock::{Mock, ResponseTemplate}; let server = wiremock::MockServer::start().await; - let base = format!("/patch/gem/nokogiri/1.18.10/tok/{uuid}"); - let mut artifacts = Vec::new(); - let mut serve = |artifact: serde_json::Value, route: String, bytes: Vec| { - artifacts.push(artifact); - Mock::given(method("GET")) - .and(path(route)) - .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + let mut files: Vec<(String, Vec)> = Vec::new(); + let mut artifact = |kind: &str, + route: String, + bytes: &[u8], + sha512: Option<&String>| { + files.push((route.clone(), bytes.to_vec())); + serde_json::json!({ + "kind": kind, + "url": format!("{}{route}", server.uri()), + "contentType": "application/octet-stream", + "sizeBytes": bytes.len(), + "integrity": { "sha512": sha512.cloned().unwrap_or_else(|| sri_sha512(bytes)) } + }) }; - let mut mocks = Vec::new(); + let base = |uuid: &str| format!("/patch/gem/nokogiri/1.18.10/tok/{uuid}"); + let mut results = serde_json::Map::new(); + let mut gem_builds: Vec = Vec::new(); + for build in builds { + let platform = build.platform; + let own = build_uuid(uuid, platform); + let listed_sha256 = build.listed_sha256.clone().unwrap_or_else(|| { + crate::utils::digest::sha256_hex_of(build.gem.as_deref().unwrap_or_default()) + }); + match build.listed { + Listed::Unlisted => continue, + Listed::PassThrough => { + gem_builds.push(serde_json::json!({ + "platform": platform, "gemChecksumSha256": listed_sha256, + "patchUuid": null + })); + continue; + } + Listed::Patched => gem_builds.push(serde_json::json!({ + "platform": platform, "gemChecksumSha256": listed_sha256, + "patchUuid": own + })), + } + let mut artifacts = Vec::new(); + if let Some(gem) = &build.gem { + let route = format!("{}/nokogiri-1.18.10-{platform}.gem", base(&own)); + artifacts.push(artifact("tarball", route, gem, build.gem_sha512.as_ref())); + } + if let Some(stub) = &build.stub { + let route = format!("{}/nokogiri-1.18.10-{platform}.gemspec", base(&own)); + artifacts.push(artifact("gem-stub-gemspec", route, stub, None)); + } + results.insert( + own, + serde_json::json!({ + "status": "granted", + "purl": format!("pkg:gem/nokogiri@1.18.10?platform={platform}"), + "artifacts": artifacts + }), + ); + } + gem_builds.sort_by_key(|build| build["platform"].as_str().map(str::to_string)); let ruby_gem = make_gem(&[(RB, RB_PATCHED), (C, &b"patched C\n"[..])]); - let route = format!("{base}/nokogiri-1.18.10.gem"); - mocks.push(serve( + let route = format!("{}/nokogiri-1.18.10.gem", base(uuid)); + let mut identifiers = serde_json::json!({ + "name": "nokogiri", "version": "1.18.10", + "gemChecksumSha256": crate::utils::digest::sha256_hex_of(&ruby_gem) + }); + let mut index_url = format!("{}/patch-registry/gem/tok/{uuid}", server.uri()); + if list { + identifiers["gemBuilds"] = serde_json::Value::Array(gem_builds); + index_url.push_str("/s/4"); + } + results.insert( + uuid.to_string(), serde_json::json!({ - "kind": "tarball", "url": format!("{}{route}", server.uri()), - "integrity": { "sha512": sri_sha512(&ruby_gem) } + "status": "granted", + "purl": NOKO, + "url": format!("{}{route}", server.uri()), + "artifacts": [artifact("tarball", route, &ruby_gem, None)], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": index_url, + "identifiers": identifiers + } }), - route, - ruby_gem, - )); - for prebuild in prebuilds { - let platform = prebuild.platform; - let files = [ - ("gem-platform", "gem", &prebuild.gem, &prebuild.gem_sha512), - ( - "gem-platform-stub-gemspec", - "gemspec", - &prebuild.stub, - &None, - ), - ]; - for (kind, ext, bytes, sha512) in files { - let Some(bytes) = bytes else { continue }; - let route = format!("{base}/nokogiri-1.18.10-{platform}.{ext}"); - let sha512 = sha512.clone().unwrap_or_else(|| sri_sha512(bytes)); - mocks.push(serve( - serde_json::json!({ - "kind": kind, "platform": platform, - "url": format!("{}{route}", server.uri()), - "contentType": "application/octet-stream", - "sizeBytes": bytes.len(), - "integrity": { "sha512": sha512 } - }), - route, - bytes.clone(), - )); - } - } - for mock in mocks { - mock.mount(&server).await; + ); + for (route, bytes) in files { + Mock::given(method("GET")) + .and(path(route)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .mount(&server) + .await; } Mock::given(method("POST")) .and(path("/v0/orgs/acme/patches/package")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { uuid: { - "status": "granted", - "purl": NOKO, - "url": format!("{}{base}/nokogiri-1.18.10.gem", server.uri()), - "artifacts": artifacts - }} - }))) + .respond_with(move |request: &wiremock::Request| { + let asked: serde_json::Value = + serde_json::from_slice(&request.body).unwrap_or_default(); + let answered: serde_json::Map = asked["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|uuid| { + let uuid = uuid.as_str()?; + Some((uuid.to_string(), results.get(uuid)?.clone())) + }) + .collect(); + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({ "results": answered })) + }) .mount(&server) .await; let cfg = gem_service_cfg(&server.uri(), VendorSource::Service, false); (server, cfg) } + /// [`serve`] with the platform gems listed. + async fn service( + uuid: &str, + builds: &[Served], + ) -> (wiremock::MockServer, VendorServiceConfig) { + serve(uuid, builds, true).await + } + + /// The uuids each package reference request to `server` named, in + /// the order the requests arrived. + async fn reference_requests(server: &wiremock::MockServer) -> Vec> { + let requests = server.received_requests().await.unwrap_or_default(); + requests + .iter() + .filter(|request| request.method.as_str() == "POST") + .map(|request| { + let asked: serde_json::Value = + serde_json::from_slice(&request.body).unwrap_or_default(); + let uuids = asked["uuids"].as_array().into_iter().flatten(); + uuids + .filter_map(|uuid| Some(uuid.as_str()?.to_string())) + .collect() + }) + .collect() + } + + /// The paths of the files downloaded from `server`. + async fn downloads(server: &wiremock::MockServer) -> Vec { + let requests = server.received_requests().await.unwrap_or_default(); + requests + .iter() + .filter(|request| request.method.as_str() == "GET") + .map(|request| request.url.path().to_string()) + .collect() + } + + /// What the ledger records of `platform`'s tree vendored from + /// [`served`]'s build of the fix `uuid`. + fn built(uuid: &str, platform: &'static str) -> GemBuildEntry { + let build = served(platform); + GemBuildEntry { + platform: platform.to_string(), + uuid: build_uuid(uuid, platform), + gem_integrity: sri_sha512(build.gem.as_deref().unwrap()), + gemspec_integrity: sri_sha512(build.stub.as_deref().unwrap()), + } + } + /// A source that is not installed (a lock-only checkout). fn not_installed(root: &Path) -> PathBuf { root.join(".socket/vendor/.uninstalled") @@ -12038,12 +12501,15 @@ mod tests { } /// The capability: every platform block moves into one PATH section, - /// each platform gets its prebuild tree and stub, the ledger records - /// the platforms and (when the lock had them) every registry - /// CHECKSUMS line, a second run is a no-op, the copy verifies, and - /// revert restores the Gemfile and the lock byte for byte. + /// each platform gets the tree and stub of its own patch's gem, the + /// ledger records each tree's patch and digests and (when the lock + /// had them) every registry CHECKSUMS line, a second run is a + /// no-op, the copy verifies, and revert restores the Gemfile and + /// the lock byte for byte. The service is asked for two package + /// references: the gem patch's, then both platform patches' in one + /// request. #[tokio::test] - async fn vendors_from_prebuilds_and_reverts_byte_for_byte() { + async fn vendors_each_platform_from_its_own_patch_and_reverts_byte_for_byte() { let registry = checksums(&sha('a'), &sha('b')); for before in [None, Some(registry.as_str())] { let lock_before = lock(before); @@ -12054,7 +12520,7 @@ mod tests { assert!(result.success, "{:?}", result.error); let entry = entry.expect("a ledger entry"); - // One prebuild tree per platform, each with its own stub. + // One tree per platform, each with its own stub. let rel = rel(UUID); for platform in [DARWIN, LINUX] { let tree = root.join(&rel).join(platform); @@ -12086,8 +12552,39 @@ mod tests { vendored(&rel, bare.as_deref()) ); - // The ledger entry. - assert_eq!(entry.gem_platforms, [DARWIN, LINUX]); + // The requests: the gem patch's reference says which + // patch each locked platform's build is, the platform + // patches' references come in ONE request, and only the + // platform gems and their stubs are downloaded. + assert_eq!( + reference_requests(&server).await, + [ + vec![UUID.to_string()], + vec![build_uuid(UUID, DARWIN), build_uuid(UUID, LINUX)], + ] + ); + let mut fetched = downloads(&server).await; + fetched.sort(); + let file = |platform: &str, ext: &str| { + let own = build_uuid(UUID, platform); + format!( + "/patch/gem/nokogiri/1.18.10/tok/{own}/nokogiri-1.18.10-{platform}.{ext}" + ) + }; + let mut expected = vec![ + file(DARWIN, "gem"), + file(DARWIN, "gemspec"), + file(LINUX, "gem"), + file(LINUX, "gemspec"), + ]; + expected.sort(); + assert_eq!(fetched, expected); + + // The ledger entry: each tree's platform, patch and digests, + // in lock order, and no bare platform list. + assert_eq!(entry.gem_builds, [built(UUID, DARWIN), built(UUID, LINUX)]); + assert!(entry.gem_platforms.is_empty()); + assert_eq!(entry.uuid, UUID); assert_eq!(entry.artifact.path, rel); let inventory = entry.artifact.file_inventory.as_ref().expect("inventory"); let inventoried: Vec<&str> = inventory.keys().map(String::as_str).collect(); @@ -12139,9 +12636,11 @@ mod tests { ts::persist(&root, NOKO, entry.clone()).await; let saved = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); assert_eq!(saved, entry); - assert!(text(root.join(".socket/vendor/state.json")) - .await - .contains("\"gemPlatforms\"")); + let ledger = text(root.join(".socket/vendor/state.json")).await; + assert!(ledger.contains("\"gemBuilds\""), "{ledger}"); + assert!(ledger.contains("\"gemIntegrity\""), "{ledger}"); + assert!(ledger.contains("\"gemspecIntegrity\""), "{ledger}"); + assert!(!ledger.contains("\"gemPlatforms\""), "{ledger}"); // Verification and discovery: one vendored reference. assert_eq!( @@ -12180,64 +12679,126 @@ mod tests { } } - /// Every locked platform needs a prebuild and its stub. While the - /// service lists none for one of them (it lists a prebuild only once - /// built), a dry run and a wet run both leave the gem alone under - /// the benign pending code: they name the gem and the platforms, - /// ask the service for the package reference and nothing else, and - /// write nothing. + /// Every locked platform needs a patched build. While the gem + /// patch's reference names none for one of them (the registry + /// serves upstream's own gem for it, does not list it, or lists no + /// platform gem at all), a dry run and a wet run both leave the gem + /// alone under the benign pending code: one line that names the gem + /// and the platforms, one request (the gem patch's reference), no + /// download and nothing written. #[tokio::test] - async fn a_locked_platform_without_a_prebuild_is_a_skip_that_downloads_nothing() { - let no_stub = || Served { - stub: None, - ..served(LINUX) + async fn a_locked_platform_without_a_patched_build_is_a_skip_that_downloads_nothing() { + let listed = |platform: &'static str, listed: Listed| Served { + listed, + ..served(platform) }; - let cases: [(Vec, Vec<&str>); 3] = [ + let cases: [(Vec, bool, &str); 5] = [ + ( + vec![served(DARWIN), listed(LINUX, Listed::PassThrough)], + true, + "nokogiri@1.18.10 is not vendored: no patched build yet for x86_64-linux-gnu \ + (arm64-darwin has one). Vendored mode needs every locked platform; `scan \ + --mode hosted` can patch the others now.", + ), + ( + vec![listed(DARWIN, Listed::Unlisted), served(LINUX)], + true, + "nokogiri@1.18.10 is not vendored: no patched build yet for arm64-darwin \ + (x86_64-linux-gnu has one). Vendored mode needs every locked platform; `scan \ + --mode hosted` can patch the others now.", + ), ( - Vec::new(), vec![ - "of `nokogiri` for `arm64-darwin`, `x86_64-linux-gnu` yet", - "none of the locked platforms", + listed(DARWIN, Listed::PassThrough), + listed(LINUX, Listed::PassThrough), ], + true, + "nokogiri@1.18.10 is not vendored: no patched build yet for arm64-darwin and \ + x86_64-linux-gnu. Vendored mode needs every locked platform.", ), ( - vec![served(DARWIN)], - vec!["for `x86_64-linux-gnu` yet (it has `arm64-darwin`)"], + Vec::new(), + true, + "nokogiri@1.18.10 is not vendored: no patched build yet for arm64-darwin and \ + x86_64-linux-gnu. Vendored mode needs every locked platform.", ), + // A patch of the ruby gem alone: its reference carries no + // list of platform gems. ( - vec![served(DARWIN), no_stub()], - vec!["for `x86_64-linux-gnu` yet ("], + vec![served(DARWIN), served(LINUX)], + false, + "nokogiri@1.18.10 is not vendored: no patched build yet for arm64-darwin and \ + x86_64-linux-gnu. Vendored mode needs every locked platform.", ), ]; - for (prebuilds, expected) in cases { + for (builds, list, line) in cases { let (_tmp, root, record) = project(&lock(Some(&checksums(&sha('a'), "")))).await; let before = ts::tree_snapshot(&root); - let (server, cfg) = service(UUID, &prebuilds).await; + let (server, cfg) = serve(UUID, &builds, list).await; for dry_run in [true, false] { - let asked = ts::request_count(&server).await; let (code, detail) = unwrap_refused( vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, ); assert_eq!(code, "vendor_prebuilt_platform_pending", "{detail}"); assert!(crate::vendor::is_unserved(code)); assert!(crate::vendor::refusals::refusal_is_benign(code)); - for text in &expected { - assert!(detail.contains(text), "{detail}"); - } + assert_eq!(detail, line); + assert!(!detail.contains('\n'), "one line: {detail}"); assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); - assert_eq!( - ts::request_count(&server).await, - asked + 1, - "the package reference is the one request: no gem is downloaded" - ); } + assert_eq!( + reference_requests(&server).await, + [vec![UUID.to_string()], vec![UUID.to_string()]], + "the gem patch's reference is each run's one request" + ); + assert_eq!(downloads(&server).await, Vec::::new()); + } + } + + /// A platform the lock gains after the gem was vendored, with no + /// patched build: the vendored copy stays in force exactly as it + /// is, dry run or not, under the same benign code and one line + /// that says why it was not brought up to date. + #[tokio::test] + async fn a_vendored_gem_whose_lock_gains_an_unpatched_platform_stays_as_it_is() { + const JAVA: &str = "java"; + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + // The lock names a third platform under the vendored section. + let lock_path = root.join(GEMFILE_LOCK); + let gained = text(lock_path.clone()).await.replace( + " nokogiri (1.18.10-x86_64-linux-gnu)\n", + " nokogiri (1.18.10-java)\n racc (~> 1.4)\n nokogiri (1.18.10-x86_64-linux-gnu)\n", + ); + tokio::fs::write(&lock_path, &gained).await.unwrap(); + let before = ts::tree_snapshot(&root); + let pass_through = Served { + listed: Listed::PassThrough, + ..served(JAVA) + }; + let (server, cfg) = service(UUID, &[served(DARWIN), pass_through, served(LINUX)]).await; + for dry_run in [true, false] { + let (code, detail) = unwrap_refused( + vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, + ); + assert_eq!(code, "vendor_prebuilt_platform_pending", "{detail}"); + assert_eq!( + detail, + "nokogiri@1.18.10 was not brought up to date: no patched build yet for java \ + (arm64-darwin and x86_64-linux-gnu have one). Vendored mode needs every \ + locked platform; its vendored copy stays in force as it is." + ); + assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); } + assert_eq!(downloads(&server).await, Vec::::new()); } - /// A copy the lock is ALREADY wired to cannot wait for a prebuild. - /// When one of its trees is lost and the service does not list that - /// platform, the rebuild is the plain miss, a failure, dry run or - /// not, and what is left of the copy stays as it was. + /// A copy the lock is ALREADY wired to cannot wait for a patched + /// build when one of its trees is lost: with that platform's build + /// gone from the registry, the rebuild is the plain miss, a + /// failure, dry run or not, and what is left of the copy stays as + /// it was. #[tokio::test] async fn a_wired_copy_that_cannot_be_rebuilt_fails_instead_of_skipping() { let (_tmp, root, record) = project(&lock(None)).await; @@ -12253,7 +12814,13 @@ mod tests { vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, ); assert_eq!(code, "vendor_prebuilt_required", "{detail}"); - assert!(detail.contains("for `x86_64-linux-gnu` yet"), "{detail}"); + assert_eq!( + detail, + "nokogiri@1.18.10 was not brought up to date: no patched build yet for \ + x86_64-linux-gnu (arm64-darwin has one). Vendored mode needs every locked \ + platform; its vendored copy is missing or damaged and cannot be rebuilt \ + until then." + ); assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); } } @@ -12382,11 +12949,12 @@ mod tests { /// The installed copy of a platform-locked gem is a platform gem dir /// (`gems/nokogiri-1.18.10-arm64-darwin`): it vendors, from the - /// prebuilds and not from that dir. No archive download is planned - /// and the ruby gem is never downloaded: the package reference - /// names the prebuilds, and they are all that is fetched. + /// platforms' patches and not from that dir. No archive download is + /// planned and the ruby gem is never downloaded: the package + /// reference names the platforms' patches, and their gems are all + /// that is fetched. #[tokio::test] - async fn an_installed_platform_gem_dir_vendors_from_the_prebuilds() { + async fn an_installed_platform_gem_dir_vendors_from_the_platform_patches() { let (tmp, root, record) = project(&lock(None)).await; let installed = tmp .path() @@ -12405,7 +12973,10 @@ mod tests { let (result, entry, _) = unwrap_done(vendor(&root, &installed, &record, &cfg, false).await); assert!(result.success, "{:?}", result.error); - assert_eq!(entry.unwrap().gem_platforms, [DARWIN, LINUX]); + assert_eq!( + entry.unwrap().gem_builds, + [built(UUID, DARWIN), built(UUID, LINUX)] + ); let asked: Vec = server .received_requests() .await @@ -12421,8 +12992,9 @@ mod tests { ); assert_eq!( asked.len(), - 5, - "the package reference, then a platform gem and its stub per platform: {asked:?}" + 6, + "the gem patch's reference, the platform patches' in one request, then a \ + platform gem and its stub per platform: {asked:?}" ); assert_eq!( tokio::fs::read(root.join(rel(UUID)).join(LINUX).join(RB)) @@ -12460,18 +13032,39 @@ mod tests { let (result, entry, _) = unwrap_done(vendor(&root, &installed, &record, &cfg, false).await); assert!(result.success, "{:?}", result.error); - assert_eq!(entry.unwrap().gem_platforms, [DARWIN, LINUX]); + assert_eq!( + entry.unwrap().gem_builds, + [built(UUID, DARWIN), built(UUID, LINUX)] + ); } - /// A prebuild is verified against its served integrity like the ruby - /// gem, and a patched file it ships must be the patched one: either - /// failure refuses with nothing written. + /// A platform gem is verified against the integrity its own patch's + /// reference states, like the ruby gem, AND against the sha256 the + /// gem patch's registry lists for that platform; a patched file it + /// ships must be the patched one, and its stub usable. Each failure + /// refuses, naming the platform, with nothing written; a platform + /// whose patch serves no gem or no stub is the plain miss. #[tokio::test] - async fn a_tampered_or_unpatched_prebuild_is_refused_with_nothing_written() { + async fn a_tampered_or_unpatched_platform_gem_is_refused_with_nothing_written() { let tampered = Served { gem_sha512: Some(sri_sha512(b"some other bytes")), ..served(LINUX) }; + // The registry lists another gem for the platform than the one + // the platform's patch serves. + let not_the_listed_gem = Served { + listed_sha256: Some("ab".repeat(32)), + ..served(LINUX) + }; + let no_gem = Served { + gem: None, + listed_sha256: Some("ab".repeat(32)), + ..served(LINUX) + }; + let no_stub = Served { + stub: None, + ..served(LINUX) + }; let unpatched = Served { gem: Some(make_gem(&[(RB, RB_PRISTINE), (SO, &b"so"[..])])), ..served(LINUX) @@ -12488,10 +13081,37 @@ mod tests { ), ..served(LINUX) }; - for (bad, code) in [ - (tampered, "vendor_prebuilt_integrity_mismatch"), - (unpatched, "vendor_prebuilt_required"), - (native_stub, "native_extensions_unsupported"), + for (bad, code, says) in [ + ( + tampered, + "vendor_prebuilt_integrity_mismatch", + "failed integrity verification", + ), + ( + not_the_listed_gem, + "vendor_prebuilt_integrity_mismatch", + "is not the gem the patch registry lists for that platform", + ), + ( + no_gem, + "vendor_prebuilt_required", + "served no patched platform gem", + ), + ( + no_stub, + "vendor_prebuilt_required", + "served no stub gemspec", + ), + ( + unpatched, + "vendor_prebuilt_required", + "does not carry the patch", + ), + ( + native_stub, + "native_extensions_unsupported", + "declares native extensions", + ), ] { let (_tmp, root, record) = project(&lock(None)).await; let before = ts::tree_snapshot(&root); @@ -12501,12 +13121,48 @@ mod tests { vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, ); assert_eq!(refused, code, "{detail}"); + assert!(detail.contains(says), "{detail}"); assert!(detail.contains(LINUX), "{detail}"); + assert!(!crate::vendor::refusals::refusal_is_benign(refused)); assert_eq!(ts::tree_snapshot(&root), before, "{code} dry_run={dry_run}"); } } } + /// A mismatch against the registry's list, or against a platform + /// patch's own reference, while rebuilding a copy the lock is + /// already wired to: a hard failure that names the platform, and + /// the existing copy, the lock and the Gemfile stay as they were. + #[tokio::test] + async fn a_mismatched_platform_gem_leaves_the_existing_copy_untouched() { + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + // A damaged tree, so the next run rebuilds the copy. + let tree = root.join(rel(UUID)).join(LINUX); + tokio::fs::write(tree.join(SO), b"another binary") + .await + .unwrap(); + let before = ts::tree_snapshot(&root); + let against_the_list = Served { + listed_sha256: Some("cd".repeat(32)), + ..served(LINUX) + }; + let against_the_reference = Served { + gem_sha512: Some(sri_sha512(b"some other bytes")), + ..served(LINUX) + }; + for bad in [against_the_list, against_the_reference] { + let (_server, cfg) = service(UUID, &[served(DARWIN), bad]).await; + let (code, detail) = unwrap_refused( + vendor(&root, ¬_installed(&root), &record, &cfg, false).await, + ); + assert_eq!(code, "vendor_prebuilt_integrity_mismatch", "{detail}"); + assert!(detail.contains("nokogiri (x86_64-linux-gnu)"), "{detail}"); + assert_eq!(ts::tree_snapshot(&root), before); + } + } + /// A patch of a source the platform gem never shipped (it ships the /// compiled extension) vendors: the prebuild carries the patched /// files it does ship. One rule then judges a tree wherever it is @@ -12549,7 +13205,7 @@ mod tests { // No inventory says which files were vendored: the unshipped // source is accepted, also for an entry synthesized from the - // lock (no platforms either), which reads the trees off the + // lock (no trees named either), which reads the trees off the // artifact. let mut bare = entry.clone(); bare.artifact.file_inventory = None; @@ -12557,7 +13213,7 @@ mod tests { check_vendored_artifact(&root, &bare, &record).await, ArtifactHealth::Healthy ); - bare.gem_platforms.clear(); + bare.gem_builds.clear(); assert_eq!( check_vendored_artifact(&root, &bare, &record).await, ArtifactHealth::Healthy @@ -12615,15 +13271,21 @@ mod tests { ); } - // A platform the ledger names must be a plain directory name. + // A platform the ledger names must be a plain directory name, + // whichever field names it. let mut poisoned = entry.clone(); - poisoned.gem_platforms = vec!["../x".to_string()]; - assert_eq!( - check_vendored_artifact(&root, &poisoned, &record).await, - ArtifactHealth::Unverifiable { - reason: "vendor_path_unsafe".to_string() - } - ); + poisoned.gem_builds[0].platform = "../x".to_string(); + let mut poisoned_list = entry.clone(); + poisoned_list.gem_builds.clear(); + poisoned_list.gem_platforms = vec!["../x".to_string()]; + for poisoned in [poisoned, poisoned_list] { + assert_eq!( + check_vendored_artifact(&root, &poisoned, &record).await, + ArtifactHealth::Unverifiable { + reason: "vendor_path_unsafe".to_string() + } + ); + } } /// The usual nokogiri patch touches only files no precompiled gem @@ -12749,7 +13411,9 @@ mod tests { /// A wired copy that lost one platform's tree is rebuilt in full by /// the next run (Gemfile and lock untouched), and `repair`'s restore - /// rebuilds it from the ledger's platforms and inventory. + /// rebuilds it from the ledger alone: each tree from the patch + /// recorded for it, asked for in one request, with the gem patch's + /// own reference never asked. #[tokio::test] async fn a_lost_platform_tree_is_rebuilt_by_a_rerun_and_by_restore() { let (_tmp, root, record) = project(&lock(Some(&checksums(&sha('a'), &sha('b'))))).await; @@ -12770,7 +13434,10 @@ mod tests { "{warnings:?}" ); let rebuilt = rebuilt.expect("a refreshed entry"); - assert_eq!(rebuilt.gem_platforms, [DARWIN, LINUX]); + assert_eq!( + rebuilt.gem_builds, + [built(UUID, DARWIN), built(UUID, LINUX)] + ); assert!(rebuilt.wiring.is_empty(), "the first run's records ride on"); assert_eq!(tokio::fs::read(tree.join(RB)).await.unwrap(), RB_PATCHED); assert_eq!( @@ -12800,9 +13467,15 @@ mod tests { reason: "file_not_found".to_string() } ); + let asked = reference_requests(&server).await.len(); crate::vendor::redownload::restore(&root, &entry, &record, &cfg) .await .expect("restore"); + assert_eq!( + reference_requests(&server).await[asked..], + [vec![build_uuid(UUID, DARWIN), build_uuid(UUID, LINUX)]], + "one request, for the patches the ledger records" + ); assert_eq!( check_vendored_artifact(&root, &entry, &record).await, ArtifactHealth::Healthy @@ -12832,6 +13505,157 @@ mod tests { assert_eq!(ts::request_count(&server).await, requests); } + /// A restore checks each download against the digest the ledger + /// recorded with its tree: a platform patch that serves another gem + /// (or another stub) than the one vendored is refused, by platform, + /// and the copy stays as it was. + #[tokio::test] + async fn a_restore_refuses_a_gem_or_stub_that_is_not_the_recorded_one() { + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + tokio::fs::remove_dir_all(root.join(rel(UUID)).join(LINUX)) + .await + .unwrap(); + let before = ts::tree_snapshot(&root); + let another_gem = Served { + gem: Some(make_gem(&[(RB, RB_PATCHED), (SO, &b"another build"[..])])), + ..served(LINUX) + }; + let another_stub = Served { + stub: Some( + String::from_utf8(stub(LINUX)) + .unwrap() + .replace("fixture", "another") + .into_bytes(), + ), + ..served(LINUX) + }; + for (other, says) in [ + (another_gem, "is not the gem this copy was vendored from"), + (another_stub, "is not the one this copy was vendored with"), + ] { + let (_server, cfg) = service(UUID, &[served(DARWIN), other]).await; + let err = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect_err("a download that is not the recorded one"); + assert!( + err.starts_with("vendor_prebuilt_integrity_mismatch"), + "{err}" + ); + assert!(err.contains(says), "{err}"); + assert!(err.contains("nokogiri (x86_64-linux-gnu)"), "{err}"); + assert_eq!(ts::tree_snapshot(&root), before); + } + } + + /// A ledger entry that names the platforms of its copy and no patch + /// for their trees (`gemPlatforms`): the copy still verifies against + /// the gem patch's record and still reverts byte for byte; a + /// restore answers that it must be vendored again; and the next + /// vendor run rebuilds it from each platform's own patch and + /// records them, the wiring untouched. While a locked platform has + /// no patched build, that run leaves the copy in force instead. + #[tokio::test] + async fn an_entry_that_names_only_platforms_verifies_reverts_and_is_converted() { + let lock_before = lock(Some(&checksums(&sha('a'), &sha('b')))); + let (_tmp, root, record) = project(&lock_before).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let current = vendor_and_persist(&root, &record, &cfg).await; + // The entry as an earlier build wrote it. + let mut old = current.clone(); + old.gem_builds.clear(); + old.gem_platforms = vec![DARWIN.to_string(), LINUX.to_string()]; + ts::persist(&root, NOKO, old.clone()).await; + let saved = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + assert_eq!(saved.gem_platforms, [DARWIN, LINUX]); + assert!(saved.gem_builds.is_empty()); + assert_eq!(saved.gem_tree_platforms(), [DARWIN, LINUX]); + + // `vendor --check`'s verdict. + assert_eq!( + check_vendored_artifact(&root, &saved, &record).await, + ArtifactHealth::Healthy + ); + // `repair`'s restore has no patch to fetch the trees by. + let err = crate::vendor::redownload::restore(&root, &saved, &record, &cfg) + .await + .expect_err("no patch is recorded for the trees"); + assert!( + err.contains("names no patch for the platform gems"), + "{err}" + ); + assert!(err.contains("scan --mode vendored"), "{err}"); + + // A run while one platform has no patched build keeps the copy. + let wired = ts::tree_snapshot(&root); + let pass_through = Served { + listed: Listed::PassThrough, + ..served(LINUX) + }; + let (_server, partial) = service(UUID, &[served(DARWIN), pass_through]).await; + let (code, detail) = unwrap_refused( + vendor(&root, ¬_installed(&root), &record, &partial, false).await, + ); + assert_eq!(code, "vendor_prebuilt_platform_pending", "{detail}"); + assert!( + detail.ends_with("its vendored copy stays in force as it is."), + "{detail}" + ); + assert_eq!(ts::tree_snapshot(&root), wired); + + // The next run with every platform patched converts the entry. + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let (result, converted, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let rebuilt = warnings + .iter() + .find(|w| w.code == "vendor_artifact_rebuilt") + .unwrap_or_else(|| panic!("{warnings:?}")); + assert!( + rebuilt + .detail + .contains("was recorded with no patch named for its platform gems"), + "{}", + rebuilt.detail + ); + assert_eq!( + reference_requests(&server).await, + [ + vec![UUID.to_string()], + vec![build_uuid(UUID, DARWIN), build_uuid(UUID, LINUX)], + ] + ); + ts::persist(&root, NOKO, converted.expect("a refreshed entry")).await; + let saved = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + assert_eq!(saved.gem_builds, [built(UUID, DARWIN), built(UUID, LINUX)]); + assert!(saved.gem_platforms.is_empty(), "the bare list is not kept"); + assert_eq!( + saved.wiring, current.wiring, + "the first run's records ride on" + ); + assert_eq!( + text(root.join(GEMFILE_LOCK)).await, + vendored(&rel(UUID), Some(&checksums("", ""))) + ); + // In sync from here on. + let requests = ts::request_count(&server).await; + let (again, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!(ts::request_count(&server).await, requests); + + // Revert of the entry as the earlier build wrote it. + let reverted = revert_gem(&old, &root, false).await; + assert!(reverted.success, "{:?}", reverted.error); + assert!(reverted.warnings.is_empty(), "{:?}", reverted.warnings); + assert_eq!(text(root.join(GEMFILE)).await, GEMFILE_NOKO); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock_before); + assert!(!root.join(".socket/vendor/gem").exists()); + } + /// A lock wired to the copy whose CHECKSUMS entry of one platform /// still carries a registry token is not in sync: refused with the /// repair path, like the plain entry's. @@ -12885,7 +13709,10 @@ mod tests { let (_server, cfg) = service(UUID_B, &[served(DARWIN), served(LINUX)]).await; let second = vendor_and_persist(&root, &record_b, &cfg).await; assert_eq!(second.uuid, UUID_B); - assert_eq!(second.gem_platforms, [DARWIN, LINUX]); + assert_eq!( + second.gem_builds, + [built(UUID_B, DARWIN), built(UUID_B, LINUX)] + ); assert_eq!( text(root.join(GEMFILE_LOCK)).await, vendored(&rel(UUID_B), Some(&checksums("", ""))) @@ -12900,6 +13727,40 @@ mod tests { assert!(!root.join(format!(".socket/vendor/gem/{UUID_B}")).exists()); } + /// A newer patch of a gem already vendored, with a locked platform + /// that has no patched build yet: the copy of the earlier patch + /// stays wired and untouched, and the skip's one line says so. + #[tokio::test] + async fn a_newer_patch_with_an_unpatched_platform_keeps_the_earlier_copy() { + let (_tmp, root, record_a) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + vendor_and_persist(&root, &record_a, &cfg).await; + let before = ts::tree_snapshot(&root); + let record_b = PatchRecord { + uuid: UUID_B.to_string(), + ..record_a.clone() + }; + let pass_through = Served { + listed: Listed::PassThrough, + ..served(LINUX) + }; + let (server, cfg) = service(UUID_B, &[served(DARWIN), pass_through]).await; + for dry_run in [true, false] { + let (code, detail) = unwrap_refused( + vendor(&root, ¬_installed(&root), &record_b, &cfg, dry_run).await, + ); + assert_eq!(code, "vendor_prebuilt_platform_pending", "{detail}"); + assert_eq!( + detail, + "nokogiri@1.18.10 was not brought up to date: no patched build yet for \ + x86_64-linux-gnu (arm64-darwin has one). Vendored mode needs every locked \ + platform; its vendored copy of an earlier patch stays in force as it is." + ); + assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); + } + assert_eq!(downloads(&server).await, Vec::::new()); + } + /// What git says of `path` (project-relative) in the work tree at /// `root`: `git -- `, trimmed. fn git(root: &Path, args: &[&str], path: &str) -> String { diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index e682769180..6333180ea4 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -135,8 +135,8 @@ pub use pnpm_lock::rush::wiring_files as rush_wiring_files; pub use pypi_requirements::requirements_include_names; pub use state::{ carry_forward_wiring, file_gitignored, ledger_gitignore_refusal, load_state, lookup_entry, - lookup_entry_kv, purl_keys_cover, save_state, save_state_shared, VendorEntry, VendorState, - LEDGER_GITIGNORED, VENDOR_STATE_REL, + lookup_entry_kv, purl_keys_cover, save_state, save_state_shared, GemBuildEntry, VendorEntry, + VendorState, LEDGER_GITIGNORED, VENDOR_STATE_REL, }; pub use verify::{ artifact_is_file_shaped, check_vendored_artifact, compute_dir_inventory, @@ -728,13 +728,14 @@ pub const VENDOR_PREBUILT_UNAVAILABLE: &str = "vendor_prebuilt_unavailable"; /// no older vendored patch to keep. pub const VENDOR_PREBUILT_REQUIRED: &str = "vendor_prebuilt_required"; -/// gem: `Gemfile.lock` pins the gem as precompiled platform gems and the -/// patch service lists no prebuilt platform gem for at least one of the -/// locked platforms. The service lists a prebuild only once it is built, so -/// "not built yet" and "never built" look the same from here: the package -/// is left as it is and the run does not fail because of it, with or -/// without an older vendored patch to keep (see [`VENDOR_PREBUILT_PENDING`] -/// for the kept one). A re-run vendors it once every platform has one. +/// gem: `Gemfile.lock` pins the gem as precompiled platform gems and at +/// least one of the locked platforms has no patched build: the gem +/// patch's registry serves upstream's own gem for it, or does not list it. +/// A patched build is named only once it is published, so "not yet" and +/// "never" look the same from here: the package is left as it is and the +/// run does not fail because of it, whether or not an earlier vendored +/// copy stays in force (the detail says which). A re-run vendors it once +/// every locked platform has one. pub const VENDOR_PREBUILT_PLATFORM_PENDING: &str = "vendor_prebuilt_platform_pending"; /// Whether `code` marks a patch the service does not serve (yet): diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 71ba3784f2..4cbb8d257b 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -250,11 +250,16 @@ pub async fn restore( .await?; } "gem" => { - let (name, _) = + let (name, version) = parse_gem_purl(&entry.base_purl).ok_or("invalid gem coordinates")?; - // A gem vendored as platform gems is restored from the - // prebuild of each platform the ledger names. - let copied = match entry.gem_platforms.as_slice() { + // A gem vendored as platform gems is restored tree by tree, + // each from the patch the ledger records for it and against + // the digests recorded with it. An entry that names its + // platforms and no patch has nothing to fetch them by. + let copied = match entry.gem_builds.as_slice() { + [] if !entry.gem_platforms.is_empty() => { + return Err(super::gem::UNATTRIBUTED_TREES.into()); + } [] => { super::gem::gem_service_copy( Some(service), @@ -267,18 +272,24 @@ pub async fn restore( ) .await } - platforms => { + builds => { + let trees = super::gem::PlatformTrees { + gem: &format!("{name}@{version}"), + from: super::gem::BuildsFrom::Recorded(builds), + standing: super::gem::Standing::Wired, + }; super::gem::gem_platform_service_copy( Some(service), record, &name, - platforms, + &trees, &stage, uuid_dir, true, &mut warnings, ) .await + .map(|_| ()) } }; copied.map_err(|outcome| detail(*outcome))?; @@ -422,9 +433,9 @@ pub async fn restore( } // Likewise a gem vendored as platform gems: only the artifact dir was // swapped in from the stage, and without the uuid dir's own metadata a - // `*.so` / `*.bundle` rule drops the prebuilt binaries from the commit. + // `*.so` / `*.bundle` rule drops the compiled binaries from the commit. let archive = super::gem::bazel::is_archive(entry); - if entry.ecosystem == "gem" && (archive || !entry.gem_platforms.is_empty()) { + if entry.ecosystem == "gem" && (archive || !entry.gem_tree_platforms().is_empty()) { if let Some(rel) = super::path::vendor_uuid_dir_rel("gem", &entry.uuid) { super::gem::restore_uuid_metadata(&root.join(rel)) .await diff --git a/crates/socket-patch-core/src/vendor/service_fetch.rs b/crates/socket-patch-core/src/vendor/service_fetch.rs index eca4508e14..886b8aa4eb 100644 --- a/crates/socket-patch-core/src/vendor/service_fetch.rs +++ b/crates/socket-patch-core/src/vendor/service_fetch.rs @@ -7,8 +7,9 @@ //! (`IntegrityMismatch`), never a silent fallback to a wrong artifact. The //! backends own the placement: write the archive or extract it into a directory. -use crate::api::client::{SecondaryArtifact, VendorServiceOutcome}; +use crate::api::client::{SecondaryArtifact, VendorReference, VendorServiceOutcome}; use crate::manifest::schema::PatchRecord; +use crate::patch::redirect::GemPlatformChecksum; use crate::vendor::lock_inventory::LockIntegrity; use crate::vendor::registry_fetch::{artifact_matches_integrity, verify_go_h1}; use crate::vendor::VendorServiceConfig; @@ -112,25 +113,41 @@ pub(crate) fn downloaded_warning( ) } -/// What the patch service lists for a patch besides its archive, learned -/// from the package reference alone ([`fetch_served_artifacts`]): still -/// unverified, and nothing of the patch is downloaded yet. +/// What the patch service's package reference says of a patch +/// ([`fetch_served_reference`]): still unverified, and nothing of the patch +/// is downloaded yet. #[derive(Debug)] -pub(crate) struct ServedArtifacts(pub Vec); +pub(crate) struct ServedReference { + /// The archive, when the reference gives it a url and a sha512. + pub archive: Option, + /// The other served artifacts (a gem's stub gemspec, …). + pub secondary: Vec, + /// gem: the platform gems of the gem's version as the patch's registry + /// serves them, each with the patch of its patched build if it has + /// one; `None` when the reference carries no list. + pub gem_builds: Option>, +} + +impl ServedReference { + /// The served secondary artifact of `kind`, if the service lists one. + pub(crate) fn secondary(&self, kind: &str) -> Option<&SecondaryArtifact> { + self.secondary.iter().find(|a| a.kind == kind) + } +} -impl ServedArtifacts { - /// The served artifact of `kind` for the gem platform `platform`, if - /// the service lists one. - pub(crate) fn platform(&self, kind: &str, platform: &str) -> Option<&SecondaryArtifact> { - self.0 - .iter() - .find(|a| a.kind == kind && a.platform.as_deref() == Some(platform)) +impl From for ServedReference { + fn from(reference: VendorReference) -> Self { + Self { + archive: reference.archive, + secondary: reference.secondary, + gem_builds: reference.gem_builds, + } } } /// What the service has for a patch: its verified archive -/// ([`fetch_verified_archive`]), or the list of its other artifacts -/// ([`fetch_served_artifacts`]). +/// ([`fetch_verified_archive`]), or what its package reference says +/// ([`fetch_served_reference`]). #[derive(Debug)] pub(crate) enum ServiceArtifact { Ready(T), @@ -202,14 +219,16 @@ pub(crate) async fn fetch_verified_archive( }) } -/// Ask the service which artifacts it serves for `uuid` besides the -/// archive, without downloading the archive: the package reference names -/// them. For a backend that vendors only those (a gem's per-platform -/// prebuilds), so a patch that has none costs one request and no download. -pub(crate) async fn fetch_served_artifacts( +/// Ask the service for the package reference of `uuid` without downloading +/// anything: it names the patch's artifacts and, for a gem, the platform +/// gems its registry serves. For a backend that vendors from other patches +/// than `uuid`'s own archive (a gem's platform gems), so a gem with a +/// locked platform that has no patched build costs one request and no +/// download. +pub(crate) async fn fetch_served_reference( cfg: &VendorServiceConfig, uuid: &str, -) -> ServiceArtifact { +) -> ServiceArtifact { let Some(client) = cfg.client.as_ref() else { return ServiceArtifact::Unavailable("vendor service not configured".to_string()); }; @@ -221,10 +240,36 @@ pub(crate) async fn fetch_served_artifacts( cfg.patch_server_url.as_deref(), ) .await; + served_reference(outcome) +} + +/// [`fetch_served_reference`] for several patches in ONE request: the +/// answer for each of `uuids`, in their order. `Err` (a log reason) when +/// the request itself failed, so nothing is known of any of them. +pub(crate) async fn fetch_served_references( + cfg: &VendorServiceConfig, + uuids: &[String], +) -> Result>, String> { + let Some(client) = cfg.client.as_ref() else { + return Err("vendor service not configured".to_string()); + }; + let outcomes = client + .fetch_vendor_references( + uuids, + cfg.use_public_proxy, + cfg.vendor_url.as_deref(), + cfg.patch_server_url.as_deref(), + ) + .await + .map_err(|e| e.to_string())?; + Ok(outcomes.into_iter().map(served_reference).collect()) +} + +fn served_reference( + outcome: VendorServiceOutcome, +) -> ServiceArtifact { match outcome { - VendorServiceOutcome::Ready(artifacts) => { - ServiceArtifact::Ready(ServedArtifacts(artifacts)) - } + VendorServiceOutcome::Ready(reference) => ServiceArtifact::Ready(reference.into()), VendorServiceOutcome::Pending => ServiceArtifact::Pending, VendorServiceOutcome::Unavailable(reason) => ServiceArtifact::Unavailable(reason), VendorServiceOutcome::Failed(err) => ServiceArtifact::Failed(err.to_string()), @@ -382,22 +427,9 @@ pub(crate) async fn fetch_verified_secondary( fetch_verified_artifact(cfg, archive.secondary.iter().find(|a| a.kind == kind)).await } -/// [`fetch_verified_secondary`] for an artifact served once per gem -/// platform (`gem-platform`, `gem-platform-stub-gemspec`): the one of -/// `kind` whose `platform` is exactly `platform`, the token `Gemfile.lock` -/// spells. -pub(crate) async fn fetch_verified_platform_secondary( - cfg: &VendorServiceConfig, - served: &ServedArtifacts, - kind: &str, - platform: &str, -) -> SecondaryArtifactResult { - fetch_verified_artifact(cfg, served.platform(kind, platform)).await -} - /// Download `artifact` and verify the bytes against its own sha512 SRI; /// `Absent` when the service referenced no such artifact. -async fn fetch_verified_artifact( +pub(crate) async fn fetch_verified_artifact( cfg: &VendorServiceConfig, artifact: Option<&SecondaryArtifact>, ) -> SecondaryArtifactResult { @@ -831,7 +863,6 @@ mod tests { secondary: vec![SecondaryArtifact { prefetched: None, kind: "gem-stub-gemspec".into(), - platform: None, url: format!("{}/stub", server.uri()), integrity_sri: PackedTarball::from_bytes(b"x").integrity, }], diff --git a/crates/socket-patch-core/src/vendor/state.rs b/crates/socket-patch-core/src/vendor/state.rs index 50989a413c..1265bda9f9 100644 --- a/crates/socket-patch-core/src/vendor/state.rs +++ b/crates/socket-patch-core/src/vendor/state.rs @@ -317,13 +317,20 @@ pub struct VendorEntry { /// pypi/pipenv extras. #[serde(default, skip_serializing_if = "Option::is_none")] pub pipenv: Option, - /// gem: the platforms of a gem vendored as precompiled platform gems, - /// in `Gemfile.lock` order (`arm64-darwin`, `x86_64-linux-gnu`, …). - /// The artifact dir then holds one unpacked prebuild per platform, at + /// gem: the trees of a gem vendored as precompiled platform gems, in + /// `Gemfile.lock` order. The artifact dir then holds one unpacked + /// patched platform gem per locked platform, at /// `//`, instead of the gem's own tree: bundler /// never builds a `path:` gem's extensions, so a gem the lock resolves - /// to platform gems is vendored as the patch service's prebuilt ones. - /// Empty for a gem vendored as its ruby-platform tree. + /// to platform gems is vendored as the patch service's patched ones, + /// each from the patch of its own platform. Empty for a gem vendored + /// as its ruby-platform tree. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub gem_builds: Vec, + /// gem: the platforms of such a copy as an entry without + /// [`Self::gem_builds`] names them, with no patch per tree. Read only: + /// the copy verifies and reverts by it, and the next vendor run + /// records [`Self::gem_builds`] in its place. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub gem_platforms: Vec, /// True when vendored WITHOUT a manifest record — the posture of every @@ -351,7 +358,62 @@ pub struct VendorEntry { pub record: Option, } +/// One tree of a gem vendored as precompiled platform gems +/// ([`VendorEntry::gem_builds`]): `//`. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct GemBuildEntry { + /// `Gem::Platform#to_s` as `Gemfile.lock` spells it. + pub platform: String, + /// The patch of this platform gem: the one the tree was unpacked from. + pub uuid: String, + /// The sha512 (SRI) of the patched platform `.gem` the tree was + /// unpacked from, as the patch service stated it and the download was + /// verified against. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub gem_integrity: String, + /// The sha512 (SRI) of the stub gemspec the tree holds, likewise. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub gemspec_integrity: String, +} + +impl GemBuildEntry { + /// The purl of this platform gem of the gem `base_purl`: + /// `pkg:gem/@?platform=`. + pub fn purl(&self, base_purl: &str) -> String { + format!( + "{}?platform={}", + crate::utils::purl::strip_purl_qualifiers(base_purl), + self.platform + ) + } +} + impl VendorEntry { + /// gem: whether every tree of [`Self::gem_builds`] names a plain gem + /// platform token. The ledger is committed, tamper-able data, and a + /// platform names a directory and a purl qualifier. + pub fn gem_builds_well_formed(&self) -> bool { + self.gem_builds + .iter() + .all(|built| super::gem::is_platform_dir_name(&built.platform)) + } + + /// gem: the platforms of a copy vendored as precompiled platform gems, + /// in lock order: those of [`Self::gem_builds`], else the ones an + /// entry without them names ([`Self::gem_platforms`]). Empty for a gem + /// vendored as its ruby-platform tree. + pub fn gem_tree_platforms(&self) -> Vec<&str> { + match self.gem_builds.is_empty() { + false => self + .gem_builds + .iter() + .map(|built| built.platform.as_str()) + .collect(), + true => self.gem_platforms.iter().map(String::as_str).collect(), + } + } + /// Create an entry with no ecosystem-specific metadata or embedded record. pub fn new( ecosystem: String, @@ -374,6 +436,7 @@ impl VendorEntry { poetry: None, pdm: None, pipenv: None, + gem_builds: Vec::new(), gem_platforms: Vec::new(), detached: false, record: None, @@ -1929,6 +1992,91 @@ mod tests { assert!(back_entry.record.is_none()); } + /// A gem vendored as platform gems records each tree's platform, patch + /// and digests under `gemBuilds`, and writes no `gemPlatforms`. An + /// entry that names only its platforms still reads, and round-trips as + /// it is. An item with fields this build does not know (a development + /// build wrote `record` and `rebuiltFromUuid` there) reads too, those + /// fields ignored. + #[tokio::test] + async fn gem_builds_round_trip_and_older_entries_still_read() { + const BUILD: &str = "2b3c4d5e-6f70-4a1b-8c2d-9e0f1a2b3c4d"; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let mut entry = sample_entry(); + entry.ecosystem = "gem".into(); + entry.base_purl = "pkg:gem/nokogiri@1.18.10".into(); + entry.gem_builds = vec![ + GemBuildEntry { + platform: "arm64-darwin".into(), + uuid: BUILD.into(), + gem_integrity: "sha512-GEM==".into(), + gemspec_integrity: "sha512-STUB==".into(), + }, + GemBuildEntry { + platform: "x86_64-linux-gnu".into(), + uuid: UUID.into(), + gem_integrity: String::new(), + gemspec_integrity: String::new(), + }, + ]; + assert_eq!( + entry.gem_tree_platforms(), + ["arm64-darwin", "x86_64-linux-gnu"] + ); + let key = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let mut state = VendorState::new(); + state.entries.insert(key.into(), entry.clone()); + save_state(root, &state).await.unwrap(); + assert_eq!(load_state(root).await.unwrap(), state); + let text = tokio::fs::read_to_string(root.join(VENDOR_STATE_REL)) + .await + .unwrap(); + let wire: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!( + wire["entries"][key]["gemBuilds"], + serde_json::json!([ + { "platform": "arm64-darwin", "uuid": BUILD, + "gemIntegrity": "sha512-GEM==", "gemspecIntegrity": "sha512-STUB==" }, + { "platform": "x86_64-linux-gnu", "uuid": UUID } + ]) + ); + assert!(!text.contains("gemPlatforms"), "{text}"); + + // An entry that names its platforms and no patch for their trees. + let mut older = wire.clone(); + let older_entry = older["entries"][key].as_object_mut().unwrap(); + older_entry.remove("gemBuilds"); + older_entry.insert( + "gemPlatforms".into(), + serde_json::json!(["arm64-darwin", "x86_64-linux-gnu"]), + ); + let read: VendorState = serde_json::from_value(older.clone()).unwrap(); + let read_entry = &read.entries[key]; + assert!(read_entry.gem_builds.is_empty()); + assert_eq!( + read_entry.gem_tree_platforms(), + ["arm64-darwin", "x86_64-linux-gnu"] + ); + assert_eq!(serde_json::to_value(&read).unwrap(), older, "kept as it is"); + + // Items with fields this build does not know. + let mut extended = wire; + for item in extended["entries"][key]["gemBuilds"] + .as_array_mut() + .unwrap() + { + let item = item.as_object_mut().unwrap(); + item.insert("rebuiltFromUuid".into(), serde_json::json!(UUID)); + item.insert( + "record".into(), + serde_json::json!({ "uuid": BUILD, "files": {}, "anything": [1, 2] }), + ); + } + let read: VendorState = serde_json::from_value(extended).unwrap(); + assert_eq!(read.entries[key].gem_builds, entry.gem_builds); + } + #[tokio::test] async fn v2_meta_structs_round_trip_with_camel_case() { let tmp = tempfile::tempdir().unwrap(); @@ -2633,6 +2781,7 @@ mod tests { poetry: None, pdm: None, pipenv: None, + gem_builds: Vec::new(), gem_platforms: Vec::new(), }; let built = VendorEntry::npm( diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 0e9785611f..85d48ec686 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -284,17 +284,17 @@ async fn gem_platform_trees( if entry.ecosystem != "gem" { return Ok(None); } - if !entry.gem_platforms.is_empty() { + let platforms = entry.gem_tree_platforms(); + if !platforms.is_empty() { // SECURITY: state.json is committed and tamper-able, and each // platform is about to name a directory that gets stat'd and hashed. - if !entry - .gem_platforms + if !platforms .iter() .all(|platform| super::gem::is_platform_dir_name(platform)) { return Err("vendor_path_unsafe".to_string()); } - let trees = entry.gem_platforms.iter().map(|p| artifact.join(p)); + let trees = platforms.iter().map(|p| artifact.join(p)); return Ok(Some(trees.collect())); } let Some((name, _)) = crate::utils::purl::parse_gem_purl(&entry.base_purl) else { From c91e968fc32e8964c6f10e0c66cd71e195b6e1c7 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 19:20:38 -0500 Subject: [PATCH 006/120] Leave the patches of platform gems out of a vendored selection Each patched platform gem has a patch of its own (`pkg:gem/@?platform=`), which a package search returns beside the patch of the gem itself. Agent mode takes it for the installed copy of that platform. Vendored mode patches a gem through the patch of the gem itself, whose reference names the patched build of every locked platform, so there the platform gem's patch is no fix of its own: selected as one, it reached the gem backend and failed as `platform_gem_unsupported`, or made the gem's records ambiguous. `scan --mode vendored` now drops those patches from the batch offers and from the selection (`ScanPolicy::leave_out_platform_gem_patches`), and `get --mode vendored` from its search results, before anything is reported, downloaded or handed to the vendor engine. A platform gem's patch named by its UUID in `get` is the caller's exact intent and still reaches the backend's own refusal. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/get.rs | 9 ++ .../src/commands/scan/discovery.rs | 92 +++++++++++++++++++ .../socket-patch-cli/src/commands/scan/mod.rs | 11 ++- .../src/commands/scan/policy.rs | 56 +++++++++++ 4 files changed, 167 insertions(+), 1 deletion(-) diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index c418c32af0..5043c3eaed 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -1716,6 +1716,15 @@ pub async fn run(args: GetArgs) -> i32 { search_response .patches .retain(|p| args.common.purl_ecosystem_selected(&p.purl)); + // A vendored run patches a gem through the patch of the gem itself: the + // patch of one of its platform gems, which a search returns beside it, + // is no fix of its own there. (One named by its UUID is the caller's + // exact intent, and reaches the backend's own refusal.) + if mode == super::scan::ScanMode::Vendored { + search_response + .patches + .retain(|p| !super::scan::is_platform_gem_patch(&p.purl)); + } if search_response.patches.is_empty() { if args.common.json { diff --git a/crates/socket-patch-cli/src/commands/scan/discovery.rs b/crates/socket-patch-cli/src/commands/scan/discovery.rs index 478df431a3..8bf43ecd34 100644 --- a/crates/socket-patch-cli/src/commands/scan/discovery.rs +++ b/crates/socket-patch-cli/src/commands/scan/discovery.rs @@ -125,6 +125,32 @@ pub(crate) async fn lockfile_supplement( out } +/// Whether `purl` names the patch of one platform gem +/// (`pkg:gem/@?platform=`, any platform but +/// `ruby`): what an installed copy of that platform gem takes in place. +/// +/// A vendored run patches a gem through the patch of the gem itself, whose +/// package reference names the patched build of every platform the +/// Bundler lock resolves. The patch of a platform gem is no fix of its own +/// there: a vendored selection leaves it out before anything is reported, +/// downloaded or handed to the engine ([`drop_platform_gem_patches`]). +pub(crate) fn is_platform_gem_patch(purl: &str) -> bool { + Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) + && socket_patch_core::utils::purl::purl_qualifier(purl, "platform") + .is_some_and(|platform| !platform.is_empty() && !platform.eq_ignore_ascii_case("ruby")) +} + +/// Take the patches of platform gems ([`is_platform_gem_patch`]) out of +/// `packages`, and the packages left with no patch on offer. +pub(super) fn drop_platform_gem_patches(packages: &mut Vec) { + for package in packages.iter_mut() { + package + .patches + .retain(|patch| !is_platform_gem_patch(&patch.purl)); + } + packages.retain(|package| !package.patches.is_empty()); +} + /// The purls of the jars that the pinned rules_jvm_external hubs of a Bazel /// workspace fetch when `--cwd` is its root, what was not read of its hubs /// and the entries of its block that are stale @@ -1103,6 +1129,72 @@ mod tests { } } + /// A vendored run patches a gem through the patch of the gem itself. + /// The patches of its platform gems, which a search returns beside it, + /// are taken out of the offers before anything is reported or + /// downloaded: the gem keeps its own patch, a gem offered nothing else + /// leaves the list, and the release variants of every other ecosystem + /// (and a gem's `ruby` platform) stay. + #[test] + fn a_vendored_selection_leaves_out_the_patches_of_platform_gems() { + let offer = |package: &str, patches: &[(&str, &str)]| { + let mut package = batch_with(package, &[]); + for (uuid, purl) in patches { + let mut patch = batch_with(purl, &[uuid]).patches.remove(0); + patch.purl = (*purl).to_string(); + package.patches.push(patch); + } + package + }; + let mut packages = vec![ + offer( + "pkg:gem/nokogiri@1.18.10", + &[ + ( + "linux", + "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + ), + ("source", "pkg:gem/nokogiri@1.18.10?platform=ruby"), + ("darwin", "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"), + ], + ), + offer( + "pkg:gem/ffi@1.17.0", + &[("java", "pkg:gem/ffi@1.17.0?platform=java")], + ), + offer("pkg:gem/rack@3.1.8", &[("rack", "pkg:gem/rack@3.1.8")]), + offer( + "pkg:pypi/six@1.16.0", + &[("wheel", "pkg:pypi/six@1.16.0?artifact_id=py2.py3-none-any")], + ), + ]; + drop_platform_gem_patches(&mut packages); + let left: Vec<(&str, Vec<&str>)> = packages + .iter() + .map(|package| { + let uuids = package.patches.iter().map(|patch| patch.uuid.as_str()); + (package.purl.as_str(), uuids.collect()) + }) + .collect(); + assert_eq!( + left, + [ + ("pkg:gem/nokogiri@1.18.10", vec!["source"]), + ("pkg:gem/rack@3.1.8", vec!["rack"]), + ("pkg:pypi/six@1.16.0", vec!["wheel"]), + ] + ); + assert!(is_platform_gem_patch("pkg:gem/a@1?platform=x64-mingw-ucrt")); + for kept in [ + "pkg:gem/a@1", + "pkg:gem/a@1?platform=ruby", + "pkg:gem/a@1?platform=", + "pkg:npm/a@1?platform=java", + ] { + assert!(!is_platform_gem_patch(kept), "{kept}"); + } + } + fn batch_with(purl: &str, uuids: &[&str]) -> BatchPackagePatches { BatchPackagePatches { purl: purl.to_string(), diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 41fcf01501..883755a2c1 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -70,7 +70,7 @@ use self::discovery::{ // and vendored-ledger crawl supplements. `pub(crate)` re-exports because // the submodules themselves stay private to scan. pub(crate) use self::discovery::{ - lockfile_supplement as project_lockfile_supplement, + is_platform_gem_patch, lockfile_supplement as project_lockfile_supplement, vendored_ledger_supplement as project_vendored_supplement, }; use self::gc::gc_into; @@ -2408,6 +2408,10 @@ async fn scan_project( let apply = args.mode == Some(ScanMode::Agent); let vendor = args.mode == Some(ScanMode::Vendored); let hosted = args.mode == Some(ScanMode::Hosted); + // A vendored run patches a gem through the patch of the gem itself. + if vendor { + policy.leave_out_platform_gem_patches(); + } // `patches.enabled: false` writes nothing, the GC included. let prune = (args.prune || args.sync) && policy.writes_allowed(); @@ -3395,6 +3399,11 @@ async fn scan_project( // drives the report, the `--json` `packages` array and the apply order, // which operators diff across runs. all_packages_with_patches.sort_by(|a, b| a.purl.cmp(&b.purl)); + // A vendored run patches a gem through the patch of the gem itself: the + // patch of one of its platform gems is no offer of its own there. + if vendor { + discovery::drop_platform_gem_patches(&mut all_packages_with_patches); + } // #604: a patch the API returned under an equivalent spelling of a // lockfile-only PyPI pin is that lockfile-only package. adopt_pypi_equivalents( diff --git a/crates/socket-patch-cli/src/commands/scan/policy.rs b/crates/socket-patch-cli/src/commands/scan/policy.rs index 616ccac1ae..c0f081d627 100644 --- a/crates/socket-patch-cli/src/commands/scan/policy.rs +++ b/crates/socket-patch-cli/src/commands/scan/policy.rs @@ -192,6 +192,9 @@ pub(crate) struct ScanPolicy { recorded: HashMap, nested: Option, report: Mutex, + /// The run does not take the patch of a platform gem as an offer of + /// its own ([`Self::leave_out_platform_gem_patches`]). + no_platform_gem_patches: bool, } impl ScanPolicy { @@ -235,9 +238,19 @@ impl ScanPolicy { recorded: HashMap::new(), nested: None, report: Mutex::new(report), + no_platform_gem_patches: false, } } + /// Have [`Self::select`] leave out the patches of platform gems + /// ([`super::discovery::is_platform_gem_patch`]), which a package + /// search returns beside the patch of the gem itself. A vendored run + /// patches a gem through that one alone, so the others are no offers + /// there: nothing is selected, reported or downloaded for them. + pub(crate) fn leave_out_platform_gem_patches(&mut self) { + self.no_platform_gem_patches = true; + } + /// Judge crawled copies under a nested project's `node_modules` by that /// project's own root (agent and report-only scans, which patch the /// crawled copies in place, see [`NestedRoots`]). A nested root is a @@ -587,6 +600,11 @@ impl ScanPolicy { { continue; } + if self.no_platform_gem_patches + && super::discovery::is_platform_gem_patch(&offer.purl) + { + continue; + } grouped.entry(offer.purl.clone()).or_default().push(offer); } } @@ -1158,6 +1176,44 @@ mod tests { .collect() } + /// A package search returns the patches of a gem's platform gems + /// beside the patch of the gem itself, and every one of them is an + /// offer under its own purl. A run told to leave them out (a vendored + /// run) selects the gem's own patch alone, and reports nothing of the + /// others: they are in no list, withheld or filtered. + #[test] + fn a_vendored_selection_takes_a_gem_through_its_own_patch_alone() { + let of = |uuid: &str, purl: &str| { + let mut offer = offer(uuid, &[(HIGH, "high")]); + offer.purl = purl.to_string(); + offer + }; + let source = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let linux = "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu"; + let darwin = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let offers = || { + let another = "cccccccc-0000-4000-8000-000000000001"; + vec![of(A1, linux), of(B1, source), of(another, darwin)] + }; + + let agent = filtered_policy("", r#"{"version": 1}"#, None); + let all = agent.select(offers()); + assert_eq!( + all.selected.keys().collect::>(), + [darwin, source, linux], + "every other mode offers each platform gem's patch" + ); + + let mut vendored = filtered_policy("", r#"{"version": 1}"#, None); + vendored.leave_out_platform_gem_patches(); + let own = vendored.select(offers()); + assert_eq!(own.selected.keys().collect::>(), [source]); + assert_eq!(own.selected[source].uuid, B1); + assert_eq!(own.unfiltered.keys().collect::>(), [source]); + assert!(own.withheld.is_empty()); + assert!(filtered_entries(&vendored).is_empty()); + } + /// The filter never changes how patches rank: a merged patch that fixes /// one needed advisory is wanted whole, its unreachable critical /// included, and wins as it always would. Only a patch that fixes From d33ed462bb47d9626d93ed21298c95f5bfeadbed Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 19:20:46 -0500 Subject: [PATCH 007/120] Attest each vendored platform gem under its own patch A gem vendored as platform gems is one committed copy, verified as one against the record of the gem's patch. What an install loads from it is one platform gem's tree, and each tree was built by a patch of its own, which the vendor ledger records. A VEX document that named the gem under the gem's patch said nothing a scanner could match to the platform gem it found, nor which patch built it. So the document names each platform gem (`pkg:gem/@?platform=`) under the patch of its tree, with the vulnerabilities of the gem patch's record: the fix is the same in every one of them. The copy is still verified once, before the view is widened, and nothing is fetched: the ledger entry says which patch built which tree. An entry that names no patch for its trees is attested as the gem itself, as before. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/vex.rs | 13 ++ .../src/commands/vex_sources.rs | 208 ++++++++++++++++++ 2 files changed, 221 insertions(+) diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 031ab34aaf..db9d1b3ec0 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -1512,6 +1512,19 @@ async fn generate_vex( tooling: Some(format!("socket-patch {}", env!("CARGO_PKG_VERSION"))), }; + // A gem vendored as platform gems was judged above as the one copy it + // is; the document names each of its platform gems, under the patch + // that built it (see `GemBuildView`). + let mut affected = affected; + let gem_builds = crate::commands::vex_sources::GemBuildView::of(&plan); + if let Some(builds) = &gem_builds { + builds.expand(&mut outcome.applied); + builds.expand(&mut outcome.vendored); + builds.expand(&mut outcome.code_not_present); + builds.expand_noted(&mut affected); + } + let manifest = gem_builds.as_ref().map_or(manifest, |builds| builds.view()); + // `--no-verify` declared these applied with nothing checked on disk. The // purls an in-run hosted redirect confirmed are attested from that run's // own evidence in either mode, so they are not among them. diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index f650a8199f..af6baea06f 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -466,6 +466,102 @@ fn gate_unattested( }); } +/// The platform gems a document names in place of the gems vendored as +/// platform gems. +/// +/// Such a gem is one vendored copy, verified as one against the record of +/// the gem's patch. What an install loads from it is one platform gem's +/// tree, and each tree was built by a patch of its own, which the ledger +/// entry records ([`VendorEntry::gem_builds`]). So the document names each +/// platform gem (`pkg:gem/@?platform=`) under +/// its own patch, with the vulnerabilities of the gem patch's record: the +/// fix is the same in every one of them. Read from the plan alone, with +/// no request: the ledger is what says which patch built which tree. An +/// entry that names no patch for its trees is attested as the gem itself. +pub(crate) struct GemBuildView { + /// The record view with each such gem's key replaced by its platform + /// gems' purls. + view: PatchManifest, + /// View purl of the gem → the purls of its platform gems. + platform_gems: BTreeMap>, +} + +impl GemBuildView { + /// `None` when `plan` attests no gem vendored as platform gems. + pub(crate) fn of(plan: &Plan) -> Option { + let gems: Vec<(&String, &VendorEntry, &PatchRecord)> = plan + .vendor_entries + .iter() + .filter(|(_, entry)| { + entry.ecosystem == "gem" + && !entry.gem_builds.is_empty() + && entry.gem_builds_well_formed() + }) + .filter_map(|(key, entry)| Some((key, entry, plan.view.patches.get(key)?))) + // The entry's trees are the builds of the entry's own patch. + .filter(|(_, entry, record)| record.uuid == entry.uuid) + .collect(); + if gems.is_empty() { + return None; + } + let mut view = plan.view.clone(); + let mut platform_gems = BTreeMap::new(); + for (key, entry, record) in gems { + view.patches.remove(key); + let purls: Vec = entry + .gem_builds + .iter() + .map(|built| { + let purl = built.purl(&entry.base_purl); + // A purl the view already attests keeps its own record. + view.patches + .entry(purl.clone()) + .or_insert_with(|| PatchRecord { + uuid: built.uuid.clone(), + ..record.clone() + }); + purl + }) + .collect(); + platform_gems.insert(key.clone(), purls); + } + Some(Self { + view, + platform_gems, + }) + } + + /// The record view to build the document from. + pub(crate) fn view(&self) -> &PatchManifest { + &self.view + } + + /// Replace each gem of `purls` by its platform gems, in place. + pub(crate) fn expand(&self, purls: &mut Vec) { + *purls = std::mem::take(purls) + .into_iter() + .flat_map(|purl| match self.platform_gems.get(&purl) { + Some(platform_gems) => platform_gems.clone(), + None => vec![purl], + }) + .collect(); + } + + /// [`Self::expand`] for purls that each carry a note. + pub(crate) fn expand_noted(&self, noted: &mut Vec<(String, String)>) { + *noted = std::mem::take(noted) + .into_iter() + .flat_map(|(purl, note)| match self.platform_gems.get(&purl) { + Some(platform_gems) => platform_gems + .iter() + .map(|purl| (purl.clone(), note.clone())) + .collect(), + None => vec![(purl, note)], + }) + .collect(); + } +} + /// One hosted-basis view purl's wiring (see [`Plan::hosted`]). #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct HostedWiring { @@ -1447,6 +1543,118 @@ mod tests { } } + /// A plan attesting the vendored gem `key` at [`U1`], its ledger entry + /// shaped by `shape`. + fn vendored_gem_plan(key: &str, shape: impl FnOnce(&mut VendorEntry)) -> Plan { + let mut entry = VendorEntry::new( + "gem".to_string(), + "pkg:gem/nokogiri@1.18.10".to_string(), + U1.to_string(), + socket_patch_core::vendor::state::VendorArtifact { + yarn_berry10c0: None, + path: format!(".socket/vendor/gem/{U1}/nokogiri-1.18.10"), + sha256: String::new(), + size: None, + platform_locked: None, + file_inventory: None, + }, + Vec::new(), + ); + shape(&mut entry); + Plan { + view: PatchManifest { + patches: HashMap::from([ + (key.to_string(), record(U1)), + ("pkg:npm/left-pad@1.3.0".to_string(), record(U2)), + ]), + setup: None, + }, + vendor_entries: HashMap::from([(key.to_string(), entry)]), + vendor_pins: HashMap::new(), + redirected: Vec::new(), + lockfile_basis: HashSet::new(), + hosted: BTreeMap::new(), + gated: Vec::new(), + notes: Vec::new(), + } + } + + fn gem_build(platform: &str, uuid: &str) -> socket_patch_core::vendor::GemBuildEntry { + socket_patch_core::vendor::GemBuildEntry { + platform: platform.to_string(), + uuid: uuid.to_string(), + gem_integrity: String::new(), + gemspec_integrity: String::new(), + } + } + + /// A gem vendored as platform gems is named per platform gem: each + /// under the patch the ledger records for its tree, with the gem + /// patch's vulnerabilities and files, and the gem's own key gone from + /// the view. Every list of attested purls follows; other packages are + /// as they were. + #[test] + fn a_vendored_gem_is_attested_per_platform_gem_under_its_own_patch() { + const DARWIN: &str = "11111111-1111-4111-8111-111111111111"; + const LINUX: &str = "22222222-2222-4222-8222-222222222222"; + let key = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let plan = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![ + gem_build("arm64-darwin", DARWIN), + gem_build("x86_64-linux-gnu", LINUX), + ]; + }); + let builds = GemBuildView::of(&plan).expect("a gem vendored as platform gems"); + let view = builds.view(); + let darwin = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let linux = "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu"; + let mut keys: Vec<&str> = view.patches.keys().map(String::as_str).collect(); + keys.sort_unstable(); + assert_eq!(keys, [darwin, linux, "pkg:npm/left-pad@1.3.0"]); + for (purl, uuid) in [(darwin, DARWIN), (linux, LINUX)] { + let attested = &view.patches[purl]; + assert_eq!(attested.uuid, uuid); + assert_eq!(attested.vulnerabilities, record(U1).vulnerabilities); + assert_eq!(attested.files, record(U1).files); + } + assert_eq!(view.patches["pkg:npm/left-pad@1.3.0"], record(U2)); + + let mut applied = vec!["pkg:npm/left-pad@1.3.0".to_string(), key.to_string()]; + builds.expand(&mut applied); + assert_eq!(applied, ["pkg:npm/left-pad@1.3.0", darwin, linux]); + let mut noted = vec![(key.to_string(), "why".to_string())]; + builds.expand_noted(&mut noted); + assert_eq!( + noted, + [ + (darwin.to_string(), "why".to_string()), + (linux.to_string(), "why".to_string()) + ] + ); + } + + /// The gem itself stays the attested package where the ledger does not + /// say which patch built which tree: an entry that names platforms + /// only, one whose trees are another patch's than the view's record, + /// and one that names a platform no gem platform token spells. + #[test] + fn a_vendored_gem_with_no_patch_named_for_its_trees_is_attested_as_the_gem() { + let key = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let platforms_only = vendored_gem_plan(key, |entry| { + entry.gem_platforms = vec!["arm64-darwin".to_string()]; + }); + assert!(GemBuildView::of(&platforms_only).is_none()); + let another_patch = vendored_gem_plan(key, |entry| { + entry.uuid = U2.to_string(); + entry.gem_builds = vec![gem_build("arm64-darwin", U2)]; + }); + assert!(GemBuildView::of(&another_patch).is_none()); + let unsafe_platform = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![gem_build("../x", U2)]; + }); + assert!(GemBuildView::of(&unsafe_platform).is_none()); + } + fn hosted_ref(purl: &str, uuid: &str, pinned: bool) -> PatchedRef { PatchedRef::hosted( purl.to_string(), From 7b1340c419c5ae3dfa38e59b9bd901f7934c1c2c Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 19:20:58 -0500 Subject: [PATCH 008/120] Report a gem vendored as platform gems once per platform gem Hosted mode reports a gem locked as platform gems once per locked build, each under that build's own patch. Vendored mode reported it as one event under the gem's patch, so the two modes disagreed about which patches a run put in place, and telemetry never named the platform patches. The vendor engine now turns the outcome of such a gem into one counted event per platform gem (`pkg:gem/@?platform=`, `uuid` the platform's patch, `details.gemFix` the gem's patch, `details.platform`): `applied` when this run vendored or rebuilt it, `skipped` / `already_vendored` on an in-sync re-run, `verified` for a dry run of a recorded copy, and `verified` or `failed` per platform gem under `vendor --check`. The builds come from the entry the backend hands back, else from the ledger. The gem is still one package: the human summary, the in-sync line and the vendored count of telemetry take the events of one gem once. A retracted run drops the gem's advisories with its per-platform events. A gem with a locked platform that has no patched build prints the backend's one line as it is, without the `Skipping :` lead, and passes through whatever the ledger holds: the line already says which vendored copy stays in force. For a gem the lockfile pins hosted (a takeover, an eject) it says the pin stays instead of naming hosted mode as what to run; an eject is refused whole on it, as for any pin it cannot vendor. Two things kept such a gem from being vendored at all: - the installed-variant probe hashed a patched file in the installed copy, which is one platform's gem at most and often ships none of the patched files, and skipped the gem silently on a miss. A gem the lock resolves as platform gems is not probed; - a damaged copy of an entry that names no patch for its trees was sent to the restore, which has nothing to fetch them by. It goes to the backend, which rebuilds it from each platform's patch. Co-Authored-By: Claude Fable 5.2 --- .../socket-patch-cli/src/commands/vendor.rs | 535 ++++++++- crates/socket-patch-cli/tests/vendor/main.rs | 3 +- .../vendor/vendor_gem_platform_builds_e2e.rs | 1064 +++++++++++++++++ 3 files changed, 1573 insertions(+), 29 deletions(-) create mode 100644 crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index e428ac5be2..c54795c172 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -132,11 +132,13 @@ use socket_patch_core::vendor::refusals::refusal_is_benign; /// `vendor_prebuilt_required` failure it always was, a failed `Done` minus /// the unserved marker (its error already says it). /// -/// One unserved refusal is a skip with nothing to keep as well: +/// One unserved refusal is a skip whatever the ledger holds: /// [`vendor::VENDOR_PREBUILT_PLATFORM_PENDING`], a gem locked as platform -/// gems whose prebuild for one of the locked platforms the service does -/// not list. A prebuild is listed only once built, so the run cannot tell -/// "not yet" from "never", and the project is exactly as it was. +/// gems with a locked platform that has no patched build. A patched build +/// is named only once it is published, so the run cannot tell "not yet" +/// from "never", and the project is exactly as it was. The backend's +/// detail is the whole line, and already says which vendored copy, if +/// any, stays in force. /// /// [`Discovery::vendor_entry_live`]: socket_patch_core::vex::discover::Discovery::vendor_entry_live async fn keep_older_vendored_patch( @@ -147,6 +149,11 @@ async fn keep_older_vendored_patch( common: &GlobalArgs, ) -> Option { let (code, detail, failed_done) = match outcome { + Some(VendorOutcome::Refused { code, detail }) + if code == vendor::VENDOR_PREBUILT_PLATFORM_PENDING => + { + return Some(VendorOutcome::Refused { code, detail }); + } Some(VendorOutcome::Refused { code, detail }) if vendor::is_unserved(code) => { (code, detail, None) } @@ -197,9 +204,6 @@ async fn keep_older_vendored_patch( entry, warnings, }, - None if code == vendor::VENDOR_PREBUILT_PLATFORM_PENDING => { - VendorOutcome::Refused { code, detail } - } None => VendorOutcome::Refused { code: vendor::VENDOR_PREBUILT_REQUIRED, detail, @@ -721,6 +725,31 @@ pub(crate) fn format_advisory(code: &str, detail: &str, verbose: bool) -> Option } } +/// The human line of a package the run leaves alone as an expected skip: +/// `Skipping : `. The detail of a gem with a locked platform +/// that has no patched build ([`vendor::VENDOR_PREBUILT_PLATFORM_PENDING`]) +/// names the gem itself and is the whole line. +fn format_skip(purl: &str, code: &str, detail: &str) -> String { + if code == vendor::VENDOR_PREBUILT_PLATFORM_PENDING { + detail.to_string() + } else { + format!("Skipping {}: {detail}", normalize_purl(purl)) + } +} + +/// The detail of [`vendor::VENDOR_PREBUILT_PLATFORM_PENDING`] for a gem the +/// lockfile pins hosted: the pin stays, so the line says that instead of +/// naming hosted mode as the way to patch the other platforms. +fn hosted_pending_detail(code: &str, detail: String) -> String { + if code != vendor::VENDOR_PREBUILT_PLATFORM_PENDING { + return detail; + } + match detail.strip_suffix(vendor::gem::HOSTED_CAN_PATCH) { + Some(head) => format!("{head}; the gem stays hosted."), + None => detail, + } +} + /// `Error: Cannot vendor : `. fn format_vendor_failure(purl: &str, detail: &str) -> String { format!("Error: Cannot vendor {}: {detail}", normalize_purl(purl)) @@ -763,6 +792,107 @@ pub(crate) fn format_state_unreadable(err: &str) -> String { } } +/// `details` key of the events of a gem vendored as platform gems: the +/// uuid of the gem's patch, the one its vendored directory and ledger +/// entry are named after. Such a gem is ONE vendored package with one +/// event per platform gem, each under that platform gem's own patch and +/// each counted in `summary`, as hosted mode reports it; the key ties +/// those events together, so a count of packages takes them once. +const GEM_FIX_DETAIL: &str = "gemFix"; +/// `details` key of those events: the platform of the event's gem. +const GEM_PLATFORM_DETAIL: &str = "platform"; + +/// `event`, the outcome of a gem vendored as platform gems, once per tree +/// of `builds`: each names that platform gem +/// (`pkg:gem/@?platform=`) and its own patch, +/// and `details` ties it to the gem's patch `fix`. +fn gem_build_events( + event: &PatchEvent, + base_purl: &str, + fix: &str, + builds: &[vendor::GemBuildEntry], +) -> Vec { + builds + .iter() + .map(|built| { + let mut event = event.clone(); + event.purl = Some(built.purl(base_purl)); + event.uuid = Some(built.uuid.clone()); + let mut details = event + .details + .take() + .filter(serde_json::Value::is_object) + .unwrap_or_else(|| serde_json::json!({})); + details[GEM_FIX_DETAIL] = serde_json::json!(fix); + details[GEM_PLATFORM_DETAIL] = serde_json::json!(built.platform); + event.details = Some(details); + event + }) + .collect() +} + +/// How many of the events `counted` picks stand for a gem that an earlier +/// one of them already stands for ([`GEM_FIX_DETAIL`]): what a count of +/// events is over a count of packages. +fn gem_fix_repeats(env: &Envelope, counted: impl Fn(&PatchEvent) -> bool) -> u32 { + let mut gems: HashSet<&str> = HashSet::new(); + env.events + .iter() + .filter(|event| counted(event)) + .filter_map(|event| event.details.as_ref()?.get(GEM_FIX_DETAIL)?.as_str()) + .filter(|fix| !gems.insert(fix)) + .count() as u32 +} + +/// How many packages `env` reports as vendored: its `applied` events, a +/// gem vendored as platform gems once. +fn vendored_packages(env: &Envelope) -> u32 { + env.summary + .applied + .saturating_sub(gem_fix_repeats(env, |event| { + event.action == PatchAction::Applied + })) +} + +/// [`Envelope::retract_applied`] for a vendor run. The advisories of a gem +/// vendored as platform gems name the gem, while its `applied` events name +/// its platform gems, so the advisories of a retracted one are dropped +/// here: the re-tagged events are the gem's one account. +fn retract_vendored( + env: &mut Envelope, + since: usize, + action: PatchAction, + code: &str, + message: &str, +) -> usize { + let since = since.min(env.events.len()); + let is_build = |event: &PatchEvent| { + event.action == PatchAction::Applied + && event + .details + .as_ref() + .is_some_and(|details| details.get(GEM_FIX_DETAIL).is_some()) + }; + let gems: HashSet = env.events[since..] + .iter() + .filter(|event| is_build(event)) + .filter_map(|event| event.purl.as_deref()) + .map(|purl| strip_purl_qualifiers(purl).to_string()) + .collect(); + let mut index = 0; + env.events.retain(|event| { + let advisory = index >= since + && event.action == PatchAction::Skipped + && event + .purl + .as_deref() + .is_some_and(|purl| gems.contains(strip_purl_qualifiers(purl))); + index += 1; + !advisory + }); + env.retract_applied(since, action, code, message) +} + /// Per-outcome counts behind the human vendor summary line. #[derive(Debug, Default, Clone, PartialEq, Eq)] struct VendorTally { @@ -782,20 +912,23 @@ impl VendorTally { /// dry-run previews whose ledger entry already records the patch (the /// backends preview those as `verified`, like a fresh vendor). fn from_envelope(env: &Envelope, dry_run: bool, dry_in_sync: u32) -> Self { + // Packages, not events: a gem vendored as platform gems has one + // event per platform gem and is one package. + let repeats = |action: PatchAction| gem_fix_repeats(env, |e| e.action == action); let code_count = |code: &str| { - env.events - .iter() - .filter(|e| { - e.action == PatchAction::Skipped && e.error_code.as_deref() == Some(code) - }) - .count() as u32 + let coded = |e: &PatchEvent| { + e.action == PatchAction::Skipped && e.error_code.as_deref() == Some(code) + }; + let events = env.events.iter().filter(|e| coded(e)).count() as u32; + events.saturating_sub(gem_fix_repeats(env, coded)) }; let already_wet = code_count("already_vendored"); let not_installed = code_count("package_not_installed"); let vendored = if dry_run { - (env.summary.applied + env.summary.verified).saturating_sub(dry_in_sync) + (vendored_packages(env) + env.summary.verified) + .saturating_sub(repeats(PatchAction::Verified) + dry_in_sync) } else { - env.summary.applied + vendored_packages(env) }; VendorTally { vendored, @@ -804,8 +937,11 @@ impl VendorTally { skipped: env .summary .skipped - .saturating_sub(already_wet + not_installed), - failed: env.summary.failed, + .saturating_sub(repeats(PatchAction::Skipped) + already_wet + not_installed), + failed: env + .summary + .failed + .saturating_sub(repeats(PatchAction::Failed)), } } } @@ -1504,7 +1640,16 @@ async fn run_check(args: &VendorArgs) -> i32 { if !args.common.json && (!args.common.silent || event.action == PatchAction::Failed) { println!("{}: {}", key, event.reason.as_deref().unwrap_or("verified")); } - env.record(event); + // A gem vendored as platform gems: the verdict of its directory, + // once per platform gem and under that gem's own patch. + if entry.ecosystem == "gem" && !entry.gem_builds.is_empty() { + for event in gem_build_events(&event, &entry.base_purl, &entry.uuid, &entry.gem_builds) + { + env.record(event); + } + } else { + env.record(event); + } } let mut unledgered_uuids: HashSet<&str> = HashSet::new(); for (key, record) in manifest @@ -2273,8 +2418,9 @@ async fn run_eject( .await { // An eject has no skip: a pin it cannot vendor stays hosted - // and the eject is refused whole, so a prebuild that is not - // built yet is the plain miss here. + // and the eject is refused whole, so a gem with a locked + // platform that has no patched build is the plain miss here. + let detail = hosted_pending_detail(code, detail); let code = match vendor::is_unserved(code) { true => vendor::VENDOR_PREBUILT_REQUIRED, false => code, @@ -2557,7 +2703,8 @@ async fn run_eject( restored: the project is still hosted, exactly as before"; // Nothing the vendored apply did survives the rollback: a // package it vendored is still hosted, not applied (#1005). - env.retract_applied( + retract_vendored( + &mut env, events_start, PatchAction::Skipped, "eject_rolled_back", @@ -2781,7 +2928,14 @@ pub(crate) async fn track_outcomes_for_vendor( ) .await; } else { - track_patch_vendored(command, env.summary.applied, dry_run, &patches, telemetry).await; + track_patch_vendored( + command, + vendored_packages(env), + dry_run, + &patches, + telemetry, + ) + .await; } } @@ -3275,6 +3429,10 @@ struct CandidateGates<'a> { refusals: &'a VendorRefusals, /// Whether the lockfiles still pin the purl hosted. hosted_pinned: &'a dyn Fn(&str) -> bool, + /// The gem purls the Bundler lock resolves as precompiled platform + /// gems: what is vendored for one is the lock's to say, never the + /// installed copy's. + platform_gems: &'a HashSet, } impl<'a> CandidateGates<'a> { @@ -3298,8 +3456,13 @@ impl<'a> CandidateGates<'a> { // dir, so it only works when those files are EXTRACTED on disk. // Maven's patch targets live INSIDE the un-extracted jar and its // vendor takes the single main jar regardless, so it is skipped. + // So is a gem the lock resolves as platform gems: it is vendored + // as the patched gem of every locked platform, the installed copy + // is one of them at most, and a patch often touches only files no + // platform gem ships. let probe_applicable = group.is_variant_eco - && !matches!(Ecosystem::from_purl(candidate), Some(Ecosystem::Maven)); + && !matches!(Ecosystem::from_purl(candidate), Some(Ecosystem::Maven)) + && !self.platform_gems.contains(candidate); // A deferred source was deferred because the ledger covers the // purl at this record's uuid: the variant the ledger vendored is // the installed one's by construction, so it answers the probe @@ -3796,6 +3959,16 @@ pub(crate) async fn vendor_records_reusing( }); let hosted_pinned = |purl: &str| hosted_pin_of(purl).is_some(); + let gem_purls: Vec<&str> = vendorable + .iter() + .filter(|purl| Ecosystem::from_purl(purl) == Some(Ecosystem::Gem)) + .map(String::as_str) + .collect(); + let platform_gems: HashSet = + vendor::gem::gems_locked_as_platform_gems(&common.cwd, &gem_purls) + .await + .into_iter() + .collect(); let gates = CandidateGates { cwd: &common.cwd, force, @@ -3803,6 +3976,7 @@ pub(crate) async fn vendor_records_reusing( refused: &fetch_failed, refusals: &refusals, hosted_pinned: &hosted_pinned, + platform_gems: &platform_gems, }; // Candidates the loop refuses as `vendor_variant_ambiguous`, joined to // `fetch_failed` once the loop is done. @@ -3879,7 +4053,7 @@ pub(crate) async fn vendor_records_reusing( // An expected skip, as for the backend's own // benign refusals below. if !common.silent && !common.json { - eprintln!("Skipping {}: {detail}", normalize_purl(candidate)); + eprintln!("{}", format_skip(candidate, code, &detail)); } env.record( PatchEvent::new(PatchAction::Skipped, candidate.clone()) @@ -4092,8 +4266,9 @@ pub(crate) async fn vendor_records_reusing( { if refusal_is_benign(code) { // The wet run's skip: nothing is taken over. + let detail = hosted_pending_detail(code, detail); if !common.silent && !common.json { - eprintln!("Skipping {}: {detail}", normalize_purl(candidate)); + eprintln!("{}", format_skip(candidate, code, &detail)); } env.record( PatchEvent::new(PatchAction::Skipped, candidate.clone()) @@ -4187,10 +4362,14 @@ pub(crate) async fn vendor_records_reusing( // inventories were recorded, or past the inventory cap) gives an // exact restore nothing to check a download against: the backend // below rebuilds its copy from a fresh verified download instead. + // Nor does a gem entry that names the platforms of its trees + // and no patch for them: the backend rebuilds that copy too, + // from each platform's own patch, and records them. if let Some(entry) = lookup_entry(&state.entries, candidate).filter(|entry| { entry.uuid == record.uuid && (entry.artifact.file_inventory.is_some() || vendor::artifact_is_file_shaped(&entry.artifact.path)) + && (entry.gem_platforms.is_empty() || !entry.gem_builds.is_empty()) }) { let redownload = match vendor::check_vendored_artifact(&common.cwd, entry, record).await { @@ -4286,6 +4465,18 @@ pub(crate) async fn vendor_records_reusing( let outcome = keep_older_vendored_patch(outcome, &state, candidate, &record.uuid, common).await; + // The trees of a gem vendored as platform gems, for its events + // below: the ones this run wrote, else the ones the ledger + // records for this patch (an in-sync re-run writes none). + let gem_builds: Vec = match &outcome { + Some(VendorOutcome::Done { + entry: Some(entry), .. + }) => entry.gem_builds.clone(), + _ => lookup_entry(&state.entries, candidate) + .filter(|entry| entry.ecosystem == "gem" && entry.uuid == record.uuid) + .map(|entry| entry.gem_builds.clone()) + .unwrap_or_default(), + }; match outcome { None => { env.record( @@ -4296,10 +4487,15 @@ pub(crate) async fn vendor_records_reusing( ); } Some(VendorOutcome::Refused { code, detail }) => { + // A takeover the backend skipped keeps its hosted pin. + let detail = match hosted_pin_of(candidate) { + Some(_) => hosted_pending_detail(code, detail), + None => detail, + }; if refusal_is_benign(code) { // An expected skip, not an error: informational. if !common.silent && !common.json { - eprintln!("Skipping {}: {detail}", normalize_purl(candidate)); + eprintln!("{}", format_skip(candidate, code, &detail)); } env.record( PatchEvent::new(PatchAction::Skipped, candidate.clone()) @@ -4384,7 +4580,24 @@ pub(crate) async fn vendor_records_reusing( } else { Vec::new() }; - env.record(event); + // A gem vendored as platform gems is reported per + // platform gem, as hosted mode reports it: where the gem + // is vendored (this run's `applied`, an in-sync + // `already_vendored`, a dry run's `verified` of a copy + // the ledger records) its one event becomes one per + // platform gem, each under that gem's own patch and + // each counted. + let per_build = + matches!(event.action, PatchAction::Applied | PatchAction::Verified) + || in_sync; + if per_build && !gem_builds.is_empty() { + for event in gem_build_events(&event, candidate, &record.uuid, &gem_builds) + { + env.record(event); + } + } else { + env.record(event); + } for w in &symlinked { record_warning(env, candidate, w, common); } @@ -4544,7 +4757,13 @@ pub(crate) async fn vendor_records_reusing( leftovers.join("; ") ); } - env.retract_applied(events_start, PatchAction::Failed, &refusal.code, &message); + retract_vendored( + env, + events_start, + PatchAction::Failed, + &refusal.code, + &message, + ); if !common.json { eprintln!("Error: {message}"); } @@ -5948,6 +6167,48 @@ mod plan_gate_tests { } } + /// A gem the Bundler lock resolves as platform gems is vendored as the + /// patched gem of every locked platform, so the installed copy (one + /// platform's gem at most, often shipping none of the patched files) + /// is not put to the variant probe: the candidate goes on to its + /// backend with the installed dir as its source. + #[tokio::test] + async fn judge_does_not_probe_the_install_of_a_gem_locked_as_platform_gems() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let purl = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let dir = root.join("gems/nokogiri-1.18.10-arm64-darwin"); + std::fs::create_dir_all(&dir).unwrap(); + let all_packages = vec![(purl.to_string(), StagedSource::Installed(dir))]; + let records = HashMap::from([(purl.to_string(), record(UUID_B))]); + let none = HashSet::new(); + let variants = HashMap::from([( + "pkg:gem/nokogiri@1.18.10".to_string(), + vec![purl.to_string()], + )]); + let groups = candidate_groups(&all_packages, &variants); + let fresh = VendorState::default(); + // The installed platform gem holds none of the record's files. + assert!(matches!( + gates(root, &records, &none) + .judge(&fresh, &groups[0], purl) + .await, + CandidateVerdict::Skip + )); + let platform_gems = HashSet::from([purl.to_string()]); + let locked = CandidateGates { + platform_gems: &platform_gems, + ..gates(root, &records, &none) + }; + assert!(matches!( + locked.judge(&fresh, &groups[0], purl).await, + CandidateVerdict::Vendor { + superseded: false, + .. + } + )); + } + /// Gates with no vendored refusals, no hosted pins and no `--force`. pub(super) fn gates<'a>( root: &'a Path, @@ -5955,6 +6216,7 @@ mod plan_gate_tests { refused: &'a HashSet, ) -> CandidateGates<'a> { static NONE: VendorRefusals = VendorRefusals::new(); + static NO_PLATFORM_GEMS: std::sync::OnceLock> = std::sync::OnceLock::new(); CandidateGates { cwd: root, force: false, @@ -5962,6 +6224,7 @@ mod plan_gate_tests { refused, refusals: &NONE, hosted_pinned: &|_| false, + platform_gems: NO_PLATFORM_GEMS.get_or_init(HashSet::new), } } @@ -8620,6 +8883,222 @@ mod ui_format_tests { ); } + /// The trees of a gem vendored as platform gems, as the ledger + /// records them. + fn nokogiri_builds() -> Vec { + [("arm64-darwin", "darwin"), ("x86_64-linux-gnu", "linux")] + .into_iter() + .map(|(platform, uuid)| vendor::GemBuildEntry { + platform: platform.to_string(), + uuid: uuid.to_string(), + gem_integrity: String::new(), + gemspec_integrity: String::new(), + }) + .collect() + } + + /// The outcome of a gem vendored as platform gems becomes one event + /// per platform gem: that gem's purl, its own patch, and details that + /// name the gem's patch and the platform beside whatever the outcome + /// carried. Everything else is the outcome's. + #[test] + fn a_gem_vendored_as_platform_gems_is_one_event_per_platform_gem() { + let outcome = PatchEvent::new( + PatchAction::Skipped, + "pkg:gem/nokogiri@1.18.10?platform=ruby", + ) + .with_reason("already_vendored", "in sync") + .with_details(serde_json::json!({ "kept": true })); + let events = gem_build_events( + &outcome, + "pkg:gem/nokogiri@1.18.10?platform=ruby", + "source", + &nokogiri_builds(), + ); + let json = serde_json::to_value(&events).unwrap(); + assert_eq!( + json, + serde_json::json!([ + { + "action": "skipped", + "purl": "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin", + "uuid": "darwin", + "reason": "in sync", + "errorCode": "already_vendored", + "details": { "kept": true, "gemFix": "source", "platform": "arm64-darwin" } + }, + { + "action": "skipped", + "purl": "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + "uuid": "linux", + "reason": "in sync", + "errorCode": "already_vendored", + "details": { "kept": true, "gemFix": "source", "platform": "x86_64-linux-gnu" } + } + ]) + ); + } + + /// A gem vendored as platform gems has one counted event per platform + /// gem, each under that gem's own patch, as in hosted mode. It is one + /// package all the same: the human tally takes the events of one gem + /// once, whatever their outcome. + #[test] + fn tally_counts_a_gem_vendored_as_platform_gems_once() { + let builds = |env: &mut Envelope, event: &PatchEvent| { + let purl = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + for event in gem_build_events(event, purl, "source", &nokogiri_builds()) { + env.record(event); + } + }; + let event = |action| PatchEvent::new(action, "pkg:gem/nokogiri@1.18.10?platform=ruby"); + let cases = [ + ( + event(PatchAction::Skipped).with_reason("already_vendored", "in sync"), + tally(0, 1, 0, 0, 0), + "1 package is already vendored; nothing to do.", + ), + ( + event(PatchAction::Applied), + tally(1, 0, 0, 0, 0), + "Vendored 1 package.", + ), + ( + event(PatchAction::Failed).with_error("x", "y"), + tally(0, 0, 0, 0, 1), + "Vendored 0 packages; 1 failed.", + ), + ]; + for (outcome, expected, line) in cases { + let mut alone = Envelope::new(Command::Vendor); + builds(&mut alone, &outcome); + let counted = VendorTally::from_envelope(&alone, false, 0); + assert_eq!(counted, expected, "{line}"); + assert_eq!(format_vendor_summary(false, &counted), line); + // Each platform gem's event is counted in the summary. + let events = alone.summary.applied + alone.summary.skipped + alone.summary.failed; + assert_eq!(events, 2, "{line}"); + // Another package beside the gem is counted by itself. + alone.record(PatchEvent::new(PatchAction::Applied, "pkg:gem/rack@3.1.8")); + let mut with_rack = expected; + with_rack.vendored += 1; + assert_eq!( + VendorTally::from_envelope(&alone, false, 0), + with_rack, + "{line}" + ); + } + // Two gems vendored as platform gems are two packages. + let mut two = Envelope::new(Command::Vendor); + builds(&mut two, &event(PatchAction::Applied)); + for event in gem_build_events( + &PatchEvent::new(PatchAction::Applied, "pkg:gem/ffi@1.17.0"), + "pkg:gem/ffi@1.17.0", + "another", + &nokogiri_builds(), + ) { + two.record(event); + } + assert_eq!(vendored_packages(&two), 2); + assert_eq!(two.summary.applied, 4); + assert_eq!( + format_vendor_summary(false, &VendorTally::from_envelope(&two, false, 0)), + "Vendored 2 packages." + ); + // A dry run previews the platform gems of a recorded copy as + // `verified`: one package, already vendored when the ledger + // records this patch. + let mut dry = Envelope::new(Command::Vendor); + builds(&mut dry, &event(PatchAction::Verified)); + assert_eq!( + VendorTally::from_envelope(&dry, true, 0), + tally(1, 0, 0, 0, 0) + ); + assert_eq!( + VendorTally::from_envelope(&dry, true, 1), + tally(0, 1, 0, 0, 0) + ); + } + + /// A gem with a locked platform that has no patched build is one plain + /// line, the backend's own; every other skip names its package first. + /// For a gem the lockfile pins hosted, the line says the pin stays + /// instead of naming hosted mode as what to run. + #[test] + fn the_pending_platform_skip_is_one_plain_line() { + let pending = vendor::VENDOR_PREBUILT_PLATFORM_PENDING; + let detail = "nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin \ + (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs \ + every locked platform; `scan --mode hosted` can patch the others now."; + let purl = "pkg:gem/nokogiri@1.19.3?platform=ruby"; + assert_eq!(format_skip(purl, pending, detail), detail); + assert_eq!( + format_skip(purl, "vendor_gem_version_not_locked", "not locked"), + "Skipping pkg:gem/nokogiri@1.19.3?platform=ruby: not locked" + ); + assert_eq!( + hosted_pending_detail(pending, detail.to_string()), + "nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin \ + (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs every \ + locked platform; the gem stays hosted." + ); + // Any other code, and a line that names no hosted mode, pass as + // they are. + assert_eq!( + hosted_pending_detail("vendor_prebuilt_required", detail.to_string()), + detail + ); + let kept = "nokogiri@1.19.3 was not brought up to date: no patched build yet for java. \ + Vendored mode needs every locked platform; its vendored copy stays in \ + force as it is."; + assert_eq!(hosted_pending_detail(pending, kept.to_string()), kept); + } + + /// A retracted run keeps one account per package: the per-platform + /// `applied` events of a gem are re-tagged, and the advisories that + /// name the gem itself are dropped with them. Another package's + /// events stay as they were. + #[test] + fn retracting_a_gem_vendored_as_platform_gems_drops_its_advisories() { + let gem = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let mut env = Envelope::new(Command::Vendor); + env.record( + PatchEvent::new(PatchAction::Skipped, "pkg:gem/rack@3.1.8") + .with_reason("already_vendored", "in sync"), + ); + let since = env.events.len(); + for event in gem_build_events( + &PatchEvent::new(PatchAction::Applied, gem), + gem, + "source", + &nokogiri_builds(), + ) { + env.record(event); + } + push_advisory_event( + &mut env, + gem, + &VendorWarning::new("vendor_prebuilt_downloaded", "vendored nokogiri"), + ); + let retracted = retract_vendored(&mut env, since, PatchAction::Failed, "refused", "undone"); + assert_eq!(retracted, 2); + let left: Vec<(PatchAction, Option<&str>)> = env + .events + .iter() + .map(|event| (event.action, event.error_code.as_deref())) + .collect(); + assert_eq!( + left, + [ + (PatchAction::Skipped, Some("already_vendored")), + (PatchAction::Failed, Some("refused")), + (PatchAction::Failed, Some("refused")), + ] + ); + assert_eq!((env.summary.applied, env.summary.failed), (0, 2)); + assert_eq!(env.summary.skipped, 1); + } + #[test] fn advisories_are_tiered() { assert_eq!( diff --git a/crates/socket-patch-cli/tests/vendor/main.rs b/crates/socket-patch-cli/tests/vendor/main.rs index ce45e93621..b9e5161caa 100644 --- a/crates/socket-patch-cli/tests/vendor/main.rs +++ b/crates/socket-patch-cli/tests/vendor/main.rs @@ -1,4 +1,4 @@ -//! `vendor`: lockfile-only gems, pristine fetch order, no-network re-runs, bun, the hosted redirects, the failure paths, the `--silent` error output and the human render. +//! `vendor`: lockfile-only gems, gems locked as platform gems, pristine fetch order, no-network re-runs, bun, the hosted redirects, the failure paths, the `--silent` error output and the human render. //! //! One test binary per command: each module was its own binary. @@ -21,6 +21,7 @@ mod npm_fixture; mod redirect_npm_allow_remote; mod vendor_failure_paths; mod vendor_gem_lockfile_only_e2e; +mod vendor_gem_platform_builds_e2e; mod vendor_render; mod vendor_rerun_no_network_e2e; mod vendor_silent_errors; diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs new file mode 100644 index 0000000000..cf524f8f47 --- /dev/null +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -0,0 +1,1064 @@ +//! Vendoring a gem the Bundler lock names as precompiled platform gems: +//! one tree per locked platform, each from that platform's own patch, and +//! what a run says of it (one event per platform gem, one package). +//! +//! The patch service is a stand-in that answers in the shape of the wire +//! contract: the gem patch's reference lists every platform gem of the +//! version (`registryOverride.identifiers.gemBuilds`) with the patch of +//! each patched build, and each such patch serves that platform's gem +//! (`tarball`) and stub gemspec. No Bundler runs here. + +use crate::common::{binary, git_sha256, hermetic, sha256_hex}; + +use std::path::Path; + +use base64::Engine as _; +use sha2::{Digest, Sha512}; +use wiremock::matchers::{method, path as wm_path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +/// A name nothing on the developer's machine can have installed. +const NAME: &str = "sockplatgem"; +const VERSION: &str = "1.0.0"; +const PURL: &str = "pkg:gem/sockplatgem@1.0.0"; +/// The gem's patch: the patch of its ruby gem. +const UUID: &str = "5eed0000-0000-4000-8000-000000000001"; +const DARWIN: &str = "arm64-darwin"; +const LINUX: &str = "x86_64-linux-gnu"; +const DARWIN_UUID: &str = "5eed0000-0000-4000-8000-0000000000da"; +const LINUX_UUID: &str = "5eed0000-0000-4000-8000-0000000000f1"; +const LIB: &str = "lib/sockplatgem.rb"; +const SO: &str = "lib/sockplatgem/ext.so"; +const PRISTINE: &[u8] = b"module SockPlatGem; VERSION = '1.0.0'; end\n"; +const PATCHED: &[u8] = b"module SockPlatGem; VERSION = '1.0.0'; SAFE = true; end\n"; +const GHSA: &str = "GHSA-plat-form-gems"; +const CVE: &str = "CVE-2026-31337"; +const ORG: &str = "test-org"; + +const GEMFILE: &str = "source \"https://rubygems.org\"\n\ngem \"sockplatgem\", \"~> 1.0\"\n"; + +/// Bundler's lock of a project that takes the gem as precompiled platform +/// gems (no `CHECKSUMS`: a bundler 2.5 lock). +fn lock() -> String { + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n {NAME} ({VERSION}-{DARWIN})\n \ + {NAME} ({VERSION}-{LINUX})\n\nPLATFORMS\n {DARWIN}\n {LINUX}\n\nDEPENDENCIES\n \ + {NAME} (~> 1.0)\n\nBUNDLED WITH\n 2.5.22\n" + ) +} + +/// A minimal `.gem`: an uncompressed tar whose `data.tar.gz` holds `files`. +fn make_gem(files: &[(&str, &[u8])]) -> Vec { + let mut data = tar::Builder::new(Vec::new()); + for (path, bytes) in files { + let mut header = tar::Header::new_gnu(); + header.set_size(bytes.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + data.append_data(&mut header, path, *bytes).unwrap(); + } + let data_tar = data.into_inner().unwrap(); + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut gz, &data_tar).unwrap(); + let data_tar_gz = gz.finish().unwrap(); + let mut gem = tar::Builder::new(Vec::new()); + let mut header = tar::Header::new_gnu(); + header.set_size(data_tar_gz.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + gem.append_data(&mut header, "data.tar.gz", data_tar_gz.as_slice()) + .unwrap(); + gem.into_inner().unwrap() +} + +/// The patched gem of `platform`: the patched Ruby file and the platform's +/// own binary. +fn platform_gem(platform: &str) -> Vec { + make_gem(&[(LIB, PATCHED), (SO, platform.as_bytes())]) +} + +fn stub(platform: &str) -> Vec { + format!( + "Gem::Specification.new do |s|\n s.name = \"{NAME}\"\n s.version = \"{VERSION}\"\n \ + s.platform = \"{platform}\"\n s.summary = \"a synthetic fixture gem\"\n \ + s.authors = [\"Socket\"]\n s.require_paths = [\"lib\"]\nend\n" + ) + .into_bytes() +} + +fn sri(bytes: &[u8]) -> String { + format!( + "sha512-{}", + base64::engine::general_purpose::STANDARD.encode(Sha512::digest(bytes)) + ) +} + +fn build_uuid(platform: &str) -> &'static str { + match platform { + DARWIN => DARWIN_UUID, + _ => LINUX_UUID, + } +} + +/// The gem patch's record as the patch API's view serves it. +fn patch_view() -> serde_json::Value { + serde_json::json!({ + "uuid": UUID, + "purl": format!("{PURL}?platform=ruby"), + "publishedAt": "2026-01-01T00:00:00Z", + "files": { + LIB: { + "beforeHash": git_sha256(PRISTINE), + "afterHash": git_sha256(PATCHED), + "blobContent": base64::engine::general_purpose::STANDARD.encode(PATCHED), + } + }, + "vulnerabilities": { + GHSA: { + "cves": [CVE], + "summary": "a synthetic vulnerability", + "severity": "high", + "description": "details" + } + }, + "description": "synthetic platform gem vendor test patch", + "license": "MIT", + "tier": "free" + }) +} + +/// A patch service where the platforms of `patched` have a patched build +/// and those of `pass_through` are listed as upstream's own gem. +async fn service(patched: &[&'static str], pass_through: &[&'static str]) -> MockServer { + let server = MockServer::start().await; + let mut results = serde_json::Map::new(); + let mut gem_builds = Vec::new(); + for platform in patched { + let own = build_uuid(platform); + let (gem, gemspec) = (platform_gem(platform), stub(platform)); + let base = format!("/patch/gem/{NAME}/{VERSION}/tok/{own}/{NAME}-{VERSION}-{platform}"); + let mut artifacts = Vec::new(); + for (kind, ext, bytes) in [ + ("tarball", "gem", &gem), + ("gem-stub-gemspec", "gemspec", &gemspec), + ] { + let route = format!("{base}.{ext}"); + artifacts.push(serde_json::json!({ + "kind": kind, + "url": format!("{}{route}", server.uri()), + "integrity": { "sha512": sri(bytes) } + })); + Mock::given(method("GET")) + .and(wm_path(route)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes.clone())) + .mount(&server) + .await; + } + gem_builds.push(serde_json::json!({ + "platform": platform, "gemChecksumSha256": sha256_hex(&gem), "patchUuid": own + })); + results.insert( + own.to_string(), + serde_json::json!({ + "status": "granted", + "purl": format!("{PURL}?platform={platform}"), + "artifacts": artifacts + }), + ); + } + for platform in pass_through { + gem_builds.push(serde_json::json!({ + "platform": platform, "gemChecksumSha256": "ab".repeat(32), "patchUuid": null + })); + } + gem_builds.sort_by_key(|build| build["platform"].as_str().map(str::to_string)); + let ruby_gem = make_gem(&[(LIB, PATCHED)]); + let ruby_url = format!( + "{}/patch/gem/{NAME}/{VERSION}/tok/{UUID}/{NAME}-{VERSION}.gem", + server.uri() + ); + results.insert( + UUID.to_string(), + serde_json::json!({ + "status": "granted", + "purl": format!("{PURL}?platform=ruby"), + "url": ruby_url, + "artifacts": [{ "kind": "tarball", "url": ruby_url, + "integrity": { "sha512": sri(&ruby_gem) } }], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": format!("{}/patch-registry/gem/tok/{UUID}/s/4", server.uri()), + "identifiers": { + "name": NAME, "version": VERSION, + "gemChecksumSha256": sha256_hex(&ruby_gem), + "gemBuilds": gem_builds + } + } + }), + ); + Mock::given(method("POST")) + .and(wm_path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(move |request: &wiremock::Request| { + let asked: serde_json::Value = + serde_json::from_slice(&request.body).unwrap_or_default(); + let answered: serde_json::Map = asked["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|uuid| { + let uuid = uuid.as_str()?; + Some((uuid.to_string(), results.get(uuid)?.clone())) + }) + .collect(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": answered })) + }) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(wm_path(format!("/v0/orgs/{ORG}/patches/view/{UUID}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(patch_view())) + .mount(&server) + .await; + server +} + +/// The uuids each package reference request named, in arrival order. +async fn reference_requests(server: &MockServer) -> Vec> { + let requests = server.received_requests().await.unwrap_or_default(); + requests + .iter() + .filter(|request| request.url.path().ends_with("/patches/package")) + .map(|request| { + let asked: serde_json::Value = + serde_json::from_slice(&request.body).unwrap_or_default(); + let uuids = asked["uuids"].as_array().into_iter().flatten(); + uuids + .filter_map(|uuid| Some(uuid.as_str()?.to_string())) + .collect() + }) + .collect() +} + +/// The paths of the artifacts downloaded from `server`. +async fn downloads(server: &MockServer) -> Vec { + let requests = server.received_requests().await.unwrap_or_default(); + let mut paths: Vec = requests + .iter() + .map(|request| request.url.path().to_string()) + .filter(|path| path.starts_with("/patch/gem/")) + .collect(); + paths.sort(); + paths +} + +/// A Bundler project locking the gem as platform gems, with the manifest +/// record of the gem's patch and its staged after-blob. +fn write_project(root: &Path) { + std::fs::write(root.join("Gemfile"), GEMFILE).unwrap(); + std::fs::write(root.join("Gemfile.lock"), lock()).unwrap(); + let socket = root.join(".socket"); + std::fs::create_dir_all(socket.join("blobs")).unwrap(); + let view = patch_view(); + let manifest = serde_json::json!({ + "patches": { + PURL: { + "uuid": UUID, + "exportedAt": "2026-01-01T00:00:00Z", + "files": { + LIB: { + "beforeHash": git_sha256(PRISTINE), + "afterHash": git_sha256(PATCHED), + } + }, + "vulnerabilities": view["vulnerabilities"], + "description": view["description"], + "license": "MIT", + "tier": "free" + } + } + }); + std::fs::write( + socket.join("manifest.json"), + serde_json::to_vec_pretty(&manifest).unwrap(), + ) + .unwrap(); + std::fs::write(socket.join("blobs").join(git_sha256(PATCHED)), PATCHED).unwrap(); +} + +/// `socket-patch ` at `root` against the stand-in service, hermetic +/// (no ambient `SOCKET_*`, `BUNDLE_*` or gem home). +fn run(root: &Path, args: &[&str], api: &str) -> (i32, String, String) { + let mut cmd = hermetic::command(&binary()); + hermetic::scrub_extra(&mut cmd, &[hermetic::Extra::Bundle]); + cmd.env_remove("GEM_HOME").env_remove("GEM_PATH"); + crate::common::jvm_env::isolate_cli(&mut cmd); + cmd.args(args) + .args([ + "--api-url", + api, + "--proxy-url", + api, + "--api-token", + "fake-token", + "--org", + ORG, + ]) + .current_dir(root); + let out = cmd.output().expect("run socket-patch"); + ( + out.status.code().unwrap_or(-1), + String::from_utf8_lossy(&out.stdout).into_owned(), + String::from_utf8_lossy(&out.stderr).into_owned(), + ) +} + +fn run_json(root: &Path, args: &[&str], api: &str) -> (i32, serde_json::Value, String) { + let (code, stdout, stderr) = run(root, args, api); + let env: serde_json::Value = serde_json::from_str(stdout.trim()) + .unwrap_or_else(|e| panic!("{args:?} must emit JSON: {e}\n{stdout}\n{stderr}")); + (code, env, stderr) +} + +const VENDOR: &[&str] = &["vendor", "--json", "--vendor-source", "service"]; + +/// The counted events of `env` with `action`, as `(purl, uuid, gemFix, +/// platform, errorCode)`. +fn events<'a>( + env: &'a serde_json::Value, + action: &str, +) -> Vec<(&'a str, &'a str, &'a str, &'a str, &'a str)> { + let text = |value: &'a serde_json::Value| value.as_str().unwrap_or_default(); + env["events"] + .as_array() + .expect("events array") + .iter() + .filter(|event| event["action"] == action) + .map(|event| { + ( + text(&event["purl"]), + text(&event["uuid"]), + text(&event["details"]["gemFix"]), + text(&event["details"]["platform"]), + text(&event["errorCode"]), + ) + }) + .collect() +} + +/// One event per platform gem, in lock order, each under its own patch. +fn per_platform_gem( + code: &'static str, +) -> Vec<( + String, + &'static str, + &'static str, + &'static str, + &'static str, +)> { + [DARWIN, LINUX] + .into_iter() + .map(|platform| { + ( + format!("{PURL}?platform={platform}"), + build_uuid(platform), + UUID, + platform, + code, + ) + }) + .collect() +} + +fn assert_per_platform_gem(env: &serde_json::Value, action: &str, code: &'static str) { + let got = events(env, action); + let got: Vec<(&str, &str, &str, &str, &str)> = got + .into_iter() + .filter(|event| !event.2.is_empty()) + .collect(); + let want = per_platform_gem(code); + let want: Vec<(&str, &str, &str, &str, &str)> = want + .iter() + .map(|(purl, uuid, fix, platform, code)| (purl.as_str(), *uuid, *fix, *platform, *code)) + .collect(); + assert_eq!(got, want, "`{action}` events per platform gem: {env:#}"); +} + +fn tree(root: &Path, platform: &str) -> std::path::PathBuf { + root.join(format!( + ".socket/vendor/gem/{UUID}/{NAME}-{VERSION}/{platform}" + )) +} + +fn ledger(root: &Path) -> serde_json::Value { + let text = std::fs::read_to_string(root.join(".socket/vendor/state.json")).unwrap(); + serde_json::from_str(&text).unwrap() +} + +/// Every locked platform has a patched build: one tree per platform from +/// that platform's own patch (one reference request for the gem's patch, +/// one for both platform patches together), the ledger records each tree's +/// patch and digests, and every run reports the gem as one package with +/// one counted event per platform gem: `applied`, then `already_vendored` +/// on a re-run, `verified` / `failed` under `--check`, and after a tree is +/// damaged a rebuild from the recorded patches alone. `vex` attests each +/// platform gem under its own patch, offline. `--revert` undoes it all. +#[tokio::test] +async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { + let server = service(&[DARWIN, LINUX], &[]).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + + // 1. Vendor. + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 2, "{env:#}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); + assert_per_platform_gem(&env, "applied", ""); + for platform in [DARWIN, LINUX] { + assert_eq!( + std::fs::read(tree(root, platform).join(LIB)).unwrap(), + PATCHED + ); + assert_eq!( + std::fs::read(tree(root, platform).join(SO)).unwrap(), + platform.as_bytes() + ); + assert!(tree(root, platform) + .join(format!("{NAME}.gemspec")) + .is_file()); + } + assert_eq!( + reference_requests(&server).await, + [ + vec![UUID.to_string()], + vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()], + ], + "the gem patch's reference, then ONE request for the platform patches" + ); + assert_eq!( + downloads(&server).await.len(), + 4, + "a gem and a stub per platform" + ); + let lock_wired = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + assert!( + lock_wired.starts_with(&format!( + "PATH\n remote: .socket/vendor/gem/{UUID}/{NAME}-{VERSION}\n specs:\n {NAME} \ + ({VERSION}-{DARWIN})\n {NAME} ({VERSION}-{LINUX})\n" + )), + "{lock_wired}" + ); + let state = ledger(root); + let entry = &state["entries"][PURL]; + assert_eq!(entry["uuid"], UUID); + assert_eq!( + entry["gemBuilds"], + serde_json::json!([ + { "platform": DARWIN, "uuid": DARWIN_UUID, + "gemIntegrity": sri(&platform_gem(DARWIN)), "gemspecIntegrity": sri(&stub(DARWIN)) }, + { "platform": LINUX, "uuid": LINUX_UUID, + "gemIntegrity": sri(&platform_gem(LINUX)), "gemspecIntegrity": sri(&stub(LINUX)) } + ]) + ); + assert!(entry.get("gemPlatforms").is_none(), "{entry:#}"); + + // 2. An in-sync re-run: one package, one event per platform gem, and + // nothing asked of the service. + let asked = server.received_requests().await.unwrap().len(); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["skipped"], 2, "{env:#}"); + assert_eq!(env["summary"]["applied"], 0, "{env:#}"); + assert_per_platform_gem(&env, "skipped", "already_vendored"); + let (code, stdout, stderr) = run( + root, + &["vendor", "--vendor-source", "service"], + &server.uri(), + ); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "the gem is one package:\n{stdout}\n{stderr}" + ); + assert_eq!(server.received_requests().await.unwrap().len(), asked); + + // 3. `vendor --check`: one verdict per platform gem. + let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["verified"], 2, "{env:#}"); + assert_per_platform_gem(&env, "verified", "vendor_check_ok"); + + // 4. `vex`, offline: each platform gem under its own patch, with the + // vulnerabilities of the gem patch's record; the gem's own patch is + // not what any statement names. + let out = root.join("vex.json"); + let (code, stdout, stderr) = run( + root, + &[ + "vex", + "--json", + "--offline", + "--product", + "pkg:gem/app@1.0.0", + "--output", + out.to_str().unwrap(), + ], + &server.uri(), + ); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + let doc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&out).unwrap()).unwrap(); + let statements = doc["statements"].as_array().expect("statements"); + assert_eq!(statements.len(), 1, "one vulnerability: {doc:#}"); + let statement = &statements[0]; + assert_eq!(statement["vulnerability"]["name"], GHSA); + assert_eq!(statement["status"], "not_affected"); + let attested: Vec<&str> = statement["products"] + .as_array() + .into_iter() + .flatten() + .flat_map(|product| product["subcomponents"].as_array().into_iter().flatten()) + .filter_map(|component| component["@id"].as_str()) + .collect(); + for platform in [DARWIN, LINUX] { + let purl = format!("{PURL}?platform={platform}"); + assert!( + attested.contains(&purl.as_str()), + "{platform}: {attested:?}" + ); + } + assert!( + !attested.contains(&format!("{PURL}?platform=ruby").as_str()), + "{attested:?}" + ); + let impact = statement["impact_statement"].as_str().unwrap_or_default(); + for own in [DARWIN_UUID, LINUX_UUID] { + let part = format!("Patched via Socket patch {own} (vendored)"); + assert!(impact.split("; ").any(|p| p == part), "{impact}"); + } + assert!(!impact.contains(UUID), "{impact}"); + assert_eq!( + server.received_requests().await.unwrap().len(), + asked, + "offline" + ); + + // 5. A damaged tree: the check fails per platform gem, and the next + // run rebuilds the copy from the patches the ledger records, asked + // for in one request (the gem patch's reference is not needed). + std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); + let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 2, "{env:#}"); + assert_per_platform_gem(&env, "failed", "vendor_check_failed"); + let before = reference_requests(&server).await.len(); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["rebuilt"], 1, "{env:#}"); + assert_per_platform_gem(&env, "skipped", "already_vendored"); + assert_eq!( + reference_requests(&server).await[before..], + [vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()]] + ); + assert_eq!( + std::fs::read(tree(root, LINUX).join(SO)).unwrap(), + LINUX.as_bytes() + ); + let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + + // 6. Revert. + let (code, env, stderr) = run_json(root, &["vendor", "--revert", "--json"], &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile")).unwrap(), + GEMFILE + ); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock() + ); + assert!(!root.join(".socket/vendor").exists()); +} + +/// A locked platform with no patched build: the gem is not vendored, the +/// run exits 0 with nothing written and nothing downloaded, and says so in +/// one plain line (a counted benign skip in `--json`). +#[tokio::test] +async fn a_locked_platform_without_a_patched_build_is_one_line_and_no_failure() { + let server = service(&[LINUX], &[DARWIN]).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let line = format!( + "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has one). \ + Vendored mode needs every locked platform; `scan --mode hosted` can patch the others now." + ); + + let (code, stdout, stderr) = run( + root, + &["vendor", "--vendor-source", "service"], + &server.uri(), + ); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + // All of stderr but the note about this test's stand-in API token. + let said: Vec<&str> = stderr + .lines() + .filter(|l| !l.contains("--api-token") && !l.contains("fake-token")) + .collect(); + assert_eq!(said, [line.as_str()], "one line, no warning:\n{stderr}"); + assert!( + stdout.contains("Vendored 0 packages; 1 skipped."), + "{stdout}" + ); + + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["status"], "success", "{env:#}"); + assert_eq!(env["summary"]["applied"], 0, "{env:#}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); + assert_eq!(env["summary"]["skipped"], 1, "{env:#}"); + let skipped = events(&env, "skipped"); + assert_eq!( + skipped, + [(PURL, "", "", "", "vendor_prebuilt_platform_pending")], + "{env:#}" + ); + assert_eq!(env["events"][0]["reason"], line.as_str()); + + assert_eq!( + std::fs::read_to_string(root.join("Gemfile")).unwrap(), + GEMFILE + ); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock() + ); + assert!(!root.join(".socket/vendor").exists(), "nothing is written"); + assert_eq!(downloads(&server).await, Vec::::new()); + assert_eq!( + reference_requests(&server).await, + [vec![UUID.to_string()], vec![UUID.to_string()]], + "each run asks for the gem patch's reference and nothing else" + ); +} + +/// A ledger entry that names the platforms of its copy and no patch for +/// their trees (`gemPlatforms`) still checks as one package, the next +/// vendor run records each tree's patch in its place, and it reverts. An +/// entry whose `gemBuilds` items carry fields this build does not know +/// reads as if they were not there. +#[tokio::test] +async fn ledger_entries_of_other_builds_still_check_convert_and_revert() { + let server = service(&[DARWIN, LINUX], &[]).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let state_path = root.join(".socket/vendor/state.json"); + let current = ledger(root); + + // Items with unknown fields. + let mut extended = current.clone(); + for item in extended["entries"][PURL]["gemBuilds"] + .as_array_mut() + .unwrap() + { + let item = item.as_object_mut().unwrap(); + item.insert("rebuiltFromUuid".into(), serde_json::json!(UUID)); + item.insert( + "record".into(), + serde_json::json!({ "uuid": UUID, "files": {} }), + ); + } + std::fs::write(&state_path, serde_json::to_vec_pretty(&extended).unwrap()).unwrap(); + let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_per_platform_gem(&env, "verified", "vendor_check_ok"); + + // Platforms only: one verdict, for the gem. + let mut older = current.clone(); + let entry = older["entries"][PURL].as_object_mut().unwrap(); + entry.remove("gemBuilds"); + entry.insert("gemPlatforms".into(), serde_json::json!([DARWIN, LINUX])); + std::fs::write(&state_path, serde_json::to_vec_pretty(&older).unwrap()).unwrap(); + let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!( + events(&env, "verified"), + [(PURL, "", "", "", "vendor_check_ok")], + "{env:#}" + ); + + // The next vendor run records the patch of each tree. + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_per_platform_gem(&env, "applied", ""); + let rebuilt = env["events"] + .as_array() + .unwrap() + .iter() + .find(|event| event["errorCode"] == "vendor_artifact_rebuilt") + .unwrap_or_else(|| panic!("{env:#}")); + assert!( + rebuilt["reason"] + .as_str() + .unwrap_or_default() + .contains("was recorded with no patch named for its platform gems"), + "{rebuilt:#}" + ); + let converted = ledger(root); + assert_eq!( + converted["entries"][PURL]["gemBuilds"], + current["entries"][PURL]["gemBuilds"] + ); + assert!(converted["entries"][PURL].get("gemPlatforms").is_none()); + assert_eq!( + converted["entries"][PURL]["wiring"], current["entries"][PURL]["wiring"], + "the wiring records ride on" + ); + + // Revert of the entry that names platforms only. + std::fs::write(&state_path, serde_json::to_vec_pretty(&older).unwrap()).unwrap(); + let (code, env, stderr) = run_json(root, &["vendor", "--revert", "--json"], &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile")).unwrap(), + GEMFILE + ); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock() + ); + assert!(!root.join(".socket/vendor").exists()); +} + +/// The hosted pair of the project: the gem pinned to the gem patch's +/// registry (a snapshot URL), every platform entry in its section. +fn write_hosted_project(root: &Path) -> (String, String) { + let registry = + format!("https://patch.socket.dev/patch-registry/gem/11111111-1111-4111-8111-111111111111/{UUID}/s/4/"); + let gemfile = format!( + "source \"https://rubygems.org\"\n\ngem \"{NAME}\", \"{VERSION}\", source: \"{registry}\"\n" + ); + let lock = format!( + "GEM\n remote: {registry}\n specs:\n {NAME} ({VERSION}-{DARWIN})\n {NAME} \ + ({VERSION}-{LINUX})\n\nGEM\n remote: https://rubygems.org/\n specs:\n\nPLATFORMS\n \ + {DARWIN}\n {LINUX}\n\nDEPENDENCIES\n {NAME} (= {VERSION})!\n\nBUNDLED WITH\n 2.5.22\n" + ); + std::fs::write(root.join("Gemfile"), &gemfile).unwrap(); + std::fs::write(root.join("Gemfile.lock"), &lock).unwrap(); + (gemfile, lock) +} + +/// An eject (`vendor` over a hosted lock) of a gem whose registry serves +/// upstream's own gem for one locked platform cannot vendor it: the eject +/// is refused whole, the reason names the platform, and the lock stays +/// hosted, byte for byte. +#[tokio::test] +async fn an_eject_of_a_gem_with_a_pass_through_platform_is_refused_whole() { + let server = service(&[LINUX], &[DARWIN]).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let (gemfile, lock) = write_hosted_project(root); + + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_eq!(env["error"]["code"], "eject_refused", "{env:#}"); + let failed = env["events"] + .as_array() + .unwrap() + .iter() + .find(|event| event["action"] == "failed") + .unwrap_or_else(|| panic!("a failed event: {env:#}")); + assert_eq!( + failed["errorCode"], "vendor_prebuilt_required", + "{failed:#}" + ); + assert_eq!( + failed["error"], + format!( + "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has \ + one). Vendored mode needs every locked platform; the gem stays hosted." + ) + .as_str(), + "{failed:#}" + ); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile")).unwrap(), + gemfile + ); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock + ); + assert!(!root.join(".socket/vendor").exists()); + assert_eq!(downloads(&server).await, Vec::::new()); +} + +/// The same hosted gem once every locked platform has a patched build: +/// the eject vendors it, one tree per platform, under the gem's patch. +#[tokio::test] +async fn an_eject_of_a_hosted_platform_gem_vendors_every_platform() { + let server = service(&[DARWIN, LINUX], &[]).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_hosted_project(root); + + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_per_platform_gem(&env, "applied", ""); + for platform in [DARWIN, LINUX] { + assert_eq!( + std::fs::read(tree(root, platform).join(LIB)).unwrap(), + PATCHED + ); + } + let lock = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + assert!( + lock.starts_with(&format!( + "PATH\n remote: .socket/vendor/gem/{UUID}/{NAME}-{VERSION}\n" + )), + "{lock}" + ); + assert!(!lock.contains("patch-registry"), "{lock}"); +} + +/// What a package search returns for the gem: the patch of the gem itself +/// and, beside it, the patch of each platform gem. Only the gem's own +/// patch has a view to download. +async fn mount_search(server: &MockServer) { + let offers = [ + (UUID, format!("{PURL}?platform=ruby")), + (DARWIN_UUID, format!("{PURL}?platform={DARWIN}")), + (LINUX_UUID, format!("{PURL}?platform={LINUX}")), + ]; + let batch: Vec = offers + .iter() + .map(|(uuid, purl)| { + serde_json::json!({ + "uuid": uuid, "purl": purl, "tier": "free", "cveIds": [CVE], + "ghsaIds": [GHSA], "severity": "high", "title": "a synthetic vulnerability" + }) + }) + .collect(); + Mock::given(method("POST")) + .and(wm_path(format!("/v0/orgs/{ORG}/patches/batch"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [{ "purl": PURL, "patches": batch }], + "canAccessPaidPatches": true, + }))) + .mount(server) + .await; + let view = patch_view(); + let found: Vec = offers + .iter() + .map(|(uuid, purl)| { + serde_json::json!({ + "uuid": uuid, "purl": purl, "publishedAt": "2026-01-01T00:00:00Z", + "description": "synthetic", "license": "MIT", "tier": "free", + "vulnerabilities": view["vulnerabilities"] + }) + }) + .collect(); + Mock::given(method("GET")) + .and(wiremock::matchers::path_regex(format!( + "^/v0/orgs/{ORG}/patches/by-package/" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": found, + "canAccessPaidPatches": true, + }))) + .mount(server) + .await; +} + +/// Install the darwin platform gem of the project the way `bundle install +/// --path vendor/bundle` leaves it, and return its directory. +fn install_darwin_gem(root: &Path) -> std::path::PathBuf { + let leaf = format!("{NAME}-{VERSION}-{DARWIN}"); + let bundle = root.join("vendor").join("bundle"); + let gem_dir = bundle.join("gems").join(&leaf); + std::fs::create_dir_all(gem_dir.join("lib").join(NAME)).unwrap(); + std::fs::write(gem_dir.join(LIB), PRISTINE).unwrap(); + std::fs::write(gem_dir.join(SO), DARWIN.as_bytes()).unwrap(); + std::fs::create_dir_all(bundle.join("specifications")).unwrap(); + std::fs::write( + bundle + .join("specifications") + .join(format!("{leaf}.gemspec")), + stub(DARWIN), + ) + .unwrap(); + gem_dir +} + +/// `scan --mode vendored` over a project whose installed copy of the gem +/// is one platform's gem, with a package search that returns the patches +/// of the platform gems beside the gem's own. The gem is vendored through +/// its own patch alone, as one tree per locked platform: the platform +/// gems' patches are no packages of their own (no download of their +/// records, no failure), and the installed copy, which is one platform's +/// at most, does not decide what is vendored. +#[tokio::test] +async fn a_vendored_scan_takes_the_gem_through_its_own_patch_alone() { + let server = service(&[DARWIN, LINUX], &[]).await; + mount_search(&server).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + std::fs::write(root.join("Gemfile"), GEMFILE).unwrap(); + std::fs::write(root.join("Gemfile.lock"), lock()).unwrap(); + let gem_dir = install_darwin_gem(root); + + let (code, env, stderr) = run_json( + root, + &["scan", "--json", "--mode", "vendored", "--yes"], + &server.uri(), + ); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); + assert_per_platform_gem(&env, "applied", ""); + for platform in [DARWIN, LINUX] { + assert_eq!( + std::fs::read(tree(root, platform).join(LIB)).unwrap(), + PATCHED + ); + } + // Nothing is said of a platform gem's patch but the tree vendored from + // it, and its record is never asked for. + for event in env["events"].as_array().unwrap() { + let own = [DARWIN_UUID, LINUX_UUID].contains(&event["uuid"].as_str().unwrap_or_default()); + assert!( + !own || event["details"]["gemFix"] == UUID, + "a platform gem's patch as a package of its own: {event:#}" + ); + } + let requests = server.received_requests().await.unwrap(); + let views: Vec<&str> = requests + .iter() + .map(|request| request.url.path()) + .filter(|path| path.contains("/patches/view/")) + .collect(); + assert!(!views.is_empty(), "the gem's own record is downloaded"); + assert!( + views.iter().all(|path| path.ends_with(UUID)), + "only the gem's own record: {views:?}" + ); + assert_eq!( + std::fs::read(gem_dir.join(LIB)).unwrap(), + PRISTINE, + "the installed copy is not touched" + ); +} + +const SCAN: &[&str] = &["scan", "--json", "--mode", "vendored", "--yes"]; + +/// `scan --mode vendored` over a lock that pins the gem hosted takes it +/// over once every locked platform has a patched build: the upstream entry +/// is restored and the gem vendored, one tree per platform. +#[tokio::test] +async fn a_vendored_scan_takes_over_a_hosted_platform_gem() { + let server = service(&[DARWIN, LINUX], &[]).await; + mount_search(&server).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_hosted_project(root); + install_darwin_gem(root); + + let (code, env, stderr) = run_json(root, SCAN, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_per_platform_gem(&env, "applied", ""); + let lock = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + assert!( + lock.starts_with(&format!( + "PATH\n remote: .socket/vendor/gem/{UUID}/{NAME}-{VERSION}\n" + )), + "{lock}" + ); + assert!(!lock.contains("patch-registry"), "{lock}"); +} + +/// The same takeover while the registry serves upstream's own gem for one +/// locked platform: the gem is not vendored and stays hosted, byte for +/// byte, the run does not fail, and its one line says the pin stays. +#[tokio::test] +async fn a_vendored_scan_leaves_a_hosted_gem_with_a_pass_through_platform_hosted() { + let server = service(&[LINUX], &[DARWIN]).await; + mount_search(&server).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let (gemfile, lock) = write_hosted_project(root); + install_darwin_gem(root); + + let (code, env, stderr) = run_json(root, SCAN, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); + assert_eq!(env["summary"]["applied"], 0, "{env:#}"); + let skipped = env["events"] + .as_array() + .unwrap() + .iter() + .find(|event| event["errorCode"] == "vendor_prebuilt_platform_pending") + .unwrap_or_else(|| panic!("the pending skip: {env:#}")); + assert_eq!(skipped["action"], "skipped", "{skipped:#}"); + assert_eq!( + skipped["reason"], + format!( + "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has \ + one). Vendored mode needs every locked platform; the gem stays hosted." + ) + .as_str(), + "{skipped:#}" + ); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile")).unwrap(), + gemfile + ); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock + ); + assert!(!root.join(".socket/vendor/gem").exists()); + assert_eq!(downloads(&server).await, Vec::::new()); +} + +/// `get --mode vendored` for the gem: the search returns the +/// patches of its platform gems beside its own, and the gem is vendored +/// through its own patch alone, one tree per locked platform, with +/// nothing downloaded or reported for the others as packages. +#[tokio::test] +async fn a_vendored_get_takes_the_gem_through_its_own_patch_alone() { + let server = service(&[DARWIN, LINUX], &[]).await; + mount_search(&server).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + std::fs::write(root.join("Gemfile"), GEMFILE).unwrap(); + std::fs::write(root.join("Gemfile.lock"), lock()).unwrap(); + + let (code, env, stderr) = run_json( + root, + &["get", PURL, "--json", "--mode", "vendored", "--yes"], + &server.uri(), + ); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); + assert_per_platform_gem(&env, "applied", ""); + for platform in [DARWIN, LINUX] { + assert_eq!( + std::fs::read(tree(root, platform).join(LIB)).unwrap(), + PATCHED + ); + } + let requests = server.received_requests().await.unwrap(); + let views: Vec<&str> = requests + .iter() + .map(|request| request.url.path()) + .filter(|path| path.contains("/patches/view/")) + .collect(); + assert!( + !views.is_empty() && views.iter().all(|path| path.ends_with(UUID)), + "only the gem's own record is downloaded: {views:?}" + ); +} From f7c3550103b3118703d484a5f4f73ac042da3d5a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 20:30:11 -0500 Subject: [PATCH 009/120] Leave a platform gem's own patch out of a hosted selection too The patch service has a patch record per patched platform gem (`pkg:gem/@?platform=`), which a search returns beside the gem's own. Agent mode takes it for the installed copy of that platform. A hosted run patches a gem through the patch of the gem itself, whose reference lists the patched build of every platform, so there the platform gem's record is no fix of its own. Selected as one it was asked about in the reference request, skipped with "the hosted patch server has no artifact for this patch" (or left "not hosted"), and every later scan offered it as a newer patch of the gem. A hosted `scan` and `get` now leave those records out as a vendored run does, before anything is reported, looked up or written, and so does the in-memory engine's selection. The predicate lives in core (`engine::is_platform_gem_patch`) so that the engines share it. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/get.rs | 14 ++- .../src/commands/scan/discovery.rs | 4 +- .../socket-patch-cli/src/commands/scan/mod.rs | 12 ++- .../tests/e2e_redirect_gem_platform_builds.rs | 98 +++++++++++++++++++ crates/socket-patch-core/src/hosted/engine.rs | 16 +++ .../src/hosted/memory/mod.rs | 50 ++++++++++ 6 files changed, 181 insertions(+), 13 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index 5043c3eaed..8b9b565484 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -1716,11 +1716,15 @@ pub async fn run(args: GetArgs) -> i32 { search_response .patches .retain(|p| args.common.purl_ecosystem_selected(&p.purl)); - // A vendored run patches a gem through the patch of the gem itself: the - // patch of one of its platform gems, which a search returns beside it, - // is no fix of its own there. (One named by its UUID is the caller's - // exact intent, and reaches the backend's own refusal.) - if mode == super::scan::ScanMode::Vendored { + // A hosted or a vendored run patches a gem through the patch of the + // gem itself: the patch of one of its platform gems, which a search + // returns beside it, is no fix of its own there. (One named by its + // UUID is the caller's exact intent, and reaches the backend's own + // refusal.) + if matches!( + mode, + super::scan::ScanMode::Vendored | super::scan::ScanMode::Hosted + ) { search_response .patches .retain(|p| !super::scan::is_platform_gem_patch(&p.purl)); diff --git a/crates/socket-patch-cli/src/commands/scan/discovery.rs b/crates/socket-patch-cli/src/commands/scan/discovery.rs index 8bf43ecd34..2a08b70c70 100644 --- a/crates/socket-patch-cli/src/commands/scan/discovery.rs +++ b/crates/socket-patch-cli/src/commands/scan/discovery.rs @@ -135,9 +135,7 @@ pub(crate) async fn lockfile_supplement( /// there: a vendored selection leaves it out before anything is reported, /// downloaded or handed to the engine ([`drop_platform_gem_patches`]). pub(crate) fn is_platform_gem_patch(purl: &str) -> bool { - Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) - && socket_patch_core::utils::purl::purl_qualifier(purl, "platform") - .is_some_and(|platform| !platform.is_empty() && !platform.eq_ignore_ascii_case("ruby")) + socket_patch_core::hosted::engine::is_platform_gem_patch(purl) } /// Take the patches of platform gems ([`is_platform_gem_patch`]) out of diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 883755a2c1..dac28c8881 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2408,8 +2408,9 @@ async fn scan_project( let apply = args.mode == Some(ScanMode::Agent); let vendor = args.mode == Some(ScanMode::Vendored); let hosted = args.mode == Some(ScanMode::Hosted); - // A vendored run patches a gem through the patch of the gem itself. - if vendor { + // A hosted or a vendored run patches a gem through the patch of the + // gem itself. + if vendor || hosted { policy.leave_out_platform_gem_patches(); } // `patches.enabled: false` writes nothing, the GC included. @@ -3399,9 +3400,10 @@ async fn scan_project( // drives the report, the `--json` `packages` array and the apply order, // which operators diff across runs. all_packages_with_patches.sort_by(|a, b| a.purl.cmp(&b.purl)); - // A vendored run patches a gem through the patch of the gem itself: the - // patch of one of its platform gems is no offer of its own there. - if vendor { + // A hosted or a vendored run patches a gem through the patch of the gem + // itself: the patch of one of its platform gems is no offer of its own + // there. + if vendor || hosted { discovery::drop_platform_gem_patches(&mut all_packages_with_patches); } // #604: a patch the API returned under an equivalent spelling of a diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs index 4cd66780e3..4329846426 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs @@ -759,6 +759,104 @@ async fn a_platform_missing_from_the_list_is_waited_for_quietly() { assert_ne!(read(proj.path(), "Gemfile.lock"), lock(true)); } +/// The patch service also has a patch record per patched platform gem +/// (`pkg:gem/@?platform=`), which a search +/// returns beside the gem's own. Agent mode takes those; a hosted run +/// patches the gem through its own patch alone. The platform gem's record +/// is no selection of its own: one reference request for the one patch, +/// no skip, and a later run offers no "newer patch". +#[tokio::test(flavor = "multi_thread")] +async fn a_platform_gems_own_record_is_no_fix_of_its_own() { + let server = MockServer::start().await; + let platform_purl = format!("{PURL}?platform={LINUX}"); + let listed = |uuid: &str, purl: &str| { + json!({ + "uuid": uuid, "purl": purl, "tier": "free", "cveIds": [], + "ghsaIds": [GHSA], "severity": "high", "title": "platform gem fixture", + }) + }; + let found = |uuid: &str, purl: &str| { + json!({ + "uuid": uuid, "purl": purl, "publishedAt": "2026-02-01T00:00:00Z", + "description": "x", "license": "MIT", "tier": "free", + "vulnerabilities": { GHSA: { + "cves": ["CVE-2026-5555"], "summary": "s", "severity": "high", + "description": "d", + }}, + }) + }; + // Ahead of `mount_api`'s own answers: the gem's patch and the linux + // gem's, the latter published later (it would rank first). + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "packages": [{ "purl": PURL, "patches": [ + listed(UUID, PURL), listed(LINUX_UUID, &platform_purl), + ]}], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path_regex(format!( + "^/v0/orgs/{ORG}/patches/by-package/.+$" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "patches": [found(LINUX_UUID, &platform_purl), found(UUID, PURL)], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(&server) + .await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "the gem is reported per build, and nothing is skipped: {env}" + ); + let selected: Vec<&Value> = env["packages"] + .as_array() + .unwrap() + .iter() + .flat_map(|package| package["selectedUuids"].as_array().unwrap()) + .collect(); + assert_eq!(selected, [&json!(UUID)], "{env}"); + let (references, _) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + + // A later run: in place, and no patch is offered as newer. + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["updates"], json!([]), "{env}"); + assert_eq!(env["rollout"]["counts"]["upgrade"], 0, "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([]), "{env}"); + + // `get` for the gem takes the gem's own patch alone, too. + let fresh = project(&lock(true)); + let (code, stdout, stderr) = hosted(fresh.path(), &api, &["get", PURL], &["--json"]); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); +} + /// `get --mode hosted` writes what `scan` writes and /// reports the gem per build the same way. #[tokio::test(flavor = "multi_thread")] diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index cc7a6f2d20..382febd3e7 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -135,6 +135,22 @@ pub fn unconfirmed_candidates( .collect() } +/// Whether `purl` is the patch purl of one platform gem +/// (`pkg:gem/@?platform=`, any platform but +/// `ruby`): what an installed copy of that platform gem takes in place +/// (agent mode). +/// +/// A hosted or a vendored run patches a gem through the patch of the gem +/// itself, whose package reference names the patched build of every +/// platform. The patch of a platform gem is no fix of its own there: such +/// a run leaves it out of what it selects, before anything is reported, +/// looked up or written, so the gem is one package with one patch. +pub fn is_platform_gem_patch(purl: &str) -> bool { + crate::crawlers::Ecosystem::from_purl(purl) == Some(crate::crawlers::Ecosystem::Gem) + && crate::utils::purl::purl_qualifier(purl, "platform") + .is_some_and(|platform| !platform.is_empty() && !platform.eq_ignore_ascii_case("ruby")) +} + /// Skip reason of a gem the Bundler lock names as precompiled platform /// builds, left on its upstream registry because the patch registry has no /// patched build yet for any platform the lock names: moving it would gain diff --git a/crates/socket-patch-core/src/hosted/memory/mod.rs b/crates/socket-patch-core/src/hosted/memory/mod.rs index 6f490b21e2..487e6b2c1e 100644 --- a/crates/socket-patch-core/src/hosted/memory/mod.rs +++ b/crates/socket-patch-core/src/hosted/memory/mod.rs @@ -1402,8 +1402,11 @@ fn select_with_policy( filtered: &mut Vec, skipped: &mut Vec, ) -> Offers { + // A gem is patched through the patch of the gem itself: the patch of + // one of its platform gems is no offer of its own here. let accessible: Vec = results .into_iter() + .filter(|p| !crate::hosted::engine::is_platform_gem_patch(&p.purl)) .filter(|p| can_access_paid || p.tier == "free") .collect(); let (admitted, dropped) = if policy.enabled() { @@ -1631,6 +1634,53 @@ mod tests { } } + /// The patch service has a patch record per patched platform gem + /// beside the gem's own. Here a gem is patched through its own patch, + /// so the platform gem's record is no offer: it is neither selected + /// nor reported as filtered or skipped. + #[test] + fn a_platform_gems_own_patch_is_no_offer() { + let found = |uuid: &str, purl: &str| PatchSearchResult { + uuid: uuid.to_string(), + purl: purl.to_string(), + published_at: "2026-01-01T00:00:00Z".to_string(), + description: String::new(), + license: "MIT".to_string(), + tier: "free".to_string(), + vulnerabilities: Default::default(), + }; + let results = vec![ + found("b", "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu"), + found("a", "pkg:gem/nokogiri@1.19.3"), + found("r", "pkg:gem/rack@3.1.8?platform=ruby"), + ]; + let (mut filtered, mut skipped) = (Vec::new(), Vec::new()); + let offers = select_with_policy( + &SelectionPolicy::unrestricted(), + results, + false, + "", + &mut filtered, + &mut skipped, + ); + let selected: Vec<(&str, &str)> = offers + .selected + .iter() + .map(|(purl, patch)| (purl.as_str(), patch.uuid.as_str())) + .collect(); + assert_eq!( + selected, + [ + ("pkg:gem/nokogiri@1.19.3", "a"), + ("pkg:gem/rack@3.1.8?platform=ruby", "r"), + ] + ); + assert!(filtered.is_empty() && skipped.is_empty()); + assert!(!offers + .unfiltered + .contains_key("pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu")); + } + fn rewritten(files: &[(&str, &str)]) -> Rewritten { let mut rewrite = RewriteResult::default(); for (rel, content) in files { From b4b07e6f6c204d0a04362bac15660c1ced92520a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 20:30:20 -0500 Subject: [PATCH 010/120] Let a hosted lock follow a withdrawn build back to upstream's gem A gem is not moved to the patch registry while no locked build is patched. The same rule kept a lock that is ALREADY on the registry where it was when the build it pins was withdrawn and no other locked build is patched: the snapshot the lock names refuses that build from then on, so `bundle install` fails on that platform until someone unwinds by hand. A lock on the registry now follows the reference whatever it lists: the URL moves to the current snapshot and the withdrawn build's checksum goes back to the upstream gem's, which that registry hands on. A lock that was never moved still stays upstream. Also brings the vendored arm of the "left to patch" test to the line vendored mode prints for a platform without a patched build. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_redirect_gem_stale_install.rs | 5 +- .../src/patch/redirect/mod.rs | 47 ++++++++++++++++++- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index 930b2c7ba1..49fae8de0c 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -3327,7 +3327,10 @@ async fn refused_platform_gem_is_counted_as_left_to_patch() { &stdout, ), _ => ( - format!("the patch service has no prebuilt platform gem of `{DEP}`"), + format!( + "{DEP}@{DEP_VERSION} is not vendored: no patched build yet for \ + {OTHER_PLATFORM}" + ), &stderr, ), }; diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index c05695483c..5bbe27bb01 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -9281,8 +9281,12 @@ fn rewrite_gem( // No locked build is patched yet: moving the gem would // gain nothing, so it stays on its upstream registry until // a later reference lists a patched build for a platform - // the lock names. - if pinned.iter().all(|build| build.patch_uuid.is_none()) { + // the lock names. A lock that is on the registry already + // goes on: a build it pins was withdrawn since, and the + // registry as it stands serves upstream's gem for it, so + // the lock follows (its registry under the snapshot it + // names refuses that build now). + if !hosted && pinned.iter().all(|build| build.patch_uuid.is_none()) { result.gem_unpatched.insert( dep.patch_uuid.clone(), pinned.into_iter().filter_map(|b| b.platform).collect(), @@ -23643,6 +23647,45 @@ mod tests { ); } + /// A patched build that was withdrawn: the registry as it stands + /// lists upstream's gem for that platform, and the snapshot the lock + /// names refuses the build. A lock already on the registry follows + /// the reference even when no locked build is patched any more, so it + /// pins what is served: the upstream sha256, under the current URL. + #[test] + fn gem_hosted_lock_follows_a_withdrawn_build_back_to_upstreams_gem() { + let arm = "a".repeat(64); + let upstream = upstream_sha("1.18.10-arm64-darwin"); + let before = gem_override_at_snapshot("1a", &[("arm64-darwin", &arm, true)]); + let lock = nokogiri_lock(&["arm64-darwin"], false, true); + let (gemfile, moved, _) = gem_redirect(NOKOGIRI_GEMFILE, &lock, before); + assert!(moved.contains(&format!("sha256={arm}")), "{moved}"); + + let after = gem_override_at_snapshot("2b", &[("arm64-darwin", &upstream, false)]); + let (gemfile_after, lock_after, r) = gem_redirect(&gemfile, &moved, after.clone()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(r.gem_unpatched.is_empty()); + assert_eq!(builds_of(&r), [(Some("arm64-darwin"), None, false)]); + let (at_one, at_two) = ( + format!("{GEM_TEST_URL}s/1a/"), + format!("{GEM_TEST_URL}s/2b/"), + ); + assert_eq!(gemfile_after, gemfile.replace(&at_one, &at_two)); + assert_eq!( + lock_after, + moved + .replace(&at_one, &at_two) + .replace(&format!("sha256={arm}"), &format!("sha256={upstream}")) + ); + // A lock that was never moved stays upstream on the same reference. + let (_, _, fresh) = gem_redirect(NOKOGIRI_GEMFILE, &lock, after); + assert!(fresh.files.is_empty()); + assert_eq!( + fresh.gem_unpatched.get("uuid").map(Vec::as_slice), + Some(&["arm64-darwin".to_string()][..]) + ); + } + /// [`gem_override_listing`] with its registry at the snapshot `key` /// (`…/uuid/s/`, as the patch service spells it: no closing /// slash). From cd060b1cb827a80429f36c013c686ed28de40ff9 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 21:42:27 -0500 Subject: [PATCH 011/120] Tell the locked builds of a hosted gem apart by the sha256 the lock installs A gem patch's registry serves a patched build for some platforms and upstream's own gem for the others, and a lock that names platform builds takes all of them from it under one `GEM` section. The lock's wiring therefore says that the gem is on the registry, not which locked build is patched. A reader that has only the committed files and the patch service to go by (a VEX document made after the run that moved the lock) had nothing to decide that with. `vex::gem_builds` decides it per build, by the one thing a patched gem and upstream's gem never share: the sha256 of the archive. - `locked_gem_pins` reads the builds a lock names of a gem version, each with the sha256 its `CHECKSUMS` pins. - `gem_build_states` holds each against the list a gem patch's reference carries (`gemBuilds`). A platform build is the patched build of its platform's patch only on the sha256 the list gives beside that patch, and upstream's gem only on the one it gives beside none. For a build the lock's `CHECKSUMS` does not pin, the archive is the one the lock's own registry serves, read from that registry's compact-index document (`gem_index_url`). - Anything else is `Unknown`, with why: nothing names the archive the lock installs, the list leaves the platform out, or the lock installs another archive than the list names. The last is a list of a later registry than the one the lock names: a build that is patched there is not shown patched for a lock that does not pin it. The ruby-platform gem a patch's registry serves is the patch itself, so that entry is the gem's patch by the lock's wiring, as for a gem locked as its ruby-platform gem alone. Co-Authored-By: Claude Fable 5.2 --- .../socket-patch-core/src/vex/gem_builds.rs | 316 ++++++++++++++++++ crates/socket-patch-core/src/vex/mod.rs | 3 + 2 files changed, 319 insertions(+) create mode 100644 crates/socket-patch-core/src/vex/gem_builds.rs diff --git a/crates/socket-patch-core/src/vex/gem_builds.rs b/crates/socket-patch-core/src/vex/gem_builds.rs new file mode 100644 index 0000000000..809c7df627 --- /dev/null +++ b/crates/socket-patch-core/src/vex/gem_builds.rs @@ -0,0 +1,316 @@ +//! Which builds a Bundler lock pins of a gem it takes from a patch +//! registry as platform builds. +//! +//! The registry of a gem's patch lists every gem of the gem's version: the +//! patched ruby gem, a patched build for some platforms, and upstream's own +//! gem for the others (`registryOverride.identifiers.gemBuilds`). A lock +//! that names platform builds takes all of them from that registry, under +//! one `GEM` section, so its wiring says only that the gem is on the +//! registry. Which locked build is a patched one is decided per build, by +//! the one thing a patched gem and upstream's gem never share: the sha256 +//! of the archive ([`gem_build_states`]). +//! +//! What a lock installs for a build is the sha256 its `CHECKSUMS` section +//! pins. A lock without that entry installs whatever its own registry +//! serves, which that registry's compact-index document says +//! ([`gem_index_url`]). The list a patch's reference carries is of the +//! registry as it stands when the reference is made, which can be later +//! than the registry the lock names: a build is a patched one only when +//! the archive the lock installs is the one the list names for it. + +use crate::formats::gem; +use crate::patch::redirect::upstream::compact_index_checksum; +use crate::patch::redirect::GemPlatformChecksum; + +/// One build a Bundler lock names of a gem version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LockedGemPin { + /// The build's platform as the lock spells it; `None` for the + /// ruby-platform gem. + pub platform: Option, + /// The sha256 the lock's `CHECKSUMS` section pins for the build; + /// `None` where the lock has no valid entry for it. + pub sha256: Option, +} + +/// The builds the Bundler lock text `lock` names of the gem `name` at +/// `version`, the ruby-platform gem first, each with its `CHECKSUMS` pin. +/// Without a platform build among them the gem is locked as its +/// ruby-platform gem alone, or not at all. +pub fn locked_gem_pins(lock: &str, name: &str, version: &str) -> Vec { + let lock = crate::utils::line_endings::to_lf(lock); + let parsed = gem::parse(&lock); + let ids = parsed.locked_builds(name, version).ids(name, version); + ids.iter() + .map(|id| LockedGemPin { + platform: id.platform.clone(), + sha256: parsed.checksum(name, &id.token()).map(str::to_string), + }) + .collect() +} + +/// The compact-index document in which the registry at `remote` (a lock's +/// `remote:`) lists the gems of `name` it serves, one +/// `[-] |checksum:` line each. `None` for +/// a remote that is no http(s) URL or a name that is no plain gem token. +pub fn gem_index_url(remote: &str, name: &str) -> Option { + let http = remote.starts_with("https://") || remote.starts_with("http://"); + (http && gem::is_plain_gem_token(name)) + .then(|| format!("{}/info/{name}", remote.trim_end_matches('/'))) +} + +/// What a lock installs for one build of a gem on a patch registry. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GemBuildState { + /// The patched build of the patch `uuid`: the gem's own patch for the + /// ruby-platform gem, the platform's for a platform gem. + Patched { uuid: String }, + /// Upstream's own gem, which the registry lists and hands on for a + /// platform with no patched build. + Upstream, + /// Neither is shown. + Unknown(GemBuildUnknown), +} + +/// Why a locked build is neither shown patched nor shown upstream's. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum GemBuildUnknown { + /// Nothing names the archive the lock installs: no `CHECKSUMS` entry, + /// and no line in the index of the lock's registry. + Unpinned, + /// The list does not name the build's platform. + Unlisted, + /// The lock installs another archive than the list names: the list is + /// of a later state of the registry than the one the lock names. + Differs, +} + +/// What a lock installs for each of `pins`, the builds it names of a gem +/// at `version` on the registry of the patch `gem_uuid`. +/// +/// `listed` is what that patch's reference lists +/// ([`RegistryOverrideIdentifiers::gem_builds`]); `index` is the +/// compact-index document of the registry the lock names +/// ([`gem_index_url`]), read for a build the lock's `CHECKSUMS` does not +/// pin, and `None` where it was not read. +/// +/// A platform build is a patched one only when the sha256 the lock +/// installs for it is the one the list gives beside a patch, and +/// upstream's only when it is the one the list gives beside none. The +/// ruby-platform gem a patch's registry serves is the patch itself, so its +/// entry is the gem's patch by the lock's wiring, as for a gem locked as +/// its ruby-platform gem alone. +/// +/// [`RegistryOverrideIdentifiers::gem_builds`]: crate::patch::redirect::RegistryOverrideIdentifiers::gem_builds +pub fn gem_build_states( + version: &str, + pins: &[LockedGemPin], + gem_uuid: &str, + listed: &[GemPlatformChecksum], + index: Option<&str>, +) -> Vec { + pins.iter() + .map(|pin| { + let Some(platform) = pin.platform.as_deref() else { + return GemBuildState::Patched { + uuid: gem_uuid.to_string(), + }; + }; + let served = || compact_index_checksum(index?, &format!("{version}-{platform}")); + let Some(installed) = pin.sha256.clone().or_else(served) else { + return GemBuildState::Unknown(GemBuildUnknown::Unpinned); + }; + let Some(build) = listed.iter().find(|build| build.platform == platform) else { + return GemBuildState::Unknown(GemBuildUnknown::Unlisted); + }; + if !installed.eq_ignore_ascii_case(&build.gem_checksum_sha256) { + return GemBuildState::Unknown(GemBuildUnknown::Differs); + } + match &build.patch_uuid { + Some(uuid) => GemBuildState::Patched { uuid: uuid.clone() }, + None => GemBuildState::Upstream, + } + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + const GEM_UUID: &str = "7b1e4f3a-2c5d-4e6f-8a9b-0c1d2e3f4a5b"; + const LINUX_UUID: &str = "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e"; + const ARM: &str = "arm64-darwin"; + const LINUX: &str = "x86_64-linux-gnu"; + + fn sha(digit: char) -> String { + digit.to_string().repeat(64) + } + + fn pin(platform: Option<&str>, sha256: Option) -> LockedGemPin { + LockedGemPin { + platform: platform.map(str::to_string), + sha256, + } + } + + fn listed(platform: &str, sha256: String, patch: Option<&str>) -> GemPlatformChecksum { + GemPlatformChecksum { + platform: platform.to_string(), + gem_checksum_sha256: sha256, + patch_uuid: patch.map(str::to_string), + } + } + + /// `arm64-darwin` on upstream's gem (`a…`), `x86_64-linux-gnu` patched + /// (`b…`), and the ruby gem (`c…`). + fn list() -> Vec { + vec![ + listed(ARM, sha('a'), None), + listed("ruby", sha('c'), Some(GEM_UUID)), + listed(LINUX, sha('b'), Some(LINUX_UUID)), + ] + } + + fn patched(uuid: &str) -> GemBuildState { + GemBuildState::Patched { + uuid: uuid.to_string(), + } + } + + /// The builds a lock names come with what its `CHECKSUMS` pins for + /// each, the ruby-platform gem first; a bare entry and a missing one + /// pin nothing, and a lock with no platform build names none. + #[test] + fn a_locks_builds_come_with_their_checksums() { + let lock = format!( + "GEM\n remote: https://patch.example/patch-registry/gem/t/{GEM_UUID}/s/4f/\n \ + specs:\n nokogiri (1.18.10)\n nokogiri (1.18.10-{ARM})\n nokogiri \ + (1.18.10-{LINUX})\n nokogiri (1.18.10-java)\n\nGEM\n remote: \ + https://rubygems.org/\n specs:\n racc (1.8.1)\n\nCHECKSUMS\n nokogiri (1.18.10) \ + sha256={}\n nokogiri (1.18.10-{ARM}) sha256={}\n nokogiri (1.18.10-{LINUX})\n racc \ + (1.8.1) sha256={}\n", + sha('c'), + sha('a'), + sha('5'), + ); + assert_eq!( + locked_gem_pins(&lock, "nokogiri", "1.18.10"), + [ + pin(None, Some(sha('c'))), + pin(Some(ARM), Some(sha('a'))), + pin(Some("java"), None), + pin(Some(LINUX), None), + ] + ); + // CRLF reads the same. + assert_eq!( + locked_gem_pins(&lock.replace('\n', "\r\n"), "nokogiri", "1.18.10").len(), + 4 + ); + assert_eq!( + locked_gem_pins(&lock, "racc", "1.8.1"), + [pin(None, Some(sha('5')))] + ); + assert_eq!(locked_gem_pins(&lock, "nokogiri", "1.18.9"), []); + } + + /// A build is a patched one, under its platform's patch, only on the + /// sha256 the list gives beside that patch, and upstream's only on the + /// one it gives beside none. The ruby-platform gem is the gem's patch. + #[test] + fn a_build_is_judged_by_the_sha256_the_lock_pins() { + let pins = [ + pin(None, Some(sha('c'))), + pin(Some(ARM), Some(sha('a'))), + pin(Some(LINUX), Some(sha('b').to_uppercase())), + ]; + assert_eq!( + gem_build_states("1.18.10", &pins, GEM_UUID, &list(), None), + [ + patched(GEM_UUID), + GemBuildState::Upstream, + patched(LINUX_UUID) + ] + ); + } + + /// The list is of a later registry than the lock's: the build it names + /// patched is not the archive the lock pins, so it is not shown + /// patched. Nor is a build of a platform the list leaves out. + #[test] + fn a_list_later_than_the_lock_shows_nothing_patched_for_a_build_the_lock_pins_otherwise() { + let mut later = list(); + later[0] = listed(ARM, sha('d'), Some("1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d")); + let pins = [ + pin(Some(ARM), Some(sha('a'))), + pin(Some(LINUX), Some(sha('b'))), + pin(Some("java"), Some(sha('e'))), + ]; + assert_eq!( + gem_build_states("1.18.10", &pins, GEM_UUID, &later, None), + [ + GemBuildState::Unknown(GemBuildUnknown::Differs), + patched(LINUX_UUID), + GemBuildState::Unknown(GemBuildUnknown::Unlisted), + ] + ); + } + + /// A lock with no `CHECKSUMS` entry installs what its own registry + /// lists: the index names the archive, by the build's whole token. + /// With no index, or none that lists the build, nothing is shown. + #[test] + fn a_build_without_a_checksum_is_judged_by_the_index_of_the_locks_registry() { + let pins = [pin(Some(ARM), None), pin(Some(LINUX), None)]; + let index = format!( + "---\n1.18.10 racc:~> 1.4|checksum:{}\n1.18.10-{ARM} racc:~> 1.4|checksum:{}\n\ + 1.18.10-{LINUX} racc:~> 1.4|checksum:{},ruby:>= 3.1\n", + sha('c'), + sha('a'), + sha('b'), + ); + assert_eq!( + gem_build_states("1.18.10", &pins, GEM_UUID, &list(), Some(&index)), + [GemBuildState::Upstream, patched(LINUX_UUID)] + ); + let unknown = GemBuildState::Unknown(GemBuildUnknown::Unpinned); + assert_eq!( + gem_build_states("1.18.10", &pins, GEM_UUID, &list(), None), + [unknown.clone(), unknown.clone()] + ); + // The index of an earlier registry, where linux was upstream's gem. + let earlier = index.replace(&sha('b'), &sha('9')); + assert_eq!( + gem_build_states("1.18.10", &pins, GEM_UUID, &list(), Some(&earlier)), + [ + GemBuildState::Upstream, + GemBuildState::Unknown(GemBuildUnknown::Differs) + ] + ); + let other_version = index.replace("1.18.10", "1.18.9"); + assert_eq!( + gem_build_states("1.18.10", &pins, GEM_UUID, &list(), Some(&other_version)), + [unknown.clone(), unknown] + ); + } + + #[test] + fn the_index_of_a_registry_is_under_its_remote() { + let index = "https://patch.example/patch-registry/gem/t/u/s/4f/info/nokogiri"; + for remote in [ + "https://patch.example/patch-registry/gem/t/u/s/4f/", + "https://patch.example/patch-registry/gem/t/u/s/4f", + ] { + assert_eq!(gem_index_url(remote, "nokogiri").as_deref(), Some(index)); + } + assert_eq!( + gem_index_url("file:.socket/vendor/gem/u/", "nokogiri"), + None + ); + assert_eq!( + gem_index_url("https://patch.example/r/", "../versions"), + None + ); + } +} diff --git a/crates/socket-patch-core/src/vex/mod.rs b/crates/socket-patch-core/src/vex/mod.rs index bac74b7535..bbe21ee2c1 100644 --- a/crates/socket-patch-core/src/vex/mod.rs +++ b/crates/socket-patch-core/src/vex/mod.rs @@ -7,6 +7,8 @@ //! * [`build`] — manifest + applied-set → [`schema::Document`]. //! * [`discover`] — manifest-less input: Socket-patched dependency //! references (hosted + vendored) recovered from the project's lockfiles. +//! * [`gem_builds`] — which locked builds are patched of a gem a Bundler +//! lock takes from a patch registry as platform builds. //! * [`product`] — auto-detect the top-level product PURL from the //! filesystem (package.json / pyproject.toml / Cargo.toml / go.mod / //! composer.json / pom.xml / *.csproj / *.gemspec). @@ -19,6 +21,7 @@ pub mod build; pub mod discover; +pub mod gem_builds; pub mod grype_config; pub mod product; pub mod schema; From ccfc271cbc9aca7ea5f88720d4ab03cbb41a7668 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 21:42:38 -0500 Subject: [PATCH 012/120] Keep the clause and word wrap of a human line with the other text helpers A hosted scan breaks the line about a gem's builds after a clause when it prints on a terminal, so that no platform name is cut in two. `vex` is about to print a line of the same shape, and a command module may not import another one's helpers. `wrap_line`, `wrap_words` and `wrap_tokens` move from the hosted scan to `ui::text`, with their tests, unchanged. The hosted scan takes them from there. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/scan/hosted.rs | 136 +---------------- crates/socket-patch-cli/src/ui/mod.rs | 2 +- crates/socket-patch-cli/src/ui/text.rs | 143 +++++++++++++++++- 3 files changed, 144 insertions(+), 137 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 74967a8bee..7149fe7916 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -19,6 +19,7 @@ use crate::commands::vex::generate_vex_from_manifest_path; use crate::json_envelope::{ Envelope, EnvelopeError, PatchAction, PatchEvent, RunWarning, VexSummary, }; +use crate::ui::{wrap_line, wrap_words}; use socket_patch_core::formats::gem::GemBuild; use super::{discover_selected, emit_scan, scan_envelope, ScanArgs}; @@ -3273,54 +3274,6 @@ fn format_error_line(msg: &str) -> String { format!("Error: {}", crate::ui::sentence_case(msg)) } -/// Split `text` into wrap tokens at whitespace, except that a -/// backtick-delimited code span (`` `pnpm install --trust-lockfile` ``) -/// stays one token so a command the user copies is never broken across -/// lines. An unclosed span falls back to plain whitespace splitting. -fn wrap_tokens(text: &str) -> Vec { - let mut tokens: Vec = Vec::new(); - let mut span: Vec<&str> = Vec::new(); - for word in text.split_whitespace() { - span.push(word); - let open = span.iter().map(|w| w.matches('`').count()).sum::() % 2 == 1; - if !open { - tokens.push(span.join(" ")); - span.clear(); - } - } - tokens.extend(span.into_iter().map(str::to_string)); - tokens -} - -/// Greedy word wrap to `width` columns (characters, not bytes). The first -/// line starts with `first_prefix`, later lines with `indent`. A word -/// longer than the line (a URL) gets a line of its own, never split; a -/// backtick code span counts as one word (see [`wrap_tokens`]). -fn wrap_words(text: &str, width: usize, first_prefix: &str, indent: &str) -> Vec { - let mut lines: Vec = Vec::new(); - let mut line = first_prefix.to_string(); - let mut line_len = first_prefix.chars().count(); - let mut empty = true; - for word in wrap_tokens(text) { - let word = word.as_str(); - let wlen = word.chars().count(); - if !empty && line_len + 1 + wlen > width { - lines.push(std::mem::replace(&mut line, indent.to_string())); - line_len = indent.chars().count(); - empty = true; - } - if !empty { - line.push(' '); - line_len += 1; - } - line.push_str(word); - line_len += wlen; - empty = false; - } - lines.push(line); - lines -} - /// Split a long guidance paragraph into its sentences, at every period /// followed by a space (host names and versions such as `patch.socket.dev` /// or `5.4` never contain one). Each sentence keeps its own period; the @@ -3582,35 +3535,6 @@ fn format_gem_build_lines( lines } -/// `line` as it prints on stdout. With `width` (stdout is a terminal with -/// a person at it) a line that does not fit breaks after a clause (`; `) -/// under a two-space hanging indent, so no clause is cut in two unless it -/// is itself wider than the terminal, where it wraps at a word. Without -/// it the line is as it is, so a pipe or a log keeps one line. -fn wrap_line(line: &str, width: Option) -> String { - const INDENT: &str = " "; - let Some(width) = width else { - return line.to_string(); - }; - let mut rows: Vec = Vec::new(); - for clause in line.split_inclusive("; ") { - let clause = clause.trim_end(); - let room = if rows.len() > 1 { INDENT.len() } else { 0 }; - match rows.last_mut() { - Some(row) if room + row.chars().count() + 1 + clause.chars().count() <= width => { - row.push(' '); - row.push_str(clause); - } - _ => rows.push(clause.to_string()), - } - } - rows.iter() - .enumerate() - .flat_map(|(at, row)| wrap_words(row, width, if at == 0 { "" } else { INDENT }, INDENT)) - .collect::>() - .join("\n") -} - /// What wiring a gem to its patch source costs the project's update /// workflow, said once per run under [`format_gem_manifest_edits`]' lines. /// @@ -4135,7 +4059,7 @@ mod tests { describe_skip_reason, format_error_line, format_hosted_summary, format_next_steps, format_redirect_summary, format_takeover_line, format_unredirected, format_warning, join_names, lock_entry_warning_count, pnpm_trust_rerun_reminder, split_sentences, - wrap_tokens, wrap_words, GemCopies, TAKEOVER_INFO_CODES, + GemCopies, TAKEOVER_INFO_CODES, }; use super::{ gem_stale_install_warnings, gem_stale_warning, prune_ignored_warning, record_hosted_events, @@ -6514,62 +6438,6 @@ mod tests { ); } - #[test] - fn wrap_words_respects_width_prefix_and_long_words() { - assert_eq!( - wrap_words("alpha beta gamma delta", 16, "W: ", " "), - vec!["W: alpha beta", " gamma delta"] - ); - // A word wider than the line sits alone, unsplit. - let url = "https://patch.socket.dev/very/long/path/that/does/not/fit"; - assert_eq!( - wrap_words(&format!("see {url} now"), 20, "", " "), - vec!["see".to_string(), format!(" {url}"), " now".to_string()] - ); - assert_eq!(wrap_words("", 10, "W: ", " "), vec!["W: "]); - // Counts characters, not bytes. - let lines = wrap_words("ééé ééé ééé", 8, "", ""); - assert_eq!(lines, vec!["ééé ééé", "ééé"]); - for line in wrap_words(&"word ".repeat(50), 30, "Warning: ", " ") { - assert!(line.chars().count() <= 30, "{line}"); - } - } - - #[test] - fn wrap_words_keeps_code_spans_whole() { - // The span crosses the wrap column: it moves to the next line whole. - assert_eq!( - wrap_words( - "never rebuild it (`pnpm clean --lockfile`), ever", - 30, - "", - " " - ), - vec!["never rebuild it", " (`pnpm clean --lockfile`),", " ever"] - ); - // A span wider than the line gets a line of its own, unsplit. - assert_eq!( - wrap_words( - "use `pnpm install --frozen-lockfile --store-dir ` now", - 20, - "", - " " - ), - vec![ - "use", - " `pnpm install --frozen-lockfile --store-dir `", - " now" - ] - ); - // Two spans in one word, and a word with a closed span, split normally. - assert_eq!( - wrap_tokens("a `b` c `d e`f g"), - vec!["a", "`b`", "c", "`d e`f", "g"] - ); - // An unclosed span never swallows the rest of the text. - assert_eq!(wrap_tokens("a `b c d"), vec!["a", "`b", "c", "d"]); - } - #[test] fn split_sentences_keeps_hosts_and_versions_whole() { assert_eq!( diff --git a/crates/socket-patch-cli/src/ui/mod.rs b/crates/socket-patch-cli/src/ui/mod.rs index bb706da3e5..4241282fa6 100644 --- a/crates/socket-patch-cli/src/ui/mod.rs +++ b/crates/socket-patch-cli/src/ui/mod.rs @@ -32,7 +32,7 @@ pub(crate) use status::StatusLine; pub(crate) use text::{ agent_next_steps, folded, manifest_error_message, next_steps, next_steps_installed, package_names, plural, printable, sentence_case, shell_word, short_uuid, sweep_failure, - truncate, worst_and_ids, + truncate, worst_and_ids, wrap_line, wrap_words, }; /// [`text::no_patches_message`] for this run: the manifest path is named diff --git a/crates/socket-patch-cli/src/ui/text.rs b/crates/socket-patch-cli/src/ui/text.rs index eb67e05ec4..38824c5e03 100644 --- a/crates/socket-patch-cli/src/ui/text.rs +++ b/crates/socket-patch-cli/src/ui/text.rs @@ -1,6 +1,6 @@ //! Pure text helpers for human output: counted nouns, one-line -//! truncation, sentence casing and the "Next steps:" block. No I/O, no -//! terminal state. +//! truncation, word wrap, sentence casing and the "Next steps:" block. No +//! I/O, no terminal state. /// `plural(1, "package", "packages")` → `"1 package"`, /// `plural(2, "package", "packages")` → `"2 packages"` (and `0 packages`). @@ -10,6 +10,89 @@ pub fn plural(n: usize, one: &str, many: &str) -> String { const ELLIPSIS: &str = "..."; +/// Split `text` into wrap tokens at whitespace, except that a +/// backtick-delimited code span (`` `pnpm install --trust-lockfile` ``) +/// stays one token so a command the user copies is never broken across +/// lines. An unclosed span falls back to plain whitespace splitting. +pub(crate) fn wrap_tokens(text: &str) -> Vec { + let mut tokens: Vec = Vec::new(); + let mut span: Vec<&str> = Vec::new(); + for word in text.split_whitespace() { + span.push(word); + let open = span.iter().map(|w| w.matches('`').count()).sum::() % 2 == 1; + if !open { + tokens.push(span.join(" ")); + span.clear(); + } + } + tokens.extend(span.into_iter().map(str::to_string)); + tokens +} + +/// Greedy word wrap to `width` columns (characters, not bytes). The first +/// line starts with `first_prefix`, later lines with `indent`. A word +/// longer than the line (a URL) gets a line of its own, never split; a +/// backtick code span counts as one word (see [`wrap_tokens`]). +pub(crate) fn wrap_words( + text: &str, + width: usize, + first_prefix: &str, + indent: &str, +) -> Vec { + let mut lines: Vec = Vec::new(); + let mut line = first_prefix.to_string(); + let mut line_len = first_prefix.chars().count(); + let mut empty = true; + for word in wrap_tokens(text) { + let word = word.as_str(); + let wlen = word.chars().count(); + if !empty && line_len + 1 + wlen > width { + lines.push(std::mem::replace(&mut line, indent.to_string())); + line_len = indent.chars().count(); + empty = true; + } + if !empty { + line.push(' '); + line_len += 1; + } + line.push_str(word); + line_len += wlen; + empty = false; + } + lines.push(line); + lines +} + +/// `line` as it prints for a person. With `width` (its stream is a +/// terminal with a person at it) a line that does not fit breaks after a +/// clause (`; `) +/// under a two-space hanging indent, so no clause is cut in two unless it +/// is itself wider than the terminal, where it wraps at a word. Without +/// it the line is as it is, so a pipe or a log keeps one line. +pub(crate) fn wrap_line(line: &str, width: Option) -> String { + const INDENT: &str = " "; + let Some(width) = width else { + return line.to_string(); + }; + let mut rows: Vec = Vec::new(); + for clause in line.split_inclusive("; ") { + let clause = clause.trim_end(); + let room = if rows.len() > 1 { INDENT.len() } else { 0 }; + match rows.last_mut() { + Some(row) if room + row.chars().count() + 1 + clause.chars().count() <= width => { + row.push(' '); + row.push_str(clause); + } + _ => rows.push(clause.to_string()), + } + } + rows.iter() + .enumerate() + .flat_map(|(at, row)| wrap_words(row, width, if at == 0 { "" } else { INDENT }, INDENT)) + .collect::>() + .join("\n") +} + /// `text` as it may be printed: without its control characters. For /// text that came from a service or a project's files, which is shown /// for reading and must never move the cursor, retitle the terminal or @@ -348,6 +431,62 @@ pub(crate) fn shell_word(word: &str) -> String { mod tests { use super::*; + #[test] + fn wrap_words_respects_width_prefix_and_long_words() { + assert_eq!( + wrap_words("alpha beta gamma delta", 16, "W: ", " "), + vec!["W: alpha beta", " gamma delta"] + ); + // A word wider than the line sits alone, unsplit. + let url = "https://patch.socket.dev/very/long/path/that/does/not/fit"; + assert_eq!( + wrap_words(&format!("see {url} now"), 20, "", " "), + vec!["see".to_string(), format!(" {url}"), " now".to_string()] + ); + assert_eq!(wrap_words("", 10, "W: ", " "), vec!["W: "]); + // Counts characters, not bytes. + let lines = wrap_words("ééé ééé ééé", 8, "", ""); + assert_eq!(lines, vec!["ééé ééé", "ééé"]); + for line in wrap_words(&"word ".repeat(50), 30, "Warning: ", " ") { + assert!(line.chars().count() <= 30, "{line}"); + } + } + + #[test] + fn wrap_words_keeps_code_spans_whole() { + // The span crosses the wrap column: it moves to the next line whole. + assert_eq!( + wrap_words( + "never rebuild it (`pnpm clean --lockfile`), ever", + 30, + "", + " " + ), + vec!["never rebuild it", " (`pnpm clean --lockfile`),", " ever"] + ); + // A span wider than the line gets a line of its own, unsplit. + assert_eq!( + wrap_words( + "use `pnpm install --frozen-lockfile --store-dir ` now", + 20, + "", + " " + ), + vec![ + "use", + " `pnpm install --frozen-lockfile --store-dir `", + " now" + ] + ); + // Two spans in one word, and a word with a closed span, split normally. + assert_eq!( + wrap_tokens("a `b` c `d e`f g"), + vec!["a", "`b`", "c", "`d e`f", "g"] + ); + // An unclosed span never swallows the rest of the text. + assert_eq!(wrap_tokens("a `b c d"), vec!["a", "`b", "c", "d"]); + } + #[test] fn packages_of_one_ecosystem_are_named_without_it() { assert_eq!( From dac30b4c1dca8694b330f6cbe69d31dfcfdf1343 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 21:43:12 -0500 Subject: [PATCH 013/120] Attest each locked build of a hosted gem by what the lock installs A gem that a Bundler lock takes from its patch registry as platform builds is one hosted pin, and a VEX document attested it as one: the gem, under the gem's patch. The registry serves a patched build for some platforms and upstream's own gem for the others, so that statement said `not_affected` of a platform that installs the unpatched gem, and it named the gem's patch where each patched build has a patch of its own. A scanner that finds the platform gem of such a platform was told to drop a finding that is real. The gem is still judged as the one pin it is. The document then names each locked build (`pkg:gem/@?platform=`, and the gem's own purl for a ruby-platform entry beside them): - a patched build is `not_affected` under its own patch, with the vulnerabilities of the gem patch's record, since the fix is the same in every build; - a build the lock installs as upstream's own gem is `affected`, with what changes that as its action statement. This is the document's rule for a package the build is known to take without its patch, the one a Bazel hub already falls under; - a build of which neither is shown is left out, and a warning names the gem, the reason and what to run (`vex_gem_build_unknown`). The records of all of them stay in the view the document is built from, so no statement names a form of the gem (the purl without a platform) that also stands for a build the document does not call patched. Where the builds come from: - `scan --mode hosted --vex` and `get --mode hosted --vex` hand over what the run reports per locked build (`engine::pin_reports`), so the run's own document costs no request beyond the run's. - A later `vex` (and the `--vex` of `apply` and `vendor`) reads the lock and asks the patch service once for the references of the gems' patches (one request for all of them). A build is attested by its patch only when the sha256 the lock's `CHECKSUMS` pins for it is the one the reference lists beside that patch. For a lock with no `CHECKSUMS`, the index of the registry the lock names is read too, once per gem: that is what such a lock installs. The reference can be of a later registry than the lock's; a build it lists as patched while the lock pins another archive is not attested. - `--offline`, a failed request, a reference with no list: nothing is known of the platform builds, and none is attested. A ruby-platform entry beside them is the gem's patch by the lock's wiring, as before. - A gem locked as its ruby-platform gem alone, and every other ecosystem, are as they were, with no request of their own. An installed copy is evidence about its own build alone. A machine of a platform on upstream's gem holds upstream's gem, as its lock entry names it; judged as the gem's copy it withheld the builds the lock does install patched. The copy of a build the lock does not install patched is not judged, and the copy of one it does still is. What a run says: - `vex --json` reports a build on upstream's gem as the hosted scan does: an uncounted `skipped` event under `gem_upstream_build_kept`, which does not make the run a partial failure. The events of every build named in place of a gem carry `details.gemFix` (the gem's patch) and `details.platform`, a gem vendored as platform gems included. - For a person, `vex` prints one line per gem under its summary, in the words of the scan's own line (`nokogiri 1.19.3: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`), with `not attested for ` for a build left out. On a terminal it breaks after a clause. - The line that folds several omissions of one reason names a platform gem with its platform, since the builds of one gem share its name. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/scan/hosted.rs | 7 + crates/socket-patch-cli/src/commands/vex.rs | 293 +++- .../src/commands/vex_sources.rs | 1392 ++++++++++++++++- crates/socket-patch-cli/src/json_envelope.rs | 7 +- .../tests/e2e_redirect_gem_platform_builds.rs | 838 ++++++++++ .../vendor/vendor_gem_platform_builds_e2e.rs | 20 + crates/socket-patch-core/src/hosted/engine.rs | 3 +- 7 files changed, 2487 insertions(+), 73 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 7149fe7916..bc81806ba1 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -2634,6 +2634,13 @@ async fn run_redirect_selected_untracked( // v5 keeps no hosted ledger: the in-run attestation fetches the // records of the pins this run confirmed. params.hosted_uuids = confirmed.iter().map(|(_, uuid)| uuid.clone()).collect(); + // A gem pinned as platform builds is one pin, and the registry + // serves upstream's own gem for a platform with no patched build: + // the document names each locked build, as this run reports them. + params.hosted_gem_builds = engine::pin_reports(&confirmed, rewrite) + .into_iter() + .filter(|report| report.gem_fix.is_some()) + .collect(); // The gem intake gate withholds every gem file. VEX independently // rediscovers older pins too, so a candidate-only set would miss some // refused hosted gems. Keep their actual installed-byte verification, diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index db9d1b3ec0..eac1d2dbe7 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -33,8 +33,9 @@ use socket_patch_core::vex::{ use crate::args::{apply_env_toggles, parse_bool_flag, GlobalArgs}; use crate::commands::vex_grype; use crate::commands::vex_sources::{ - self, Plan, RunApiClient, Sources, GO_WORKSPACE_OVERRIDE, RECORD_MISMATCH, RECORD_UNAVAILABLE, - REDIRECT_UNWIRED, VENDOR_UNWIRED, WIRING_CONFLICT, + self, GemBuildInfo, HostedGemBuild, Plan, RunApiClient, Sources, GEM_BUILD_UNKNOWN, + GO_WORKSPACE_OVERRIDE, RECORD_MISMATCH, RECORD_UNAVAILABLE, REDIRECT_UNWIRED, VENDOR_UNWIRED, + WIRING_CONFLICT, }; use crate::ecosystem_dispatch::{find_manifest_package_copies_reusing, JvmScope}; use crate::json_envelope::{Command, Envelope, EnvelopeError, PatchAction, PatchEvent, RunWarning}; @@ -226,6 +227,7 @@ impl VexEmbedArgs { flag_prefix: "--vex-", npm_prior: None, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), warnings_printed: Default::default(), } } @@ -296,6 +298,14 @@ pub(crate) struct VexBuildParams { /// standalone `vex` finds them through the lockfiles instead). Empty /// everywhere else. pub hosted_uuids: Vec, + /// Embedded hosted `scan --vex` only: what THIS RUN reports for each + /// locked build of the gems it pinned as platform builds + /// (`engine::pin_reports`, the reports that name a gem patch). The + /// document names those builds one by one, each patched build under + /// its own patch, and the plan asks nothing more to tell them apart + /// (see `vex_sources::Sources::hosted_gem_builds`). Empty everywhere + /// else. + pub hosted_gem_builds: Vec, /// The run's API client (see [`RunApiClient`]): seeded by a host /// command, else built at most once when the plan must fetch records. /// Telemetry reads its route when it exists. @@ -327,8 +337,21 @@ impl VexBuildParams { /// Successful result of [`generate_vex`]. pub(crate) struct VexWriteSummary { pub statements: usize, - /// How many of them say `affected` ([`unbuilt_by_bazel`]). + /// How many of them say `affected`: of a package Bazel builds without + /// its patch ([`unbuilt_by_bazel`]), or of a gem build the lockfile + /// takes from a patch registry as upstream's own gem + /// ([`GemBuildView::kept_upstream`]). + /// + /// [`GemBuildView::kept_upstream`]: crate::commands::vex_sources::GemBuildView::kept_upstream pub affected: usize, + /// The builds the document names in place of a gem (a gem vendored as + /// platform gems, or taken from its patch registry as platform + /// builds), by purl: the standalone `vex` envelope says of each event + /// which gem patch it goes by. + pub gem_builds: std::collections::BTreeMap, + /// One line per gem whose locked builds this run told apart + /// ([`gem_build_lines`]), for a person. + pub gem_build_lines: Vec, pub failed: Vec, /// The built document — returned so the standalone `vex` command can /// emit its per-subcomponent envelope without rebuilding. @@ -362,6 +385,9 @@ pub(crate) struct VexGenError { /// diagnostics say why a lockfile's mention is not live wiring). The /// `--json` error envelopes carry them. pub warnings: Vec, + /// The builds among `failed` that the document would have named in + /// place of a gem, by purl (see [`VexWriteSummary::gem_builds`]). + pub gem_builds: std::collections::BTreeMap, } impl VexGenError { @@ -463,6 +489,7 @@ pub async fn run(args: VexArgs) -> i32 { flag_prefix: "--", npm_prior: None, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), api_client: RunApiClient::new(), warnings_printed: Default::default(), }; @@ -501,6 +528,25 @@ pub async fn run(args: VexArgs) -> i32 { } None => eprintln!("{}", format_vex_emitted(count, summary.affected)), } + // Under it, which builds are attested of a gem the lock + // takes from its patch registry as platform builds. Beside + // the summary: stdout holds the document when it holds no + // summary. On a terminal a long line breaks after a clause. + let on_stdout = output.is_some(); + let width = + match on_stdout { + true => crate::ui::attended(crate::ui::Stream::Stdout) + .then(crate::ui::stdout_width), + false => crate::ui::attended(crate::ui::Stream::Stderr) + .then(crate::ui::stderr_width), + }; + for line in &summary.gem_build_lines { + let line = crate::ui::wrap_line(line, width); + match on_stdout { + true => println!("{line}"), + false => eprintln!("{line}"), + } + } if let Some(line) = grype.as_ref().and_then(|g| g.human_line()) { println!("{line}"); } @@ -591,7 +637,7 @@ pub async fn run(args: VexArgs) -> i32 { &args, e.code, &message, - &e.failed, + (&e.failed, &e.gem_builds), &gems, &run_warnings, grype.as_ref(), @@ -867,7 +913,6 @@ async fn generate_vex( && purl.starts_with("pkg:gem/") && plan.hosted.contains_key(purl)) }; - let redirected: &[String] = &plan.redirected; let product_id = match resolve_product_id( common, params.product.as_deref(), @@ -1012,13 +1057,21 @@ async fn generate_vex( // maven's suffixed version; every copy where hosted and registry // bytes share a location) — never by a pristine sibling the // crawler's first match may be. See `vex_consumed`. - let hosted = crate::commands::vex_consumed::hosted_consumed_copies( + let mut hosted = crate::commands::vex_consumed::hosted_consumed_copies( common, &plan.hosted, &copies, params.npm_prior.as_ref(), ) .await; + // A gem the lock takes from its registry as platform builds: the + // copy of a build the lock does not install patched is upstream's + // own gem by the lock, and says nothing of the other builds. + for (purl, gem) in &plan.hosted_gems { + if let Some(consumed) = hosted.get_mut(purl) { + consumed.paths.retain(|path| gem.judges(purl, path)); + } + } let vendor = VendorContext { project_root: common.cwd.clone(), entries: plan.vendor_entries.clone(), @@ -1512,18 +1565,24 @@ async fn generate_vex( tooling: Some(format!("socket-patch {}", env!("CARGO_PKG_VERSION"))), }; - // A gem vendored as platform gems was judged above as the one copy it - // is; the document names each of its platform gems, under the patch - // that built it (see `GemBuildView`). + // A gem vendored as platform gems, or taken from its patch registry as + // platform builds, was judged above as the one copy or pin it is; the + // document names each of its builds: a patched one under the patch + // that built it, and a hosted one the lock installs as upstream's own + // gem as affected (see `GemBuildView`). let mut affected = affected; + let mut redirected = plan.redirected.clone(); let gem_builds = crate::commands::vex_sources::GemBuildView::of(&plan); if let Some(builds) = &gem_builds { builds.expand(&mut outcome.applied); builds.expand(&mut outcome.vendored); builds.expand(&mut outcome.code_not_present); + builds.expand(&mut redirected); builds.expand_noted(&mut affected); + affected.extend(builds.kept_upstream().iter().cloned()); } let manifest = gem_builds.as_ref().map_or(manifest, |builds| builds.view()); + let redirected: &[String] = &redirected; // `--no-verify` declared these applied with nothing checked on disk. The // purls an in-run hosted redirect confirmed are attested from that run's @@ -1577,6 +1636,9 @@ async fn generate_vex( failed: outcome.failed, hosted, warnings: Vec::new(), + gem_builds: gem_builds + .map(|builds| builds.builds().clone()) + .unwrap_or_default(), }); } }; @@ -1668,6 +1730,10 @@ async fn generate_vex( Ok(VexWriteSummary { statements: doc.statements.len(), affected: doc.statements.iter().filter(says_affected).count(), + gem_build_lines: gem_build_lines(&plan, &outcome.applied), + gem_builds: gem_builds + .map(|builds| builds.builds().clone()) + .unwrap_or_default(), failed: outcome.failed, doc, warnings: Vec::new(), @@ -2175,6 +2241,58 @@ fn vendored_out_of_sync_detail(purl: &str, copies: &[&Path], notes: &str) -> Str ) } +/// Which builds the document attests of each gem whose locked builds this +/// run told apart (the gems of [`Plan::hosted_gems`] the plan worked out), +/// one line per gem, in the words of the hosted scan's own line: +/// `nokogiri 1.19.3: patched for x86_64-linux-gnu; upstream gem kept for +/// arm64-darwin (no patched build yet)`. A build the document leaves out +/// (nothing shows what the lock installs for it, or the gem's installed +/// copy did not verify) is `not attested for `: the run's +/// warnings say why. The ruby-platform gem, where the lock names it beside +/// the platform builds, is the platform `ruby`. `applied` are the purls +/// the document attests as patched. +fn gem_build_lines(plan: &Plan, applied: &[String]) -> Vec { + use socket_patch_core::vex::gem_builds::GemBuildState; + let attested = |build: &HostedGemBuild| { + matches!(build.state, GemBuildState::Patched { .. }) && applied.contains(&build.purl) + }; + let kept = |build: &HostedGemBuild| build.state == GemBuildState::Upstream; + plan.hosted_gems + .values() + .filter(|gem| gem.resolved) + .map(|gem| { + let platforms = |keep: &dyn Fn(&HostedGemBuild) -> bool| -> String { + let named: Vec<&str> = gem + .builds + .iter() + .filter(|build| keep(build)) + .map(|build| build.platform.as_deref().unwrap_or("ruby")) + .collect(); + named.join(", ") + }; + let parts = [ + ("patched for", platforms(&attested), ""), + ( + "upstream gem kept for", + platforms(&kept), + " (no patched build yet)", + ), + ( + "not attested for", + platforms(&|build| !attested(build) && !kept(build)), + "", + ), + ]; + let parts: Vec = parts + .into_iter() + .filter(|(_, platforms, _)| !platforms.is_empty()) + .map(|(lead, platforms, tail)| format!("{lead} {platforms}{tail}")) + .collect(); + format!("{} {}: {}", gem.name, gem.version, parts.join("; ")) + }) + .collect() +} + /// Record a run-level advisory: into `warnings`, which the `--json` /// envelope carries in `warnings[]`. A human run prints it later, folded /// with the others of its kind ([`flush_warnings`]): nothing prints while @@ -2511,6 +2629,7 @@ async fn generate_vex_from_manifest_path_inner( discovery, // Their records join a pre-v5 ledger's as the hosted record source. hosted_uuids: params.hosted_uuids.clone(), + hosted_gem_builds: params.hosted_gem_builds.clone(), }; if sources.is_empty() { // A discovery diagnostic (an unparseable lock, a rejected reference) @@ -2530,6 +2649,7 @@ async fn generate_vex_from_manifest_path_inner( failed: Vec::new(), hosted: Vec::new(), warnings: Vec::new(), + gem_builds: Default::default(), } } else { fail(common, params, "manifest_not_found", message).await @@ -2566,6 +2686,7 @@ async fn fail( failed: Vec::new(), hosted: Vec::new(), warnings: Vec::new(), + gem_builds: Default::default(), } } @@ -2757,14 +2878,19 @@ async fn synthesize_go_patches( /// Emit a `vex` error to the active output channel: an error envelope on /// stdout in `--json` mode, a stderr message otherwise. `failures` lists /// patches omitted by verification (populated for `no_applicable_patches`, -/// empty everywhere else), `gems` the hosted gems among them that the hint -/// sends to the scan; `warnings` are the run's advisories, already on -/// stderr in human mode, folded into the envelope's `warnings[]` here. +/// empty everywhere else), with the builds among them that stand for a gem +/// ([`VexGenError::gem_builds`]); `gems` are the hosted gems among them +/// that the hint sends to the scan; `warnings` are the run's advisories, +/// already on stderr in human mode, folded into the envelope's +/// `warnings[]` here. fn emit_envelope_error( args: &VexArgs, code: &str, message: &str, - failures: &[FailedPatch], + (failures, gem_builds): ( + &[FailedPatch], + &std::collections::BTreeMap, + ), gems: &StaleHostedGems, warnings: &[RunWarning], grype: Option<&vex_grype::GrypeConfigOutcome>, @@ -2776,10 +2902,7 @@ fn emit_envelope_error( } env.dry_run = args.common.dry_run; for f in failures { - env.record( - PatchEvent::new(PatchAction::Skipped, f.purl.clone()) - .with_reason(f.reason.clone(), omission_reason_message(&f.reason)), - ); + env.record(omission_event(f, gem_builds)); } env.mark_error(EnvelopeError::new(code, message.to_string())); env.warnings = warnings.to_vec(); @@ -2904,6 +3027,10 @@ fn omission_phrase(reason: &str) -> &'static str { "another package bundles its own copy, which no Socket wiring reaches (the \ warning above names it)" } + GEM_BUILD_UNKNOWN => { + "it is not shown whether the lockfile installs a patched build for this platform \ + (the warning above says why, and what to run)" + } _ => "the patch could not be verified", } } @@ -2917,6 +3044,28 @@ fn format_omission_warning(purl: &str, reason: &str) -> String { ) } +/// How a line names the packages `purls` it leaves out +/// ([`crate::ui::package_names`]), a platform gem with its platform: the +/// builds of one gem share its name and version. +fn omitted_names(purls: &[&str]) -> Vec { + use socket_patch_core::crawlers::Ecosystem; + use socket_patch_core::utils::purl::{percent_decode_purl_component, purl_qualifier}; + crate::ui::package_names(purls) + .into_iter() + .zip(purls) + .map(|(name, purl)| { + let platform = purl_qualifier(purl, "platform") + .filter(|_| Ecosystem::from_purl(purl) == Some(Ecosystem::Gem)); + match platform { + Some(platform) => { + format!("{name} ({})", percent_decode_purl_component(platform)) + } + None => name, + } + }) + .collect() +} + /// The stderr lines for the patches left out of the document: one per /// reason, with the count and the first few packages (a project that has /// not installed its patched packages yet leaves every one of them out @@ -2946,7 +3095,7 @@ fn omission_lines(failed: &[FailedPatch], verbose: bool) -> Vec { "Warning: omitting {} packages from VEX: {} ({reason}): {}{}", purls.len(), omission_phrase(reason), - crate::ui::folded(&crate::ui::package_names(&purls), NAMES_SHOWN), + crate::ui::folded(&omitted_names(&purls), NAMES_SHOWN), if purls.len() > NAMES_SHOWN { " (--verbose lists them all)" } else { @@ -3096,39 +3245,95 @@ fn omission_reason_message(reason: &str) -> String { format!("patch omitted from VEX: {}", omission_phrase(reason)) } +/// Say in `details` which gem patch a build named in place of a gem goes +/// by (`gemFix`), and its platform, as the hosted and vendored runs' own +/// events do. +fn gem_build_details(build: &GemBuildInfo, details: &mut serde_json::Value) { + details["gemFix"] = serde_json::json!(build.gem_fix); + if let Some(platform) = &build.platform { + details["platform"] = serde_json::json!(platform); + } +} + +/// The `skipped` event of a patch the document leaves out: its routing +/// tag as `errorCode`, the reason in words, and, for a build among +/// `gem_builds`, the gem patch it goes by ([`gem_build_details`]). +fn omission_event( + f: &FailedPatch, + gem_builds: &std::collections::BTreeMap, +) -> PatchEvent { + let event = PatchEvent::new(PatchAction::Skipped, f.purl.clone()) + .with_reason(f.reason.clone(), omission_reason_message(&f.reason)); + match gem_builds.get(&f.purl) { + Some(build) => { + let mut details = serde_json::json!({}); + gem_build_details(build, &mut details); + event.with_details(details) + } + None => event, + } +} + fn emit_envelope_success( summary: &VexWriteSummary, dry_run: bool, grype: Option<&vex_grype::GrypeConfigOutcome>, ) { + use socket_patch_core::hosted::engine::{ + gem_upstream_build_kept_detail, GEM_UPSTREAM_BUILD_KEPT, + }; let mut env = Envelope::new(Command::Vex); env.dry_run = dry_run; + // Some package is in the document as affected because its patch is not + // in what gets built. + let mut unbuilt = false; for st in &summary.doc.statements { for prod in &st.products { for sub in &prod.subcomponents { + let mut details = serde_json::json!({ + "vulnerability": st.vulnerability.name, + "aliases": st.vulnerability.aliases, + "status": st.status, + }); + let build = summary.gem_builds.get(&sub.id); + if let Some(build) = build { + gem_build_details(build, &mut details); + } // A package the document says is affected is not reported // as verified, nor counted as such: it is skipped, like a // patch the document leaves out, under its own code. let event = match st.status { - Status::Affected => PatchEvent::new(PatchAction::Skipped, sub.id.clone()) - .with_reason(BAZEL_NOT_IN_BUILD, AFFECTED_REASON), + Status::Affected => match build.filter(|build| build.kept_upstream) { + // A gem build on upstream's gem: nothing was + // skipped and nothing failed, that platform is as + // it was. Reported as the hosted run reports it, + // and counted nowhere. + Some(build) => { + let platform = build.platform.as_deref().unwrap_or_default(); + let event = PatchEvent::new(PatchAction::Skipped, sub.id.clone()) + .with_reason( + GEM_UPSTREAM_BUILD_KEPT, + gem_upstream_build_kept_detail(platform), + ); + env.events.push(event.with_details(details)); + continue; + } + None => { + unbuilt = true; + PatchEvent::new(PatchAction::Skipped, sub.id.clone()) + .with_reason(BAZEL_NOT_IN_BUILD, AFFECTED_REASON) + } + }, _ => PatchEvent::new(PatchAction::Verified, sub.id.clone()), }; - env.record(event.with_details(serde_json::json!({ - "vulnerability": st.vulnerability.name, - "aliases": st.vulnerability.aliases, - "status": st.status, - }))); + env.record(event.with_details(details)); } } } for f in &summary.failed { - env.record( - PatchEvent::new(PatchAction::Skipped, f.purl.clone()) - .with_reason(f.reason.clone(), omission_reason_message(&f.reason)), - ); + env.record(omission_event(f, &summary.gem_builds)); } - if !summary.failed.is_empty() || summary.affected > 0 { + if !summary.failed.is_empty() || unbuilt { env.mark_partial_failure(); } env.warnings = summary.warnings.clone(); @@ -3363,6 +3568,29 @@ mod tests { content (not_applied): pkg:npm/a@1.0.0, pkg:pypi/b@2.0.0" ] ); + // The builds of one gem share its name: each is named with its + // platform. + assert_eq!( + omission_lines( + &[ + failed( + "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin", + GEM_BUILD_UNKNOWN + ), + failed( + "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + GEM_BUILD_UNKNOWN + ), + ], + false + ), + [ + "Warning: omitting 2 packages from VEX: it is not shown whether the lockfile \ + installs a patched build for this platform (the warning above says why, and what \ + to run) (vex_gem_build_unknown): nokogiri@1.18.10 (arm64-darwin), nokogiri@1.18.10 \ + (x86_64-linux-gnu)" + ] + ); } /// Advisories of one kind print once in full, then as one line naming @@ -3955,6 +4183,7 @@ mod npm_prior_tests { flag_prefix: "--vex-", npm_prior: prior, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), api_client: RunApiClient::new(), warnings_printed: Default::default(), }; @@ -4084,6 +4313,7 @@ mod mirror_refusal_tests { redirected: vec![purls[0].to_string(), purls[2].to_string()], lockfile_basis: HashSet::from([purls[0].to_string(), purls[2].to_string()]), hosted, + hosted_gems: Default::default(), gated: Vec::new(), notes: Vec::new(), }; @@ -4206,6 +4436,7 @@ mod mirror_refusal_tests { redirected: vec![gem.to_string(), npm.to_string()], lockfile_basis: HashSet::from([gem.to_string(), npm.to_string()]), hosted, + hosted_gems: Default::default(), gated: Vec::new(), notes: Vec::new(), }; @@ -4385,6 +4616,7 @@ mod unjudged_tests { .into_iter() .collect::>(), hosted, + hosted_gems: Default::default(), gated: Vec::new(), notes: Vec::new(), }; @@ -4512,6 +4744,7 @@ mod bazel_tests { redirected: vec![purls[2].to_string()], lockfile_basis: HashSet::new(), hosted: BTreeMap::from([(purls[2].to_string(), wiring)]), + hosted_gems: Default::default(), gated: Vec::new(), notes: Vec::new(), }; diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index af6baea06f..bccdf1a1b7 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -72,6 +72,18 @@ //! DISCOVERED Socket-host reference with a lockfile pin, attests from the //! pinned wiring (the in-run `scan --mode hosted --vex` evidence); //! `Installed` is the agent-mode path. +//! +//! A gem that a Bundler lock takes from its patch registry as platform +//! builds is one hosted pin, but not one answer: the registry serves a +//! patched build for some platforms and upstream's own gem for the others. +//! The plan works out what the lock installs for each build it names +//! ([`Plan::hosted_gems`]): from the hosted run it is part of, or from the +//! lock and at most two requests per gem (the gem patch's reference, and +//! the index of the lock's registry where the lock has no `CHECKSUMS`). +//! The gem is judged as its one pin, and the document then names each +//! build ([`GemBuildView`]): a patched one under its own patch, one on +//! upstream's gem as affected, and one of which neither is shown not at +//! all (`vex_gem_build_unknown`). use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; @@ -79,17 +91,22 @@ use futures_util::StreamExt; use socket_patch_core::api::client::{ build_proxy_fallback_client, get_api_client_with_overrides, hold_back_debug, - is_fallback_candidate, ApiClient, + is_fallback_candidate, ApiClient, PatchApi, }; +use socket_patch_core::crawlers::Ecosystem; +use socket_patch_core::hosted::engine::PinReport; use socket_patch_core::manifest::schema::{PatchManifest, PatchRecord}; -use socket_patch_core::patch::redirect::RedirectState; +use socket_patch_core::patch::redirect::{GemPlatformChecksum, RedirectState}; use socket_patch_core::utils::concurrent::{api_concurrency, ordered_concurrent}; -use socket_patch_core::utils::purl::strip_purl_qualifiers; +use socket_patch_core::utils::purl::{purl_parts, strip_purl_qualifiers}; use socket_patch_core::utils::purl_key::{canonical_base_purl, PurlKey}; use socket_patch_core::vendor::state::{VendorArtifact, VendorEntry, VendorState}; use socket_patch_core::vex::discover::{ vendor_ref, Discovery, LedgerLiveness, PatchedRef, RecordLiveness, WiringMode, }; +use socket_patch_core::vex::gem_builds::{ + gem_build_states, gem_index_url, locked_gem_pins, GemBuildState, GemBuildUnknown, LockedGemPin, +}; use socket_patch_core::vex::{FailedPatch, Unattested, UnattestedKind}; use crate::args::GlobalArgs; @@ -144,6 +161,13 @@ pub(crate) struct Sources { /// v5 hosted mode keeps no ledger, so [`plan`] fetches their records /// and files them as hosted records. Empty everywhere else. pub hosted_uuids: Vec, + /// Embedded hosted `scan --vex` only: what that run reports for each + /// locked build of the gems it pinned as platform builds + /// (`engine::pin_reports`, the reports that name a gem patch). The run + /// read the patch service's list of those builds to move the lock, so + /// [`plan`] takes the builds from here and asks nothing. Empty + /// everywhere else. + pub hosted_gem_builds: Vec, } impl Sources { @@ -183,6 +207,12 @@ pub(crate) struct Plan { /// installed copy the build CONSUMES through that wiring /// ([`crate::commands::vex_consumed`]). pub hosted: BTreeMap, + /// The gems of `hosted` that a Bundler lock takes from their patch + /// registry as platform builds, by view purl: what the lock installs + /// for each build it names ([`HostedGem`]). Such a gem is judged as the + /// one pin it is, and the document then names its builds + /// ([`GemBuildView`]). + pub hosted_gems: BTreeMap, /// Candidates omitted by a gate, with their routing tag. pub gated: Vec, /// Run advisories (wiring conflicts, superseded or dead records, record @@ -310,6 +340,17 @@ pub(crate) const GO_WORKSPACE_OVERRIDE: &str = "go_workspace_override"; /// package to the artifact; `vex::Unattested`, /// `UnattestedKind::LockNotRead`). const NOTE_LOCK_NOT_READ: &str = "vex_lock_not_read"; +/// Omission tag and note: a platform build of a gem the lockfile takes from +/// a patch registry, of which nothing shows whether the lock installs a +/// patched build or upstream's own gem ([`GemBuildState::Unknown`]). The +/// build is left out of the document, never attested on the strength of +/// the gem's one pin. +pub(crate) const GEM_BUILD_UNKNOWN: &str = "vex_gem_build_unknown"; + +/// Largest compact-index document read for a gem's builds +/// ([`gem_index`]). The registry of a patch lists one version, a few +/// hundred bytes a line. +const MAX_GEM_INDEX_BYTES: u64 = 1024 * 1024; /// The omission tag of an [`Unattested`](socket_patch_core::vex::Unattested) /// ref, and the remedy its note ends with. @@ -466,30 +507,72 @@ fn gate_unattested( }); } -/// The platform gems a document names in place of the gems vendored as -/// platform gems. +/// The builds a document names in place of a gem that is one pin for +/// several platform gems. +/// +/// A gem vendored as platform gems is one vendored copy, verified as one +/// against the record of the gem's patch. What an install loads from it is +/// one platform gem's tree, and each tree was built by a patch of its own, +/// which the ledger entry records ([`VendorEntry::gem_builds`]). So the +/// document names each platform gem +/// (`pkg:gem/@?platform=`) under its own patch, +/// with the vulnerabilities of the gem patch's record: the fix is the same +/// in every one of them. Read from the plan alone, with no request: the +/// ledger is what says which patch built which tree. An entry that names +/// no patch for its trees is attested as the gem itself. /// -/// Such a gem is one vendored copy, verified as one against the record of -/// the gem's patch. What an install loads from it is one platform gem's -/// tree, and each tree was built by a patch of its own, which the ledger -/// entry records ([`VendorEntry::gem_builds`]). So the document names each -/// platform gem (`pkg:gem/@?platform=`) under -/// its own patch, with the vulnerabilities of the gem patch's record: the -/// fix is the same in every one of them. Read from the plan alone, with -/// no request: the ledger is what says which patch built which tree. An -/// entry that names no patch for its trees is attested as the gem itself. +/// A gem a lock takes from its patch registry as platform builds is one +/// hosted pin, judged as one. The registry serves a patched build for some +/// platforms and upstream's own gem for the others, so the pin does not +/// say that every locked build is patched ([`Plan::hosted_gems`]). The +/// document names each locked build: a patched one under its own patch, +/// like a vendored one; one on upstream's gem as `affected` +/// ([`Self::kept_upstream`]), because the lock is known to install it +/// without the patch; and one of which neither is shown not at all (the +/// plan left it out, [`GEM_BUILD_UNKNOWN`]). The record of every build +/// stays in the view, so that no statement names a form of the gem that +/// also stands for a build the document does not call patched. pub(crate) struct GemBuildView { - /// The record view with each such gem's key replaced by its platform - /// gems' purls. + /// The record view with each such gem's key replaced by its builds' + /// purls. view: PatchManifest, - /// View purl of the gem → the purls of its platform gems. + /// View purl of the gem → the purls of its builds that are patched. platform_gems: BTreeMap>, + /// The hosted builds on upstream's gem, each with what to do about it. + kept_upstream: Vec<(String, String)>, + /// Every build the view names in place of a gem, by purl. + builds: BTreeMap, +} + +/// One build a [`GemBuildView`] names, as the run's events describe it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct GemBuildInfo { + /// The gem patch's uuid: the one pin, or the one vendored copy, all + /// the builds of the gem go by. + pub gem_fix: String, + /// `None` for the ruby-platform gem. + pub platform: Option, + /// A hosted build the patch registry serves as upstream's own gem. + pub kept_upstream: bool, +} + +/// The action statement of a hosted gem build on upstream's gem +/// ([`GemBuildState::Upstream`]): why the lock installs it without the +/// gem's patch `gem_fix`, and what changes that. +fn upstream_build_action(platform: &str, gem_fix: &str) -> String { + format!( + "The patch registry has no patched build of this gem for {platform} yet and serves \ + upstream's own gem for it, so an install on that platform is without Socket patch \ + {gem_fix}. Run `socket-patch scan --mode hosted` again later: the lockfile takes the \ + patched build once it is published." + ) } impl GemBuildView { - /// `None` when `plan` attests no gem vendored as platform gems. + /// `None` when `plan` attests no gem vendored as platform gems and no + /// gem a lock takes from a patch registry as platform builds. pub(crate) fn of(plan: &Plan) -> Option { - let gems: Vec<(&String, &VendorEntry, &PatchRecord)> = plan + let vendored: Vec<(&String, &VendorEntry, &PatchRecord)> = plan .vendor_entries .iter() .filter(|(_, entry)| { @@ -501,12 +584,21 @@ impl GemBuildView { // The entry's trees are the builds of the entry's own patch. .filter(|(_, entry, record)| record.uuid == entry.uuid) .collect(); - if gems.is_empty() { + let hosted: Vec<(&String, &HostedGem, &PatchRecord)> = plan + .hosted_gems + .iter() + .filter_map(|(key, gem)| Some((key, gem, plan.view.patches.get(key)?))) + // The builds are those of the patch the pin attests. + .filter(|(_, gem, record)| record.uuid == gem.gem_fix) + .collect(); + if vendored.is_empty() && hosted.is_empty() { return None; } let mut view = plan.view.clone(); let mut platform_gems = BTreeMap::new(); - for (key, entry, record) in gems { + let mut kept_upstream = Vec::new(); + let mut builds = BTreeMap::new(); + for (key, entry, record) in vendored { view.patches.remove(key); let purls: Vec = entry .gem_builds @@ -520,14 +612,66 @@ impl GemBuildView { uuid: built.uuid.clone(), ..record.clone() }); + builds.insert( + purl.clone(), + GemBuildInfo { + gem_fix: entry.uuid.clone(), + platform: Some(built.platform.clone()), + kept_upstream: false, + }, + ); purl }) .collect(); platform_gems.insert(key.clone(), purls); } + for (key, gem, record) in hosted { + view.patches.remove(key); + let mut patched = Vec::new(); + for build in &gem.builds { + // A purl the view already attests keeps its own record, + // and the outcome of its own check. + if view.patches.contains_key(&build.purl) { + continue; + } + let uuid = match &build.state { + GemBuildState::Patched { uuid } => uuid, + GemBuildState::Upstream | GemBuildState::Unknown(_) => &record.uuid, + }; + view.patches.insert( + build.purl.clone(), + PatchRecord { + uuid: uuid.clone(), + ..record.clone() + }, + ); + let upstream = build.state == GemBuildState::Upstream; + match (&build.state, build.platform.as_deref()) { + (GemBuildState::Patched { .. }, _) => patched.push(build.purl.clone()), + (GemBuildState::Upstream, Some(platform)) => kept_upstream.push(( + build.purl.clone(), + upstream_build_action(platform, &gem.gem_fix), + )), + // Left out by the plan; the ruby-platform gem of a + // patch's registry is never upstream's. + (GemBuildState::Upstream, None) | (GemBuildState::Unknown(_), _) => {} + } + builds.insert( + build.purl.clone(), + GemBuildInfo { + gem_fix: gem.gem_fix.clone(), + platform: build.platform.clone(), + kept_upstream: upstream, + }, + ); + } + platform_gems.insert(key.clone(), patched); + } Some(Self { view, platform_gems, + kept_upstream, + builds, }) } @@ -536,7 +680,18 @@ impl GemBuildView { &self.view } - /// Replace each gem of `purls` by its platform gems, in place. + /// The hosted builds the lock installs as upstream's own gem, each with + /// its action statement: what the document says `affected` of. + pub(crate) fn kept_upstream(&self) -> &[(String, String)] { + &self.kept_upstream + } + + /// Every build the view names in place of a gem, by purl. + pub(crate) fn builds(&self) -> &BTreeMap { + &self.builds + } + + /// Replace each gem of `purls` by its patched builds, in place. pub(crate) fn expand(&self, purls: &mut Vec) { *purls = std::mem::take(purls) .into_iter() @@ -573,6 +728,89 @@ pub(crate) struct HostedWiring { pub refs: Vec, } +/// A gem a Bundler lock takes from its patch registry as platform builds +/// (see [`Plan::hosted_gems`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct HostedGem { + /// The gem patch's uuid: the one pin all the builds go by. + pub gem_fix: String, + /// The gem's name and version, as a person reads them. + pub name: String, + pub version: String, + /// The builds the lock names, the ruby-platform gem first. + pub builds: Vec, + /// The plan worked the builds out from the lock and the patch service. + /// Not so for the pins of the run that moved the lock, which says its + /// builds itself. + pub resolved: bool, +} + +/// One build a lock names of a [`HostedGem`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct HostedGemBuild { + /// `None` for the ruby-platform gem. + pub platform: Option, + /// What the document names the build: + /// `pkg:gem/@?platform=`, or the gem's own + /// view purl for the ruby-platform gem. + pub purl: String, + /// What the lock installs for it. + pub state: GemBuildState, +} + +impl HostedGem { + /// The builds of the gem at the view purl `key`, each named and in + /// the state `state` gives for its platform. + fn of( + key: &str, + gem_fix: &str, + builds: impl IntoIterator, GemBuildState)>, + resolved: bool, + ) -> Option { + let (_, name, version) = purl_parts(key)?; + let base = strip_purl_qualifiers(key); + let builds = builds + .into_iter() + .map(|(platform, state)| HostedGemBuild { + purl: match &platform { + Some(platform) => format!("{base}?platform={platform}"), + None => key.to_string(), + }, + platform, + state, + }) + .collect(); + Some(HostedGem { + gem_fix: gem_fix.to_string(), + name, + version, + builds, + resolved, + }) + } + + /// Whether the installed copy at `path` is evidence about the gem at + /// the view purl `key`. A copy of a platform build the lock does not + /// install as a patched one is not: the document never calls that + /// build patched, and a machine of that platform holds what its lock + /// entry names. Judged as the gem's copy, upstream's own gem there + /// would withhold the builds the lock does install patched. + pub(crate) fn judges(&self, key: &str, path: &std::path::Path) -> bool { + use socket_patch_core::formats::gem::GemBuild; + let leaf = path.file_name().and_then(|leaf| leaf.to_str()); + let Some(platform) = leaf + .and_then(|leaf| GemBuild::of_leaf(key, leaf)) + .and_then(|build| build.platform) + else { + return true; + }; + !self.builds.iter().any(|build| { + build.platform.as_deref() == Some(platform.as_str()) + && !matches!(build.state, GemBuildState::Patched { .. }) + }) + } +} + /// How one view purl is verified. enum Basis { /// The agent-mode path: installed tree / go-patches copy. @@ -653,6 +891,7 @@ pub(crate) async fn plan( mut redirect, discovery, hosted_uuids, + hosted_gem_builds, } = sources; let mut notes = Vec::new(); // The in-run hosted pins' records, filed under the API's purl like a @@ -976,6 +1215,7 @@ pub(crate) async fn plan( redirected: Vec::new(), lockfile_basis: HashSet::new(), hosted: BTreeMap::new(), + hosted_gems: BTreeMap::new(), gated, notes, }; @@ -1040,6 +1280,7 @@ pub(crate) async fn plan( plan.view.patches.insert(cand.key, record); } plan.redirected.sort(); + resolve_hosted_gems(common, root, &mut plan, &hosted_gem_builds, api_client).await; // One skip per (purl, reason): a collision gates its key once per // colliding candidate. let mut seen: HashSet<(String, String)> = HashSet::new(); @@ -1369,6 +1610,33 @@ fn local_record_by_uuid( .map(|(k, r)| ((*k).clone(), (*r).clone())) } +/// The run's client: the host's, or built here once (standalone `vex`). +async fn run_client( + common: &GlobalArgs, + api_client: &RunApiClient, + notes: &mut Vec, +) -> ApiClient { + let overrides = common.api_client_overrides(); + let built_here = !api_client.initialized(); + let client = api_client + .get_or_init(|| async { get_api_client_with_overrides(overrides).await.0 }) + .await + .clone(); + // A client built here whose org could not be resolved put the run on + // the proxy. Its construction already warned on stderr, so only the + // `--json` envelope needs the note (a host that seeded its client + // reports this itself). + if built_here && common.json { + if let Some(reason) = client.org_unresolved() { + notes.push(PlanNote { + code: NOTE_API_AUTH_FALLBACK, + detail: reason.to_string(), + }); + } + } + client +} + /// Fetch the patch view for each of `uuids` (online only; empty under /// `--offline`) with bounded concurrency and `get`'s one-shot 401/403 → /// public-proxy fallback. Returns `uuid → (api purl, record)` for every view @@ -1398,24 +1666,7 @@ async fn fetch_records( return out; } let overrides = common.api_client_overrides(); - // The run's client: the host's, or built here once (standalone `vex`). - let built_here = !api_client.initialized(); - let mut client = api_client - .get_or_init(|| async { get_api_client_with_overrides(overrides.clone()).await.0 }) - .await - .clone(); - // A client built here whose org could not be resolved put the run on - // the proxy. Its construction already warned on stderr, so only the - // `--json` envelope needs the note (a host that seeded its client - // reports this itself). - if built_here && common.json { - if let Some(reason) = client.org_unresolved() { - notes.push(PlanNote { - code: NOTE_API_AUTH_FALLBACK, - detail: reason.to_string(), - }); - } - } + let mut client = run_client(common, api_client, notes).await; let mut use_public_proxy = client.uses_public_proxy(); let mut pending: Vec = uuids.to_vec(); // Each view is a heavy response: say what the run is waiting on (a live @@ -1503,6 +1754,352 @@ async fn fetch_records( out } +/// Why nothing is known of the platform builds of a gem +/// ([`resolve_hosted_gems`]). +#[derive(Debug, Clone, PartialEq, Eq)] +enum BuildsUnread { + /// `--offline` forbids asking. + Offline, + /// The reference request failed; its error, safe to print. + Request(String), + /// The patch service gave no list of the patch's builds; why. + NoList(String), +} + +/// A hosted gem whose builds the plan works out. +struct PendingGem { + /// Its view purl. + key: String, + /// The gem patch's uuid. + uuid: String, + name: String, + version: String, + /// The registry the lock takes the gem from. + remote: String, + /// The builds the lock names. + pins: Vec, +} + +impl PendingGem { + /// The lock's `CHECKSUMS` does not pin every platform build: what the + /// lock installs for those is what its registry serves. + fn needs_index(&self) -> bool { + self.pins + .iter() + .any(|pin| pin.platform.is_some() && pin.sha256.is_none()) + } +} + +/// What to run for a build whose state a later run can read. +const GEM_BUILD_RETRY: &str = "Run `socket-patch vex` again to attest each build."; +/// What to run for a build the lock and the patch registry disagree about. +const GEM_BUILD_RESCAN: &str = "Run `socket-patch scan --mode hosted` to bring the lockfile up \ + to date, then `socket-patch vex` again."; + +/// The [`GEM_BUILD_UNKNOWN`] note of the gem at `key`: the builds for +/// `platforms` are left out, `why`, and `remedy` is what to run. +fn gem_build_note( + key: &str, + gem_fix: &str, + platforms: &[&str], + why: &str, + remedy: &str, +) -> PlanNote { + let one = platforms.len() == 1; + PlanNote { + code: GEM_BUILD_UNKNOWN, + detail: format!( + "{key}: the lockfile takes its {} for {} from the registry of Socket patch {gem_fix}, \ + which serves a patched build for some platforms and upstream's own gem for the \ + others. Which it is for {} could not be told ({why}), so {} not attested. {remedy}", + if one { "build" } else { "builds" }, + platforms.join(", "), + if one { "this one" } else { "these" }, + if one { "it is" } else { "they are" }, + ), + } +} + +/// Work out [`Plan::hosted_gems`], and leave out the builds of which +/// nothing shows what the lock installs. +/// +/// A gem `in_run` reports (a pin of the hosted run this plan is part of) +/// takes its builds from there. Any other hosted gem is read from the lock +/// that wires it. One the lock names as its ruby-platform gem alone stays +/// the one pin it is, and nothing is asked for it. For the others the +/// patch service is asked once for the references of all their patches +/// (each lists its patch's builds), and the registry a lock names once per +/// gem, only where that lock's `CHECKSUMS` does not pin every build +/// ([`gem_index`]). +/// +/// Under `--offline`, and where a request fails or the answers do not +/// settle a build, nothing is known of it: the build is omitted +/// ([`GEM_BUILD_UNKNOWN`]) and a note names the gem and what to run, once +/// per gem and reason. The ruby-platform gem a lock names beside the +/// platform builds is the gem's patch by the lock's wiring, whatever the +/// requests say. +async fn resolve_hosted_gems( + common: &GlobalArgs, + root: &std::path::Path, + plan: &mut Plan, + in_run: &[PinReport], + api_client: &RunApiClient, +) { + let mut pending: Vec = Vec::new(); + for (key, wiring) in &plan.hosted { + if Ecosystem::from_purl(key) != Some(Ecosystem::Gem) { + continue; + } + let reported: Vec<(Option, GemBuildState)> = in_run + .iter() + .filter(|report| report.gem_fix.as_deref() == Some(wiring.uuid.as_str())) + .map(|report| { + let state = match &report.uuid { + Some(uuid) => GemBuildState::Patched { uuid: uuid.clone() }, + None => GemBuildState::Upstream, + }; + (report.platform.clone(), state) + }) + .collect(); + if !reported.is_empty() { + if let Some(gem) = HostedGem::of(key, &wiring.uuid, reported, false) { + plan.hosted_gems.insert(key.clone(), gem); + } + continue; + } + let Some((_, name, version)) = purl_parts(key) else { + continue; + }; + // The lock that wires the gem, and the registry it names there. + let wired = wiring + .refs + .iter() + .find_map(|r| Some((r.source_file.as_path(), r.url.clone()?))); + let Some((lock, remote)) = wired else { + continue; + }; + let Ok(text) = socket_patch_core::utils::fs::read_regular_to_string(&root.join(lock)).await + else { + continue; + }; + let pins = locked_gem_pins(&text, &name, &version); + if pins.iter().all(|pin| pin.platform.is_none()) { + continue; + } + pending.push(PendingGem { + key: key.clone(), + uuid: wiring.uuid.clone(), + name, + version, + remote, + pins, + }); + } + if pending.is_empty() { + return; + } + + // What each patch's reference lists, and what each lock's registry + // serves where the lock does not say. + let (lists, indexes) = if common.offline { + let unread = |_: &PendingGem| Err(BuildsUnread::Offline); + let lists: Vec<_> = pending.iter().map(unread).collect(); + (lists, pending.iter().map(|_| None).collect()) + } else { + crate::ui::busy( + common, + "Reading gem builds", + read_gem_builds(common, api_client, &pending, &mut plan.notes), + ) + .await + }; + + for ((gem, list), index) in pending.iter().zip(lists).zip(indexes) { + let (listed, unread) = match list { + Ok(listed) => (listed, None), + Err(unread) => (Vec::new(), Some(unread)), + }; + let served = index.as_ref().and_then(|read| read.as_deref().ok()); + let states = gem_build_states(&gem.version, &gem.pins, &gem.uuid, &listed, served); + let builds = gem.pins.iter().map(|pin| pin.platform.clone()).zip(states); + let Some(hosted) = HostedGem::of(&gem.key, &gem.uuid, builds, true) else { + continue; + }; + let mut unknown: BTreeMap> = BTreeMap::new(); + for build in &hosted.builds { + if let (GemBuildState::Unknown(why), Some(platform)) = + (&build.state, build.platform.as_deref()) + { + plan.gated.push(failed(&build.purl, GEM_BUILD_UNKNOWN)); + unknown.entry(*why).or_default().push(platform); + } + } + let note = |platforms: &[&str], why: &str, remedy: &str| { + gem_build_note(&gem.key, &gem.uuid, platforms, why, remedy) + }; + if let Some(unread) = unread { + let platforms: Vec<&str> = unknown.into_values().flatten().collect(); + let (why, remedy) = match &unread { + BuildsUnread::Offline => ( + "--offline forbids asking the patch API".to_string(), + "Run `socket-patch vex` without --offline to attest each build.", + ), + BuildsUnread::Request(error) => ( + format!("the patch API request failed: {error}"), + GEM_BUILD_RETRY, + ), + BuildsUnread::NoList(why) => (why.clone(), GEM_BUILD_RESCAN), + }; + if !platforms.is_empty() { + plan.notes.push(note(&platforms, &why, remedy)); + } + } else { + for (why, platforms) in unknown { + let them = if platforms.len() == 1 { "it" } else { "them" }; + let (why, remedy) = match (why, &index) { + (GemBuildUnknown::Unpinned, Some(Err(error))) => ( + format!( + "the lockfile has no CHECKSUMS entry for {them}, and its registry's \ + index could not be read: {error}" + ), + GEM_BUILD_RETRY, + ), + (GemBuildUnknown::Unpinned, _) => ( + format!( + "neither the lockfile's CHECKSUMS nor its registry's index names an \ + archive for {them}" + ), + GEM_BUILD_RESCAN, + ), + (GemBuildUnknown::Unlisted, _) => ( + format!("the patch registry does not list {them} now"), + GEM_BUILD_RESCAN, + ), + (GemBuildUnknown::Differs, _) => ( + format!( + "the lockfile installs another archive for {them} than the patch \ + registry lists now" + ), + GEM_BUILD_RESCAN, + ), + }; + plan.notes.push(note(&platforms, &why, remedy)); + } + } + plan.hosted_gems.insert(gem.key.clone(), hosted); + } +} + +/// The two reads [`resolve_hosted_gems`] makes for `gems`: per gem, the +/// builds its patch's reference lists (ONE request for all of them, with +/// `get`'s one-shot 401/403 → public-proxy fallback), and the index of the +/// registry its lock names, read only for a gem that has a list and whose +/// lock does not pin every build ([`PendingGem::needs_index`]). +async fn read_gem_builds( + common: &GlobalArgs, + api_client: &RunApiClient, + gems: &[PendingGem], + notes: &mut Vec, +) -> ( + Vec, BuildsUnread>>, + Vec>>, +) { + use socket_patch_core::utils::redact::redact_urls_in; + let mut uuids: Vec = gems.iter().map(|gem| gem.uuid.clone()).collect(); + uuids.sort(); + uuids.dedup(); + let mut client = run_client(common, api_client, notes).await; + let mut references = hold_back_debug(client.fetch_registry_references(&uuids)) + .await + .release(); + if let Err(error) = &references { + if !client.uses_public_proxy() && is_fallback_candidate(error) { + // Same stale-credential recovery (and warning text) as the + // record fetch. + notes.push(PlanNote { + code: NOTE_API_AUTH_FALLBACK, + detail: format!( + "authenticated API returned {error}; falling back to public patch API proxy \ + (free patches only)." + ), + }); + client = build_proxy_fallback_client(&common.api_client_overrides()); + references = hold_back_debug(client.fetch_registry_references(&uuids)) + .await + .release(); + } + } + let lists: Vec, BuildsUnread>> = gems + .iter() + .map(|gem| match &references { + Err(error) => Err(BuildsUnread::Request( + redact_urls_in(&error.to_string()).into_owned(), + )), + Ok(references) => { + let reference = references.get(&gem.uuid); + let granted = reference + .filter(|reference| matches!(reference.status.as_str(), "granted" | "reused")); + granted + .and_then(|reference| reference.registry_override.as_ref()) + .and_then(|registry| registry.identifiers.gem_builds.clone()) + .ok_or_else(|| { + BuildsUnread::NoList( + match reference.map(|reference| reference.status.as_str()) { + Some("granted" | "reused") => { + "the patch API lists no builds for that patch" + } + Some("withdrawn") => "the patch API says that patch is withdrawn", + Some("forbidden") => { + "the patch API does not grant that patch to this run" + } + _ => "the patch API has no reference for that patch", + } + .to_string(), + ) + }) + } + }) + .collect(); + let client = &client; + let indexes = ordered_concurrent( + gems.iter().zip(&lists), + fetch_concurrency(client.uses_public_proxy()), + |(gem, list)| async move { + match list.is_ok() && gem.needs_index() { + true => Some(hold_back_debug(gem_index(client, &gem.remote, &gem.name)).await), + false => None, + } + }, + ) + .collect::>() + .await; + let indexes = indexes + .into_iter() + .map(|read| read.map(|held| held.release())) + .collect(); + (lists, indexes) +} + +/// The compact-index document of the registry a lock names for the gem +/// `name` ([`gem_index_url`]): the sha256 of each gem that registry +/// serves, for a lock whose `CHECKSUMS` does not say what it installs. +/// +/// `remote` is the `remote:` of a lock section that lockfile discovery +/// read as hosted wiring, so it is on a patch server this run was given. +/// The document can only keep a build from being attested: a build is a +/// patched one only on the sha256 the patch service lists beside its +/// patch. The error is safe to print (the URL carries a grant token). +async fn gem_index(client: &ApiClient, remote: &str, name: &str) -> Result { + let url = gem_index_url(remote, name) + .ok_or_else(|| "the lockfile names no registry URL to read it from".to_string())?; + let bytes = PatchApi::download_artifact(client, &url, MAX_GEM_INDEX_BYTES) + .await + .map_err(|error| { + socket_patch_core::utils::redact::redact_urls_in(&error.to_string()).into_owned() + })?; + String::from_utf8(bytes).map_err(|_| "it is not UTF-8 text".to_string()) +} + #[cfg(test)] mod tests { use super::*; @@ -1574,6 +2171,7 @@ mod tests { redirected: Vec::new(), lockfile_basis: HashSet::new(), hosted: BTreeMap::new(), + hosted_gems: BTreeMap::new(), gated: Vec::new(), notes: Vec::new(), } @@ -1920,6 +2518,7 @@ mod tests { redirect: Some(redirect), discovery: discovery(vec![hosted_ref("pkg:npm/x@1.0.0", U2, true)]), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert_eq!(plan.view.patches["pkg:npm/x@1.0.0"].uuid, U2); @@ -1976,6 +2575,7 @@ mod tests { redirect: Some(redirect), discovery: discovery(refs), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert_eq!(plan.redirected, vec![key.to_string()], "{what}"); @@ -2000,6 +2600,7 @@ mod tests { redirect: None, discovery: discovery(vec![hosted_ref("pkg:npm/x@1.0.0", U2, true)]), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert!( @@ -2036,6 +2637,7 @@ mod tests { redirect: Some(redirect), discovery: discovery(vec![hosted_ref("pkg:npm/x@1.0.0", U1, true)]), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert!(plan @@ -2079,6 +2681,7 @@ mod tests { hosted_ref("pkg:npm/y@1.0.0", U2, true), ]), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert_eq!(plan.gated, vec![failed("pkg:npm/x@1.0.0", WIRING_CONFLICT)]); @@ -2128,6 +2731,7 @@ mod tests { redirect: Some(redirect.clone()), discovery: Discovery::default(), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let live = plan( &common(tmp.path()), @@ -2246,6 +2850,7 @@ mod tests { redirect: Some(redirect.clone()), discovery, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; // Control — nothing recognized: the hosted ledger's own recorded @@ -2333,6 +2938,7 @@ mod tests { redirect: Some(redirect), discovery: discovery(vec![hosted_ref("pkg:npm/x@1.0.0", U1, true)]), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; let wiring = &plan.hosted["pkg:npm/x@1.0.0"]; @@ -2365,6 +2971,7 @@ mod tests { redirect: Some(redirect.clone()), discovery, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let gated = plan( &common(tmp.path()), @@ -2466,6 +3073,7 @@ mod tests { redirect: Some(redirect.clone()), discovery, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let mut both = discovery(vec![ go_ref(PURL, U1, "go.work"), @@ -2518,6 +3126,7 @@ mod tests { redirect: Some(redirect), discovery: found, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert_eq!(plan.hosted[PURL].uuid, U1); @@ -2557,6 +3166,7 @@ mod tests { redirect: Some(redirect), discovery: found, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }, &[], &RunApiClient::new(), @@ -2613,6 +3223,7 @@ mod tests { redirect: None, discovery: found, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }, &[], &RunApiClient::new(), @@ -2663,6 +3274,7 @@ mod tests { redirect: None, discovery: found, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }, &[], &RunApiClient::new(), @@ -2699,6 +3311,7 @@ mod tests { redirect: Some(redirect), discovery: Discovery::default(), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan( &common(tmp.path()), @@ -2776,6 +3389,7 @@ mod tests { // not a discovery input: the ledger fallback decides. discovery: Discovery::default(), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan(&common(root), sources, &[], &RunApiClient::new()).await; if gemfile_wired { @@ -2792,4 +3406,702 @@ mod tests { } } } + + // ── A gem a lock takes from its patch registry as platform builds ── + + const GEM: &str = "pkg:gem/nokogiri@1.18.10"; + const GEM_ARM: &str = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + const GEM_LINUX: &str = "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu"; + /// The patches of the gem's patched platform builds. + const ARM_UUID: &str = "11111111-1111-4111-8111-111111111111"; + const LINUX_UUID: &str = "22222222-2222-4222-8222-222222222222"; + /// Upstream's `arm64-darwin` gem, and the patched ones. + const ARM_UPSTREAM: &str = "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0"; + const ARM_PATCHED: &str = "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1"; + const LINUX_PATCHED: &str = "b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1"; + const RUBY_PATCHED: &str = "c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1"; + + /// The registry of the gem's patch on `origin`, at the snapshot `key`. + fn gem_registry(origin: &str, key: &str) -> String { + format!("{origin}/patch-registry/gem/tok/{U1}/s/{key}/") + } + + /// A lock that takes the gem's builds `tokens` (`1.18.10`, + /// `1.18.10-arm64-darwin`, …) from `remote`, pinned as `checksums` + /// say (no `CHECKSUMS` section without any), and the sources that read + /// it: the lock's one hosted pin of the gem's patch [`U1`], whose + /// record a pre-v5 ledger holds, so no record is fetched. + fn hosted_gem_sources( + root: &Path, + remote: &str, + tokens: &[&str], + checksums: &[(&str, &str)], + ) -> Sources { + let mut lock = format!("GEM\n remote: {remote}\n specs:\n"); + for token in tokens { + lock.push_str(&format!(" nokogiri ({token})\n")); + } + lock.push_str("\nDEPENDENCIES\n nokogiri (= 1.18.10)!\n"); + if !checksums.is_empty() { + lock.push_str("\nCHECKSUMS\n"); + for (token, sha256) in checksums { + lock.push_str(&format!(" nokogiri ({token}) sha256={sha256}\n")); + } + } + std::fs::write(root.join("Gemfile.lock"), lock).unwrap(); + let pin = checksums + .first() + .map(|(_, sha256)| LockIntegrity::Sha256Hex(sha256.to_string())); + let wired = PatchedRef::hosted( + GEM.to_string(), + U1.to_string(), + "Gemfile.lock", + Some(remote), + pin, + !checksums.is_empty(), + ); + let mut redirect = RedirectState::new(); + redirect.records.insert(GEM.into(), record(U1)); + redirect + .records + .insert("pkg:npm/x@1.0.0".into(), record(U2)); + Sources { + manifest: PatchManifest::new(), + vendor: VendorState::new(), + redirect: Some(redirect), + discovery: discovery(vec![wired, hosted_ref("pkg:npm/x@1.0.0", U2, true)]), + hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), + } + } + + /// The patch API of the gem's patch on `server`: its reference lists + /// `builds` (platform, sha256, patch) under the snapshot `key`. + async fn mount_gem_reference( + server: &wiremock::MockServer, + key: &str, + builds: &[(&str, &str, Option<&str>)], + ) { + use wiremock::matchers::{method, path as wm_path}; + use wiremock::{Mock, ResponseTemplate}; + let listed: Vec = builds + .iter() + .map(|(platform, sha256, patch)| { + serde_json::json!({ + "platform": platform, "gemChecksumSha256": sha256, "patchUuid": patch, + }) + }) + .collect(); + Mock::given(method("POST")) + .and(wm_path("/v0/orgs/acme/patches/package")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "results": { U1: { + "status": "granted", + "purl": GEM, + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": gem_registry(&server.uri(), key), + "identifiers": { + "name": "nokogiri", "version": "1.18.10", + "gemChecksumSha256": RUBY_PATCHED, "gemBuilds": listed, + }, + }, + }} + }))) + .mount(server) + .await; + } + + /// The index of the registry at the snapshot `key` on `server`. + async fn mount_gem_index(server: &wiremock::MockServer, key: &str, lines: &[(&str, &str)]) { + use wiremock::matchers::{method, path as wm_path}; + use wiremock::{Mock, ResponseTemplate}; + let mut body = "---\n".to_string(); + for (token, sha256) in lines { + body.push_str(&format!("{token} racc:~> 1.4|checksum:{sha256}\n")); + } + Mock::given(method("GET")) + .and(wm_path(format!( + "/patch-registry/gem/tok/{U1}/s/{key}/info/nokogiri" + ))) + .respond_with(ResponseTemplate::new(200).set_body_string(body)) + .mount(server) + .await; + } + + /// A run against the patch API on `server`, authenticated. + fn online(root: &Path, server: &wiremock::MockServer) -> GlobalArgs { + GlobalArgs { + cwd: root.to_path_buf(), + json: true, + silent: true, + api_url: Some(server.uri()), + api_token: Some("sktsec_placeholder_value_for_tests_api".into()), + org: Some("acme".into()), + ..GlobalArgs::default() + } + } + + /// The paths of the requests `server` received, in arrival order. + async fn asked(server: &wiremock::MockServer) -> Vec { + let requests = server.received_requests().await.unwrap_or_default(); + requests + .iter() + .map(|request| request.url.path().to_string()) + .collect() + } + + /// What `plan` says of the gem's builds, by purl. + fn gem_states(plan: &Plan) -> Vec<(&str, &GemBuildState)> { + let gem = &plan.hosted_gems[GEM]; + assert_eq!((gem.gem_fix.as_str(), gem.resolved), (U1, true)); + gem.builds + .iter() + .map(|build| (build.purl.as_str(), &build.state)) + .collect() + } + + fn patched(uuid: &str) -> GemBuildState { + GemBuildState::Patched { + uuid: uuid.to_string(), + } + } + + const REFERENCE: &str = "/v0/orgs/acme/patches/package"; + const ONE_PATCHED: [(&str, &str, Option<&str>); 2] = [ + ("arm64-darwin", ARM_UPSTREAM, None), + ("x86_64-linux-gnu", LINUX_PATCHED, Some(LINUX_UUID)), + ]; + const LOCKED: [&str; 2] = ["1.18.10-arm64-darwin", "1.18.10-x86_64-linux-gnu"]; + const PINNED: [(&str, &str); 2] = [ + ("1.18.10-arm64-darwin", ARM_UPSTREAM), + ("1.18.10-x86_64-linux-gnu", LINUX_PATCHED), + ]; + + /// A lock whose `CHECKSUMS` pins every build is settled by ONE + /// request, the gem patch's reference: the build on the sha256 the + /// list gives beside a patch is that patch's, the one on the sha256 it + /// gives beside none is upstream's gem. Nothing is omitted and nothing + /// is noted, and the registry is not asked. + #[tokio::test] + #[serial_test::serial] + async fn a_checksummed_lock_tells_its_builds_apart_in_one_request() { + let server = wiremock::MockServer::start().await; + mount_gem_reference(&server, "4f", &ONE_PATCHED).await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + let sources = hosted_gem_sources(tmp.path(), &remote, &LOCKED, &PINNED); + let plan = plan( + &online(tmp.path(), &server), + sources, + &[], + &RunApiClient::new(), + ) + .await; + assert_eq!( + gem_states(&plan), + [ + (GEM_ARM, &GemBuildState::Upstream), + (GEM_LINUX, &patched(LINUX_UUID)) + ] + ); + assert!(plan.gated.is_empty(), "{:?}", plan.gated); + assert!(plan.notes.is_empty(), "{:?}", plan.notes); + assert_eq!(asked(&server).await, [REFERENCE]); + // The gem is still the one pin the checks judge. + assert_eq!(plan.view.patches[GEM].uuid, U1); + assert!(plan.redirected.contains(&GEM.to_string())); + } + + /// A lock with no `CHECKSUMS` installs what its own registry serves: + /// a second request reads that registry's index, and the builds are + /// told apart by it. Two requests, and no more. + #[tokio::test] + #[serial_test::serial] + async fn a_lock_without_checksums_asks_its_own_registry_too() { + let server = wiremock::MockServer::start().await; + mount_gem_reference(&server, "4f", &ONE_PATCHED).await; + mount_gem_index(&server, "4f", &PINNED).await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + let sources = hosted_gem_sources(tmp.path(), &remote, &LOCKED, &[]); + let plan = plan( + &online(tmp.path(), &server), + sources, + &[], + &RunApiClient::new(), + ) + .await; + assert_eq!( + gem_states(&plan), + [ + (GEM_ARM, &GemBuildState::Upstream), + (GEM_LINUX, &patched(LINUX_UUID)) + ] + ); + assert!(plan.gated.is_empty(), "{:?}", plan.gated); + assert_eq!( + asked(&server).await, + [ + REFERENCE.to_string(), + format!("/patch-registry/gem/tok/{U1}/s/4f/info/nokogiri") + ] + ); + } + + /// The index of the lock's registry cannot be read: the builds are + /// omitted, and one note names the gem, the reason and what to run. + #[tokio::test] + #[serial_test::serial] + async fn an_unreadable_index_omits_the_builds_of_a_lock_without_checksums() { + let server = wiremock::MockServer::start().await; + mount_gem_reference(&server, "4f", &ONE_PATCHED).await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + let sources = hosted_gem_sources(tmp.path(), &remote, &LOCKED, &[]); + let plan = plan( + &online(tmp.path(), &server), + sources, + &[], + &RunApiClient::new(), + ) + .await; + let unpinned = GemBuildState::Unknown(GemBuildUnknown::Unpinned); + assert_eq!( + gem_states(&plan), + [(GEM_ARM, &unpinned), (GEM_LINUX, &unpinned)] + ); + assert_eq!( + plan.gated, + [ + failed(GEM_ARM, GEM_BUILD_UNKNOWN), + failed(GEM_LINUX, GEM_BUILD_UNKNOWN) + ] + ); + let [note] = plan.notes.as_slice() else { + panic!("one note for the gem: {:?}", plan.notes); + }; + assert_eq!(note.code, GEM_BUILD_UNKNOWN); + assert!( + note.detail.starts_with(&format!( + "{GEM}: the lockfile takes its builds for arm64-darwin, x86_64-linux-gnu from \ + the registry of Socket patch {U1}" + )) && note.detail.contains( + "the lockfile has no CHECKSUMS entry for them, and its registry's index could \ + not be read" + ) && note.detail.ends_with(GEM_BUILD_RETRY), + "{}", + note.detail + ); + assert!(!note.detail.contains("/tok/"), "the grant token: {note:?}"); + } + + /// The reference is of a later registry than the lock names: it lists + /// a patched build for a platform the lock still pins upstream's gem + /// for. That build is not attested as patched, on either way of + /// telling what the lock installs; the build the lock does pin patched + /// is. The note sends the reader to the scan. + #[tokio::test] + #[serial_test::serial] + async fn a_reference_newer_than_the_lock_attests_no_build_the_lock_pins_otherwise() { + let both = [ + ("arm64-darwin", ARM_PATCHED, Some(ARM_UUID)), + ("x86_64-linux-gnu", LINUX_PATCHED, Some(LINUX_UUID)), + ]; + for checksums in [true, false] { + let server = wiremock::MockServer::start().await; + mount_gem_reference(&server, "5a", &both).await; + mount_gem_index(&server, "4f", &PINNED).await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + let pinned: &[(&str, &str)] = if checksums { &PINNED } else { &[] }; + let sources = hosted_gem_sources(tmp.path(), &remote, &LOCKED, pinned); + let plan = plan( + &online(tmp.path(), &server), + sources, + &[], + &RunApiClient::new(), + ) + .await; + assert_eq!( + gem_states(&plan), + [ + (GEM_ARM, &GemBuildState::Unknown(GemBuildUnknown::Differs)), + (GEM_LINUX, &patched(LINUX_UUID)) + ], + "checksums: {checksums}" + ); + assert_eq!(plan.gated, [failed(GEM_ARM, GEM_BUILD_UNKNOWN)]); + let [note] = plan.notes.as_slice() else { + panic!("one note for the gem: {:?}", plan.notes); + }; + assert!( + note.detail.contains("its build for arm64-darwin from") + && note.detail.contains( + "(the lockfile installs another archive for it than the patch registry \ + lists now), so it is not attested." + ) + && note.detail.ends_with(GEM_BUILD_RESCAN), + "{}", + note.detail + ); + assert_eq!( + asked(&server).await.len(), + if checksums { 1 } else { 2 }, + "checksums: {checksums}" + ); + } + } + + /// `--offline`: nothing is asked, so nothing says which locked build + /// is patched. The platform builds are omitted with one note; the + /// ruby-platform gem the lock names beside them is the gem's patch by + /// the lock's wiring alone. + #[tokio::test] + #[serial_test::serial] + async fn offline_attests_no_platform_build_and_asks_nothing() { + let server = wiremock::MockServer::start().await; + mount_gem_reference(&server, "4f", &ONE_PATCHED).await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + let sources = hosted_gem_sources( + tmp.path(), + &remote, + &["1.18.10", LOCKED[0], LOCKED[1]], + &[("1.18.10", RUBY_PATCHED), PINNED[0], PINNED[1]], + ); + let common = GlobalArgs { + offline: true, + ..online(tmp.path(), &server) + }; + let plan = plan(&common, sources, &[], &RunApiClient::new()).await; + let unlisted = GemBuildState::Unknown(GemBuildUnknown::Unlisted); + assert_eq!( + gem_states(&plan), + [ + (GEM, &patched(U1)), + (GEM_ARM, &unlisted), + (GEM_LINUX, &unlisted) + ] + ); + assert_eq!( + plan.gated, + [ + failed(GEM_ARM, GEM_BUILD_UNKNOWN), + failed(GEM_LINUX, GEM_BUILD_UNKNOWN) + ] + ); + let [note] = plan.notes.as_slice() else { + panic!("one note for the gem: {:?}", plan.notes); + }; + assert_eq!( + note.detail, + format!( + "{GEM}: the lockfile takes its builds for arm64-darwin, x86_64-linux-gnu from \ + the registry of Socket patch {U1}, which serves a patched build for some \ + platforms and upstream's own gem for the others. Which it is for these could \ + not be told (--offline forbids asking the patch API), so they are not attested. \ + Run `socket-patch vex` without --offline to attest each build." + ) + ); + assert_eq!(asked(&server).await, Vec::::new()); + + // The document: the ruby-platform gem alone, under the gem's patch. + let builds = GemBuildView::of(&plan).expect("a gem locked as platform builds"); + let mut applied = vec![GEM.to_string()]; + builds.expand(&mut applied); + assert_eq!(applied, [GEM]); + assert!(builds.kept_upstream().is_empty()); + } + + /// The reference request fails, or the reference carries no list: no + /// build is attested, the note says which it was, and the registry is + /// not asked for an index nothing could be held against. + #[tokio::test] + #[serial_test::serial] + async fn a_failed_or_listless_reference_attests_no_platform_build() { + use wiremock::matchers::{method, path as wm_path}; + use wiremock::{Mock, ResponseTemplate}; + let no_list = serde_json::json!({ "results": { U1: { + "status": "granted", "purl": GEM, + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": format!("https://patch.example/patch-registry/gem/tok/{U1}/"), + "identifiers": { + "name": "nokogiri", "version": "1.18.10", "gemChecksumSha256": RUBY_PATCHED, + }, + }, + }}}); + for (answer, why, remedy) in [ + ( + ResponseTemplate::new(500), + "the patch API request failed: ", + GEM_BUILD_RETRY, + ), + ( + ResponseTemplate::new(200).set_body_json(no_list), + "(the patch API lists no builds for that patch)", + GEM_BUILD_RESCAN, + ), + ] { + let server = wiremock::MockServer::start().await; + Mock::given(method("POST")) + .and(wm_path(REFERENCE)) + .respond_with(answer) + .mount(&server) + .await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + // No `CHECKSUMS`: with a list, the index would be read. + let sources = hosted_gem_sources(tmp.path(), &remote, &LOCKED, &[]); + let plan = plan( + &online(tmp.path(), &server), + sources, + &[], + &RunApiClient::new(), + ) + .await; + assert_eq!( + plan.gated, + [ + failed(GEM_ARM, GEM_BUILD_UNKNOWN), + failed(GEM_LINUX, GEM_BUILD_UNKNOWN) + ], + "{why}" + ); + let [note] = plan.notes.as_slice() else { + panic!("one note for the gem: {:?}", plan.notes); + }; + assert!( + note.code == GEM_BUILD_UNKNOWN + && note.detail.contains(why) + && note.detail.ends_with(remedy), + "{}", + note.detail + ); + let asked = asked(&server).await; + assert!( + !asked.is_empty() && asked.iter().all(|path| path == REFERENCE), + "{asked:?}" + ); + // Nothing of the gem is in the document. + let builds = GemBuildView::of(&plan).expect("a gem locked as platform builds"); + let mut applied = vec![GEM.to_string()]; + builds.expand(&mut applied); + assert!(applied.is_empty() && builds.kept_upstream().is_empty()); + } + } + + /// A gem the lock names as its ruby-platform gem alone is the one pin + /// it always was, and so is every other ecosystem's: no request, and + /// nothing for the document to name in its place. + #[tokio::test] + #[serial_test::serial] + async fn a_gem_locked_as_its_ruby_gem_alone_asks_nothing() { + let server = wiremock::MockServer::start().await; + mount_gem_reference(&server, "4f", &ONE_PATCHED).await; + let tmp = tempfile::tempdir().unwrap(); + let remote = format!("{}/patch-registry/gem/tok/{U1}/", server.uri()); + let sources = hosted_gem_sources( + tmp.path(), + &remote, + &["1.18.10"], + &[("1.18.10", RUBY_PATCHED)], + ); + let plan = plan( + &online(tmp.path(), &server), + sources, + &[], + &RunApiClient::new(), + ) + .await; + assert!(plan.hosted_gems.is_empty(), "{:?}", plan.hosted_gems); + assert_eq!(plan.redirected, [GEM, "pkg:npm/x@1.0.0"]); + assert!(plan.gated.is_empty() && plan.notes.is_empty()); + assert!(GemBuildView::of(&plan).is_none()); + assert_eq!(asked(&server).await, Vec::::new()); + } + + /// The pins of the hosted run the plan is part of come with what that + /// run reports for each locked build: the plan takes them as they are + /// and asks nothing, whatever the lock's `CHECKSUMS` hold. + #[tokio::test] + #[serial_test::serial] + async fn the_builds_a_hosted_run_reports_are_taken_without_a_request() { + let server = wiremock::MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + let report = |platform: Option<&str>, uuid: Option<&str>| PinReport { + purl: match platform { + Some(platform) => format!("{GEM}?platform={platform}"), + None => GEM.to_string(), + }, + uuid: uuid.map(str::to_string), + gem_fix: Some(U1.to_string()), + platform: platform.map(str::to_string), + newly_patched: uuid.is_some(), + }; + let sources = Sources { + hosted_gem_builds: vec![ + report(None, Some(U1)), + report(Some("arm64-darwin"), None), + report(Some("x86_64-linux-gnu"), Some(LINUX_UUID)), + ], + ..hosted_gem_sources(tmp.path(), &remote, &LOCKED, &[]) + }; + let plan = plan( + &online(tmp.path(), &server), + sources, + &[GEM.to_string()], + &RunApiClient::new(), + ) + .await; + let gem = &plan.hosted_gems[GEM]; + assert!(!gem.resolved, "the run says its builds itself"); + let states: Vec<(&str, &GemBuildState)> = gem + .builds + .iter() + .map(|build| (build.purl.as_str(), &build.state)) + .collect(); + assert_eq!( + states, + [ + (GEM, &patched(U1)), + (GEM_ARM, &GemBuildState::Upstream), + (GEM_LINUX, &patched(LINUX_UUID)) + ] + ); + assert!(plan.gated.is_empty() && plan.notes.is_empty()); + assert_eq!(asked(&server).await, Vec::::new()); + } + + /// A plan attesting the hosted gem [`GEM`] at [`U1`], locked as the + /// builds `builds` (platform and state). + fn hosted_gem_plan(builds: Vec<(Option<&str>, GemBuildState)>) -> Plan { + let builds = builds + .into_iter() + .map(|(platform, state)| (platform.map(str::to_string), state)); + let gem = HostedGem::of(GEM, U1, builds, true).unwrap(); + Plan { + view: PatchManifest { + patches: HashMap::from([ + (GEM.to_string(), record(U1)), + ("pkg:npm/left-pad@1.3.0".to_string(), record(U2)), + ]), + setup: None, + }, + vendor_entries: HashMap::new(), + vendor_pins: HashMap::new(), + redirected: vec![GEM.to_string()], + lockfile_basis: HashSet::new(), + hosted: BTreeMap::new(), + hosted_gems: BTreeMap::from([(GEM.to_string(), gem)]), + gated: Vec::new(), + notes: Vec::new(), + } + } + + /// A gem a lock takes from its patch registry as platform builds is + /// named per locked build. A patched build goes under its own patch, + /// with the gem patch's vulnerabilities, wherever the gem was; a build + /// on upstream's gem is in no list of attested purls and is handed + /// over as affected, with what to do; a build nothing is known of is + /// in neither. All three keep a record in the view, so no statement + /// names a form of the gem that stands for an unpatched build too. + #[test] + fn a_hosted_gem_is_attested_per_locked_build() { + const JAVA: &str = "pkg:gem/nokogiri@1.18.10?platform=java"; + let plan = hosted_gem_plan(vec![ + (None, patched(U1)), + (Some("arm64-darwin"), GemBuildState::Upstream), + ( + Some("java"), + GemBuildState::Unknown(GemBuildUnknown::Unlisted), + ), + (Some("x86_64-linux-gnu"), patched(LINUX_UUID)), + ]); + let builds = GemBuildView::of(&plan).expect("a gem locked as platform builds"); + let view = builds.view(); + let mut keys: Vec<&str> = view.patches.keys().map(String::as_str).collect(); + keys.sort_unstable(); + assert_eq!( + keys, + [GEM, GEM_ARM, JAVA, GEM_LINUX, "pkg:npm/left-pad@1.3.0"] + ); + assert_eq!(view.patches[GEM].uuid, U1); + assert_eq!(view.patches[GEM_LINUX].uuid, LINUX_UUID); + for purl in [GEM, GEM_ARM, JAVA, GEM_LINUX] { + assert_eq!( + view.patches[purl].vulnerabilities, + record(U1).vulnerabilities + ); + } + + for mut attested in [ + vec!["pkg:npm/left-pad@1.3.0".to_string(), GEM.to_string()], + plan.redirected.clone(), + ] { + let others = attested.len() - 1; + builds.expand(&mut attested); + assert_eq!(attested[others..], [GEM, GEM_LINUX]); + } + let [(purl, action)] = builds.kept_upstream() else { + panic!("one build on upstream's gem: {:?}", builds.kept_upstream()); + }; + assert_eq!(purl, GEM_ARM); + assert_eq!( + action, + &format!( + "The patch registry has no patched build of this gem for arm64-darwin yet and \ + serves upstream's own gem for it, so an install on that platform is without \ + Socket patch {U1}. Run `socket-patch scan --mode hosted` again later: the \ + lockfile takes the patched build once it is published." + ) + ); + let described: Vec<(&str, Option<&str>, bool)> = builds + .builds() + .iter() + .map(|(purl, build)| { + assert_eq!(build.gem_fix, U1); + ( + purl.as_str(), + build.platform.as_deref(), + build.kept_upstream, + ) + }) + .collect(); + assert_eq!( + described, + [ + (GEM, None, false), + (GEM_ARM, Some("arm64-darwin"), true), + (JAVA, Some("java"), false), + (GEM_LINUX, Some("x86_64-linux-gnu"), false), + ] + ); + } + + /// An installed copy of a platform build the lock does not install + /// patched is no evidence about the gem: it is upstream's own gem by + /// the lock. Every other copy is judged, the ruby-platform one and one + /// of a platform the lock does not name included. + #[test] + fn the_copy_of_a_build_the_lock_installs_unpatched_is_not_judged() { + let plan = hosted_gem_plan(vec![ + (Some("arm64-darwin"), GemBuildState::Upstream), + ( + Some("java"), + GemBuildState::Unknown(GemBuildUnknown::Differs), + ), + (Some("x86_64-linux-gnu"), patched(LINUX_UUID)), + ]); + let gem = &plan.hosted_gems[GEM]; + let judged = |leaf: &str| gem.judges(GEM, &Path::new("/home/gems").join(leaf)); + assert!(!judged("nokogiri-1.18.10-arm64-darwin")); + assert!(!judged("nokogiri-1.18.10-java")); + assert!(judged("nokogiri-1.18.10-x86_64-linux-gnu")); + assert!(judged("nokogiri-1.18.10")); + assert!(judged("nokogiri-1.18.10-aarch64-linux-gnu")); + assert!(judged("nokogiri-1.18.9-arm64-darwin")); + } } diff --git a/crates/socket-patch-cli/src/json_envelope.rs b/crates/socket-patch-cli/src/json_envelope.rs index e399cb2917..a37acd3d86 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -165,8 +165,11 @@ pub struct VexSummary { pub path: String, /// Number of OpenVEX statements in the document. pub statements: usize, - /// How many of them say `affected` (see `vex_bazel_not_in_build`), not - /// `not_affected`. Omitted from JSON when none does. + /// How many of them say `affected`, not `not_affected`: of a package + /// Bazel builds without its patch (see `vex_bazel_not_in_build`), or of + /// a gem build the lockfile takes from a patch registry as upstream's + /// own gem (`gem_upstream_build_kept`). Omitted from JSON when none + /// does. #[serde(skip_serializing_if = "is_zero")] pub affected: usize, /// Document format tag, e.g. `"openvex-0.2.0"`. diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs index 4329846426..e9a8110e29 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs @@ -20,6 +20,22 @@ //! patched; //! * a platform the registry does not list, or a reference with no list at //! all, leaves the gem alone under `redirect_gem_platform_unsupported`. +//! +//! The VEX document is truthful per locked build, in the run's own `--vex` +//! and in a later `socket-patch vex` over the lock the run left: +//! +//! * a patched build is `not_affected` under its own patch, a build on +//! upstream's gem is `affected`, and no statement names a form of the gem +//! that stands for both; +//! * the run's own document costs no request beyond the run's; a later +//! `vex` asks for the gem patch's reference once, and for the index of +//! the lock's registry only when the lock has no `CHECKSUMS`; +//! * a build is attested by its patch only on the sha256 the lock installs +//! for it: one the lock pins otherwise, or that nothing could be read +//! about (`--offline`, a failed request), is left out and the run says +//! what to run (`vex_gem_build_unknown`); +//! * a gem locked as its ruby-platform gem alone is one pin, with no +//! request of its own. use std::path::Path; @@ -29,6 +45,8 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; #[path = "common/mod.rs"] mod common; +#[path = "vex_e2e_common/mod.rs"] +mod vex_e2e_common; const ORG: &str = "test-org"; const DEP: &str = "platform-probe"; @@ -936,3 +954,823 @@ async fn rollout_and_the_severity_floor_count_the_gem_once() { assert_eq!(env["policy"]["counts"]["filtered"], 1, "{env}"); assert_eq!(hosted_events(&env), Vec::::new(), "{env}"); } + +// ── VEX ─────────────────────────────────────────────────────────────── + +const PRODUCT: &str = "pkg:gem/app@1.0.0"; +const CVE: &str = "CVE-2026-5555"; + +/// The path of the index the gem patch's registry serves at snapshot `4`. +fn index_path() -> String { + format!("/patch-registry/gem/{TOKEN}/{UUID}/s/4/info/{DEP}") +} + +fn build_purl(platform: &str) -> String { + format!("{PURL}?platform={platform}") +} + +/// The form Grype and Syft report a platform gem under. +fn grype_form(platform: &str) -> String { + format!("{PURL}-{platform}") +} + +/// What one statement of a document says: its status, the packages of the +/// project it is about, the products it names beside the project, and its +/// impact statement (`not_affected`) or action statement (`affected`). +#[derive(Debug, PartialEq)] +struct Said { + status: &'static str, + packages: Vec, + products: Vec, + words: String, +} + +/// Every statement of `doc`, each about the one vulnerability of the +/// gem patch's record. +fn said(doc: &Value) -> Vec { + let ids = |list: &Value, key: &str| -> Vec { + let items = list.as_array().into_iter().flatten(); + items + .filter_map(|item| item[key].as_str().map(str::to_string)) + .collect() + }; + let statements = doc["statements"].as_array().expect("statements"); + statements + .iter() + .map(|st| { + assert_eq!(st["vulnerability"]["name"], GHSA, "{st}"); + assert_eq!(st["vulnerability"]["aliases"], json!([CVE]), "{st}"); + assert_eq!(st["products"][0]["@id"], PRODUCT, "{st}"); + let status = match st["status"].as_str() { + Some("not_affected") => "not_affected", + Some("affected") => "affected", + other => panic!("unexpected status {other:?}: {st}"), + }; + let words = match status { + "affected" => &st["action_statement"], + _ => &st["impact_statement"], + }; + Said { + status, + packages: ids(&st["products"][0]["subcomponents"], "@id"), + products: ids(&st["products"], "@id")[1..].to_vec(), + words: words.as_str().unwrap_or_default().to_string(), + } + }) + .collect() +} + +/// The statement of the builds `platforms`, each patched by the patch +/// beside it; `shared` when every locked build is among them, so that the +/// form Trivy reports the gem under stands for patched builds alone. +fn patched_statement(platforms: &[(&str, &str)], shared: bool) -> Said { + let mut products: Vec = Vec::new(); + products.extend(shared.then(|| PURL.to_string())); + products.extend(platforms.iter().map(|(platform, _)| grype_form(platform))); + products.extend(platforms.iter().map(|(platform, _)| build_purl(platform))); + let mut parts: Vec = platforms + .iter() + .map(|(_, patch)| format!("Patched via Socket patch {patch} (redirected)")) + .collect(); + parts.sort(); + Said { + status: "not_affected", + packages: platforms.iter().map(|(p, _)| build_purl(p)).collect(), + products, + words: parts.join("; "), + } +} + +/// The statement of the build for `platform`, which the lock installs as +/// upstream's own gem. +fn upstream_statement(platform: &str) -> Said { + Said { + status: "affected", + packages: vec![build_purl(platform)], + products: vec![grype_form(platform), build_purl(platform)], + words: format!( + "The patch registry has no patched build of this gem for {platform} yet and serves \ + upstream's own gem for it, so an install on that platform is without Socket patch \ + {UUID}. Run `socket-patch scan --mode hosted` again later: the lockfile takes the \ + patched build once it is published." + ), + } +} + +/// A `--json` hosted scan with `--vex`: exit code, envelope and document. +fn scan_vex(proj: &Path, api: &str) -> (i32, Value, Option) { + let out = proj.join("out.vex.json"); + let (code, env) = scan_json( + proj, + api, + &[ + "--vex", + out.to_str().expect("utf8 temp path"), + "--vex-product", + PRODUCT, + "--patch-server-url", + api, + ], + ); + (code, env, vex_e2e_common::read_doc(&out)) +} + +/// A later `socket-patch vex` over `proj`, against `api`. +fn vex_run(api: &str) -> vex_e2e_common::VexRun { + vex_e2e_common::VexRun { + api_url: Some(api.to_string()), + api_token: Some(API_TOKEN.to_string()), + org: Some(ORG.to_string()), + // The lock's registry is on the mock origin. + patch_server_url: Some(api.to_string()), + product: Some(PRODUCT.to_string()), + ..vex_e2e_common::VexRun::default() + } +} + +fn vex(proj: &Path, api: &str) -> vex_e2e_common::VexOutcome { + vex_e2e_common::run_vex(&vex_e2e_common::binary(), proj, &vex_run(api)) +} + +/// A project as a hosted run left it: the gem's two builds on the patch +/// registry `index`, pinned to `arm` and `linux`, or by source alone +/// (`checksums: false`, the lock of a Bundler that writes no `CHECKSUMS`). +fn hosted_project(index: &str, arm: &str, linux: &str, checksums: bool) -> tempfile::TempDir { + let mut lock = hosted_lock(index, arm, linux); + if !checksums { + let at = lock.find("CHECKSUMS\n").expect("a CHECKSUMS section"); + let end = lock.find("BUNDLED WITH").expect("a BUNDLED WITH section"); + lock.replace_range(at..end, ""); + } + let dir = project(&lock); + std::fs::write(dir.path().join("Gemfile"), hosted_gemfile(index)).unwrap(); + dir +} + +/// The index the patch registry serves at snapshot `4`: the sha256 of +/// each build it lists. +async fn mount_index(server: &MockServer, arm: &str, linux: &str) { + Mock::given(method("GET")) + .and(path(index_path())) + .respond_with(ResponseTemplate::new(200).set_body_string(format!( + "---\n{DEP_VERSION}-{ARM} racc:~> 1.4|checksum:{arm}\n{DEP_VERSION}-{LINUX} racc:~> \ + 1.4|checksum:{linux}\n" + ))) + .mount(server) + .await; +} + +/// How many times the gem patch's record was asked for. +async fn view_requests(server: &MockServer) -> usize { + let view = format!("/v0/orgs/{ORG}/patches/view/{UUID}"); + let requests = server.received_requests().await.unwrap_or_default(); + requests + .iter() + .filter(|request| request.url.path() == view) + .count() +} + +/// The `vex` events of the gem's builds: `(action, purl, errorCode)`, +/// each naming the gem's patch as its fix and its own platform. +fn build_events(env: &Value) -> Vec<(String, String, String)> { + let events = env["events"].as_array().expect("events"); + events + .iter() + .map(|event| { + let purl = event["purl"].as_str().unwrap_or_default(); + let details = &event["details"]; + assert_eq!(details["gemFix"], UUID, "{event}"); + let platform = details["platform"].as_str().unwrap_or_default(); + assert_eq!(purl, build_purl(platform), "{event}"); + let text = |key: &str| event[key].as_str().unwrap_or_default().to_string(); + (text("action"), text("purl"), text("errorCode")) + }) + .collect() +} + +fn event(action: &str, platform: &str, code: &str) -> (String, String, String) { + (action.to_string(), build_purl(platform), code.to_string()) +} + +/// The run's own `--vex`, one locked build patched and one on upstream's +/// gem: the patched build is attested under its own patch, the other is +/// said affected, and neither statement names the gem without a platform +/// (the form a scanner that drops the platform would match both by). No +/// request beyond the run's own: one reference request, one record, and +/// none to the registry. The same holds on a machine whose platform is +/// the one on upstream's gem, with that gem installed. +#[tokio::test(flavor = "multi_thread")] +async fn the_runs_vex_attests_the_patched_build_and_says_affected_of_the_upstream_one() { + for installed in [false, true] { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let proj = project(&lock(true)); + if installed { + let gem = format!("vendor/bundle/ruby/3.3.0/gems/{DEP}-{DEP_VERSION}-{ARM}/lib"); + std::fs::create_dir_all(proj.path().join(&gem)).unwrap(); + std::fs::write( + proj.path().join(gem).join("platform_probe.rb"), + "upstream\n", + ) + .unwrap(); + } + let (code, env, doc) = scan_vex(proj.path(), &api); + assert_eq!(code, 0, "installed: {installed}: {env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + said(&doc.expect("a document")), + [ + patched_statement(&[(LINUX, LINUX_UUID)], false), + upstream_statement(ARM) + ], + "installed: {installed}" + ); + assert_eq!(env["vex"]["statements"], 2, "{env}"); + assert_eq!(env["vex"]["affected"], 1, "{env}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); + assert_eq!(view_requests(&server).await, 1, "the gem patch's record"); + } +} + +/// Every locked build patched: one statement names both builds, each under +/// its own patch, and the gem without a platform too. The gem patch's own +/// uuid is in no statement: no locked build is its ruby-platform gem. +#[tokio::test(flavor = "multi_thread")] +async fn the_runs_vex_attests_every_patched_build_under_its_own_patch() { + let server = MockServer::start().await; + mount_api(&server, Some((&BOTH_PATCHED[..], 4))).await; + let api = server.uri(); + let proj = project(&lock(true)); + let (code, env, doc) = scan_vex(proj.path(), &api); + assert_eq!(code, 0, "{env}"); + let doc = doc.expect("a document"); + assert_eq!( + said(&doc), + [patched_statement( + &[(ARM, ARM_UUID), (LINUX, LINUX_UUID)], + true + )] + ); + assert!(!doc.to_string().contains(UUID), "{doc}"); + assert_eq!(env["vex"]["statements"], 1, "{env}"); + assert_eq!(env["vex"]["affected"], Value::Null, "{env}"); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); +} + +/// A lock that names the ruby-platform gem beside the platform builds: +/// that entry is the gem's own patch, attested as the gem itself, beside +/// the patched platform build; the build on upstream's gem is affected. +#[tokio::test(flavor = "multi_thread")] +async fn the_runs_vex_attests_the_ruby_entry_under_the_gems_own_patch() { + let listing: [Listed; 3] = [ + (ARM, ARM_UPSTREAM, None), + ("ruby", RUBY_PATCHED, Some(UUID)), + (LINUX, LINUX_PATCHED, Some(LINUX_UUID)), + ]; + let server = MockServer::start().await; + mount_api(&server, Some((&listing[..], 4))).await; + let api = server.uri(); + let with_ruby = lock(true) + .replace( + &format!(" {DEP} ({DEP_VERSION}-{ARM})\n"), + &format!(" {DEP} ({DEP_VERSION})\n {DEP} ({DEP_VERSION}-{ARM})\n"), + ) + .replace( + &format!(" {DEP} ({DEP_VERSION}-{ARM}) sha256="), + &format!( + " {DEP} ({DEP_VERSION}) sha256={}\n {DEP} ({DEP_VERSION}-{ARM}) sha256=", + "d".repeat(64) + ), + ); + let proj = project(&with_ruby); + let (code, env, doc) = scan_vex(proj.path(), &api); + assert_eq!(code, 0, "{env}"); + let after = read(proj.path(), "Gemfile.lock"); + assert!( + after.contains(&format!(" {DEP} ({DEP_VERSION}) sha256={RUBY_PATCHED}\n")), + "{after}" + ); + let mut patched = patched_statement(&[(LINUX, LINUX_UUID)], false); + patched.packages.insert(0, PURL.to_string()); + patched.words = format!( + "Patched via Socket patch {LINUX_UUID} (redirected); Patched via Socket patch {UUID} \ + (redirected)" + ); + assert_eq!( + said(&doc.expect("a document")), + [patched, upstream_statement(ARM)] + ); + assert_eq!(env["vex"]["affected"], 1, "{env}"); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); +} + +/// A later `vex` over a lock with `CHECKSUMS`: ONE request beyond the +/// record, the gem patch's reference. The document is the run's own, the +/// envelope reports each build with the gem's patch as its fix, and the +/// build on upstream's gem is neither counted nor a failure. A person +/// reads which builds are attested, with no warning. +#[tokio::test(flavor = "multi_thread")] +async fn a_later_vex_tells_the_builds_of_a_checksummed_lock_apart_in_one_request() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, true); + + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!( + said(out.doc()), + [ + patched_statement(&[(LINUX, LINUX_UUID)], false), + upstream_statement(ARM) + ] + ); + let env = &out.envelope; + assert_eq!(env["status"], "success", "{out}"); + assert_eq!( + build_events(env), + [ + event("verified", LINUX, ""), + event("skipped", ARM, "gem_upstream_build_kept") + ], + "{out}" + ); + assert_eq!( + env["events"][1]["reason"], + format!("the patch registry serves upstream's own gem for {ARM}: no patched build yet"), + "{out}" + ); + assert_eq!(env["events"][1]["details"]["status"], "affected", "{out}"); + assert_eq!( + (&env["summary"]["verified"], &env["summary"]["skipped"]), + (&json!(1), &json!(0)), + "the build on upstream's gem is counted nowhere: {out}" + ); + assert_eq!(warning_codes(env), Vec::::new(), "{out}"); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); + assert_eq!(view_requests(&server).await, 1); + + let human = vex_e2e_common::VexRun { + human: true, + ..vex_run(&api) + }; + let out = vex_e2e_common::run_vex(&vex_e2e_common::binary(), proj.path(), &human); + assert_eq!(out.code, Some(0), "{out}"); + assert!( + out.stdout.contains(&format!( + "Wrote OpenVEX document with 2 statements (1 affected) to {}\n{DEP} {DEP_VERSION}: \ + patched for {LINUX}; upstream gem kept for {ARM} (no patched build yet)\n", + out.output.display() + )), + "{out}" + ); + assert!(!out.stderr.contains("Warning"), "{out}"); +} + +/// A later `vex` over a lock with no `CHECKSUMS`: the lock installs what +/// its own registry serves, so a SECOND request reads that registry's +/// index. Two requests, the same document. With the index unreadable the +/// builds are left out, and the run says why and what to run. +#[tokio::test(flavor = "multi_thread")] +async fn a_later_vex_asks_the_registry_of_a_lock_without_checksums() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + mount_index(&server, ARM_UPSTREAM, LINUX_PATCHED).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, false); + assert!(!read(proj.path(), "Gemfile.lock").contains("CHECKSUMS")); + + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!( + said(out.doc()), + [ + patched_statement(&[(LINUX, LINUX_UUID)], false), + upstream_statement(ARM) + ] + ); + assert_eq!(out.envelope["status"], "success", "{out}"); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, [index_path()], "and the lock's own registry, once"); + + // No index to read: nothing says what the lock installs. + let silent = MockServer::start().await; + mount_api(&silent, Some((&ONE_PATCHED[..], 4))).await; + let api = silent.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, false); + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(1), "{out}"); + assert_eq!( + out.envelope["error"]["code"], "no_applicable_patches", + "{out}" + ); + assert!(out.doc.is_none(), "{out}"); + assert_eq!( + build_events(&out.envelope), + [ + event("skipped", ARM, "vex_gem_build_unknown"), + event("skipped", LINUX, "vex_gem_build_unknown") + ], + "{out}" + ); + assert_eq!( + warning_codes(&out.envelope), + ["vex_gem_build_unknown"], + "{out}" + ); + let detail = out.envelope["warnings"][0]["detail"].as_str().unwrap(); + assert!( + detail.contains( + "the lockfile has no CHECKSUMS entry for them, and its registry's index could not \ + be read" + ) && detail.ends_with("Run `socket-patch vex` again to attest each build.") + && !detail.contains(TOKEN), + "{detail}" + ); +} + +/// The reference a later `vex` gets is of a newer registry than the lock +/// names: it lists a patched build for the platform the lock still pins +/// upstream's gem for. That build is NOT attested: the lock does not +/// install it. The build the lock does pin patched is, and the run sends +/// the reader to the scan that moves the lock. +#[tokio::test(flavor = "multi_thread")] +async fn a_later_vex_attests_no_build_a_newer_reference_lists_but_the_lock_does_not_pin() { + for checksums in [true, false] { + let server = MockServer::start().await; + mount_api(&server, Some((&BOTH_PATCHED[..], 5))).await; + // The registry the lock names still serves upstream's gem there. + mount_index(&server, ARM_UPSTREAM, LINUX_PATCHED).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, checksums); + + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "checksums: {checksums}: {out}"); + assert_eq!( + said(out.doc()), + [patched_statement(&[(LINUX, LINUX_UUID)], false)], + "checksums: {checksums}" + ); + assert!(!out.doc().to_string().contains(ARM_UUID), "{out}"); + assert_eq!( + build_events(&out.envelope), + [ + event("verified", LINUX, ""), + event("skipped", ARM, "vex_gem_build_unknown") + ], + "{out}" + ); + assert_eq!(out.envelope["status"], "partialFailure", "{out}"); + assert_eq!( + warning_codes(&out.envelope), + ["vex_gem_build_unknown"], + "{out}" + ); + assert_eq!( + out.envelope["warnings"][0]["detail"], + format!( + "{PURL}: the lockfile takes its build for {ARM} from the registry of Socket patch \ + {UUID}, which serves a patched build for some platforms and upstream's own gem \ + for the others. Which it is for this one could not be told (the lockfile \ + installs another archive for it than the patch registry lists now), so it is \ + not attested. Run `socket-patch scan --mode hosted` to bring the lockfile up to \ + date, then `socket-patch vex` again." + ), + "{out}" + ); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other.len(), usize::from(!checksums), "{other:?}"); + + // A person reads the warning, the build left out, and which + // builds the document attests. + let human = vex_e2e_common::VexRun { + human: true, + ..vex_run(&api) + }; + let out = vex_e2e_common::run_vex(&vex_e2e_common::binary(), proj.path(), &human); + assert_eq!(out.code, Some(0), "{out}"); + assert!( + out.stdout.ends_with(&format!( + "\n{DEP} {DEP_VERSION}: patched for {LINUX}; not attested for {ARM}\n" + )), + "{out}" + ); + assert!( + out.stderr.contains(&format!( + "Warning: {PURL}: the lockfile takes its build for {ARM} from the registry of \ + Socket patch {UUID}" + )) && out.stderr.contains(&format!( + "Warning: omitting {} from VEX: it is not shown whether the lockfile installs \ + a patched build for this platform (the warning above says why, and what to \ + run) (vex_gem_build_unknown)\n", + build_purl(ARM) + )), + "{out}" + ); + + // The scan the note names moves the lock, and the next document + // attests both builds. + let (code, env, doc) = scan_vex(proj.path(), &api); + assert_eq!(code, 0, "{env}"); + assert_eq!( + said(&doc.expect("a document")), + [patched_statement( + &[(ARM, ARM_UUID), (LINUX, LINUX_UUID)], + true + )] + ); + } +} + +/// The record of the gem's patch as a pre-v5 hosted ledger holds it: the +/// one way a hosted pin has a record with no request. +fn write_record_ledger(proj: &Path) { + let view = json!({ + "uuid": UUID, + "files": { "lib/platform_probe.rb": { + "beforeHash": "a".repeat(64), "afterHash": "b".repeat(64), + }}, + "vulnerabilities": { GHSA: { + "cves": [CVE], "summary": "s", "severity": "high", "description": "d", + }}, + "description": "x", "license": "MIT", "tier": "free", + }); + vex_e2e_common::write_legacy_redirect_ledger(proj, PURL, &view); +} + +/// `--offline`: no request at all, so nothing says which locked build is +/// patched. With the record at hand the gem's one pin would have attested +/// every build; instead the platform builds are left out, and one warning +/// names the gem and what to run. +#[tokio::test(flavor = "multi_thread")] +async fn an_offline_vex_attests_no_platform_build_and_says_so_once() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, true); + write_record_ledger(proj.path()); + let offline = vex_e2e_common::VexRun { + offline: true, + ..vex_run(&api) + }; + + let out = vex_e2e_common::run_vex(&vex_e2e_common::binary(), proj.path(), &offline); + assert_eq!(out.code, Some(1), "{out}"); + assert_eq!( + out.envelope["error"]["code"], "no_applicable_patches", + "{out}" + ); + assert!(out.doc.is_none(), "{out}"); + assert_eq!( + build_events(&out.envelope), + [ + event("skipped", ARM, "vex_gem_build_unknown"), + event("skipped", LINUX, "vex_gem_build_unknown") + ], + "{out}" + ); + assert_eq!( + out.envelope["warnings"], + json!([{ + "code": "vex_gem_build_unknown", + "detail": format!( + "{PURL}: the lockfile takes its builds for {ARM}, {LINUX} from the registry of \ + Socket patch {UUID}, which serves a patched build for some platforms and \ + upstream's own gem for the others. Which it is for these could not be told \ + (--offline forbids asking the patch API), so they are not attested. Run \ + `socket-patch vex` without --offline to attest each build." + ), + }]), + "{out}" + ); + assert_eq!( + server.received_requests().await.unwrap_or_default().len(), + 0, + "--offline asks nothing" + ); + + // Online, the same project is the document of the run that moved it. + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!( + said(out.doc()), + [ + patched_statement(&[(LINUX, LINUX_UUID)], false), + upstream_statement(ARM) + ] + ); + assert_eq!(view_requests(&server).await, 0, "the ledger has the record"); +} + +/// The reference request fails: the record is there, the list of the +/// gem's builds is not. No build is attested, the registry is not asked, +/// and the warning carries the failure. +#[tokio::test(flavor = "multi_thread")] +async fn a_failed_reference_request_attests_no_platform_build() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(ResponseTemplate::new(500)) + .with_priority(1) + .mount(&server) + .await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, true); + + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(1), "{out}"); + assert!(out.doc.is_none(), "{out}"); + assert_eq!( + build_events(&out.envelope), + [ + event("skipped", ARM, "vex_gem_build_unknown"), + event("skipped", LINUX, "vex_gem_build_unknown") + ], + "{out}" + ); + assert_eq!( + warning_codes(&out.envelope), + ["vex_gem_build_unknown"], + "{out}" + ); + let detail = out.envelope["warnings"][0]["detail"].as_str().unwrap(); + assert!( + detail.contains("could not be told (the patch API request failed: ") + && detail.ends_with("Run `socket-patch vex` again to attest each build."), + "{detail}" + ); + let (references, other) = requests(&server).await; + assert!( + !references.is_empty() && references.iter().all(|asked| asked == &[UUID.to_string()]), + "{references:?}" + ); + assert_eq!(other, Vec::::new(), "no registry request"); + + // A person reads one warning for the gem and one line for its builds, + // each named with its platform. + let human = vex_e2e_common::VexRun { + human: true, + ..vex_run(&api) + }; + let out = vex_e2e_common::run_vex(&vex_e2e_common::binary(), proj.path(), &human); + assert_eq!(out.code, Some(1), "{out}"); + assert_eq!(out.stderr.matches("Warning: ").count(), 2, "{out}"); + assert!( + out.stderr.contains(&format!( + "Warning: omitting 2 packages from VEX: it is not shown whether the lockfile \ + installs a patched build for this platform (the warning above says why, and what \ + to run) (vex_gem_build_unknown): {DEP}@{DEP_VERSION} ({ARM}), {DEP}@{DEP_VERSION} \ + ({LINUX})\n" + )), + "{out}" + ); + assert!( + out.stderr + .ends_with("Error: No applied patches with vulnerability metadata to attest.\n"), + "{out}" + ); +} + +/// A gem locked as its ruby-platform gem alone is the one pin it always +/// was: attested as the gem under the gem's patch, with the record as the +/// only request. No reference is asked for and no registry is read. +#[tokio::test(flavor = "multi_thread")] +async fn a_later_vex_of_a_gem_locked_as_its_ruby_gem_alone_asks_nothing_new() { + let server = MockServer::start().await; + mount_api(&server, None).await; + let api = server.uri(); + let index = index_url(&api, None); + let lock = format!( + "GEM\n remote: {index}\n specs:\n {DEP} ({DEP_VERSION})\n\nGEM\n remote: \ + https://rubygems.org/\n specs:\n racc (1.8.1)\n\nPLATFORMS\n ruby\n\nDEPENDENCIES\n \ + {DEP} (= {DEP_VERSION})!\n racc (= 1.8.1)\n\nCHECKSUMS\n {DEP} ({DEP_VERSION}) \ + sha256={RUBY_PATCHED}\n racc (1.8.1) sha256={RACC}\n\nBUNDLED WITH\n 4.0.15\n" + ); + let proj = project(&lock); + std::fs::write(proj.path().join("Gemfile"), hosted_gemfile(&index)).unwrap(); + + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!( + said(out.doc()), + [Said { + status: "not_affected", + packages: vec![PURL.to_string()], + products: vec![PURL.to_string()], + words: format!("Patched via Socket patch {UUID} (redirected)"), + }] + ); + assert_eq!( + out.envelope["events"], + json!([{ + "action": "verified", "purl": PURL, + "details": { "vulnerability": GHSA, "aliases": [CVE], "status": "not_affected" }, + }]), + "{out}" + ); + let (references, other) = requests(&server).await; + assert_eq!( + references, + Vec::>::new(), + "no reference request" + ); + assert_eq!(other, Vec::::new(), "no registry request"); + assert_eq!( + server.received_requests().await.unwrap_or_default().len(), + 1, + "the record, and nothing else" + ); +} + +/// Installed copies are judged per build. A machine of the platform on +/// upstream's gem holds upstream's gem, as its lock entry names it: that +/// copy is no evidence against the build the lock installs patched. A copy +/// of that patched build is: one that does not hold the patch withholds +/// it, and the build on upstream's gem is affected either way. +#[tokio::test(flavor = "multi_thread")] +async fn an_installed_copy_is_evidence_about_its_own_build_alone() { + let patched = b"module PlatformProbe\n FIXED = true\nend\n"; + let upstream = b"module PlatformProbe\n FIXED = false\nend\n"; + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{UUID}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "uuid": UUID, "purl": PURL, "publishedAt": "2026-01-01T00:00:00Z", + "files": { "lib/platform_probe.rb": { + "beforeHash": vex_e2e_common::git_sha256(upstream), + "afterHash": vex_e2e_common::git_sha256(patched), + }}, + "vulnerabilities": { GHSA: { + "cves": [CVE], "summary": "s", "severity": "high", "description": "d", + }}, + "description": "x", "license": "MIT", "tier": "free", + }))) + .with_priority(1) + .mount(&server) + .await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, true); + let install = |platform: &str, content: &[u8]| { + let lib = proj.path().join(format!( + "vendor/bundle/ruby/3.3.0/gems/{DEP}-{DEP_VERSION}-{platform}/lib" + )); + std::fs::create_dir_all(&lib).unwrap(); + std::fs::write(lib.join("platform_probe.rb"), content).unwrap(); + }; + let both = [ + patched_statement(&[(LINUX, LINUX_UUID)], false), + upstream_statement(ARM), + ]; + + // This machine's platform is the one on upstream's gem. + install(ARM, upstream); + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!(said(out.doc()), both, "{out}"); + assert_eq!(out.envelope["status"], "success", "{out}"); + + // The patched build installed beside it, holding the patch. + install(LINUX, patched); + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!(said(out.doc()), both, "{out}"); + + // That copy still on upstream's files: the build is not attested, and + // no build of the gem is, so the gem without a platform is affected. + install(LINUX, upstream); + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + let mut unpatched = upstream_statement(ARM); + unpatched.products.insert(0, PURL.to_string()); + assert_eq!(said(out.doc()), [unpatched], "{out}"); + vex_e2e_common::assert_not_attested(&out.envelope, PURL, "not_applied"); + assert_eq!(out.envelope["status"], "partialFailure", "{out}"); +} diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index cf524f8f47..794a605530 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -538,6 +538,26 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { assert!(impact.split("; ").any(|p| p == part), "{impact}"); } assert!(!impact.contains(UUID), "{impact}"); + // The run's events name the gem's patch as the fix of each platform gem. + let envelope: serde_json::Value = serde_json::from_str(&stdout).expect("the vex envelope"); + let fixes: Vec<(&str, &str, &str)> = envelope["events"] + .as_array() + .into_iter() + .flatten() + .map(|event| { + let details = &event["details"]; + ( + event["action"].as_str().unwrap_or_default(), + details["platform"].as_str().unwrap_or_default(), + details["gemFix"].as_str().unwrap_or_default(), + ) + }) + .collect(); + assert_eq!( + fixes, + [("verified", DARWIN, UUID), ("verified", LINUX, UUID)], + "{envelope:#}" + ); assert_eq!( server.received_requests().await.unwrap().len(), asked, diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index 382febd3e7..dab68193ef 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -161,7 +161,8 @@ pub const GEM_NO_PATCHED_BUILD: &str = "redirect_gem_no_patched_build"; /// Code of the uncounted event of one locked platform build of a hosted /// gem that the patch registry serves as upstream's own gem (no patched /// build yet): that platform installs what it installed before, and is -/// neither counted nor attested as patched. +/// neither counted nor attested as patched. A VEX document says +/// `affected` of such a build, and `vex` reports it under this code. pub const GEM_UPSTREAM_BUILD_KEPT: &str = "gem_upstream_build_kept"; /// What a host says beside [`GEM_UPSTREAM_BUILD_KEPT`] for the locked From 85b686414f66c560974a03e7cf967000c05cbba1 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 21:48:10 -0500 Subject: [PATCH 014/120] Check the VEX of a machine whose platform is on upstream's gem The hosted scan leaves the installed copy of a platform on upstream's gem alone: it is the gem that platform's lock entry names. The VEX of such a machine has to agree with that, in the run's own document and in a later `vex`: the copy must not be attested as patched, and it must not withhold the build of the other platform, which the lock does install patched. The stale-install suite already builds that machine, with a real gem home, with and without the gem's cached archive. It now also checks both documents there: the other platform's build under its own patch, this machine's build as affected. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_redirect_gem_stale_install.rs | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index 49fae8de0c..78a4f8517a 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -3133,6 +3133,69 @@ async fn a_platform_served_as_upstreams_gem_is_no_stale_install() { "cached={cached}:\n{stderr}" ); assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "cached={cached}"); + + // The VEX of this machine, from the run itself and from a later + // `vex`: the other platform's build is attested under its own + // patch, and this machine's build is said affected. The installed + // copy is upstream's gem, as its lock entry names it, and is no + // evidence against the build the lock installs patched. + let patched_part = format!("Patched via Socket patch {LINUX_UUID} (redirected)"); + let expected = [ + ( + "not_affected".to_string(), + format!("{PURL}?platform={OTHER_PLATFORM}"), + patched_part, + ), + ( + "affected".to_string(), + format!("{PURL}?platform={PLATFORM}"), + String::new(), + ), + ]; + let said = |doc: &serde_json::Value| -> Vec<(String, String, String)> { + let text = |value: &serde_json::Value| value.as_str().unwrap_or_default().to_string(); + let statements = doc["statements"].as_array().expect("statements"); + statements + .iter() + .map(|st| { + let packages = st["products"][0]["subcomponents"].as_array(); + assert_eq!(packages.map(Vec::len), Some(1), "{st}"); + ( + text(&st["status"]), + text(&st["products"][0]["subcomponents"][0]["@id"]), + text(&st["impact_statement"]), + ) + }) + .collect() + }; + let vex_path = proj.join("run.vex.json"); + let with_vex = [ + "--json", + "--vex", + vex_path.to_str().unwrap(), + "--vex-product", + "pkg:gem/app@1.0.0", + ]; + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &with_vex), &[]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "cached={cached}: {env}\nstderr:\n{stderr}"); + assert_eq!(env["vex"]["affected"], 1, "cached={cached}: {env}"); + let doc = vex_e2e_common::read_doc(&vex_path).expect("the run's document"); + assert_eq!(said(&doc), expected, "cached={cached}: {doc}"); + + let later = vex_e2e_common::VexRun { + api_url: Some(uri.clone()), + api_token: Some("fake".into()), + org: Some(ORG.into()), + patch_server_url: Some(uri.clone()), + product: Some("pkg:gem/app@1.0.0".into()), + ..vex_e2e_common::VexRun::default() + }; + let out = vex_e2e_common::run_vex(&vex_e2e_common::binary(), &proj, &later); + assert_eq!(out.code, Some(0), "cached={cached}: {out}"); + assert_eq!(said(out.doc()), expected, "cached={cached}: {out}"); + assert_eq!(out.envelope["status"], "success", "cached={cached}: {out}"); } } From 11944bfc79e76441c58332f2c27dc4944f036277 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 22:26:05 -0500 Subject: [PATCH 015/120] Hold the platform gem tests to the fixture and helper rules of the suites Two things the full suites check that the tests of the platform builds did not meet. The golden fixture of a lock that names a platform the list leaves out still expected `redirect_gem_platform_unsupported`. That platform is one whose patched build is being made, which is no warning: the fixture expects none, and is named for what it holds (`platform-build-pending`). The hosted and vendored end-to-end files read the `--json` envelope with helpers of their own under names the shared readers have (`warning_codes`, `events`). They use `common::envelope` for it. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_redirect_gem_platform_builds.rs | 10 +--------- .../vendor/vendor_gem_platform_builds_e2e.rs | 12 +++++------- .../expected-edits.json | 0 .../expected-warnings.json | 1 + .../input/Gemfile | 0 .../input/Gemfile.lock | 0 .../overrides.json | 0 .../expected-warnings.json | 1 - .../vex-discover-golden/redirect-gem.json | 16 ++++++++-------- 9 files changed, 15 insertions(+), 25 deletions(-) rename crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/{platform-prebuild-missing => platform-build-pending}/expected-edits.json (100%) create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-pending/expected-warnings.json rename crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/{platform-prebuild-missing => platform-build-pending}/input/Gemfile (100%) rename crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/{platform-prebuild-missing => platform-build-pending}/input/Gemfile.lock (100%) rename crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/{platform-prebuild-missing => platform-build-pending}/overrides.json (100%) delete mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-warnings.json diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs index e9a8110e29..daf6dabe5a 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs @@ -45,6 +45,7 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; #[path = "common/mod.rs"] mod common; +use common::envelope::warning_codes; #[path = "vex_e2e_common/mod.rs"] mod vex_e2e_common; @@ -279,15 +280,6 @@ fn hosted_events(env: &Value) -> Vec { .collect() } -fn warning_codes(env: &Value) -> Vec { - env["warnings"] - .as_array() - .into_iter() - .flatten() - .map(|w| w["code"].as_str().unwrap_or_default().to_string()) - .collect() -} - /// The event of a patched build: `applied` (`verified` on a dry run) under /// the build's own patch. fn patched_event(action: &str, platform: &str, patch: &str, newly: bool) -> Value { diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index 794a605530..a0e2edbe28 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -323,14 +323,12 @@ const VENDOR: &[&str] = &["vendor", "--json", "--vendor-source", "service"]; /// The counted events of `env` with `action`, as `(purl, uuid, gemFix, /// platform, errorCode)`. -fn events<'a>( +fn gem_events<'a>( env: &'a serde_json::Value, action: &str, ) -> Vec<(&'a str, &'a str, &'a str, &'a str, &'a str)> { let text = |value: &'a serde_json::Value| value.as_str().unwrap_or_default(); - env["events"] - .as_array() - .expect("events array") + crate::common::envelope::events(env) .iter() .filter(|event| event["action"] == action) .map(|event| { @@ -370,7 +368,7 @@ fn per_platform_gem( } fn assert_per_platform_gem(env: &serde_json::Value, action: &str, code: &'static str) { - let got = events(env, action); + let got = gem_events(env, action); let got: Vec<(&str, &str, &str, &str, &str)> = got .into_iter() .filter(|event| !event.2.is_empty()) @@ -639,7 +637,7 @@ async fn a_locked_platform_without_a_patched_build_is_one_line_and_no_failure() assert_eq!(env["summary"]["applied"], 0, "{env:#}"); assert_eq!(env["summary"]["failed"], 0, "{env:#}"); assert_eq!(env["summary"]["skipped"], 1, "{env:#}"); - let skipped = events(&env, "skipped"); + let skipped = gem_events(&env, "skipped"); assert_eq!( skipped, [(PURL, "", "", "", "vendor_prebuilt_platform_pending")], @@ -707,7 +705,7 @@ async fn ledger_entries_of_other_builds_still_check_convert_and_revert() { let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); assert_eq!(code, 0, "{env:#}\n{stderr}"); assert_eq!( - events(&env, "verified"), + gem_events(&env, "verified"), [(PURL, "", "", "", "vendor_check_ok")], "{env:#}" ); diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-pending/expected-edits.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-edits.json rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-pending/expected-edits.json diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-pending/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-pending/expected-warnings.json new file mode 100644 index 0000000000..fe51488c70 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-pending/expected-warnings.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/input/Gemfile b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-pending/input/Gemfile similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/input/Gemfile rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-pending/input/Gemfile diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/input/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-pending/input/Gemfile.lock similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/input/Gemfile.lock rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-pending/input/Gemfile.lock diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-pending/overrides.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/overrides.json rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-pending/overrides.json diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-warnings.json deleted file mode 100644 index 57ef0136a3..0000000000 --- a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-warnings.json +++ /dev/null @@ -1 +0,0 @@ -["redirect_gem_platform_unsupported"] diff --git a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json index f865f322de..a1eb67a7c0 100644 --- a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json +++ b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json @@ -44,6 +44,14 @@ "elsewhere": [], "live_claims": [] }, + "redirect/gem/bundler/platform-build-pending/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, "redirect/gem/bundler/platform-pass-through/expected": { "refs": [ { @@ -89,14 +97,6 @@ "elsewhere": [], "live_claims": [] }, - "redirect/gem/bundler/platform-prebuild-missing/input": { - "refs": [], - "diagnostics": [], - "recognized": [], - "unlocked_pins": [], - "elsewhere": [], - "live_claims": [] - }, "redirect/gem/bundler/platform-prebuilds/expected": { "refs": [ { From 4d4b7ee1cc9b2ac400a5398a2b0b9a46eba27048 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 21:24:51 -0500 Subject: [PATCH 016/120] Serve the list of a gem's builds from the stand-in patch service The stand-in patch service of the nokogiri end-to-end script still answered the way the patch service did before a gem's fix became one patch: it named the patched platform gems as artifacts of the gem's patch (`gem-platform`, `gem-platform-stub-gemspec`) and as `gemPlatforms`, under the plain registry URL. The CLI reads none of that any more, so the hosted and vendored legs of the nokogiri workflow had nothing to install from. The stand-in now answers as the service does: - each patched platform gem has a patch of its own, which the search routes return beside the gem's and whose reference serves that gem (`tarball`) and its stub gemspec; one reference request answers for every uuid it names; - a reference request that carries `gemBuilds: true` gets the registry under a snapshot URL, whose key is derived from what the registry lists, and the list of the version's gems (the ruby gem, each patched platform gem with its patch, each platform still on upstream's gem with none); a request without it gets the plain URL and no list; - the registry under a snapshot lists every gem of that list, and answers the file of a platform with no patched build with a 302 to a stand-in of the upstream registry's file host on a second port, which serves the real gem. Nothing leaves the machine for it; - `publish` makes a platform's patched build appear under a newer snapshot, and the earlier snapshot keeps answering as it did. The script's hosted scenario checks what a run reports per locked build and that every reference request asks for the list. With `--pass-through` (and `--add-platform`, to lock a platform nothing here installs) one locked platform has no patched build at first: the lock keeps upstream's checksum for it, a frozen install on that platform gets upstream's nokogiri through the redirect, and the scan after `publish` moves the lock to the newer snapshot and the install to the patched gem. With no locked build patched, nothing moves. The vendored scenario checks that the platform patches are asked for in one request, that no record of theirs is fetched, and that a gem with a platform that has no patched build is not vendored until it has one. The workflow gains two hosted legs (the runner's own platform passed through, and another one) and one vendored leg. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/nokogiri-compatibility.yml | 37 +- tests/nokogiri/nokogiri_e2e.rb | 287 ++++++++++++--- tests/nokogiri/patch_service.rb | 367 ++++++++++++++----- 3 files changed, 545 insertions(+), 146 deletions(-) diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index 1aba3f0f90..90f2c56bd4 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -54,16 +54,24 @@ name: nokogiri patch compatibility # # The `hosted` legs run the script's hosted scenario instead: a hosted scan # of a lock that pins nokogiri as platform gems, against a stand-in for the -# patch service (tests/nokogiri/patch_service.rb) that serves a patched build -# of each real platform gem; then a frozen install from a fresh checkout, -# `vex` and a byte-identical `rollback`. On JRuby the platform is `java`. +# patch service (tests/nokogiri/patch_service.rb) whose registry lists every +# locked platform gem: a patched build of the real one, under a patch of its +# own, or upstream's own gem behind a redirect while the platform has no +# patched build; then a frozen install from a fresh checkout, `vex` and a +# byte-identical `rollback`. On JRuby the platform is `java`. In the `passed +# through` legs one locked platform has no patched build at first: the +# runner's own, so that the frozen install gets upstream's gem through the +# redirect, or another one. Once the service has that build, the next scan +# moves the lock to the newer registry snapshot. # # The `vendored` legs run the script's vendored scenario instead: a vendored -# scan of a lock that pins nokogiri as platform gems, against a stand-in for -# the patch service (tests/nokogiri/patch_service.rb) that serves a patched -# build of each real platform gem; then a frozen install from a fresh -# checkout with the service unreachable, `vex` and a `rollback` to the lock -# as it was. On JRuby the platform is `java`. +# scan of a lock that pins nokogiri as platform gems, against the same +# stand-in, which serves a patched build of each real platform gem from that +# platform's own patch; then a frozen install from a fresh checkout with the +# service unreachable, `vex` and a `rollback` to the lock as it was. On +# JRuby the platform is `java`. In the `passed through` leg one locked +# platform has no patched build at first: nothing is vendored and the run +# succeeds, and the scan after the service has that build vendors the gem. # # Every leg downloads gems from rubygems.org, and a rebuild of a precompiled # install downloads the source gem and `mini_portile2` from it too. @@ -184,6 +192,16 @@ jobs: - {os: ubuntu-latest, ruby: '3.1', nokogiri: '1.15.7', install: precompiled, args: '--scenarios hosted', note: hosted} - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, cli: build, args: '--scenarios hosted', note: hosted} - {os: ubuntu-latest, ruby: 'jruby-9.4', nokogiri: '1.18.10', install: java, args: '--scenarios hosted', note: hosted} + # The same with one locked platform that has no patched build at + # first, so that the registry lists upstream's own gem for it and + # answers its file with a redirect. `own` is the runner's + # platform: the frozen install gets upstream's gem through the + # redirect, then the patched gem once the build is there. + # `others` is every other locked platform, which nothing here + # installs (`--add-platform` locks one where Bundler locks the + # runner's alone). + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--scenarios hosted --add-platform aarch64-linux-gnu --pass-through own', note: 'hosted, own platform passed through'} + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--scenarios hosted --add-platform aarch64-linux-gnu --pass-through others', note: 'hosted, another platform passed through'} # Vendored mode on a lock that pins nokogiri as platform gems: the # scan commits a patched build of each real platform gem, served # by a stand-in for the patch service, under `.socket/vendor/gem`, @@ -194,6 +212,9 @@ jobs: - {os: ubuntu-latest, ruby: '3.1', nokogiri: '1.15.7', install: precompiled, args: '--scenarios vendored', note: vendored} - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, cli: build, args: '--scenarios vendored', note: vendored} - {os: ubuntu-latest, ruby: 'jruby-9.4', nokogiri: '1.18.10', install: java, args: '--scenarios vendored', note: vendored} + # The same with a locked platform that has no patched build at + # first: nothing is vendored until the service has it. + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--scenarios vendored --add-platform aarch64-linux-gnu --pass-through others', note: 'vendored, a platform passed through'} needs: static-cli runs-on: ${{ vars.DISABLE_DEPOT_RUNNERS != 'true' && matrix.os == 'ubuntu-latest' && 'depot-ubuntu-24.04-4' || matrix.os }} timeout-minutes: 60 diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index a4340b60c6..1dfb897cbd 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -288,6 +288,9 @@ def install puts "Installing nokogiri #{@version} (#{want}) with #{sh!({}, *bundle('--version')).strip}, #{ruby_label}" bundle_install!(@install_env) + # The platforms the project also deploys to: one more platform gem of + # nokogiri in the lock for each, none of them installed here. + @opts[:add_platforms].each { |platform| sh!(@install_env, *bundle("lock", "--add-platform", platform)) } # The copy Bundler loads, wherever this environment keeps its gems. where = sh!({}, *bundle("exec", RbConfig.ruby, "-e", @@ -511,10 +514,31 @@ def scenario(name) # # Both deliver a patched gem through Bundler instead of patching the # installed one. For a precompiled install the lock names one platform gem - # per platform, so what is delivered is a patched platform gem for each - # (PatchService repacks the real ones). The scenario scans, then installs - # the result from a fresh checkout with the lock frozen, as CI and a - # deploy do, and asks the Ruby there what it loaded. + # per platform. The gem's fix is one patch, and the patch service makes a + # patched build of each platform gem under a patch of its own + # (PatchService repacks the real ones). Until a platform's build is there + # the service hands on upstream's own gem for it: `--pass-through` names + # such platforms, and `--add-platform` locks one more than this machine's. + # + # hosted The scan moves every locked platform gem to the patch + # registry as soon as one of them is patched, each pinned to + # the sha256 the registry serves for it, and reports the gem + # per locked build. A fresh checkout installs with the lock + # frozen, as CI and a deploy do, and Ruby there loads the + # patched gem where this machine's platform has one and + # upstream's own gem, which the registry answers with a + # redirect, where it has none yet. With no locked build + # patched nothing moves. Once the service has the builds that + # were missing, the next scan moves the lock to the newer + # registry snapshot and the install is the patched gem. + # vendored The scan commits the patched platform gem of every locked + # platform, each from its own patch, and a fresh checkout + # installs from that tree with the service unreachable. While + # a locked platform has no patched build nothing is vendored: + # the run says so and exits 0. + # + # Either way the scenario ends with `vex` and a `rollback` to the lock as + # it was. def lock_path File.join(@proj, "Gemfile.lock") @@ -525,10 +549,29 @@ def locked_platforms File.read(lock_path).scan(/^ nokogiri \(#{Regexp.escape(@version)}-([^)\s]+)\)$/).flatten.uniq end + # The platform of the gem this machine installs, as the lock spells it. + def own_platform + @full_name.sub("nokogiri-#{@version}-", "") + end + + # The locked platforms `--pass-through` names: `own` is this machine's, + # `others` is every other one. + def pass_through + @opts[:pass_through].flat_map do |which| + case which + when "own" then [own_platform] + when "others" then locked_platforms - [own_platform] + else [which] + end + end.uniq + end + + # A new stand-in service for the lock as it is. def patch_service - @patch_service ||= PatchService.new( + @patch_service.stop if @patch_service + @patch_service = PatchService.new( "nokogiri", @version, locked_platforms, UUID, GHSA, File.join(File.dirname(@proj), "patch-service"), - "\nmodule Nokogiri\n #{RB_CONST} = 1\nend\n" + "\nmodule Nokogiri\n #{RB_CONST} = 1\nend\n", :pass_through => pass_through ) end @@ -538,8 +581,8 @@ def sp_service(*args) # `--patch-server-url`: a hosted reference in the lock counts only on a # Socket host or the one the run is told is the patch server, and this # one is on loopback. - args += ["--api-url", patch_service.url, "--org", PatchService::ORG, "--api-token", "fake", - "--patch-server-url", patch_service.url] + args += ["--api-url", @patch_service.url, "--org", PatchService::ORG, "--api-token", "fake", + "--patch-server-url", @patch_service.url] started = Time.now out, err, status = Open3.capture3(base_env.merge(env), @bin, *args, :chdir => @proj) [status.exitstatus || -1, out, err, Time.now - started] @@ -570,60 +613,23 @@ def delivered(mode) return skip("the lock pins no platform gem of nokogiri: nothing here is specific to a precompiled install") if locked_platforms.empty? return skip("needs a gem home of its own (--gem-home project)") unless project_home? service = patch_service - service.bring_up gemfile, lock = File.read(File.join(@proj, "Gemfile")), File.read(lock_path) platforms = locked_platforms + waiting = platforms.reject { |p| service.uuid_of(p) } + unless waiting.empty? + puts " #{waiting.join(', ')}: no patched build yet, the registry hands on upstream's gem" + end - code, stdout, stderr, secs = sp_service("scan", "--mode", mode, "--yes", "--json") - check(code.zero?, "`scan --mode #{mode}` succeeds (#{secs.round}s)", "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") - # What the scan warned about, for a later check that fails because of it. - scan_said = begin - JSON.pretty_generate(JSON.parse(stdout).fetch("warnings", [])) - rescue JSON::ParserError - tail(stdout) - end + tail(stderr) - rewritten = File.read(lock_path) - check(rewritten != lock, "it rewires the lock", tail(stdout) + tail(stderr)) if mode == "hosted" - section = rewritten[/^GEM\n remote: #{Regexp.escape(service.index_url)}\n specs:\n((?: .*\n)+)/, 1].to_s - missing = platforms.reject { |p| section.include?(" nokogiri (#{@version}-#{p})\n") } - check(missing.empty?, "every platform gem of nokogiri now comes from the patch registry", - "not moved: #{missing.inspect}\n#{rewritten}") - platforms.each do |p| - next unless rewritten.include?("\nCHECKSUMS\n") - check(rewritten.include?(" nokogiri (#{@version}-#{p}) sha256=#{service.sha256_of(p)}\n"), - "the lock pins the patched #{p} gem's checksum", rewritten[/^CHECKSUMS\n(?: .*\n)+/]) - end + rewritten = hosted(service, platforms, waiting, lock) else - vendored = Dir.glob(File.join(@proj, ".socket", "vendor", "gem", "**", "*.gemspec")) - check(vendored.size >= platforms.size, "a patched gem is vendored for each of #{platforms.size} platforms", - vendored.inspect) - check(rewritten =~ /^PATH\n remote: \.socket\/vendor\/gem\//, "the lock takes nokogiri from the vendored path", rewritten) - # From here on nothing may need the patch service. - service.take_down - service.forget_requests - end - - checkout = fresh_checkout(mode == "vendored" ? [".socket"] : []) - in_project(checkout) do - code, out = bundle_install("BUNDLE_FROZEN" => "true") - check(code.zero?, "a fresh checkout installs with the lock frozen", tail(out)) - check(File.read(lock_path) == rewritten, "and the install leaves the lock as it was") - now = probe - check(now[RB_CONST] == 1, "Ruby there loads the patched nokogiri", JSON.pretty_generate(now)) - check(now["binary_sha256"] == @baseline["binary_sha256"], "with the precompiled binary, nothing compiled") - check(now["smoke"] == @baseline["smoke"], "and nokogiri parses, queries, transforms and validates") - if mode == "vendored" - check(now["loaded_from"].to_s.include?("/.socket/vendor/"), "from the vendored tree", now["loaded_from"].inspect) - asked = service.requests.reject { |_, _, status| status == 200 } - check(asked.empty?, "without asking the patch service for anything", asked.inspect) - end + rewritten = vendored(service, platforms, waiting, lock, gemfile) end - FileUtils.rm_rf(checkout) + installs_frozen(service, mode, rewritten, true) # The project itself, after one more `bundle install`. bundle_install! - check(probe[RB_CONST] == 1, "the scanned project loads the patched nokogiri too", scan_said) + check(probe[RB_CONST] == 1, "the scanned project loads the patched nokogiri too") service.bring_up code, stdout, stderr, = sp_service("vex", "--product", PRODUCT, "--output", File.join(@proj, "vex.json")) statuses = begin @@ -645,6 +651,174 @@ def delivered(mode) check(probe == @baseline, "after `bundle install`, Ruby loads what it loaded before the patch") end + # The hosted scans, up to the lock that pins a patched build of every + # locked platform. Returns that lock. + def hosted(service, platforms, waiting, lock) + patched = platforms - waiting + if patched.empty? + # No locked build is patched: moving the gem would gain nothing. + code, stdout, stderr, secs = sp_service("scan", "--mode", "hosted", "--yes", "--json") + left = events(stdout).find { |e| e["errorCode"] == "redirect_gem_no_patched_build" } || {} + check(code.zero? && left["action"] == "skipped", + "`scan --mode hosted` leaves a gem with no patched build where it is, and succeeds (#{secs.round}s)", + "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + check(redirect_warnings(stdout).empty?, "without a warning", redirect_warnings(stdout).inspect) + check(File.read(lock_path) == lock, "the lock is untouched") + elsif !waiting.empty? + rewritten = hosted_scan(service, platforms, lock, []) + installs_frozen(service, "hosted", rewritten, patched.include?(own_platform)) + end + # The builds that were missing are there: a newer registry snapshot. + earlier = service.index_url + waiting.each { |platform| service.publish(platform) } + rewritten = hosted_scan(service, platforms, lock, waiting.empty? ? [] : patched) + unless waiting.empty? || patched.empty? + check(!rewritten.include?(earlier) && rewritten.include?(service.index_url), + "the lock follows the registry to its newer snapshot", rewritten) + end + rewritten + end + + # One hosted scan that moves the gem: every locked platform gem under the + # patch registry, pinned to what it serves, and reported per build. + # `in_place` names the platforms an earlier scan already pinned patched. + # Returns the lock. + def hosted_scan(service, platforms, lock, in_place) + service.forget_requests + code, stdout, stderr, secs = sp_service("scan", "--mode", "hosted", "--yes", "--json") + said = tail(stdout) + tail(stderr) + check(code.zero?, "`scan --mode hosted` succeeds (#{secs.round}s)", "exit #{code}\n#{said}") + rewritten = File.read(lock_path) + section = rewritten[/^GEM\n remote: #{Regexp.escape(service.index_url)}\n specs:\n((?: .*\n)+)/, 1].to_s + missing = platforms.reject { |p| section.include?(" nokogiri (#{@version}-#{p})\n") } + check(missing.empty?, "every platform gem of nokogiri comes from the patch registry's snapshot", + "not moved: #{missing.inspect}\n#{rewritten}\n#{said}") + platforms.each do |p| + next unless rewritten.include?("\nCHECKSUMS\n") + pin = " nokogiri (#{@version}-#{p}) sha256=#{service.sha256_of(p)}\n" + if service.uuid_of(p) + check(rewritten.include?(pin) && !lock.include?(pin), "the lock pins the patched #{p} gem's checksum", + rewritten[/^CHECKSUMS\n(?: .*\n)+/]) + else + check(rewritten.include?(pin) && lock.include?(pin), "the lock keeps upstream's checksum for #{p}", + rewritten[/^CHECKSUMS\n(?: .*\n)+/]) + end + end + + # One `applied` event per patched build, under that build's own patch, + # and an uncounted one per build that stays upstream's gem. + applied, kept = {}, [] + events(stdout).each do |e| + details = e["details"] || {} + next unless details["gemFix"] == UUID && details["platform"] + if e["errorCode"] == "gem_upstream_build_kept" + kept << details["platform"] + elsif e["action"] == "applied" + applied[details["platform"]] = [e["uuid"], details["newlyPatched"] == true] + end + end + want = {} + platforms.each { |p| want[p] = [service.uuid_of(p), !in_place.include?(p)] if service.uuid_of(p) } + check(applied == want, "the run reports each patched build under its own patch", + "expected #{want.inspect}\ngot #{applied.inspect}\n#{said}") + check(kept.sort == platforms.reject { |p| service.uuid_of(p) }.sort, + "and each build that stays upstream's gem as kept, not patched", "#{kept.inspect}\n#{said}") + check(redirect_warnings(stdout).empty?, "without a warning about the gem", redirect_warnings(stdout).inspect) + asked = service.reference_requests + check(!asked.empty? && asked.all? { |body| body["gemBuilds"] == true }, + "every package reference request asks for the list of the gem's builds", asked.inspect) + check(asked.all? { |body| body["uuids"] == [UUID] }, + "and none asks about a platform gem's own patch", asked.inspect) + rewritten + end + + # The `redirect_gem_*` warnings of a `--json` run that are neither the + # note of a refreshed install nor the caveat of a lock with no + # `CHECKSUMS` section. + def redirect_warnings(stdout) + warning_codes(stdout).select { |code| code.to_s.start_with?("redirect_gem_") } - + %w[redirect_gem_install_refreshed redirect_gem_no_checksums_section] + end + + # The vendored scans, up to the lock that takes nokogiri from the + # committed tree. Returns that lock. + def vendored(service, platforms, waiting, lock, gemfile) + unless waiting.empty? + # A locked platform with no patched build: nothing is vendored. + code, stdout, stderr, secs = sp_service("scan", "--mode", "vendored", "--yes", "--json") + pending = events(stdout).find { |e| e["errorCode"] == "vendor_prebuilt_platform_pending" } || {} + check(code.zero? && pending["action"] == "skipped", + "`scan --mode vendored` does not vendor a gem that lacks a patched build, and succeeds (#{secs.round}s)", + "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + check(waiting.all? { |p| pending["reason"].to_s.include?(p) } && + pending["reason"].to_s.include?("is not vendored: no patched build yet for"), + "and names the platforms that have none", pending["reason"].inspect) + check(File.read(lock_path) == lock && File.read(File.join(@proj, "Gemfile")) == gemfile && + !File.exist?(File.join(@proj, ".socket", "vendor", "gem")), "nothing is written") + fetched = service.requests.select { |_, path, _| path.start_with?("/artifacts/") } + check(fetched.empty?, "and nothing is downloaded", fetched.inspect) + waiting.each { |platform| service.publish(platform) } + end + + service.forget_requests + code, stdout, stderr, secs = sp_service("scan", "--mode", "vendored", "--yes", "--json") + said = tail(stdout) + tail(stderr) + check(code.zero?, "`scan --mode vendored` succeeds (#{secs.round}s)", "exit #{code}\n#{said}") + rewritten = File.read(lock_path) + check(rewritten != lock, "it rewires the lock", said) + vendored = Dir.glob(File.join(@proj, ".socket", "vendor", "gem", "**", "*.gemspec")) + check(vendored.size >= platforms.size, "a patched gem is vendored for each of #{platforms.size} platforms", + vendored.inspect) + check(rewritten =~ /^PATH\n remote: \.socket\/vendor\/gem\//, "the lock takes nokogiri from the vendored path", rewritten) + # Each platform's tree comes from that platform's own patch, and the + # run asks for those patches in one request. + own = platforms.map { |p| service.uuid_of(p) }.sort + asked = service.reference_requests + check(!asked.empty? && asked.all? { |body| body["gemBuilds"] == true }, + "every package reference request asks for the list of the gem's builds", asked.inspect) + batches = asked.map { |body| Array(body["uuids"]).sort }.reject { |uuids| (uuids & own).empty? } + check(batches == [own], "the patches of the platform gems are asked for in one request", asked.inspect) + views = service.requests.select { |_, path, _| path.include?("/view/") && !path.end_with?("/#{UUID}") } + check(views.empty?, "and no record of a platform gem's patch is fetched", views.inspect) + # From here on nothing may need the patch service. + service.take_down + service.forget_requests + rewritten + end + + # A fresh checkout of what the scan left to commit installs with the lock + # frozen, and Ruby there loads nokogiri: the patched gem when `patched`, + # else upstream's own, which the patch registry hands on. + def installs_frozen(service, mode, rewritten, patched) + checkout = fresh_checkout(mode == "vendored" ? [".socket"] : []) + service.forget_requests + in_project(checkout) do + code, out = bundle_install("BUNDLE_FROZEN" => "true") + check(code.zero?, "a fresh checkout installs with the lock frozen", tail(out)) + check(File.read(lock_path) == rewritten, "and the install leaves the lock as it was") + now = probe + if patched + check(now[RB_CONST] == 1, "Ruby there loads the patched nokogiri", JSON.pretty_generate(now)) + else + check(now[RB_CONST].nil?, "Ruby there loads upstream's nokogiri: this platform has no patched build yet", + JSON.pretty_generate(now)) + file = "nokogiri-#{@version}-#{own_platform}.gem" + redirected = service.requests.any? { |_, path, status| status == 302 && path.end_with?("/gems/#{file}") } + check(redirected && service.upstream_requests.include?(["GET", "/gems/#{file}", 200]), + "which the patch registry answers with a redirect to the upstream registry", + (service.requests + service.upstream_requests).inspect) + end + check(now["binary_sha256"] == @baseline["binary_sha256"], "with the precompiled binary, nothing compiled") + check(now["smoke"] == @baseline["smoke"], "and nokogiri parses, queries, transforms and validates") + if mode == "vendored" + check(now["loaded_from"].to_s.include?("/.socket/vendor/"), "from the vendored tree", now["loaded_from"].inspect) + asked = service.requests.reject { |_, _, status| status == 200 } + check(asked.empty?, "without asking the patch service for anything", asked.inspect) + end + end + FileUtils.rm_rf(checkout) + end + def skip(why) puts " skip #{why}" true @@ -933,7 +1107,7 @@ class SocketPatchE2E < Rails::Application end opts = { :install => "any", :build => "ok", :gem_home => "project", :scenarios => %w[ruby c libxml2], :gems => [], - :settings => [], :unread_check => true } + :settings => [], :unread_check => true, :add_platforms => [], :pass_through => [] } parser = OptionParser.new do |o| o.banner = "usage: ruby nokogiri_e2e.rb --socket-patch BIN --nokogiri VERSION [options]" o.on("--socket-patch BIN", "the socket-patch binary under test") { |v| opts[:socket_patch] = v } @@ -956,6 +1130,11 @@ class SocketPatchE2E < Rails::Application "in an official Ruby image is /usr/local/bundle; only for a throwaway environment)") { |v| opts[:gem_home] = v } o.on("--scenarios LIST", Array, "of ruby,c,libxml2 (default: all three, agent mode) and hosted,vendored", "(a scan against a stand-in patch service that serves repacked platform gems)") { |v| opts[:scenarios] = v } + o.on("--add-platform PLATFORM", "also lock nokogiri's gem of this platform (`bundle lock --add-platform`), for", + "example aarch64-linux-gnu; may be given more than once") { |v| opts[:add_platforms] << v } + o.on("--pass-through LIST", Array, "hosted and vendored: the locked platforms the stand-in patch service has no", + "patched build of yet, so that it hands on upstream's own gem for them: platform names,", + "`own` (this machine's) or `others` (every other locked one)") { |v| opts[:pass_through].concat(v) } o.on("--rails VERSION", "also install this Rails (a Gemfile requirement, for example '~> 7.1.0') and check", "that a booted application sanitizes HTML through the patched nokogiri") { |v| opts[:rails] = v } o.on("--bundle-setting KEY=VALUE", "one more Bundler setting for the install, for example", diff --git a/tests/nokogiri/patch_service.rb b/tests/nokogiri/patch_service.rb index e33262d891..3b1d384500 100644 --- a/tests/nokogiri/patch_service.rb +++ b/tests/nokogiri/patch_service.rb @@ -1,8 +1,9 @@ # frozen_string_literal: true # A stand-in for Socket's patch service, for the hosted and vendored -# scenarios of nokogiri_e2e.rb: the patches API, the per-patch gem registry -# (a RubyGems compact index) and the artifact downloads, on a loopback port. +# scenarios of nokogiri_e2e.rb: the patches API, the gem patch's registry +# (a RubyGems compact index) and the artifact downloads, on a loopback port, +# and on a second port a stand-in for the upstream registry's file host. # # What it serves is real: the ruby-platform nokogiri gem and every platform # gem the project's lock names, downloaded from rubygems.org and repacked @@ -12,6 +13,36 @@ # binaries were rebuilt on the service's side), so the client paths under # test are the same. # +# It answers the way the patch service does: +# +# * The gem's fix is one patch (`uuid`), the ruby gem's. Each patched +# platform gem has a patch of its own (`uuid_of(platform)`): the search +# routes return its record beside the gem's, and its reference serves +# that gem (`tarball`) and its stub gemspec (`gem-stub-gemspec`). One +# reference request answers for every uuid it names. +# * A reference request that carries `"gemBuilds": true` gets the gem +# patch's registry under a snapshot URL (`…//s/`, the key +# derived from what the registry lists) and the list of the version's +# gems (`gemBuilds`): the ruby gem under the gem's patch, each patched +# platform gem under its own, and each pass-through platform with +# `"patchUuid": null`. A request without it gets the plain URL and no +# list. +# * The registry under a snapshot lists every gem of that list. A +# pass-through platform is upstream's own line, and its file is a 302 to +# the upstream stand-in (`upstream_url`), which serves the real gem. A +# platform whose patched build is still being made is in neither the +# list nor the registry. A snapshot answers as it did after `publish` +# made a newer one. +# +# service = PatchService.new("nokogiri", "1.18.10", %w[arm64-darwin x86_64-linux-gnu], +# uuid, ghsa, dir, mark, :pass_through => %w[arm64-darwin]) +# service.index_url # what a hosted lock names as the gem's remote +# service.publish("arm64-darwin") # its patched build is there: a newer snapshot +# +# Options: `:pass_through` (platforms served as upstream's own gem), +# `:building` (platforms left out of the list), `:list => false` (a patch of +# the ruby gem alone: no list for any request). +# # No gem dependencies, and nothing newer than Ruby 2.1 syntax: the file is # loaded on every leg, though its scenarios only run where nokogiri has # platform gems (Ruby 2.5 and later). @@ -35,35 +66,63 @@ class PatchService attr_reader :uuid, :ghsa # `platforms`: the platform tokens the lock names (`x86_64-linux-gnu`, …). - # `mark`: the Ruby text appended to `lib/.rb` of every gem. - def initialize(name, version, platforms, uuid, ghsa, work, mark) + # `mark`: the Ruby text appended to `lib/.rb` of every patched gem. + def initialize(name, version, platforms, uuid, ghsa, work, mark, options = {}) @name = name @version = version @uuid = uuid @ghsa = ghsa @work = work @mark = mark + @list = options.fetch(:list, true) @requests = [] + @upstream_requests = [] + @reference_requests = [] @lock = Mutex.new @patch_routes_up = true FileUtils.mkdir_p(@work) - @ruby_gem = repack(nil) - @prebuilds = platforms.sort.map { |platform| repack(platform) } + pass_through = options.fetch(:pass_through, []) + building = options.fetch(:building, []) + @states = {} + @upstream = {} + @patched = {} + ([nil] + platforms.sort).each do |platform| + @upstream[platform], @patched[platform] = repack(platform) + next unless platform + @states[platform] = if building.include?(platform) then :building + elsif pass_through.include?(platform) then :pass_through + else :patched + end + end + @snapshots = {} @server = TCPServer.new("127.0.0.1", 0) - @thread = Thread.new { loop { serve(@server.accept) } } + @files = TCPServer.new("127.0.0.1", 0) + @threads = [[@server, :respond], [@files, :respond_upstream]].map do |server, route| + Thread.new { loop { serve(server.accept, route) } } + end end def url "http://127.0.0.1:#{@server.addr[1]}" end + # The stand-in for the upstream registry's file host: `gems/` of + # every gem of the version, as upstream published it. + def upstream_url + "http://127.0.0.1:#{@files.addr[1]}" + end + + # The gem patch's registry as a lock names it after a hosted scan: the + # snapshot of what the registry lists now, closed by a slash. def index_url - "#{url}/patch-registry/gem/#{TOKEN}/#{@uuid}/" + key, = @lock.synchronize { snapshot } + key ? "#{url}#{registry_path}/s/#{key}/" : "#{url}#{registry_path}/" end def stop - @thread.kill + @threads.each(&:kill) @server.close + @files.close end # From now on the registry and the downloads answer 503: what a machine @@ -76,17 +135,44 @@ def bring_up @lock.synchronize { @patch_routes_up = true } end + # The patched build of `platform` is there: the list names its patch from + # now on, under a newer snapshot. Returns that snapshot's `index_url`. + def publish(platform) + @lock.synchronize do + raise ArgumentError, "#{platform} is not a platform of this service" unless @states.key?(platform) + @states[platform] = :patched + end + index_url + end + # [verb, path, status] of every request so far. def requests @lock.synchronize { @requests.dup } end + # The same for the upstream stand-in. + def upstream_requests + @lock.synchronize { @upstream_requests.dup } + end + + # The body of every package reference request so far, parsed. + def reference_requests + @lock.synchronize { @reference_requests.dup } + end + def forget_requests - @lock.synchronize { @requests.clear } + @lock.synchronize { [@requests, @upstream_requests, @reference_requests].each(&:clear) } end + # The sha256 the registry lists for `platform` now: its patched build's, + # or upstream's own gem's for a pass-through platform. def sha256_of(platform) - (@prebuilds.find { |b| b.platform == platform } || @ruby_gem).sha256 + @lock.synchronize { (@states[platform] == :patched ? @patched : @upstream).fetch(platform).sha256 } + end + + # The patch of `platform`'s patched build, or nil while it has none. + def uuid_of(platform) + @lock.synchronize { @states[platform] == :patched ? build_uuid(platform) : nil } end private @@ -110,8 +196,9 @@ def fetch(file) path end - # The upstream gem of `platform` (nil: the ruby gem) with the mark appended - # to `lib/.rb`, and the facts the index and the API state about it. + # The upstream gem of `platform` (nil: the ruby gem) as it is, and with + # the mark appended to `lib/.rb`, each with the facts the index and + # the API state about it. # # A `.gem` is a tar of `metadata.gz` (the gemspec), `data.tar.gz` (the # files) and `checksums.yaml.gz`. Like the service's own repack, this one @@ -140,12 +227,13 @@ def repack(platform) tar.add_file_simple(name, 0o444, bytes.bytesize) { |io| io.write(bytes) } end end - bytes = out.string deps = spec.runtime_dependencies.map { |d| "#{d.name}:#{d.requirement.as_list.join('&')}" }.sort.join(",") - Built.new(file, platform ? "#{@version}-#{platform}" : @version, platform, bytes, - Digest::SHA256.hexdigest(bytes), "sha512-" + [Digest::SHA512.digest(bytes)].pack("m0"), - spec.to_ruby, deps, spec.required_ruby_version.as_list.join("&"), - spec.required_rubygems_version.as_list.join("&")) + [File.binread(upstream), out.string].map do |bytes| + Built.new(file, platform ? "#{@version}-#{platform}" : @version, platform, bytes, + Digest::SHA256.hexdigest(bytes), sri(bytes), spec.to_ruby, deps, + spec.required_ruby_version.as_list.join("&"), + spec.required_rubygems_version.as_list.join("&")) + end end def gzip(bytes) @@ -195,14 +283,52 @@ def sri(bytes) "sha512-" + [Digest::SHA512.digest(bytes)].pack("m0") end + # ---- what the service has ------------------------------------------------ + # + # Everything below reads `@states` and `@snapshots`, and runs with `@lock` + # held. + + # The uuid of the patch of `platform`'s patched build (nil: the gem's). + def build_uuid(platform) + return @uuid unless platform + hex = Digest::SHA256.hexdigest("#{@uuid}/#{platform}") + [hex[0, 8], hex[8, 4], "4" + hex[13, 3], "8" + hex[17, 3], hex[20, 12]].join("-") + end + + # The platforms with a patched build. + def patched_platforms + @states.select { |_, state| state == :patched }.keys + end + + # What the registry lists now, as [state, gem] rows: the patched ruby gem, + # then each platform gem that is patched or passed through. + def listing + rows = [[:patched, @patched[nil]]] + @states.each do |platform, state| + rows << [state, (state == :patched ? @patched : @upstream).fetch(platform)] unless state == :building + end + rows + end + + # [key, rows] of the snapshot of `listing`, which answers under that key + # from now on; nil for a service with no list. + def snapshot + return nil unless @list + rows = listing + text = rows.map { |state, gem| [gem.token, gem.sha256, state].join(" ") }.join("\n") + key = Digest::SHA256.hexdigest(text)[0, 12] + @snapshots[key] ||= rows + [key, rows] + end + # ---- the routes ---------------------------------------------------------- - def all_gems - [@ruby_gem] + @prebuilds + def registry_path + "/patch-registry/gem/#{TOKEN}/#{@uuid}" end - def info_body - lines = all_gems.map do |g| + def info_body(rows) + lines = rows.map do |_, g| "#{g.token} #{g.deps}|checksum:#{g.sha256},ruby:#{g.ruby},rubygems:#{g.rubygems}\n" end "---\n" + lines.join @@ -212,8 +338,9 @@ def base_purl "pkg:gem/#{@name}@#{@version}" end - def patch_purl - "#{base_purl}?platform=ruby" + # The purl of the patch of `platform`'s gem (nil: the gem's own patch). + def patch_purl(platform = nil) + "#{base_purl}?platform=#{platform || 'ruby'}" end def vulnerabilities @@ -221,90 +348,161 @@ def vulnerabilities "description" => "nokogiri end-to-end test" } } end - def artifact_url(leaf) - "#{url}/artifacts/#{@uuid}/#{leaf}" + def artifact_url(platform, leaf) + "#{url}/artifacts/#{build_uuid(platform)}/#{leaf}" + end + + # The gem and the stub gemspec of the patch of `platform`'s gem. + def artifacts(platform) + gem = @patched.fetch(platform) + [{ "kind" => "tarball", "url" => artifact_url(platform, gem.file), + "contentType" => "application/octet-stream", "sizeBytes" => gem.bytes.bytesize, + "integrity" => { "sha512" => gem.sri, "sha256" => gem.sha256 } }, + { "kind" => "gem-stub-gemspec", "url" => artifact_url(platform, gem.file.sub(/\.gem\z/, ".gemspec")), + "contentType" => "text/plain", "sizeBytes" => gem.stub.bytesize, + "integrity" => { "sha512" => sri(gem.stub) } }] end - def package_result - artifacts = [{ "kind" => "tarball", "url" => artifact_url(@ruby_gem.file), - "contentType" => "application/octet-stream", "sizeBytes" => @ruby_gem.bytes.bytesize, - "integrity" => { "sha512" => @ruby_gem.sri, "sha256" => @ruby_gem.sha256 } }] - @prebuilds.each do |g| - stub_leaf = g.file.sub(/\.gem\z/, ".gemspec") - artifacts << { "kind" => "gem-platform", "platform" => g.platform, "url" => artifact_url(g.file), - "contentType" => "application/octet-stream", "sizeBytes" => g.bytes.bytesize, - "integrity" => { "sha512" => g.sri, "sha256" => g.sha256 } } - artifacts << { "kind" => "gem-platform-stub-gemspec", "platform" => g.platform, - "url" => artifact_url(stub_leaf), "contentType" => "text/plain", - "sizeBytes" => g.stub.bytesize, "integrity" => { "sha512" => sri(g.stub) } } + # The reference of the patch `uuid`, or nil for a uuid that is no patch + # here. `with_list`: the request asked for the list of the gem's builds. + def package_result(uuid, with_list) + platform = patched_platforms.find { |p| build_uuid(p) == uuid } + if platform + return { "status" => "granted", "url" => artifact_url(platform, @patched.fetch(platform).file), + "purl" => patch_purl(platform), "artifacts" => artifacts(platform) } + end + return nil unless uuid == @uuid + ruby_gem = @patched[nil] + identifiers = { "name" => @name, "version" => @version, "gemChecksumSha256" => ruby_gem.sha256 } + index = "#{url}#{registry_path}/" + key, rows = with_list ? snapshot : nil + if key + index += "s/#{key}" + builds = rows.map do |state, gem| + { "platform" => gem.platform || "ruby", "gemChecksumSha256" => gem.sha256, + "patchUuid" => state == :patched ? build_uuid(gem.platform) : nil } + end + identifiers["gemBuilds"] = builds.sort_by { |build| build["platform"] } end { "status" => "granted", - "url" => "#{url}/patch/gem/#{@name}/#{@version}/#{TOKEN}/#{@uuid}/#{@ruby_gem.file}", + "url" => "#{url}/patch/gem/#{@name}/#{@version}/#{TOKEN}/#{@uuid}/#{ruby_gem.file}", "purl" => patch_purl, - "artifacts" => artifacts, - "registryOverride" => { - "kind" => "rubygems-compact-index", - "indexUrl" => index_url, - "identifiers" => { - "name" => @name, "version" => @version, "gemChecksumSha256" => @ruby_gem.sha256, - "gemPlatforms" => @prebuilds.map { |g| { "platform" => g.platform, "gemChecksumSha256" => g.sha256 } } - } - } + "artifacts" => artifacts(nil), + "registryOverride" => { "kind" => "rubygems-compact-index", "indexUrl" => index, "identifiers" => identifiers } } end + # The patches a search finds for the gem: the gem's own, and the patch of + # each patched platform gem, published after it. + def found_patches + [nil] + patched_platforms + end + def json(body) [200, "application/json", JSON.generate(body)] end - # status, content type, body of the answer to `verb path`. - def respond(verb, path) + # status, content type, body and extra headers of the answer to `verb + # path` on the service's port. + def respond(verb, path, body) + @lock.synchronize { route(verb, path, body) } + end + + def route(verb, path, body) api = "/v0/orgs/#{ORG}/patches" - registry = "/patch-registry/gem/#{TOKEN}/#{@uuid}" if verb == "POST" && path == "#{api}/batch" - return json("packages" => [{ "purl" => base_purl, "patches" => [{ - "uuid" => @uuid, "purl" => patch_purl, "tier" => "free", "cveIds" => [], - "ghsaIds" => [@ghsa], "severity" => "high", "title" => "nokogiri end-to-end test" - }] }], "canAccessPaidPatches" => false) + patches = found_patches.map do |platform| + { "uuid" => build_uuid(platform), "purl" => patch_purl(platform), "tier" => "free", "cveIds" => [], + "ghsaIds" => [@ghsa], "severity" => "high", "title" => "nokogiri end-to-end test" } + end + return json("packages" => [{ "purl" => base_purl, "patches" => patches }], "canAccessPaidPatches" => false) elsif path.start_with?("#{api}/by-package/") - return json("patches" => [{ "uuid" => @uuid, "purl" => patch_purl, - "publishedAt" => "2026-02-01T00:00:00Z", "description" => "nokogiri end-to-end test", - "license" => "MIT", "tier" => "free", "vulnerabilities" => vulnerabilities }], - "canAccessPaidPatches" => false) - elsif path == "#{api}/view/#{@uuid}" - return json("uuid" => @uuid, "purl" => patch_purl, "publishedAt" => "2026-02-01T00:00:00Z", + patches = found_patches.reverse.map do |platform| + { "uuid" => build_uuid(platform), "purl" => patch_purl(platform), + "publishedAt" => platform ? "2026-03-01T00:00:00Z" : "2026-02-01T00:00:00Z", + "description" => "nokogiri end-to-end test", "license" => "MIT", "tier" => "free", + "vulnerabilities" => vulnerabilities } + end + return json("patches" => patches, "canAccessPaidPatches" => false) + elsif path.start_with?("#{api}/view/") + platform = found_patches.find { |p| build_uuid(p) == File.basename(path) } + return [404, "text/plain", ""] unless platform || File.basename(path) == @uuid + return json("uuid" => build_uuid(platform), "purl" => patch_purl(platform), + "publishedAt" => "2026-02-01T00:00:00Z", "files" => { "lib/#{@name}.rb" => { "beforeHash" => git_sha256(@before), "afterHash" => git_sha256(@after) } }, "vulnerabilities" => vulnerabilities, "description" => "nokogiri end-to-end test", "license" => "MIT", "tier" => "free") elsif verb == "POST" && path == "#{api}/package" - return json("results" => { @uuid => package_result }) + asked = begin + JSON.parse(body.to_s) + rescue JSON::ParserError + {} + end + @reference_requests << asked + results = {} + Array(asked["uuids"]).each do |uuid| + result = package_result(uuid, asked["gemBuilds"] == true) + results[uuid] = result if result + end + return json("results" => results) end - serves_patch = path.start_with?(registry) || path.start_with?("/artifacts/") || path.start_with?("/patch/") + serves_patch = path.start_with?(registry_path + "/") || path.start_with?("/artifacts/") || + path.start_with?("/patch/") return [404, "text/plain", ""] unless serves_patch - return [503, "text/plain", ""] unless @lock.synchronize { @patch_routes_up } - - info = info_body - case path - when "#{registry}/versions" - tokens = all_gems.map(&:token).join(",") - [200, "text/plain", "created_at: 2026-01-01T00:00:00Z\n---\n#{@name} #{tokens} #{Digest::MD5.hexdigest(info)}\n"] - when "#{registry}/info/#{@name}" then [200, "text/plain", info] - when "#{registry}/names" then [200, "text/plain", "---\n#{@name}\n"] + return [503, "text/plain", ""] unless @patch_routes_up + return download(File.basename(path)) unless path.start_with?(registry_path + "/") + + # The registry: under a snapshot, the gems that snapshot lists; under + # the plain URL, the patched ruby gem alone. + rest = path[(registry_path.size + 1)..-1] + rows = [[:patched, @patched[nil]]] + if rest =~ %r{\As/([0-9a-f]+)/(.*)\z} + rows = @snapshots[Regexp.last_match(1)] + rest = Regexp.last_match(2) + return [404, "text/plain", ""] unless rows + end + index = { "Cache-Control" => "public, no-cache" } + info = info_body(rows) + case rest + when "versions" + tokens = rows.map { |_, g| g.token }.join(",") + [200, "text/plain", + "created_at: 2026-01-01T00:00:00Z\n---\n#{@name} #{tokens} #{Digest::MD5.hexdigest(info)}\n", index] + when "info/#{@name}" then [200, "text/plain", info, index] + when "names" then [200, "text/plain", "---\n#{@name}\n", index] else - leaf = File.basename(path) - gem = all_gems.find { |g| g.file == leaf } - stub = @prebuilds.find { |g| g.file.sub(/\.gem\z/, ".gemspec") == leaf } - if gem then [200, "application/octet-stream", gem.bytes] - elsif stub then [200, "text/plain", stub.stub] + state, gem = rows.find { |_, g| "gems/#{g.file}" == rest } + if state == :pass_through + [302, "text/plain", "", { "Location" => "#{upstream_url}/gems/#{gem.file}", "Cache-Control" => "no-store" }] + elsif gem then [200, "application/octet-stream", gem.bytes] else [404, "text/plain", ""] end end end - def serve(socket) + # An artifact of a patch, by its file name: a patched gem or its stub. + def download(leaf) + gems = @patched.values + gem = gems.find { |g| g.file == leaf } + stub = gems.find { |g| g.file.sub(/\.gem\z/, ".gemspec") == leaf } + if gem then [200, "application/octet-stream", gem.bytes] + elsif stub then [200, "text/plain", stub.stub] + else [404, "text/plain", ""] + end + end + + # The answer of the upstream stand-in: upstream's own gem files. + def respond_upstream(_verb, path, _body) + gem = @upstream.values.find { |g| "/gems/#{g.file}" == path } + gem ? [200, "application/octet-stream", gem.bytes] : [404, "text/plain", ""] + end + + REASONS = { 200 => "OK", 302 => "Found", 404 => "Not Found", 503 => "Service Unavailable" }.freeze + + def serve(socket, route) line = socket.gets return unless line verb, target, = line.split(" ") @@ -313,14 +511,15 @@ def serve(socket) key, value = header.split(":", 2) length = value.to_i if key.casecmp("content-length").zero? end - socket.read(length) if length > 0 + sent = length > 0 ? socket.read(length) : nil path = target.to_s.split("?").first - status, type, body = respond(verb, path) - @lock.synchronize { @requests << [verb, path, status] } - reason = { 200 => "OK", 404 => "Not Found", 503 => "Service Unavailable" }.fetch(status) - socket.write("HTTP/1.1 #{status} #{reason}\r\nContent-Type: #{type}\r\n" \ + status, type, body, headers = send(route, verb, path, sent) + log = route == :respond ? @requests : @upstream_requests + @lock.synchronize { log << [verb, path, status] } + extra = (headers || {}).map { |name, value| "#{name}: #{value}\r\n" }.join + socket.write("HTTP/1.1 #{status} #{REASONS.fetch(status)}\r\nContent-Type: #{type}\r\n" \ "Content-Length: #{body.bytesize}\r\nETag: \"#{Digest::MD5.hexdigest(body)}\"\r\n" \ - "Connection: close\r\n\r\n") + "#{extra}Connection: close\r\n\r\n") socket.write(body) unless verb == "HEAD" rescue StandardError nil From 5328b7da00dedd91205e9219ee0e55c6a32ac9da Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 21:43:20 -0500 Subject: [PATCH 017/120] Drive a gem's platform builds through the list of builds with real Bundler The real-Bundler hosted capstones for a gem locked as precompiled platform gems mounted a patch API that named the patched platform gems as `gemPlatforms` and `gem-platform` artifacts of the gem's patch, under the plain registry URL. The CLI reads the list of the version's gems (`gemBuilds`) under a registry snapshot instead, so all five failed at the scan, and nothing proved the new behaviours against a bundler. The platform cases now share one fixture, `PlatformProject`: the gems, a project the real bundler locked and installed, and a stand-in for the patch service that answers as the wire contract has it. Each patched platform gem has a patch of its own, which the search routes return beside the gem's; a reference request gets the snapshot URL and the list only when it asks (`gemBuilds: true`), and every helper that reads the reference requests asserts that each one asked; the registry under a snapshot lists every gem of that list and answers the file of a platform with no patched build with a 302 to a second wiremock, the stand-in of the upstream registry's file host, so nothing leaves the machine; a later listing is a newer snapshot beside the earlier ones. The five capstones are converted (every locked build patched: with and without `CHECKSUMS`, with the ruby entry beside the builds, and taken over by a vendored run, which now asks for the platform patches in one request) and assert the per-build events. New cases, all on a `CHECKSUMS` lock: - one platform patched and one on upstream's gem, with this machine in either role: the scan moves both, `bundle lock` agrees byte for byte, and a fresh checkout installs frozen, in deployment mode and unfrozen. The machine of the patched platform gets the patched gem; the other gets upstream's gem through the redirect, and the scan downloads nothing for it. `rollback` restores the pair; - no locked build patched, then one platform missing from the list: nothing moves, quietly, until the list has it; - a newer snapshot: the URL and the one changed checksum are rewritten, the build is reported as newly patched, `bundle install` installs it, and the earlier snapshot still installs what it did; - `bundle lock --add-platform` over a hosted lock resolves the new platforms from the registry, patched or not, and a re-scan reports them and writes nothing; - the refresh's download of `gems/` follows a redirect the registry answers with. A machine of platform X is this machine: bundler installs the platform gem of its host, so the cases that turn on which platform is patched run twice with the roles swapped. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_redirect_gem_build.rs | 2566 ++++++++++++----- 1 file changed, 1908 insertions(+), 658 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs index 93f020012f..9700454aa5 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -93,6 +93,21 @@ //! (the Gemfile's option kept) re-converges on the next unfrozen install, //! and on the next hosted scan. //! +//! PLATFORM GEMS (the cases at the end of the file, on a lock the real +//! bundler wrote for a gem published as precompiled platform gems): the +//! gem's fix is one patch, whose reference lists every platform gem of the +//! version under a registry snapshot. Every locked build moves to that +//! registry once one of them is patched. A machine of a patched platform +//! installs the patched gem; a machine of a platform with no patched build +//! yet installs upstream's gem, which the registry answers with a redirect +//! to the upstream registry's file (here a second wiremock). The cases: +//! every locked build patched (with and without `CHECKSUMS`, with the ruby +//! entry beside the builds, and taken over by a vendored run), one build +//! patched (this machine in either role), none patched or one still being +//! made (nothing moves, quietly), a newer snapshot, `bundle lock +//! --add-platform` over a hosted lock, and a refresh whose download the +//! registry redirects. +//! //! VERSION MATRIX: the arms run on bundler 1.17 → 4.x (the CHECKSUMS arm //! from 2.6, the CHECKSUMS-era floor; every other arm from 1.17). Pick the //! bundler with `PATH` (CI: `ruby/setup-ruby`'s `bundler:` input) and name @@ -6724,7 +6739,31 @@ async fn gem_hosted_scan_says_the_gem_is_held_at_its_version() { ); } -// ── precompiled platform gems ("prebuilds") ─────────────────────────── +// ── precompiled platform gems ───────────────────────────────────────── +// +// The fixture gem as bundler locks a gem that ships precompiled platform +// gems (`vuln-gem (1.0.0-arm64-darwin)`), against a stand-in for the patch +// service that answers as the wire contract has it: +// +// * the gem's fix is ONE patch, [`UUID`], the ruby gem's. Each patched +// platform gem has a patch of its own ([`build_uuid`]), which the search +// routes return beside the gem's and whose reference serves that gem +// (`tarball`) and its stub gemspec; +// * a reference request that carries `"gemBuilds": true` gets the gem +// patch's registry under a snapshot URL (`…//s/`) and the +// list of the version's gems: the ruby gem, each patched platform gem +// with its patch, each platform still on upstream's gem with none. A +// request without it gets the plain URL and no list; +// * the registry under a snapshot lists every gem of that list, serves +// the file of a patched build, and answers the file of a platform with +// none with a 302 to the upstream registry's own file: here a second +// wiremock, the stand-in of that registry's file host, so nothing leaves +// the machine. A platform whose build is still being made is in neither. +// A snapshot answers as it did once a later one exists. +// +// "A machine of platform X" is this machine: bundler installs the platform +// gem of the host it runs on, so each case that turns on which platform is +// patched runs with this machine's platform in either role. /// One build a compact index serves: its gem, the token the index lists it /// under (`` for the ruby gem, `-` for a @@ -6735,13 +6774,29 @@ struct IndexBuild { token: String, deps: Vec, gem: Vec, + /// Where the download route sends the client instead of serving `gem`, + /// which the index still lists by its sha256. + redirect: Option, } /// [`mount_compact_index`] for gems published as several builds, the way /// rubygems.org serves a gem with precompiled platform variants: one /// `versions` line per gem listing every token, one `info/` line and -/// one `gems/-.gem` route per build. -async fn mount_build_index(server: &MockServer, base: &str, builds: &[IndexBuild]) { +/// one `gems/-.gem` route per build. `index_headers` go on +/// every index response. +async fn mount_build_index( + server: &MockServer, + base: &str, + builds: &[IndexBuild], + index_headers: &[(&str, &str)], +) { + let index = |body: String| { + let mut response = compact_index_body(body); + for (name, value) in index_headers { + response = response.insert_header(*name, *value); + } + response + }; let mut names: Vec<&str> = Vec::new(); for build in builds { if !names.contains(&build.name) { @@ -6761,12 +6816,16 @@ async fn mount_build_index(server: &MockServer, base: &str, builds: &[IndexBuild sha256_hex(&build.gem) )); tokens.push(&build.token); + let file = match &build.redirect { + Some(location) => ResponseTemplate::new(302) + .insert_header("Location", location.as_str()) + .insert_header("Cache-Control", "no-store"), + None => ResponseTemplate::new(200) + .set_body_raw(build.gem.clone(), "application/octet-stream"), + }; Mock::given(method("GET")) .and(path(format!("{base}/gems/{name}-{}.gem", build.token))) - .respond_with( - ResponseTemplate::new(200) - .set_body_raw(build.gem.clone(), "application/octet-stream"), - ) + .respond_with(file) .mount(server) .await; } @@ -6778,18 +6837,18 @@ async fn mount_build_index(server: &MockServer, base: &str, builds: &[IndexBuild names_body.push_str(&format!("{name}\n")); Mock::given(method("GET")) .and(path(format!("{base}/info/{name}"))) - .respond_with(compact_index_body(info_body)) + .respond_with(index(info_body)) .mount(server) .await; } Mock::given(method("GET")) .and(path(format!("{base}/versions"))) - .respond_with(compact_index_body(versions_body)) + .respond_with(index(versions_body)) .mount(server) .await; Mock::given(method("GET")) .and(path(format!("{base}/names"))) - .respond_with(compact_index_body(names_body)) + .respond_with(index(names_body)) .mount(server) .await; } @@ -6808,7 +6867,7 @@ fn build_marked(lib: String) -> String { /// pure-Ruby gem whose gemspec sets `s.platform` is one. Every build /// carries the same `lib/vuln_gem.rb` (`lib`, the file the patch replaces) /// and its own `lib/vuln_gem/build.rb`, which says which build Ruby loaded: -/// a real prebuild differs from the ruby gem only outside the patched +/// a real platform gem differs from the ruby gem only outside the patched /// files, so one patch record's hashes hold for every build. fn build_gem_build(stage: &Path, tag: &str, platform: Option<&str>, lib: &str) -> Vec { let build = platform.unwrap_or("ruby"); @@ -6827,7 +6886,7 @@ fn build_gem_build(stage: &Path, tag: &str, platform: Option<&str>, lib: &str) - dir.join(format!("{DEP}.gemspec")), format!( "Gem::Specification.new do |s|\n s.name = \"{DEP}\"\n s.version = \"{DEP_VERSION}\"\n{platform_line} \ - s.summary = \"socket-patch hosted-gem prebuild fixture\"\n s.authors = [\"socket-patch e2e\"]\n \ + s.summary = \"socket-patch hosted-gem platform fixture\"\n s.authors = [\"socket-patch e2e\"]\n \ s.files = [\"lib/vuln_gem.rb\", \"lib/vuln_gem/build.rb\"]\n s.require_paths = [\"lib\"]\n \ s.add_dependency \"{TRANSITIVE}\", \">= 0\"\nend\n" ), @@ -6874,180 +6933,245 @@ fn own_and_foreign_platform() -> (String, String) { (own, foreign.to_string()) } -/// A gem bundler locks as precompiled platform builds, with a prebuild for -/// every platform the lock names, against the REAL bundler end to end: -/// -/// 1. upstream publishes the gem as a ruby gem AND as platform gems (this -/// machine's platform, and a foreign one); the real `bundle install` + -/// `bundle lock --add-platform` lock both platform builds and install -/// this machine's platform gem. `ruby_entry` picks the lock's -/// PLATFORMS: without `ruby` the lock holds the platform builds -/// alone, with it bundler keeps the ruby-platform -/// `name (version)` entry beside them (what bundler 4 locks by default -/// for a gem that also ships a ruby gem), and that entry moves too; -/// 2. the hosted scan moves BOTH entries into the patch registry's `GEM` -/// section, pins `DEPENDENCIES`, and (on a `CHECKSUMS` lock) sets each -/// entry to its own prebuild's sha256 — the lock the real `bundle lock` -/// writes for that Gemfile, byte for byte — and replaces the platform -/// copy bundler had installed with the patched platform gem; -/// 3. a fresh checkout's FROZEN `bundle install` fetches exactly this -/// machine's prebuild from the patch registry (never the ruby gem, so -/// nothing is compiled), leaves the lock byte-identical, and Ruby -/// loads the PATCHED file from the platform build; -/// 4. a re-scan is a no-op; -/// 5. `rollback` hands back the pre-scan pair byte for byte and puts the -/// installed copy back on the upstream platform gem; -/// 6. standalone `vex` attests the gem from the lock, hash-verified -/// against the installed platform build. -/// -/// With `takeover` (#2174), a vendored run takes the gem over before step -/// 5, which leaves the patched platform copy the hosted scan installed. -/// Step 5 is then a vendored unwind, and `remove` and `vendor --revert` -/// run over copies of the project as well: each must put the installed -/// platform copy back on the upstream platform gem. -async fn platform_prebuilds_install_frozen_and_roll_back( - tag: &str, - checksums_lock: bool, - ruby_entry: bool, - takeover: bool, -) { - // Bundler locks the specific platform's gem from 2.2; `CHECKSUMS` from - // 2.6. Vendor takes platform gems from a lock bundler 2.3 or newer wrote. - let floor = match (checksums_lock, takeover) { - (true, _) => (2, 6), - (false, true) => (2, 3), - (false, false) => (2, 2), - }; - let Some(bundler) = bundler_e2e::gate("e2e_redirect_gem_build", tag, floor, &|c| { - cache_env::isolate(c); - }) else { - return; - }; - let (own, foreign) = own_and_foreign_platform(); - let platforms = [own.as_str(), foreign.as_str()]; - let tmp = tempfile::tempdir().unwrap(); - let stage = tmp.path().join("gem-stage"); - let (orig, patched) = (build_marked(orig_lib()), build_marked(patched_lib())); - let builds_of = |tag: &str, lib: &str| -> Vec { - [None, Some(own.as_str()), Some(foreign.as_str())] - .into_iter() - .map(|platform| IndexBuild { - name: DEP, - token: match platform { - Some(p) => format!("{DEP_VERSION}-{p}"), - None => DEP_VERSION.to_string(), - }, - deps: vec![format!("{TRANSITIVE}:>= 0")], - gem: build_gem_build(&stage, tag, platform, lib), - }) - .collect() - }; - let mut upstream_builds = builds_of("orig", &orig); - let patched_builds = builds_of("patched", &patched); - let sha_of = |builds: &[IndexBuild], token: &str| { - let build = builds.iter().find(|b| b.token == token).expect("build"); - sha256_hex(&build.gem) - }; - let token = |platform: &str| format!("{DEP_VERSION}-{platform}"); +/// Shaped like a Socket API token, so that no run warns about the token +/// itself and a case can hold a run's warnings to an exact list. +const API_TOKEN: &str = "sktsec_00000000000000000000000000000000000000000000_api"; + +/// How the patch service has one platform gem of the fixture gem's version. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Has { + /// A patched build, under a patch of its own. + Patched, + /// No patched build yet: the registry lists upstream's own gem and + /// answers its file with a redirect to the upstream registry. + Upstream, + /// A patched build is being made: no list names the platform yet. + Building, +} - // One wiremock: upstream registry, patch registry, patches API. - let server = MockServer::start().await; - upstream_builds.push(IndexBuild { - name: TRANSITIVE, - token: "1.0.0".to_string(), - deps: vec![], - gem: build_gem(&stage, TRANSITIVE, "1.0.0", "tiny_dep.rb", TINY_LIB, &[]), - }); - mount_build_index(&server, "/upstream", &upstream_builds).await; - let registry_base = format!("/patch-registry/gem/{TOKEN}/{UUID}"); - let index_url = format!("{}{registry_base}/", server.uri()); - mount_build_index(&server, ®istry_base, &patched_builds).await; - Mock::given(method("POST")) - .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "packages": [{ - "purl": PURL, - "patches": [{ - "uuid": UUID, "purl": PURL, "tier": "free", - "cveIds": [], "ghsaIds": [], "severity": "high", - "title": "gem prebuild capstone fixture" - }] - }], - "canAccessPaidPatches": false, - }))) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path_regex(format!( - "^/v0/orgs/{ORG}/patches/by-package/.+$" - ))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "patches": [{ - "uuid": UUID, "purl": PURL, - "publishedAt": "2026-01-01T00:00:00Z", - "description": "x", "license": "MIT", "tier": "free", - "vulnerabilities": {} - }], - "canAccessPaidPatches": false, - }))) - .mount(&server) - .await; - // The reference of a patch that has prebuilds: a `gem-platform` - // artifact per prebuild (with `platform`) and `gemPlatforms` in the - // override's identifiers. - let hosted_url = format!( - "{}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{UUID}/{DEP}-{DEP_VERSION}.gem", - server.uri() - ); - let ruby_sha = sha_of(&patched_builds, DEP_VERSION); - let mut artifacts = vec![serde_json::json!({ - "kind": "tarball", "url": hosted_url, "integrity": { "sha256": ruby_sha } - })]; - let mut gem_platforms = Vec::new(); - for platform in platforms { - let sha = sha_of(&patched_builds, &token(platform)); - artifacts.push(serde_json::json!({ - "kind": "gem-platform", "platform": platform, - "url": format!("{index_url}gems/{DEP}-{DEP_VERSION}-{platform}.gem"), - "contentType": "application/octet-stream", "sizeBytes": 4096, - "integrity": { "sha256": sha } - })); - gem_platforms.push(serde_json::json!({ "platform": platform, "gemChecksumSha256": sha })); +/// The uuid of the patch of `platform`'s patched build. +fn build_uuid(platform: &str) -> String { + let hex = sha256_hex(format!("{UUID}/{platform}").as_bytes()); + format!( + "{}-{}-4{}-8{}-{}", + &hex[..8], + &hex[8..12], + &hex[13..16], + &hex[17..20], + &hex[20..32] + ) +} + +/// A build's token in the lock, the compact index and its file name: +/// `` for the ruby gem, `-` for a platform gem. +fn build_token(platform: Option<&str>) -> String { + match platform { + Some(platform) => format!("{DEP_VERSION}-{platform}"), + None => DEP_VERSION.to_string(), } - Mock::given(method("POST")) - .and(path(format!("/v0/orgs/{ORG}/patches/package"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { - UUID: { - "status": "granted", - "url": hosted_url, - "purl": PURL, - "artifacts": artifacts, - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": index_url, - "identifiers": { - "name": DEP, - "version": DEP_VERSION, - "gemChecksumSha256": ruby_sha, - "gemPlatforms": gem_platforms, - } - } - } +} + +/// The purl of a platform gem, as a run reports it and as its own patch's +/// record names it. +fn platform_purl(platform: &str) -> String { + format!("{PURL}?platform={platform}") +} + +/// One gem of the version as the registry lists it. +struct ListedGem { + /// `None`: the ruby gem. + platform: Option, + /// The sha256 of the archive the registry serves for it. + sha256: String, + /// The patch of its patched build; `None`: upstream's own gem. + patch: Option, +} + +/// The key of the registry snapshot that lists `listed`: derived from the +/// list, so that the same list is the same URL. +fn snapshot_key(listed: &[ListedGem]) -> String { + let text: String = listed + .iter() + .map(|gem| { + format!( + "{} {} {}\n", + gem.platform.as_deref().unwrap_or("ruby"), + gem.sha256, + gem.patch.as_deref().unwrap_or("-") + ) + }) + .collect(); + sha256_hex(text.as_bytes())[..12].to_string() +} + +/// What the stand-in patch service answers from: the gems, and how it has +/// each platform gem now. +struct PlatformService { + /// The origin of the wiremock that plays the patch service. + api: String, + /// The origin of the stand-in of the upstream registry's file host. + files: String, + /// `lib/vuln_gem.rb` before and after the patch. + orig: String, + patched: String, + /// Upstream's gems, the patched builds and the stub gemspecs of the + /// patched builds, each by [`build_token`]. + upstream: std::collections::BTreeMap>, + builds: std::collections::BTreeMap>, + stubs: std::collections::BTreeMap>, + /// How the service has each platform gem; `None`: it has no list for + /// the gem (a patch of the ruby gem alone). + listing: std::sync::Mutex>>, +} + +impl PlatformService { + /// The sha256 of the gem of `platform`: its patched build, or + /// upstream's own. + fn sha(&self, platform: Option<&str>, patched: bool) -> String { + let gems = if patched { + &self.builds + } else { + &self.upstream + }; + sha256_hex(&gems[&build_token(platform)]) + } + + /// What the registry lists now: the patched ruby gem, then each + /// platform gem that is patched or on upstream's gem. + fn listed(&self) -> Option> { + let listing = self.listing.lock().unwrap().clone()?; + let mut listed = vec![ListedGem { + platform: None, + sha256: self.sha(None, true), + patch: Some(UUID.to_string()), + }]; + for (platform, has) in listing { + let patched = match has { + Has::Patched => true, + Has::Upstream => false, + Has::Building => continue, + }; + listed.push(ListedGem { + sha256: self.sha(Some(&platform), patched), + patch: patched.then(|| build_uuid(&platform)), + platform: Some(platform), + }); + } + Some(listed) + } + + /// The patches a search finds for the gem, as `(uuid, purl)`: the gem's + /// own, and the patch of each patched platform gem. + fn found(&self) -> Vec<(String, String)> { + let mut found = vec![(UUID.to_string(), PURL.to_string())]; + for gem in self.listed().unwrap_or_default() { + if let (Some(platform), Some(patch)) = (gem.platform, gem.patch) { + found.push((patch, platform_purl(&platform))); } - }))) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path(format!("/v0/orgs/{ORG}/patches/view/{UUID}"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "uuid": UUID, + } + found + } + + /// The path the artifact `leaf` of the patch `uuid` is served at. + fn artifact_path(uuid: &str, leaf: &str) -> String { + format!("/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{uuid}/{leaf}") + } + + /// The artifacts of the patch `uuid` of the gem of `platform`: the + /// patched gem and its stub gemspec. + fn artifacts(&self, uuid: &str, platform: Option<&str>) -> serde_json::Value { + let token = build_token(platform); + let (gem, stub) = (&self.builds[&token], &self.stubs[&token]); + let url = |ext: &str| { + let leaf = format!("{DEP}-{token}.{ext}"); + format!("{}{}", self.api, Self::artifact_path(uuid, &leaf)) + }; + serde_json::json!([ + { "kind": "tarball", "url": url("gem"), + "integrity": { "sha512": sri(gem), "sha256": sha256_hex(gem) } }, + { "kind": "gem-stub-gemspec", "url": url("gemspec"), + "integrity": { "sha512": sri(stub) } }, + ]) + } + + /// The reference of the gem's patch. `with_list`: the request asked for + /// the list of the gem's builds. + fn gem_reference(&self, with_list: bool) -> serde_json::Value { + let mut identifiers = serde_json::json!({ + "name": DEP, + "version": DEP_VERSION, + "gemChecksumSha256": self.sha(None, true), + }); + let mut index_url = format!("{}/patch-registry/gem/{TOKEN}/{UUID}/", self.api); + if let Some(listed) = self.listed().filter(|_| with_list) { + index_url = format!("{index_url}s/{}", snapshot_key(&listed)); + let mut builds: Vec = listed + .iter() + .map(|gem| { + serde_json::json!({ + "platform": gem.platform.as_deref().unwrap_or("ruby"), + "gemChecksumSha256": gem.sha256, + "patchUuid": gem.patch, + }) + }) + .collect(); + builds.sort_by_key(|build| build["platform"].as_str().map(str::to_string)); + identifiers["gemBuilds"] = builds.into(); + } + let artifacts = self.artifacts(UUID, None); + serde_json::json!({ + "status": "granted", + "url": artifacts[0]["url"], "purl": PURL, + "artifacts": artifacts, + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": index_url, + "identifiers": identifiers, + } + }) + } + + /// The answer to one package reference request: every uuid it names + /// that is a patch here. + fn references(&self, request: &wiremock::Request) -> ResponseTemplate { + let asked: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default(); + let with_list = asked["gemBuilds"] == true; + let found = self.found(); + let mut results = serde_json::Map::new(); + for uuid in asked["uuids"].as_array().into_iter().flatten() { + let Some(uuid) = uuid.as_str() else { continue }; + let Some((_, purl)) = found.iter().find(|(patch, _)| patch == uuid) else { + continue; + }; + let reference = match purl.split_once("?platform=") { + None => self.gem_reference(with_list), + Some((_, platform)) => { + let artifacts = self.artifacts(uuid, Some(platform)); + serde_json::json!({ + "status": "granted", + "url": artifacts[0]["url"], + "purl": purl, + "artifacts": artifacts, + }) + } + }; + results.insert(uuid.to_string(), reference); + } + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": results })) + } + + /// The record of the patch `uuid` of `purl`: every build carries the + /// one patched file. + fn view(&self, uuid: &str, purl: &str) -> serde_json::Value { + serde_json::json!({ + "uuid": uuid, + "purl": purl, "publishedAt": "2026-01-01T00:00:00Z", "files": { "lib/vuln_gem.rb": { - "beforeHash": compute_git_sha256_from_bytes(orig.as_bytes()), - "afterHash": compute_git_sha256_from_bytes(patched.as_bytes()), + "beforeHash": compute_git_sha256_from_bytes(self.orig.as_bytes()), + "afterHash": compute_git_sha256_from_bytes(self.patched.as_bytes()), } }, "vulnerabilities": { @@ -7059,365 +7183,1012 @@ async fn platform_prebuilds_install_frozen_and_roll_back( } }, "description": "x", "license": "MIT", "tier": "free" - }))) - .mount(&server) - .await; + }) + } - // 1. The project, locked and installed by the real bundler. - let proj = tmp.path().join("proj"); - std::fs::create_dir_all(&proj).unwrap(); - std::fs::write( - proj.join("Gemfile"), - format!("source \"{}/upstream\"\n\ngem \"{DEP}\"\n", server.uri()), - ) - .unwrap(); - let bundle_ok = |dir: &Path, args: &[&str]| { - let out = bundle(dir, args); - assert!( - out.status.success(), - "bundle {args:?} failed:\nstdout:\n{}\nstderr:\n{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr), + /// Mount the patches API, the artifacts of every patch, and the gem + /// patch's registry under its plain URL, which lists the patched ruby + /// gem alone. + async fn mount(self: &std::sync::Arc, server: &MockServer) { + let api = format!("/v0/orgs/{ORG}/patches"); + let service = self.clone(); + Mock::given(method("POST")) + .and(path(format!("{api}/batch"))) + .respond_with(move |_: &wiremock::Request| { + let patches: Vec = service + .found() + .iter() + .map(|(uuid, purl)| { + serde_json::json!({ + "uuid": uuid, "purl": purl, "tier": "free", + "cveIds": [], "ghsaIds": [], "severity": "high", + "title": "gem platform capstone fixture" + }) + }) + .collect(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [{ "purl": PURL, "patches": patches }], + "canAccessPaidPatches": false, + })) + }) + .mount(server) + .await; + // A platform gem's patch is published after the gem's: a search + // ranks it first. + let service = self.clone(); + Mock::given(method("GET")) + .and(path_regex(format!("^{api}/by-package/.+$"))) + .respond_with(move |_: &wiremock::Request| { + let patches: Vec = service + .found() + .iter() + .rev() + .map(|(uuid, purl)| { + let published = match uuid.as_str() { + UUID => "2026-01-01T00:00:00Z", + _ => "2026-02-01T00:00:00Z", + }; + serde_json::json!({ + "uuid": uuid, "purl": purl, "publishedAt": published, + "description": "x", "license": "MIT", "tier": "free", + "vulnerabilities": {} + }) + }) + .collect(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": patches, + "canAccessPaidPatches": false, + })) + }) + .mount(server) + .await; + let service = self.clone(); + Mock::given(method("POST")) + .and(path(format!("{api}/package"))) + .respond_with(move |request: &wiremock::Request| service.references(request)) + .mount(server) + .await; + for token in self.builds.keys() { + let platform = token.strip_prefix(&format!("{DEP_VERSION}-")); + let (uuid, purl) = match platform { + Some(platform) => (build_uuid(platform), platform_purl(platform)), + None => (UUID.to_string(), PURL.to_string()), + }; + Mock::given(method("GET")) + .and(path(format!("{api}/view/{uuid}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(self.view(&uuid, &purl))) + .mount(server) + .await; + for (ext, bytes) in [ + ("gem", &self.builds[token]), + ("gemspec", &self.stubs[token]), + ] { + let leaf = format!("{DEP}-{token}.{ext}"); + Mock::given(method("GET")) + .and(path(Self::artifact_path(&uuid, &leaf))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes.clone())) + .mount(server) + .await; + } + } + let ruby_gem = IndexBuild { + name: DEP, + token: build_token(None), + deps: vec![format!("{TRANSITIVE}:>= 0")], + gem: self.builds[&build_token(None)].clone(), + redirect: None, + }; + let plain = format!("/patch-registry/gem/{TOKEN}/{UUID}"); + mount_build_index(server, &plain, &[ruby_gem], REGISTRY_INDEX_HEADERS).await; + } +} + +/// What the patch registry sends with every index response. +const REGISTRY_INDEX_HEADERS: &[(&str, &str)] = &[("Cache-Control", "public, no-cache")]; + +/// A project the real bundler locked to the fixture gem's platform gems of +/// this machine's platform ([`Self::own`]) and of one it is not +/// ([`Self::foreign`]) and installed, with the stand-in patch service. +struct PlatformProject { + /// The project, its pair before any scan, and the wiremock that plays + /// the upstream registry, the patch registry and the patches API. + /// `index_url` is the registry of the listing served last. + fx: RedirectFixture, + /// The stand-in of the upstream registry's file host: where the patch + /// registry sends a client for a platform it has no patched build of. + files: MockServer, + service: std::sync::Arc, + /// The registry snapshots mounted so far, by path. + snapshots: std::collections::BTreeSet, + own: String, + foreign: String, + /// The lock has a `CHECKSUMS` section. + checksums: bool, +} + +impl PlatformProject { + /// Build the gems, start both servers, and let the real bundler lock + /// and install the project. Upstream publishes the gem as a ruby gem + /// and as platform gems for this machine's platform, a foreign one and + /// each of `more`; the lock names the first two. `ruby_entry` picks the + /// lock's PLATFORMS: without `ruby` the lock holds the platform builds + /// alone, with it bundler keeps the ruby-platform `name (version)` + /// entry beside them (what bundler 4 locks by default for a gem that + /// also ships a ruby gem). `None`: the bundler is below `floor` or + /// missing (said on stdout). + async fn start( + tag: &str, + floor: (u32, u32), + checksums: bool, + ruby_entry: bool, + more: &[&str], + ) -> Option { + let bundler = bundler_e2e::gate("e2e_redirect_gem_build", tag, floor, &|c| { + cache_env::isolate(c); + })?; + let (own, foreign) = own_and_foreign_platform(); + let tmp = tempfile::tempdir().unwrap(); + let stage = tmp.path().join("gem-stage"); + let (orig, patched) = (build_marked(orig_lib()), build_marked(patched_lib())); + let platforms = [own.as_str(), foreign.as_str()]; + let published = std::iter::once(None) + .chain(platforms.into_iter().map(Some)) + .chain(more.iter().copied().map(Some)); + let mut upstream = std::collections::BTreeMap::new(); + let mut builds = std::collections::BTreeMap::new(); + let mut stubs = std::collections::BTreeMap::new(); + for platform in published { + let token = build_token(platform); + upstream.insert( + token.clone(), + build_gem_build(&stage, "orig", platform, &orig), + ); + let build = build_gem_build(&stage, "patched", platform, &patched); + stubs.insert(token.clone(), stub_gemspec(&build)); + builds.insert(token, build); + } + + let server = MockServer::start().await; + let files = MockServer::start().await; + let mut index: Vec = upstream + .iter() + .map(|(token, gem)| IndexBuild { + name: DEP, + token: token.clone(), + deps: vec![format!("{TRANSITIVE}:>= 0")], + gem: gem.clone(), + redirect: None, + }) + .collect(); + index.push(IndexBuild { + name: TRANSITIVE, + token: "1.0.0".to_string(), + deps: vec![], + gem: build_gem(&stage, TRANSITIVE, "1.0.0", "tiny_dep.rb", TINY_LIB, &[]), + redirect: None, + }); + mount_build_index(&server, "/upstream", &index, &[]).await; + for (token, gem) in &upstream { + Mock::given(method("GET")) + .and(path(format!("/gems/{DEP}-{token}.gem"))) + .respond_with( + ResponseTemplate::new(200) + .set_body_raw(gem.clone(), "application/octet-stream"), + ) + .mount(&files) + .await; + } + let service = std::sync::Arc::new(PlatformService { + api: server.uri(), + files: files.uri(), + orig: orig.clone(), + patched: patched.clone(), + upstream, + builds, + stubs, + listing: std::sync::Mutex::new(None), + }); + service.mount(&server).await; + + // The project, locked and installed by the real bundler. + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!("source \"{}/upstream\"\n\ngem \"{DEP}\"\n", server.uri()), + ) + .unwrap(); + let config_args = bundler.config_local_args("path", "vendor/bundle"); + let config_args: Vec<&str> = config_args.iter().map(String::as_str).collect(); + bundle_ok(&proj, &config_args); + if !checksums && bundler.at_least(2, 6) { + bundle_ok( + &proj, + &["config", "set", "--local", "lockfile_checksums", "false"], + ); + } + bundle_ok(&proj, &["install"]); + bundle_ok(&proj, &["lock", "--add-platform", &foreign]); + // Bundler adds platforms by itself to a lock it creates (4.0.15 + // does): `ruby` when every locked gem has a ruby-platform gem, and + // the common platforms every locked gem has a gem for. Pin the + // shape either way. + let locks = |platform: &str| { + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + let platforms = lock.split("\nPLATFORMS\n").nth(1).unwrap_or_default(); + let platforms = platforms.split("\n\n").next().unwrap_or_default(); + platforms.lines().any(|line| line.trim() == platform) + }; + if ruby_entry && !locks("ruby") { + bundle_ok(&proj, &["lock", "--add-platform", "ruby"]); + } else if !ruby_entry && locks("ruby") { + bundle_ok(&proj, &["lock", "--remove-platform", "ruby"]); + } + for platform in more { + if locks(platform) { + bundle_ok(&proj, &["lock", "--remove-platform", platform]); + } + } + if checksums { + bundle_ok(&proj, &["lock", "--add-checksums"]); + } + let pristine_gemfile = std::fs::read(proj.join("Gemfile")).unwrap(); + let pristine_lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + for platform in platforms { + assert!( + pristine_lock.contains(&format!(" {DEP} ({})\n", build_token(Some(platform)))), + "the fixture lock must pin the {platform} build:\n{pristine_lock}" + ); + } + assert_eq!( + pristine_lock.contains(&format!(" {DEP} ({DEP_VERSION})\n")), + ruby_entry, + "the fixture lock's ruby-platform entry must match the case:\n{pristine_lock}" ); - }; - let config_args = bundler.config_local_args("path", "vendor/bundle"); - let config_args: Vec<&str> = config_args.iter().map(String::as_str).collect(); - bundle_ok(&proj, &config_args); - if !checksums_lock && bundler.at_least(2, 6) { - bundle_ok( - &proj, - &["config", "set", "--local", "lockfile_checksums", "false"], + assert_eq!( + pristine_lock.matches(&format!(" {DEP} (")).count(), + 2 + usize::from(ruby_entry), + "the fixture lock must name no other build:\n{pristine_lock}" + ); + assert_eq!( + pristine_lock.contains("\nCHECKSUMS\n"), + checksums, + "fixture lock CHECKSUMS presence must match the case:\n{pristine_lock}" + ); + let project = PlatformProject { + fx: RedirectFixture { + tmp, + proj, + index_url: String::new(), + gemfile_name: "Gemfile", + lock_name: "Gemfile.lock", + patched: patched.into_bytes(), + pristine_gemfile, + pristine_lock: pristine_lock.into_bytes(), + bundler, + _server: server, + }, + files, + service, + snapshots: std::collections::BTreeSet::new(), + own, + foreign, + checksums, + }; + assert_eq!( + std::fs::read_to_string(project.installed_lib(&project.fx.proj)) + .expect("bundler installed the platform gem"), + orig, + "premise: the upstream platform gem is installed before the scan" ); + Some(project) } - bundle_ok(&proj, &["install"]); - bundle_ok(&proj, &["lock", "--add-platform", &foreign]); - // Bundler adds the `ruby` platform by itself when every locked gem has - // a ruby-platform gem (4.0.15 does); pin the arm's shape either way. - let locks_ruby = |lock: String| lock.contains("\nPLATFORMS\n") && lock.contains("\n ruby\n"); - let locked_ruby = locks_ruby(std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap()); - if ruby_entry && !locked_ruby { - bundle_ok(&proj, &["lock", "--add-platform", "ruby"]); - } else if !ruby_entry && locked_ruby { - bundle_ok(&proj, &["lock", "--remove-platform", "ruby"]); + + fn api(&self) -> String { + self.fx._server.uri() } - if checksums_lock { - bundle_ok(&proj, &["lock", "--add-checksums"]); + + fn pristine_lock(&self) -> String { + String::from_utf8(self.fx.pristine_lock.clone()).unwrap() } - let pristine_gemfile = std::fs::read(proj.join("Gemfile")).unwrap(); - let pristine_lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); - for platform in platforms { - assert!( - pristine_lock.contains(&format!(" {DEP} ({})\n", token(platform))), - "the fixture lock must pin the {platform} build:\n{pristine_lock}" - ); + + fn pristine_gemfile(&self) -> String { + String::from_utf8(self.fx.pristine_gemfile.clone()).unwrap() } - let ruby_beside = pristine_lock.contains(&format!(" {DEP} ({DEP_VERSION})\n")); - assert_eq!( - ruby_beside, ruby_entry, - "the fixture lock's ruby-platform entry must match the arm:\n{pristine_lock}" - ); - assert_eq!( - pristine_lock.contains("\nCHECKSUMS\n"), - checksums_lock, - "fixture lock CHECKSUMS presence must match the arm:\n{pristine_lock}" - ); - let own_leaf = format!("{DEP}-{DEP_VERSION}-{own}"); - let warm_lib = fresh_installed_lib(&proj, &own_leaf, "vuln_gem.rb"); - assert_eq!( - std::fs::read_to_string(&warm_lib).expect("bundler installed the platform gem"), - orig, - "premise: the upstream platform gem is installed before the scan" - ); - // 2. The hosted scan. - let api = server.uri(); - let proj_str = proj.to_str().expect("utf8 tmp path"); - let scan = || { - run_socket( - &proj, + fn lock(&self) -> String { + std::fs::read_to_string(self.fx.proj.join("Gemfile.lock")).unwrap() + } + + fn gemfile(&self) -> String { + std::fs::read_to_string(self.fx.proj.join("Gemfile")).unwrap() + } + + /// `--` of this machine's platform gem. + fn own_leaf(&self) -> String { + format!("{DEP}-{}", build_token(Some(&self.own))) + } + + /// `lib/vuln_gem.rb` of this machine's platform gem as bundler + /// installed it under `dir`. + fn installed_lib(&self, dir: &Path) -> PathBuf { + fresh_installed_lib(dir, &self.own_leaf(), "vuln_gem.rb") + } + + /// From now on the service has the platform gems as `listing` says + /// (`None`: it has no list for the gem), and its registry answers under + /// the snapshot of that listing beside every earlier one. Returns the + /// registry URL as a lock names it. + async fn serve(&mut self, listing: Option<&[(&str, Has)]>) -> String { + *self.service.listing.lock().unwrap() = listing.map(|listing| { + listing + .iter() + .map(|(platform, has)| (platform.to_string(), *has)) + .collect() + }); + let mut base = format!("/patch-registry/gem/{TOKEN}/{UUID}"); + if let Some(listed) = self.service.listed() { + base = format!("{base}/s/{}", snapshot_key(&listed)); + if self.snapshots.insert(base.clone()) { + let index: Vec = listed + .iter() + .map(|gem| { + let token = build_token(gem.platform.as_deref()); + let (gems, redirect) = match gem.patch { + Some(_) => (&self.service.builds, None), + None => ( + &self.service.upstream, + Some(format!("{}/gems/{DEP}-{token}.gem", self.service.files)), + ), + }; + IndexBuild { + name: DEP, + deps: vec![format!("{TRANSITIVE}:>= 0")], + gem: gems[&token].clone(), + token, + redirect, + } + }) + .collect(); + mount_build_index(&self.fx._server, &base, &index, REGISTRY_INDEX_HEADERS).await; + } + } + self.fx.index_url = format!("{}{base}/", self.api()); + self.fx.index_url.clone() + } + + /// `socket-patch --mode hosted` over `dir` against the + /// stand-in service, with `extra` arguments. + fn hosted(&self, dir: &Path, command: &[&str], extra: &[&str]) -> (i32, String, String) { + let api = self.api(); + let mut args: Vec<&str> = command.to_vec(); + args.extend([ + "--mode", + "hosted", + "--yes", + "--cwd", + dir.to_str().expect("utf8 tmp path"), + "--api-url", + &api, + "--org", + ORG, + "--api-token", + API_TOKEN, + ]); + args.extend_from_slice(extra); + run_socket(dir, &args) + } + + /// A `--json` hosted scan of the project, which must exit 0: its + /// envelope. + fn scan(&self, extra: &[&str]) -> serde_json::Value { + let mut args = vec!["--json"]; + args.extend_from_slice(extra); + let (code, stdout, stderr) = self.hosted(&self.fx.proj, &["scan"], &args); + assert_eq!( + code, 0, + "scan failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("scan --json is not JSON: {e}\nstdout:\n{stdout}")) + } + + /// A scan that leaves the gem where it is, quietly: exit 0, both files + /// byte-identical, no warning, and one counted `skipped` event under + /// `code` whose reason is `line`; a person reads that one line on + /// stdout, and nothing on stderr warns or names the gem. The copy + /// bundler installed stays upstream's. + fn assert_left_alone(&self, code: &str, line: &str) { + let untouched = |when: &str| { + assert_eq!(self.lock(), self.pristine_lock(), "{when}: the lock"); + assert_eq!( + self.gemfile(), + self.pristine_gemfile(), + "{when}: the Gemfile" + ); + assert_eq!( + std::fs::read_to_string(self.installed_lib(&self.fx.proj)).unwrap(), + self.service.orig, + "{when}: the installed copy" + ); + }; + let env = self.scan(&[]); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + hosted_events(&env), + [serde_json::json!({ + "action": "skipped", "purl": PURL, "uuid": UUID, + "errorCode": code, "reason": line, + "details": { "mode": "hosted" }, + })], + "{env}" + ); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + ( + &serde_json::json!(0), + &serde_json::json!(1), + &serde_json::json!(0) + ), + "{env}" + ); + assert_eq!(env["redirect"]["rewrittenFiles"], serde_json::json!([])); + untouched("--json"); + + let (code, stdout, stderr) = self.hosted(&self.fx.proj, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&format!("\n{line}\n")), "{stdout}"); + assert!( + !stderr.contains("No patches could be switched") + && !stderr.contains("Warning") + && !stderr.contains(DEP), + "nothing on stderr names it:\n{stderr}" + ); + untouched("for a person"); + } + + /// The project's pair as a hosted scan must leave it for the registry + /// `index_url`, where `pinned` says of each locked platform whether its + /// patched build is what the lock pins: the Gemfile's declaration with + /// the `source:` option, every build of the gem under the registry's + /// `GEM` section and none upstream, each `CHECKSUMS` entry on the sha256 + /// the registry serves for it, and `DEPENDENCIES` source-pinned. + /// Returns the lock. + fn assert_hosted_pair(&self, index_url: &str, pinned: &[(&str, bool)]) -> String { + assert_eq!( + self.gemfile(), + with_source_option( + &self.pristine_gemfile(), + &format!("gem \"{DEP}\""), + index_url + ), + "the Gemfile edit is the one a ruby gem gets" + ); + let lock = self.lock(); + let registry_section = lock + .split("\n\n") + .find(|section| section.contains(&format!("remote: {index_url}\n"))) + .unwrap_or_else(|| panic!("no GEM section of {index_url}:\n{lock}")); + let pristine = self.pristine_lock(); + for (platform, patched) in pinned { + let token = build_token(Some(platform)); + assert!( + registry_section.contains(&format!(" {DEP} ({token})\n {TRANSITIVE}")), + "the {platform} build is under the patch registry with its sub-lines:\n{lock}" + ); + if self.checksums { + let pin = format!( + " {DEP} ({token}) sha256={}\n", + self.service.sha(Some(platform), *patched) + ); + assert!( + lock.contains(&pin), + "CHECKSUMS pins the {platform} build to the sha256 the registry serves for \ + it (patched: {patched}):\n{lock}" + ); + assert_eq!( + pristine.contains(&pin), + !*patched, + "a build on upstream's gem keeps the sha256 it had, a patched one does not" + ); + } + } + let entries = |text: &str| text.matches(&format!(" {DEP} (")).count(); + assert_eq!( + entries(&lock), + entries(&pristine), + "every build, each listed once:\n{lock}" + ); + assert_eq!( + entries(registry_section), + entries(&lock), + "all of them under the patch registry:\n{lock}" + ); + if self.checksums && pristine.contains(&format!(" {DEP} ({DEP_VERSION})\n")) { + let ruby_sha = self.service.sha(None, true); + assert!( + lock.contains(&format!(" {DEP} ({DEP_VERSION}) sha256={ruby_sha}\n")), + "CHECKSUMS pins the ruby-platform entry to the patched ruby gem:\n{lock}" + ); + } + assert!( + lock.contains(&format!("\nDEPENDENCIES\n {DEP}!\n")), + "DEPENDENCIES is source-pinned:\n{lock}" + ); + lock + } + + /// The lock the host bundler itself writes for `gemfile` over the lock + /// `before`, in a scratch dir named `name`. + fn bundler_lock(&self, name: &str, gemfile: &str, before: &str) -> String { + let relock = self.fx.tmp.path().join(name); + std::fs::create_dir_all(&relock).unwrap(); + std::fs::write(relock.join("Gemfile"), gemfile).unwrap(); + std::fs::write(relock.join("Gemfile.lock"), before).unwrap(); + copy_dir_recursive(&self.fx.proj.join(".bundle"), &relock.join(".bundle")); + bundle_ok(&relock, &["lock"]); + std::fs::read_to_string(relock.join("Gemfile.lock")).unwrap() + } + + /// A fresh checkout of the committed pair, named `name`, after the + /// real `bundle install` with `envs` succeeded there and left the lock + /// byte-identical. + fn install_fresh(&self, name: &str, envs: &[(&str, &str)]) -> PathBuf { + let fresh = stage_fresh_checkout(&self.fx, name); + let install = bundle_env(&fresh, &["install"], envs); + assert!( + install.status.success(), + "`bundle install` ({envs:?}) of a fresh checkout must succeed.\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&install.stdout), + String::from_utf8_lossy(&install.stderr), + ); + assert_eq!( + std::fs::read_to_string(fresh.join("Gemfile.lock")).unwrap(), + self.lock(), + "`bundle install` ({envs:?}) must leave the lock byte-identical (bundler {})", + self.fx.bundler.version + ); + fresh + } + + /// `dir` holds this machine's platform gem, the patched build or + /// upstream's own as `patched` says, never the ruby gem, and Ruby loads + /// that file from that platform gem. + fn assert_installed(&self, dir: &Path, patched: bool) { + let (lib, status) = if patched { + (&self.service.patched, patched_marker()) + } else { + (&self.service.orig, "VULNERABLE".to_string()) + }; + assert_eq!( + &std::fs::read_to_string(self.installed_lib(dir)) + .expect("the platform gem is installed"), + lib, + "the install holds the file of the {} platform gem", + if patched { "patched" } else { "upstream" } + ); + assert!( + !fresh_installed_lib(dir, &format!("{DEP}-{DEP_VERSION}"), "vuln_gem.rb").exists(), + "the ruby-platform gem is not what bundler installs" + ); + let probe = bundle( + dir, &[ - "scan", - "--mode", - "hosted", - "--json", - "--yes", - "--cwd", - proj_str, - "--api-url", - &api, - "--org", - ORG, - "--api-token", - "fake", - "--vex", - "out.vex.json", - "--vex-product", - PRODUCT, + "exec", + "ruby", + "-e", + "require \"vuln_gem\"\nputs VulnGem.status\nputs VulnGem::BUILD\nputs TinyDep::VALUE\nputs $LOADED_FEATURES.grep(%r{/vuln_gem\\.rb\\z})", ], + ); + assert!( + probe.status.success(), + "bundle exec require probe failed.\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&probe.stdout), + String::from_utf8_lossy(&probe.stderr), + ); + let out = String::from_utf8_lossy(&probe.stdout).into_owned(); + let lines: Vec<&str> = out.lines().collect(); + assert_eq!( + lines.len(), + 4, + "status, build, dep and the loaded file:\n{out}" + ); + assert_eq!( + lines[..3], + [status.as_str(), self.own.as_str(), "tiny-ok"], + "Ruby loads that file, from this machine's platform build:\n{out}" + ); + assert!( + lines[3].contains("/vendor/bundle/") + && lines[3].contains(&format!("/gems/{}/lib/", self.own_leaf())), + "vuln_gem.rb loads from the installed platform gem:\n{out}" + ); + } + + /// How many requests the patch service and the upstream file host have + /// answered: a mark for [`Self::fetched_since`]. + async fn mark(&self) -> (usize, usize) { + ( + request_paths(&self.fx._server, 0).await.len(), + request_paths(&self.files, 0).await.len(), ) - }; - let (code, stdout, stderr) = scan(); - assert_eq!( - code, 0, - "scan failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + } + + /// The gem files asked for since `mark`: of the patch registry (each + /// with the snapshot path it was asked under), and of the upstream file + /// host. + async fn fetched_since(&self, mark: (usize, usize)) -> (Vec, Vec) { + let registry = request_paths(&self.fx._server, mark.0) + .await + .into_iter() + .filter(|path| path.starts_with("/patch-registry/") && path.contains("/gems/")) + .collect(); + let files = request_paths(&self.files, mark.1) + .await + .into_iter() + .filter_map(|path| path.strip_prefix("/gems/").map(str::to_string)) + .collect(); + (registry, files) + } + + /// The body of every package reference request since `mark`, after + /// asserting that each asked for the list of the gem's builds. + async fn references_since(&self, mark: (usize, usize)) -> Vec> { + let requests = self.fx._server.received_requests().await; + let mut asked = Vec::new(); + for request in requests.unwrap_or_default().iter().skip(mark.0) { + if !request.url.path().ends_with("/patches/package") { + continue; + } + let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default(); + assert_eq!( + body["gemBuilds"], true, + "every package reference request asks for the list of the gem's builds: {body}" + ); + let uuids = body["uuids"].as_array().into_iter().flatten(); + asked.push( + uuids + .filter_map(|uuid| uuid.as_str().map(str::to_string)) + .collect(), + ); + } + asked + } + + /// The patch records fetched since `mark`, by uuid. + async fn views_since(&self, mark: (usize, usize)) -> Vec { + let requests = self.fx._server.received_requests().await; + let requests = requests.unwrap_or_default(); + let paths = requests.iter().skip(mark.0).map(|r| r.url.path()); + paths + .filter_map(|path| path.rsplit_once("/patches/view/")) + .map(|(_, uuid)| uuid.to_string()) + .collect() + } + + /// `text` with the mock upstream spelled as rubygems.org on a + /// `CHECKSUMS` lock: an unwind re-derives a `CHECKSUMS` sha256 only for + /// a rubygems.org remote, so there the pair names that registry and the + /// mock serves it (`SOCKET_RUBYGEMS_URL`). + fn as_committed(&self, text: &str) -> String { + let upstream = format!("{}/upstream", self.api()); + if self.checksums { + text.replace(&format!("\"{upstream}\""), "\"https://rubygems.org\"") + .replace(&format!("{upstream}/"), "https://rubygems.org/") + } else { + text.to_string() + } + } + + /// Spell the project's pair as [`Self::as_committed`] does. No bundler + /// runs on a `CHECKSUMS` project after this. + fn commit_pair(&self) { + for file in ["Gemfile", "Gemfile.lock"] { + let path = self.fx.proj.join(file); + let text = std::fs::read_to_string(&path).unwrap(); + std::fs::write(&path, self.as_committed(&text)).unwrap(); + } + } + + /// `socket-patch --json` over `dir` as an unwind runs: against + /// the stand-in service, which is also the patch server, with the mock + /// upstream as the gem registry. Returns the exit code, stdout, stderr. + fn unwind(&self, dir: &Path, argv: &[&str]) -> (i32, String, String) { + let api = self.api(); + let upstream = format!("{api}/upstream"); + let mut args: Vec<&str> = argv.to_vec(); + args.extend([ + "--json", + "--cwd", + dir.to_str().expect("utf8 tmp path"), + "--api-url", + &api, + "--org", + ORG, + "--api-token", + API_TOKEN, + "--patch-server-url", + &api, + ]); + run_socket_env(dir, &args, &[("SOCKET_RUBYGEMS_URL", &upstream)]) + } + + /// `rollback` of the gem: the pair before any scan, byte for byte. + /// Returns the run's stdout. + fn roll_back(&self) -> String { + self.commit_pair(); + let (code, stdout, stderr) = self.unwind(&self.fx.proj, &["rollback", PURL]); + assert_eq!(code, 0, "rollback:\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!( + self.lock(), + self.as_committed(&self.pristine_lock()), + "rollback must hand the lock back byte for byte" + ); + assert_eq!( + self.gemfile(), + self.as_committed(&self.pristine_gemfile()), + "rollback must hand the Gemfile back byte for byte" + ); + stdout + } +} + +/// The path of every request `server` has answered, after the first `skip`. +async fn request_paths(server: &MockServer, skip: usize) -> Vec { + let requests = server.received_requests().await.unwrap_or_default(); + let paths = requests.iter().skip(skip); + paths + .map(|request| request.url.path().to_string()) + .collect() +} + +/// `bundle ` in `dir`, which must succeed. +fn bundle_ok(dir: &Path, args: &[&str]) { + let out = bundle(dir, args); + assert!( + out.status.success(), + "bundle {args:?} failed:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), ); - let env: serde_json::Value = serde_json::from_str(&stdout) - .unwrap_or_else(|e| panic!("scan --json is not JSON: {e}\nstdout:\n{stdout}")); - assert_eq!(env["status"], "success", "envelope: {env}"); - assert_eq!(env["summary"]["applied"], 1, "one gem redirected: {env}"); - let warning_codes: Vec<&str> = env["warnings"] +} + +/// The hosted events of a run (`details.mode: "hosted"`), by the platform +/// they name (the ruby gem's, which names none, first). +fn hosted_events(env: &serde_json::Value) -> Vec { + let mut events: Vec = env["events"] .as_array() .into_iter() .flatten() - .filter_map(|w| w["code"].as_str()) + .filter(|event| event["details"]["mode"] == "hosted") + .cloned() .collect(); - for code in [ - "redirect_gem_platform_unsupported", - "redirect_gem_stale_install", - "redirect_gem_frozen_install", - ] { - assert!(!warning_codes.contains(&code), "no {code}: {env}"); + events.sort_by_key(|event| { + let platform = event["details"]["platform"].as_str(); + platform.map(str::to_string) + }); + events +} + +/// The warning codes of a run, in envelope order. +fn warning_codes(env: &serde_json::Value) -> Vec { + let warnings = env["warnings"].as_array().into_iter().flatten(); + warnings + .map(|w| w["code"].as_str().unwrap_or_default().to_string()) + .collect() +} + +/// The event of a patched build: `applied`, under the build's own patch, +/// with `newlyPatched` when the run put the build in place. +fn patched_event(platform: &str, newly: bool) -> serde_json::Value { + let mut details = serde_json::json!({ "gemFix": UUID, "platform": platform, "mode": "hosted" }); + if newly { + details["newlyPatched"] = serde_json::json!(true); } + serde_json::json!({ + "action": "applied", "purl": platform_purl(platform), "uuid": build_uuid(platform), + "details": details, + }) +} + +/// The event of the ruby-platform entry a lock keeps beside the platform +/// builds: `applied`, under the gem's own patch. +fn ruby_event(newly: bool) -> serde_json::Value { + let mut details = serde_json::json!({ "gemFix": UUID, "mode": "hosted" }); + if newly { + details["newlyPatched"] = serde_json::json!(true); + } + serde_json::json!({ "action": "applied", "purl": PURL, "uuid": UUID, "details": details }) +} + +/// The uncounted event of a build that stays upstream's gem. +fn upstream_event(platform: &str) -> serde_json::Value { + serde_json::json!({ + "action": "skipped", + "purl": platform_purl(platform), + "errorCode": "gem_upstream_build_kept", + "reason": format!( + "the patch registry serves upstream's own gem for {platform}: no patched build yet" + ), + "details": { "gemFix": UUID, "platform": platform, "mode": "hosted" }, + }) +} + +/// `events`, by platform as [`hosted_events`] orders a run's. +fn by_platform(mut events: Vec) -> Vec { + events.sort_by_key(|event| { + let platform = event["details"]["platform"].as_str(); + platform.map(str::to_string) + }); + events +} + +/// A gem bundler locks as precompiled platform builds, with a patched build +/// for every platform the lock names, against the REAL bundler end to end: +/// +/// 1. upstream publishes the gem as a ruby gem AND as platform gems (this +/// machine's platform, and a foreign one); the real `bundle install` + +/// `bundle lock --add-platform` lock both platform builds and install +/// this machine's platform gem. `ruby_entry` picks the lock's +/// PLATFORMS: without `ruby` the lock holds the platform builds +/// alone, with it bundler keeps the ruby-platform +/// `name (version)` entry beside them (what bundler 4 locks by default +/// for a gem that also ships a ruby gem), and that entry moves too; +/// 2. the hosted scan asks for the gem patch's reference alone, moves +/// EVERY entry into the `GEM` section of the registry snapshot that +/// reference names, pins `DEPENDENCIES`, and (on a `CHECKSUMS` lock) +/// sets each entry to the sha256 the registry serves for it — the lock +/// the real `bundle lock` writes for that Gemfile, byte for byte. It +/// reports one `applied` event per locked build, each under that +/// build's own patch, and replaces the platform copy bundler had +/// installed with the patched platform gem; +/// 3. a fresh checkout's FROZEN `bundle install` fetches exactly this +/// machine's patched build from the patch registry (never the ruby +/// gem, so nothing is compiled), leaves the lock byte-identical, and +/// Ruby loads the PATCHED file from the platform build; +/// 4. a re-scan is a no-op, and offers no patch as newer although a +/// search returns the platform gems' own patches beside the gem's; +/// 5. `rollback` hands back the pre-scan pair byte for byte and puts the +/// installed copy back on the upstream platform gem; +/// 6. standalone `vex` attests the gem from the lock, hash-verified +/// against the installed platform build. +/// +/// With `takeover`, a vendored run takes the gem over before step 5, each +/// platform's tree from that platform's own patch (asked for in one +/// request), which leaves the patched platform copy the hosted scan +/// installed. Step 5 is then a vendored unwind, and `remove` and +/// `vendor --revert` run over copies of the project as well: each must put +/// the installed platform copy back on the upstream platform gem. +async fn platform_prebuilds_install_frozen_and_roll_back( + tag: &str, + checksums_lock: bool, + ruby_entry: bool, + takeover: bool, +) { + // Bundler locks the specific platform's gem from 2.2; `CHECKSUMS` from + // 2.6. Vendor takes platform gems from a lock bundler 2.3 or newer wrote. + let floor = match (checksums_lock, takeover) { + (true, _) => (2, 6), + (false, true) => (2, 3), + (false, false) => (2, 2), + }; + let Some(mut p) = PlatformProject::start(tag, floor, checksums_lock, ruby_entry, &[]).await + else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let index_url = p.serve(Some(&every)).await; + let registry = index_url[p.api().len()..].to_string(); + let warm_lib = p.installed_lib(&p.fx.proj); + let (orig, patched) = (p.service.orig.clone(), p.service.patched.clone()); + + // 2. The hosted scan. + let vex = ["--vex", "out.vex.json", "--vex-product", PRODUCT]; + let scanned = p.mark().await; + let env = p.scan(&vex); + assert_eq!(env["status"], "success", "envelope: {env}"); + let reported = |newly: bool| { + let mut events = vec![patched_event(&own, newly), patched_event(&foreign, newly)]; + if ruby_entry { + events.push(ruby_event(newly)); + } + by_platform(events) + }; assert_eq!( - warning_codes.contains(&"redirect_gem_no_checksums_section"), - !checksums_lock, - "{env}" - ); - // The platform copy bundler had installed is the prebuild now. - assert!( - warning_codes.contains(&"redirect_gem_install_refreshed"), - "the warm platform install is refreshed: {env}" + hosted_events(&env), + reported(true), + "one `applied` event per locked build, each under its own patch: {env}" ); + assert_eq!( + env["summary"]["applied"], + reported(true).len(), + "every patched build is counted: {env}" + ); + // The platform copy bundler had installed is the patched build now, and + // nothing warns about platforms. + let caveats = |refreshed: bool| { + let mut codes = Vec::new(); + if refreshed { + codes.push("redirect_gem_install_refreshed".to_string()); + } + if !checksums_lock { + codes.push("redirect_gem_no_checksums_section".to_string()); + } + codes + }; + let mut codes = warning_codes(&env); + codes.sort(); + assert_eq!(codes, caveats(true), "{env}"); assert_eq!( std::fs::read_to_string(&warm_lib).unwrap(), patched, "the installed platform copy holds the patched file" ); assert_eq!(env["vex"]["statements"], 1, "vex block: {env}"); - - let gemfile = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); - assert_eq!( - gemfile, - with_source_option( - &String::from_utf8(pristine_gemfile.clone()).unwrap(), - &format!("gem \"{DEP}\""), - &index_url - ), - "the Gemfile edit is the one a ruby gem gets" - ); - let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); - // Every platform entry sits in the patch registry's section, none in - // the upstream one. - let registry_section = lock - .split("\n\n") - .find(|section| section.contains(&format!("remote: {index_url}"))) - .unwrap_or_else(|| panic!("no patch-registry GEM section:\n{lock}")); - for platform in platforms { - assert!( - registry_section.contains(&format!( - " {DEP} ({})\n {TRANSITIVE}", - token(platform) - )), - "the {platform} build moved to the patch registry with its sub-lines:\n{lock}" - ); - if checksums_lock { - assert!( - lock.contains(&format!( - " {DEP} ({}) sha256={}\n", - token(platform), - sha_of(&patched_builds, &token(platform)) - )), - "CHECKSUMS pins the {platform} prebuild's own sha256:\n{lock}" - ); - } - } - assert_eq!( - lock.matches(&format!(" {DEP} (")).count(), - 2 + usize::from(ruby_beside), - "every build, each listed once:\n{lock}" - ); - assert_eq!( - registry_section.matches(&format!(" {DEP} (")).count(), - 2 + usize::from(ruby_beside), - "all of them under the patch registry:\n{lock}" - ); - if ruby_beside && checksums_lock { - assert!( - lock.contains(&format!(" {DEP} ({DEP_VERSION}) sha256={ruby_sha}\n")), - "CHECKSUMS pins the ruby-platform entry to the patched ruby gem:\n{lock}" - ); - } + let asked = p.references_since(scanned).await; assert!( - lock.contains(&format!("\nDEPENDENCIES\n {DEP}!\n")), - "DEPENDENCIES is source-pinned:\n{lock}" + !asked.is_empty() && asked.iter().all(|uuids| uuids == &[UUID]), + "the scan asks for the reference of the gem's own patch alone: {asked:?}" ); + + let lock = p.assert_hosted_pair(&index_url, &[(&own, true), (&foreign, true)]); + let gemfile = p.gemfile(); // The lock is the one the host bundler writes for that Gemfile over the // pre-scan lock, byte for byte. - let relock = tmp.path().join("relock"); - std::fs::create_dir_all(&relock).unwrap(); - std::fs::write(relock.join("Gemfile"), &gemfile).unwrap(); - std::fs::write(relock.join("Gemfile.lock"), &pristine_lock).unwrap(); - copy_dir_recursive(&proj.join(".bundle"), &relock.join(".bundle")); - bundle_ok(&relock, &["lock"]); assert_eq!( lock, - std::fs::read_to_string(relock.join("Gemfile.lock")).unwrap(), + p.bundler_lock("relock", &gemfile, &p.pristine_lock()), "the scan's lock must be what bundler {} writes for the redirected Gemfile", - bundler.version + p.fx.bundler.version ); - assert_no_redirect_ledger(&proj); - - let fx = RedirectFixture { - tmp, - proj: proj.clone(), - index_url: index_url.clone(), - gemfile_name: "Gemfile", - lock_name: "Gemfile.lock", - patched: patched.clone().into_bytes(), - pristine_gemfile, - pristine_lock: pristine_lock.clone().into_bytes(), - bundler, - _server: server, - }; + assert_no_redirect_ledger(&p.fx.proj); - // 3. A fresh checkout's frozen install. - let asked_before = request_count(&fx).await; - let (fresh, install) = fresh_checkout_bundle_install(&fx); - assert!( - install.status.success(), - "fresh-checkout frozen `bundle install` must succeed from the patch registry.\nstdout:\n{}\nstderr:\n{}", - String::from_utf8_lossy(&install.stdout), - String::from_utf8_lossy(&install.stderr), - ); - assert_lock_untouched_by_install(&fx, &fresh); - let installed = fresh_installed_lib(&fresh, &own_leaf, "vuln_gem.rb"); - assert_eq!( - std::fs::read_to_string(&installed).expect("the platform gem is installed"), - patched, - "the fresh install holds the PATCHED file in the platform gem's dir" - ); - assert!( - !fresh_installed_lib(&fresh, &format!("{DEP}-{DEP_VERSION}"), "vuln_gem.rb").exists(), - "the ruby-platform gem is not what bundler installs" - ); - // Exactly this machine's prebuild came from the patch registry. - let gems_prefix = format!("{registry_base}/gems/"); - let fetched: Vec = fx - ._server - .received_requests() - .await - .unwrap_or_default() - .iter() - .skip(asked_before) - .filter_map(|r| r.url.path().strip_prefix(&gems_prefix).map(str::to_string)) - .collect(); + // 3. A fresh checkout's frozen install: exactly this machine's patched + // build, from the patch registry. + let installing = p.mark().await; + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, true); + let (fetched, redirected) = p.fetched_since(installing).await; assert_eq!( fetched, - [format!("{own_leaf}.gem")], + [format!("{registry}gems/{}.gem", p.own_leaf())], "the frozen install fetches the one platform gem of this machine" ); - let probe = bundle( - &fresh, - &[ - "exec", - "ruby", - "-e", - "require \"vuln_gem\"\nputs VulnGem.status\nputs VulnGem::BUILD\nputs TinyDep::VALUE\nputs $LOADED_FEATURES.grep(%r{/vuln_gem\\.rb\\z})", - ], - ); - assert!( - probe.status.success(), - "bundle exec require probe failed.\nstdout:\n{}\nstderr:\n{}", - String::from_utf8_lossy(&probe.stdout), - String::from_utf8_lossy(&probe.stderr), - ); - let out = String::from_utf8_lossy(&probe.stdout).into_owned(); - let lines: Vec<&str> = out.lines().collect(); - let marker = patched_marker(); - assert_eq!( - lines.len(), - 4, - "status, build, dep and the loaded file:\n{out}" - ); - assert_eq!( - lines[..3], - [marker.as_str(), own.as_str(), "tiny-ok"], - "Ruby loads the patched file, from this machine's platform build:\n{out}" - ); - assert!( - lines[3].contains("/vendor/bundle/") - && lines[3].contains(&format!("/gems/{own_leaf}/lib/")), - "vuln_gem.rb loads from the installed platform gem:\n{out}" - ); + assert_eq!(redirected, Vec::::new(), "and nothing of upstream"); // 4. A re-scan changes nothing. - let (code, stdout, stderr) = scan(); + let env = p.scan(&vex); + assert_eq!(p.lock(), lock, "a re-scan leaves the lock byte-identical"); + assert_eq!(p.gemfile(), gemfile); + assert_eq!(hosted_events(&env), reported(false), "{env}"); + let mut codes = warning_codes(&env); + codes.sort(); assert_eq!( - code, 0, - "re-scan failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + codes, + caveats(false), + "a re-scan has nothing to refresh, warn about or skip: {env}" ); assert_eq!( - std::fs::read_to_string(fx.proj.join("Gemfile.lock")).unwrap(), - lock, - "a re-scan leaves the lock byte-identical" - ); - assert_eq!( - std::fs::read_to_string(fx.proj.join("Gemfile")).unwrap(), - gemfile - ); - assert!( - !stdout.contains("redirect_gem_install_refreshed") - && !stdout.contains("redirect_gem_stale_install") - && !stdout.contains("redirect_gem_platform_unsupported"), - "a re-scan has nothing to refresh, warn about or skip:\n{stdout}" + env["updates"], + serde_json::json!([]), + "a platform gem's own patch is no newer patch of the gem: {env}" ); // 5. Rollback: the pre-scan pair, byte for byte, and the installed - // copy back on the upstream platform gem. The restore re-derives a - // `CHECKSUMS` sha256 only for a rubygems.org remote, so that arm - // spells the mock upstream as rubygems.org in the pair and serves - // that registry from the mock (`SOCKET_RUBYGEMS_URL`). No bundler - // runs on that arm's project after this point. - let upstream = format!("{api}/upstream"); - let as_committed = |text: &str| { - if checksums_lock { - text.replace(&format!("\"{upstream}\""), "\"https://rubygems.org\"") - .replace(&format!("{upstream}/"), "https://rubygems.org/") - } else { - text.to_string() - } - }; - for file in ["Gemfile", "Gemfile.lock"] { - let path = fx.proj.join(file); - let text = std::fs::read_to_string(&path).unwrap(); - std::fs::write(&path, as_committed(&text)).unwrap(); - } + // copy back on the upstream platform gem. + p.commit_pair(); if takeover { - mount_vendored_platform_grant(&fx, &hosted_url, &patched_builds, &platforms).await; - let (code, stdout, stderr) = run_socket_env( - &fx.proj, - &[ - "get", - UUID, - "--mode", - "vendored", - "--yes", - "--json", - "--cwd", - proj_str, - "--api-url", - &api, - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - &api, - ], - &[("SOCKET_RUBYGEMS_URL", &upstream)], - ); + let taking = p.mark().await; + let (code, stdout, stderr) = + p.unwind(&p.fx.proj, &["get", UUID, "--mode", "vendored", "--yes"]); assert_eq!(code, 0, "takeover:\nstdout:\n{stdout}\nstderr:\n{stderr}"); - let vendored_lock = std::fs::read_to_string(fx.proj.join("Gemfile.lock")).unwrap(); + let vendored_lock = p.lock(); assert!( vendored_lock.starts_with("PATH\n remote: .socket/vendor/gem/"), "premise: the gem is vendored:\n{vendored_lock}\nstdout:\n{stdout}" @@ -7427,46 +8198,50 @@ async fn platform_prebuilds_install_frozen_and_roll_back( patched, "premise: the takeover leaves the patched platform copy installed" ); + // Each platform's tree comes from that platform's own patch: the + // gem patch's reference, then ONE request for both. + let mut own_patches = [build_uuid(&own), build_uuid(&foreign)]; + own_patches.sort(); + let asked: Vec> = p + .references_since(taking) + .await + .into_iter() + .filter(|uuids| uuids != &[UUID]) + .map(|mut uuids| { + uuids.sort(); + uuids + }) + .collect(); + assert_eq!( + asked, + [own_patches.to_vec()], + "the platform patches are asked for in one request" + ); // `remove` and `vendor --revert`, each over its own copy of the // project; `rollback` runs on the project itself below. for command in ["remove", "vendor --revert"] { - let dir = fx.tmp.path().join(format!("unwind-{}", &command[..6])); - copy_dir_recursive(&fx.proj, &dir); + let dir = p.fx.tmp.path().join(format!("unwind-{}", &command[..6])); + copy_dir_recursive(&p.fx.proj, &dir); // What a `bundle cache` taken under the hosted pin left: this - // machine's patched prebuild in Bundler's cache dir. - let cached = dir.join("vendor/cache").join(format!("{own_leaf}.gem")); - let prebuild = patched_builds.iter().find(|b| b.token == token(&own)); + // machine's patched build in Bundler's cache dir. + let cached = dir + .join("vendor/cache") + .join(format!("{}.gem", p.own_leaf())); std::fs::create_dir_all(cached.parent().unwrap()).unwrap(); - std::fs::write(&cached, &prebuild.expect("own prebuild").gem).unwrap(); - let cwd = dir.to_str().expect("utf8 tmp path"); - let mut argv: Vec<&str> = match command { - "remove" => vec!["remove", PURL, "--yes"], - _ => vec!["vendor", "--revert", "--yes"], + std::fs::write(&cached, &p.service.builds[&build_token(Some(&own))]).unwrap(); + let argv: &[&str] = match command { + "remove" => &["remove", PURL, "--yes"], + _ => &["vendor", "--revert", "--yes"], }; - argv.extend([ - "--json", - "--cwd", - cwd, - "--api-url", - &api, - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - &api, - ]); - let (code, stdout, stderr) = - run_socket_env(&dir, &argv, &[("SOCKET_RUBYGEMS_URL", &upstream)]); + let (code, stdout, stderr) = p.unwind(&dir, argv); assert_eq!(code, 0, "{command}:\nstdout:\n{stdout}\nstderr:\n{stderr}"); assert_eq!( std::fs::read_to_string(dir.join("Gemfile.lock")).unwrap(), - as_committed(&pristine_lock), + p.as_committed(&p.pristine_lock()), "{command} must hand the lock back byte for byte" ); assert_eq!( - std::fs::read_to_string(fresh_installed_lib(&dir, &own_leaf, "vuln_gem.rb")) - .unwrap(), + std::fs::read_to_string(p.installed_lib(&dir)).unwrap(), orig, "{command}: the installed platform copy is the upstream build again:\n{stdout}" ); @@ -7484,46 +8259,17 @@ async fn platform_prebuilds_install_frozen_and_roll_back( .flatten() .filter(|e| e["errorCode"] == "upstream_gem_stale_cache") .map(|e| e.to_string()) - .collect(); - assert_eq!(named.len(), 1, "{command}: one stale-cache warning: {env}"); - assert!( - named[0].contains(&cached.display().to_string()) - && named[0].contains("non-upstream"), - "{command}: the patched platform archive in the cache dir is named: {}", - named[0] - ); - } - } - let (code, stdout, stderr) = run_socket_env( - &fx.proj, - &[ - "rollback", - PURL, - "--json", - "--cwd", - proj_str, - "--api-url", - &api, - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - &api, - ], - &[("SOCKET_RUBYGEMS_URL", &upstream)], - ); - assert_eq!(code, 0, "rollback:\nstdout:\n{stdout}\nstderr:\n{stderr}"); - assert_eq!( - std::fs::read_to_string(fx.proj.join("Gemfile.lock")).unwrap(), - as_committed(&pristine_lock), - "rollback must hand the lock back byte for byte" - ); - assert_eq!( - std::fs::read_to_string(fx.proj.join("Gemfile")).unwrap(), - as_committed(&String::from_utf8_lossy(&fx.pristine_gemfile)), - "rollback must hand the Gemfile back byte for byte" - ); + .collect(); + assert_eq!(named.len(), 1, "{command}: one stale-cache warning: {env}"); + assert!( + named[0].contains(&cached.display().to_string()) + && named[0].contains("non-upstream"), + "{command}: the patched platform archive in the cache dir is named: {}", + named[0] + ); + } + } + let stdout = p.roll_back(); assert_eq!( std::fs::read_to_string(&warm_lib).unwrap(), orig, @@ -7534,19 +8280,13 @@ async fn platform_prebuilds_install_frozen_and_roll_back( && !stdout.contains("upstream_gem_stale_cache"), "nothing is left on the patched build:\n{stdout}" ); - // The arm whose pair still names the mock upstream: bundler loads the + // The case whose pair still names the mock upstream: bundler loads the // upstream code, and a reinstall from the gem home's archive succeeds. if takeover && !checksums_lock { let probe = "require \"vuln_gem\"; print VulnGem.status"; for args in [&["install"][..], &["pristine"]] { - let out = bundle(&fx.proj, args); - assert!( - out.status.success(), - "bundle {args:?} after the unwind:\nstdout:\n{}\nstderr:\n{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - ); - let run = bundle(&fx.proj, &["exec", "ruby", "-e", probe]); + bundle_ok(&p.fx.proj, args); + let run = bundle(&p.fx.proj, &["exec", "ruby", "-e", probe]); assert_eq!( String::from_utf8_lossy(&run.stdout), "VULNERABLE", @@ -7557,96 +8297,7 @@ async fn platform_prebuilds_install_frozen_and_roll_back( } // 6. Standalone VEX over the fresh checkout bundler installed. - manifestless_vex_matrix(&fx, &fresh).await; -} - -/// The grant of [`UUID`] as the patch service answers it once the patch has -/// prebuilds a vendored run can take: the hosted reference -/// [`platform_prebuilds_install_frozen_and_roll_back`] mounts, plus each -/// prebuild's sha512 and its stub gemspec. -async fn mount_vendored_platform_grant( - fx: &RedirectFixture, - hosted_url: &str, - patched_builds: &[IndexBuild], - platforms: &[&str], -) { - let server = &fx._server; - let gem_of = |token: &str| { - let build = patched_builds - .iter() - .find(|b| b.name == DEP && b.token == token); - &build.expect("build").gem - }; - let ruby_gem = gem_of(DEP_VERSION); - let ruby_sha = sha256_hex(ruby_gem); - let stubs = format!("/artifacts/{UUID}"); - let mut served = vec![( - format!("{DEP}-{DEP_VERSION}.gemspec"), - stub_gemspec(ruby_gem), - )]; - let mut artifacts = vec![ - serde_json::json!({ - "kind": "tarball", "url": hosted_url, - "integrity": { "sha512": sri(ruby_gem), "sha256": ruby_sha } - }), - serde_json::json!({ - "kind": "gem-stub-gemspec", - "url": format!("{}{stubs}/{DEP}-{DEP_VERSION}.gemspec", server.uri()), - "integrity": { "sha512": sri(&served[0].1) } - }), - ]; - let mut gem_platforms = Vec::new(); - for platform in platforms { - let leaf = format!("{DEP}-{DEP_VERSION}-{platform}"); - let gem = gem_of(&format!("{DEP_VERSION}-{platform}")); - let stub = stub_gemspec(gem); - let sha = sha256_hex(gem); - artifacts.push(serde_json::json!({ - "kind": "gem-platform", "platform": platform, - "url": format!("{}gems/{leaf}.gem", fx.index_url), - "contentType": "application/octet-stream", "sizeBytes": gem.len(), - "integrity": { "sha512": sri(gem), "sha256": sha } - })); - artifacts.push(serde_json::json!({ - "kind": "gem-platform-stub-gemspec", "platform": platform, - "url": format!("{}{stubs}/{leaf}.gemspec", server.uri()), - "integrity": { "sha512": sri(&stub) } - })); - gem_platforms.push(serde_json::json!({ "platform": platform, "gemChecksumSha256": sha })); - served.push((format!("{leaf}.gemspec"), stub)); - } - Mock::given(method("POST")) - .and(path(format!("/v0/orgs/{ORG}/patches/package"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { - UUID: { - "status": "granted", - "url": hosted_url, - "purl": PURL, - "artifacts": artifacts, - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": fx.index_url, - "identifiers": { - "name": DEP, - "version": DEP_VERSION, - "gemChecksumSha256": ruby_sha, - "gemPlatforms": gem_platforms, - } - } - } - } - }))) - .with_priority(1) - .mount(server) - .await; - for (leaf, bytes) in served { - Mock::given(method("GET")) - .and(path(format!("{stubs}/{leaf}"))) - .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) - .mount(server) - .await; - } + manifestless_vex_matrix(&p.fx, &fresh).await; } #[tokio::test(flavor = "multi_thread")] @@ -7683,7 +8334,7 @@ async fn gem_hosted_platform_prebuilds_without_checksums_install_frozen_and_roll .await; } -/// #2174: a platform gem that went from hosted to vendored, then unwound. +/// A platform gem that went from hosted to vendored, then unwound. #[tokio::test(flavor = "multi_thread")] #[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] @@ -7709,3 +8360,602 @@ async fn gem_vendored_unwind_restores_a_platform_install_without_checksums() { ) .await; } + +/// A lock with ONE patched platform and one the registry still serves as +/// upstream's own gem, on a `CHECKSUMS` lock, against the REAL bundler. +/// `own_patched` says which of the two this machine is, so the two cases +/// are a machine of the patched platform and a machine of the other: +/// +/// 1. the scan moves BOTH builds to the patch registry (one reference +/// request, for the gem's patch, asking for the list), pins the +/// patched build's sha256 and keeps upstream's for the other, and +/// reports the patched build under its own patch and the other as +/// kept, with no warning. The lock is what the real `bundle lock` +/// writes for that Gemfile, and a later `bundle lock` leaves it alone; +/// 2. `bundle install` of a fresh checkout works frozen, in deployment +/// mode and unfrozen, and leaves the lock byte-identical: a machine of +/// the patched platform gets the PATCHED gem from the registry, a +/// machine of the other gets UPSTREAM's gem, which the registry +/// answers with a 302 that bundler follows to the upstream file host; +/// 3. the scan itself downloads the patched build to refresh the copy +/// bundler had installed on the patched platform, and nothing at all +/// on the other, whose installed copy is upstream's gem as its lock +/// entry pins it; +/// 4. a re-scan changes nothing, reports no build as newly patched and +/// offers no newer patch; a person reads one plain line; +/// 5. `rollback` hands back the pre-scan pair byte for byte. +async fn one_platform_patched_and_one_on_upstream(tag: &str, own_patched: bool) { + let Some(mut p) = PlatformProject::start(tag, (2, 6), true, false, &[]).await else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let (patched, upstream) = if own_patched { + (own.as_str(), foreign.as_str()) + } else { + (foreign.as_str(), own.as_str()) + }; + let index_url = p + .serve(Some(&[(patched, Has::Patched), (upstream, Has::Upstream)])) + .await; + let own_file = format!("{}gems/{}.gem", &index_url[p.api().len()..], p.own_leaf()); + let warm_lib = p.installed_lib(&p.fx.proj); + let installed = if own_patched { + p.service.patched.clone() + } else { + p.service.orig.clone() + }; + + // 1. The scan. + let scanned = p.mark().await; + let env = p.scan(&[]); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + hosted_events(&env), + by_platform(vec![patched_event(patched, true), upstream_event(upstream)]), + "{env}" + ); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + ( + &serde_json::json!(1), + &serde_json::json!(0), + &serde_json::json!(0) + ), + "the build on upstream's gem is counted nowhere: {env}" + ); + let refreshed: &[&str] = if own_patched { + &["redirect_gem_install_refreshed"] + } else { + &[] + }; + assert_eq!(warning_codes(&env), refreshed, "{env}"); + assert_eq!( + env["redirect"]["rewrittenFiles"], + serde_json::json!(["Gemfile", "Gemfile.lock"]) + ); + let lock = p.assert_hosted_pair(&index_url, &[(patched, true), (upstream, false)]); + assert_eq!( + lock, + p.bundler_lock("relock", &p.gemfile(), &p.pristine_lock()), + "the scan's lock must be what bundler {} writes for the redirected Gemfile", + p.fx.bundler.version + ); + assert_eq!( + p.references_since(scanned).await, + [[UUID]], + "one reference request, for the gem's own patch" + ); + assert_eq!( + p.views_since(scanned).await, + Vec::::new(), + "no patch record is fetched" + ); + // 3. What the scan itself downloaded. + let (fetched, redirected) = p.fetched_since(scanned).await; + let refresh: &[String] = if own_patched { + std::slice::from_ref(&own_file) + } else { + &[] + }; + assert_eq!( + fetched, refresh, + "the scan downloads the patched build of this machine's platform, when there is one" + ); + assert_eq!(redirected, Vec::::new()); + assert_eq!(std::fs::read_to_string(&warm_lib).unwrap(), installed); + + // A later `bundle lock` has nothing to change. + bundle_ok(&p.fx.proj, &["lock"]); + assert_eq!( + p.lock(), + lock, + "`bundle lock` leaves the lock byte-identical" + ); + + // 2. A machine of this platform installs from a fresh checkout. + let modes: [(&str, &[(&str, &str)]); 3] = [ + ("frozen", &[("BUNDLE_FROZEN", "true")]), + ("deployment", &[("BUNDLE_DEPLOYMENT", "true")]), + ("unfrozen", &[]), + ]; + for (name, envs) in modes { + let installing = p.mark().await; + let fresh = p.install_fresh(name, envs); + p.assert_installed(&fresh, own_patched); + let (fetched, redirected) = p.fetched_since(installing).await; + assert_eq!( + fetched, + std::slice::from_ref(&own_file), + "{name}: bundler asks the patch registry for this machine's platform gem alone" + ); + let handed_on: &[String] = if own_patched { + &[] + } else { + &[format!("{}.gem", p.own_leaf())] + }; + assert_eq!( + redirected, handed_on, + "{name}: the registry hands a platform with no patched build on to the upstream \ + file host, and serves a patched build itself" + ); + } + + // 4. A re-scan. + let rescanned = p.mark().await; + let env = p.scan(&[]); + assert_eq!(p.lock(), lock, "a re-scan leaves the lock byte-identical"); + assert_eq!( + hosted_events(&env), + by_platform(vec![ + patched_event(patched, false), + upstream_event(upstream) + ]), + "in place, not newly patched: {env}" + ); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], serde_json::json!([])); + assert_eq!(env["updates"], serde_json::json!([]), "{env}"); + assert_eq!(p.references_since(rescanned).await, [[UUID]]); + let (code, stdout, stderr) = p.hosted(&p.fx.proj, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already on hosted patches; nothing to rewrite.\n"), + "one package, whatever its builds:\n{stdout}" + ); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {patched}; upstream gem kept for {upstream} (no \ + patched build yet)\n" + )), + "{stdout}" + ); + assert!(!stderr.contains("Warning"), "{stderr}"); + + // 5. Rollback. + let stdout = p.roll_back(); + assert_eq!( + std::fs::read_to_string(&warm_lib).unwrap(), + p.service.orig, + "the installed platform copy is upstream's gem" + ); + assert_eq!( + stdout.contains("upstream_gem_install_refreshed"), + own_patched, + "only a patched copy is put back:\n{stdout}" + ); + assert!( + !stdout.contains("upstream_gem_stale_install") + && !stdout.contains("upstream_gem_stale_cache"), + "nothing is left on the patched build:\n{stdout}" + ); +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_machine_of_the_patched_platform_installs_the_patched_gem() { + one_platform_patched_and_one_on_upstream("platform-one-patched-own", true).await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_machine_of_a_platform_with_no_patched_build_installs_upstreams_gem() { + one_platform_patched_and_one_on_upstream("platform-one-patched-other", false).await; +} + +/// A gem is moved only once a locked build is patched and every locked +/// platform is listed, and until then a run says so quietly. On the lock +/// the real bundler wrote (with `CHECKSUMS`): +/// +/// 1. no locked build has a patched build: exit 0, both files +/// byte-identical, no warning, one skipped event, one plain line; +/// 2. this machine's platform has one, and the other is missing from the +/// list (its patched build is still being made): the same, under its +/// own code and line; +/// 3. the list has it: the run moves the gem, and a fresh checkout +/// installs the patched gem frozen. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_platform_gem_waits_quietly_for_its_patched_builds() { + let Some(mut p) = PlatformProject::start("platform-waits", (2, 6), true, false, &[]).await + else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let mut locked = [own.as_str(), foreign.as_str()]; + locked.sort(); + + // 1. No locked build is patched. + let none = [ + (own.as_str(), Has::Upstream), + (foreign.as_str(), Has::Upstream), + ]; + p.serve(Some(&none)).await; + p.assert_left_alone( + "redirect_gem_no_patched_build", + &format!( + "{DEP} {DEP_VERSION}: no patched build yet for {}, {}; left on its upstream registry", + locked[0], locked[1] + ), + ); + + // 2. A locked platform is missing from the list. + let building = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Building), + ]; + p.serve(Some(&building)).await; + p.assert_left_alone( + "redirect_gem_build_pending", + &format!( + "{DEP} {DEP_VERSION}: the patch registry does not list {foreign} yet (a patched build \ + is still being made); left as it is until it does" + ), + ); + + // 3. The build is there. + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let index_url = p.serve(Some(&every)).await; + let env = p.scan(&[]); + assert_eq!( + hosted_events(&env), + by_platform(vec![ + patched_event(&own, true), + patched_event(&foreign, true) + ]), + "{env}" + ); + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + p.assert_hosted_pair(&index_url, &[(&own, true), (&foreign, true)]); + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, true); +} + +/// A newer registry snapshot upgrades a hosted lock. This machine's +/// platform has no patched build at first, so the lock pins upstream's +/// gem for it and bundler installs that. Once the build is published the +/// reference names a newer snapshot: +/// +/// 1. the next scan rewrites the registry URL in the Gemfile and the +/// lock and the ONE checksum that changed, reports that build as +/// newly patched and the other as in place, and replaces the copy +/// bundler had installed with the patched gem, downloaded from the +/// newer snapshot; +/// 2. `bundle lock` leaves that lock alone, and `bundle install` (frozen, +/// from a fresh checkout, and in the project) installs the newly +/// patched gem; +/// 3. the earlier snapshot answers as it did: a checkout of the earlier +/// pair still installs upstream's gem frozen; +/// 4. `rollback` hands back the pre-scan pair byte for byte. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_newer_registry_snapshot_installs_the_newly_patched_build() { + let Some(mut p) = + PlatformProject::start("platform-newer-snapshot", (2, 6), true, false, &[]).await + else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let warm_lib = p.installed_lib(&p.fx.proj); + let at_first = [ + (own.as_str(), Has::Upstream), + (foreign.as_str(), Has::Patched), + ]; + let first = p.serve(Some(&at_first)).await; + let env = p.scan(&[]); + assert_eq!( + hosted_events(&env), + by_platform(vec![upstream_event(&own), patched_event(&foreign, true)]), + "{env}" + ); + let first_lock = p.assert_hosted_pair(&first, &[(&own, false), (&foreign, true)]); + let first_gemfile = p.gemfile(); + let earlier = p.install_fresh("earlier", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&earlier, false); + // The earlier pair, with nothing installed: for a person's run below. + let committed = stage_fresh_checkout(&p.fx, "committed"); + + // The patched build of this machine's platform is published. + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let second = p.serve(Some(&every)).await; + assert_ne!(first, second, "a newer snapshot is another URL"); + + // 1. The upgrade. + let upgrading = p.mark().await; + let env = p.scan(&[]); + assert_eq!( + hosted_events(&env), + by_platform(vec![ + patched_event(&own, true), + patched_event(&foreign, false) + ]), + "{env}" + ); + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + assert_eq!( + env["redirect"]["rewrittenFiles"], + serde_json::json!(["Gemfile", "Gemfile.lock"]) + ); + let lock = p.assert_hosted_pair(&second, &[(&own, true), (&foreign, true)]); + let pin = |patched: bool| { + let token = build_token(Some(&own)); + let sha = p.service.sha(Some(&own), patched); + format!(" {DEP} ({token}) sha256={sha}\n") + }; + assert_eq!( + lock, + first_lock + .replace(&first, &second) + .replace(&pin(false), &pin(true)), + "the URL and the one checksum that changed" + ); + assert_eq!(p.gemfile(), first_gemfile.replace(&first, &second)); + let (fetched, redirected) = p.fetched_since(upgrading).await; + assert_eq!( + fetched, + [format!( + "{}gems/{}.gem", + &second[p.api().len()..], + p.own_leaf() + )], + "the refresh takes the patched build from the newer snapshot" + ); + assert_eq!(redirected, Vec::::new()); + assert_eq!( + std::fs::read_to_string(&warm_lib).unwrap(), + p.service.patched, + "the copy bundler had installed is the patched build" + ); + // For a person: which build this run found patched. + let (code, stdout, stderr) = p.hosted(&committed, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: now also patched for {own}; already patched for {foreign}\n" + )), + "{stdout}" + ); + assert!(!stderr.contains("Warning"), "{stderr}"); + assert_eq!( + std::fs::read_to_string(committed.join("Gemfile.lock")).unwrap(), + lock + ); + + // 2. Bundler agrees with the lock and installs the patched gem. + bundle_ok(&p.fx.proj, &["lock"]); + assert_eq!( + p.lock(), + lock, + "`bundle lock` leaves the lock byte-identical" + ); + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, true); + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), lock); + p.assert_installed(&p.fx.proj, true); + + // 3. The earlier snapshot answers as it did. + let again = p.fx.tmp.path().join("earlier-again"); + std::fs::create_dir_all(&again).unwrap(); + std::fs::write(again.join("Gemfile"), &first_gemfile).unwrap(); + std::fs::write(again.join("Gemfile.lock"), &first_lock).unwrap(); + copy_dir_recursive(&p.fx.proj.join(".bundle"), &again.join(".bundle")); + let install = bundle_env(&again, &["install"], &[("BUNDLE_FROZEN", "true")]); + assert!( + install.status.success(), + "the earlier pair still installs frozen:\n{}", + String::from_utf8_lossy(&install.stderr) + ); + p.assert_installed(&again, false); + + // 4. Rollback. + let stdout = p.roll_back(); + assert_eq!( + std::fs::read_to_string(&warm_lib).unwrap(), + p.service.orig, + "the installed platform copy is the upstream build again" + ); + assert!( + !stdout.contains("upstream_gem_stale_install") + && !stdout.contains("upstream_gem_stale_cache"), + "nothing is left on the patched build:\n{stdout}" + ); +} + +/// `bundle lock --add-platform` on a hosted lock: the real bundler resolves +/// the new platform's gem from the patch registry, whose snapshot lists +/// every platform gem of the version, and pins the sha256 listed there: the +/// patched build's for a platform that has one, upstream's for one that +/// has none. Nothing else of the lock changes, and the Gemfile not at all. +/// The next scan reports the new builds with the others and writes nothing. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_bundle_lock_add_platform_resolves_from_the_patch_registry() { + // Two platforms the lock does not name at first, neither this + // machine's nor the foreign one. + const WITH_BUILD: &str = "aarch64-linux"; + const WITHOUT_BUILD: &str = "x64-mingw-ucrt"; + let more = [WITH_BUILD, WITHOUT_BUILD]; + let Some(mut p) = PlatformProject::start("platform-add", (2, 6), true, false, &more).await + else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let listing = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Upstream), + (WITH_BUILD, Has::Patched), + (WITHOUT_BUILD, Has::Upstream), + ]; + let index_url = p.serve(Some(&listing)).await; + let env = p.scan(&[]); + assert_eq!( + hosted_events(&env), + by_platform(vec![patched_event(&own, true), upstream_event(&foreign)]), + "the builds the lock names: {env}" + ); + let hosted_lock = p.assert_hosted_pair(&index_url, &[(&own, true), (&foreign, false)]); + let gemfile = p.gemfile(); + + for platform in more { + bundle_ok(&p.fx.proj, &["lock", "--add-platform", platform]); + } + let lock = p.lock(); + assert_eq!(p.gemfile(), gemfile, "bundler leaves the Gemfile alone"); + // The lock gained exactly the new platforms, their entries and their + // checksums, and lost nothing. + let had: Vec<&str> = hosted_lock.lines().collect(); + let mut gained: Vec<&str> = lock.lines().filter(|line| !had.contains(line)).collect(); + gained.sort(); + let pin = |platform: &str, patched: bool| { + let token = build_token(Some(platform)); + let sha = p.service.sha(Some(platform), patched); + format!(" {DEP} ({token}) sha256={sha}") + }; + let mut want = vec![ + format!(" {WITH_BUILD}"), + format!(" {WITHOUT_BUILD}"), + format!(" {DEP} ({})", build_token(Some(WITH_BUILD))), + format!(" {DEP} ({})", build_token(Some(WITHOUT_BUILD))), + pin(WITH_BUILD, true), + pin(WITHOUT_BUILD, false), + ]; + want.sort(); + assert_eq!( + gained, want, + "the new platforms resolve from the patch registry:\n{lock}" + ); + let lines: Vec<&str> = lock.lines().collect(); + let lost: Vec<&&str> = had.iter().filter(|line| !lines.contains(line)).collect(); + assert_eq!(lost, Vec::<&&str>::new(), "nothing else changes:\n{lock}"); + let registry_section = lock + .split("\n\n") + .find(|section| section.contains(&format!("remote: {index_url}\n"))) + .unwrap_or_else(|| panic!("no GEM section of {index_url}:\n{lock}")); + for platform in more { + assert!( + registry_section.contains(&format!( + " {DEP} ({})\n {TRANSITIVE}", + build_token(Some(platform)) + )), + "the {platform} build is under the patch registry:\n{lock}" + ); + } + + // The next scan reports the new builds and writes nothing. + let env = p.scan(&[]); + assert_eq!(p.lock(), lock, "the scan changes nothing:\n{env}"); + assert_eq!(p.gemfile(), gemfile); + assert_eq!(env["redirect"]["rewrittenFiles"], serde_json::json!([])); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + by_platform(vec![ + patched_event(&own, false), + upstream_event(&foreign), + patched_event(WITH_BUILD, false), + upstream_event(WITHOUT_BUILD), + ]), + "{env}" + ); + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, true); +} + +/// The stale-install refresh downloads `gems/` from the patch +/// registry, which may answer a file with a redirect (it does for every +/// platform it has no patched build of). The download follows it: here +/// the registry answers the file of this machine's patched build with a +/// 302 to another host, and the copy bundler had installed is replaced +/// with the gem that host serves, verified against the sha256 the list +/// names. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_refresh_follows_a_redirect_from_the_patch_registry() { + let Some(mut p) = + PlatformProject::start("platform-refresh-302", (2, 6), true, false, &[]).await + else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let index_url = p.serve(Some(&every)).await; + let file = format!("{}.gem", p.own_leaf()); + let elsewhere = format!("/elsewhere/{file}"); + Mock::given(method("GET")) + .and(path(format!("{}gems/{file}", &index_url[p.api().len()..]))) + .respond_with( + ResponseTemplate::new(302) + .insert_header("Location", format!("{}{elsewhere}", p.files.uri()).as_str()) + .insert_header("Cache-Control", "no-store"), + ) + .with_priority(1) + .mount(&p.fx._server) + .await; + Mock::given(method("GET")) + .and(path(elsewhere.clone())) + .respond_with(ResponseTemplate::new(200).set_body_raw( + p.service.builds[&build_token(Some(&own))].clone(), + "application/octet-stream", + )) + .mount(&p.files) + .await; + + let env = p.scan(&[]); + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + assert_eq!( + std::fs::read_to_string(p.installed_lib(&p.fx.proj)).unwrap(), + p.service.patched, + "the installed copy is the patched build" + ); + let served = p.files.received_requests().await.unwrap_or_default(); + let served: Vec<&str> = served.iter().map(|request| request.url.path()).collect(); + assert_eq!(served, [elsewhere], "the download followed the redirect"); +} From 666c647c0896748a28bbbc6259ebfe406bd6ff93 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 21:43:30 -0500 Subject: [PATCH 018/120] Vendor each platform tree from its own patch in the real-Bundler capstone The vendored platform-gem capstone served the patched platform gems as `gem-platform` / `gem-platform-stub-gemspec` artifacts of the gem's patch and expected the wording of that model (backticked platforms, "kept the vendored patch"), so it failed at its second step. Vendored mode takes each platform's gem from that platform's own patch, which the gem patch's reference names in `gemBuilds`. Its stand-in service now answers that way (one request answers for every uuid it names, the list only on request, a platform with no patched build listed as upstream's own gem), and the capstone checks, against the real bundler: - one locked platform with no patched build: exit 0, the one line, a counted skip, the gem patch's reference alone asked for, nothing downloaded or written; - every platform patched: the gem patch's reference and then ONE request for the platform patches, each tree that platform's own gem (the fixture gems carry a file that names their build), the ledger's `gemBuilds`, one event per platform gem, and one package for a person; - `vex` and the manifest-less `vex` attest each platform gem under the patch of its tree, `vendor --check` gives one verdict per platform gem; - a newer patch that lacks a platform leaves the vendored one in force, in the line the engine prints for it; - a ledger entry that names platforms only (`gemPlatforms`) still checks and reverts, and the next run records each tree's patch. The frozen and unfrozen installs from the committed tree, the tampered foreign tree, the in-sync re-run and the byte-for-byte revert stay. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_vendor_gem_build.rs | 683 ++++++++++++++---- 1 file changed, 528 insertions(+), 155 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs index 14ffd294ac..e69a2df39e 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -52,9 +52,11 @@ //! PLATFORM GEMS (`gem_vendor_platform_gems_fresh_checkout_bundle_install_and_revert`, //! bundler >= 2.3): a gem the real bundler locks as precompiled platform //! gems, from a local source that publishes it that way, is vendored as the -//! patch service's prebuilt platform gem of every locked platform; the -//! fresh checkout loads the patched file from the tree of the platform it -//! runs on, with no request to the service. +//! patched platform gem of every locked platform, each from that platform's +//! own patch, which the gem patch's reference names; the fresh checkout +//! loads the patched file from the tree of the platform it runs on, with no +//! request to the service. While a locked platform has no patched build +//! the gem is not vendored, and the run says so in one line. //! //! VERSION MATRIX: every capstone runs on bundler 1.17 → 4.x (verified //! 1.17.3, 2.0.2 … 2.7.2, 4.0.15, 4.0.21 — the pair edit's PATH + @@ -2767,12 +2769,14 @@ const PLAT_PRISTINE: &str = "module Sockplat\n VERSION = \"1.0.0\"\nend\n"; /// sets `platform` is one. /// * `service/`: what the patch service serves for the patch of /// `sockplat` — the patched ruby gem, the patched platform gem of each -/// platform (a "prebuild") and the stub gemspec of each +/// platform and the stub gemspec of each /// (`Gem::Specification#to_ruby`). /// * `platforms`: the platforms, this machine's first. /// /// `pristine.rb` / `patched.rb` (the caller's) are `lib/sockplat.rb` -/// before and after the patch. +/// before and after the patch. Beside it every gem carries +/// `lib//build`, which names the build it is: the one file that +/// tells one platform's gem from another's. const PLATFORM_GEMS_RB: &str = r##" require "rubygems/package" require "zlib" @@ -2786,15 +2790,16 @@ bodies = { "upstream" => File.read("pristine.rb"), "patched" => File.read("patch build = lambda do |dir, name, platform, body, deps| work = File.join(out, dir, "#{name}-#{platform || "ruby"}") - FileUtils.mkdir_p(File.join(work, "lib")) + FileUtils.mkdir_p(File.join(work, "lib", name)) File.write(File.join(work, "lib/#{name}.rb"), body) + File.write(File.join(work, "lib/#{name}/build"), platform || "ruby") spec = Gem::Specification.new do |s| s.name = name s.version = "1.0.0" s.platform = platform if platform s.summary = "fixture" s.authors = ["fixture"] - s.files = ["lib/#{name}.rb"] + s.files = ["lib/#{name}.rb", "lib/#{name}/build"] deps.each { |dep| s.add_runtime_dependency(dep, ">= 1.0") } end [spec, Dir.chdir(work) { File.join(work, Gem::Package.build(spec)) }] @@ -2824,74 +2829,174 @@ end File.write("platforms", platforms.join("\n")) "##; -/// A patch service answering for the patch `uuid` the way the wire -/// contract of gem prebuilds has it: the ruby gem as the `tarball` (with -/// its stub), and a `gem-platform` gem + `gem-platform-stub-gemspec` for -/// each of `prebuilds`, each naming its `platform`. The URLs name the -/// production host, so the run reaches them only through +/// The `sha512-` SRI string of `bytes`. +fn sri(bytes: &[u8]) -> String { + use sha2::{Digest as _, Sha512}; + format!("sha512-{}", b64(&Sha512::digest(bytes))) +} + +fn sha256_hex(bytes: &[u8]) -> String { + use sha2::{Digest as _, Sha256}; + hex::encode(Sha256::digest(bytes)) +} + +/// The uuid of the patch of `platform`'s patched build, for the gem patch +/// `uuid`: each patched platform gem has a patch of its own. +fn build_uuid(uuid: &str, platform: &str) -> String { + let hex = sha256_hex(format!("{uuid}/{platform}").as_bytes()); + format!( + "{}-{}-4{}-8{}-{}", + &hex[..8], + &hex[8..12], + &hex[13..16], + &hex[17..20], + &hex[20..32] + ) +} + +/// The purl of the fixture gem's platform gem of `platform`. +fn platform_purl(platform: &str) -> String { + format!("pkg:gem/{PLAT}@{PLAT_VERSION}?platform={platform}") +} + +/// A patch service answering for the gem patch `uuid` the way the wire +/// contract has it. The gem's fix is that one patch, the ruby gem's +/// (`purl`). Its reference serves the ruby gem (`tarball`) with its stub +/// and, for a request that asks (`"gemBuilds": true`), names its registry +/// under a snapshot URL and lists every gem of the version +/// (`registryOverride.identifiers.gemBuilds`): the ruby gem, each platform +/// of `patched` with the patch of its patched build ([`build_uuid`]), and +/// each of `upstream` with none (the registry hands on upstream's own gem +/// for it). Each of those patches serves that platform's gem (`tarball`) +/// and stub gemspec, and one request answers for every uuid it names. The +/// URLs name the production host, so the run reaches them only through /// `--patch-server-url`. async fn platform_patch_service( - service: &Path, + fixture: &Path, purl: &str, uuid: &str, - prebuilds: &[String], + patched: &[String], + upstream: &[String], ) -> MockServer { - use base64::Engine as _; - use sha2::{Digest as _, Sha512}; let server = MockServer::start().await; let leaf = format!("{PLAT}-{PLAT_VERSION}"); - let mut served: Vec<(&str, Option<&str>, String)> = vec![ - ("tarball", None, format!("{leaf}.gem")), - ("gem-stub-gemspec", None, format!("{leaf}.gemspec")), - ]; - for platform in prebuilds { - served.push(( - "gem-platform", - Some(platform.as_str()), - format!("{leaf}-{platform}.gem"), - )); - served.push(( - "gem-platform-stub-gemspec", - Some(platform.as_str()), - format!("{leaf}-{platform}.gemspec"), - )); + let file_of = |platform: Option<&str>| match platform { + Some(platform) => format!("{leaf}-{platform}"), + None => leaf.clone(), + }; + let read = |dir: &str, file: String| std::fs::read(fixture.join(dir).join(file)).unwrap(); + // The artifacts of the patch `own` of the gem of `platform`, each + // mounted where its URL says. + let mut mounts = Vec::new(); + let mut artifacts = |own: &str, platform: Option<&str>| { + let mut out = Vec::new(); + for (kind, ext) in [("tarball", "gem"), ("gem-stub-gemspec", "gemspec")] { + let bytes = read("service", format!("{}.{ext}", file_of(platform))); + let route = format!( + "/patch/gem/{PLAT}/{PLAT_VERSION}/grant-token/{own}/{}.{ext}", + file_of(platform) + ); + out.push(serde_json::json!({ + "kind": kind, + "url": format!("https://patch.socket.dev{route}"), + "contentType": "application/octet-stream", + "sizeBytes": bytes.len(), + "integrity": { "sha512": sri(&bytes) }, + })); + mounts.push((route, bytes)); + } + serde_json::Value::Array(out) + }; + + let ruby_sha = sha256_hex(&read("service", format!("{leaf}.gem"))); + let mut builds = vec![serde_json::json!({ + "platform": "ruby", "gemChecksumSha256": ruby_sha, "patchUuid": uuid, + })]; + let mut references = serde_json::Map::new(); + for platform in patched { + let own = build_uuid(uuid, platform); + let gem = read("service", format!("{}.gem", file_of(Some(platform)))); + builds.push(serde_json::json!({ + "platform": platform, "gemChecksumSha256": sha256_hex(&gem), "patchUuid": own, + })); + let artifacts = artifacts(&own, Some(platform)); + references.insert( + own, + serde_json::json!({ + "status": "granted", + "purl": platform_purl(platform), + "url": artifacts[0]["url"], + "artifacts": artifacts, + }), + ); + } + for platform in upstream { + let gem = read("repo/gems", format!("{}.gem", file_of(Some(platform)))); + builds.push(serde_json::json!({ + "platform": platform, "gemChecksumSha256": sha256_hex(&gem), "patchUuid": null, + })); } - let mut artifacts = Vec::new(); - for (kind, platform, file) in served { - let bytes = std::fs::read(service.join(&file)).unwrap(); - let route = format!("/patch/gem/{PLAT}/{PLAT_VERSION}/grant-token/{uuid}/{file}"); - let mut artifact = serde_json::json!({ - "kind": kind, - "url": format!("https://patch.socket.dev{route}"), - "contentType": "application/octet-stream", - "sizeBytes": bytes.len(), - "integrity": { "sha512": format!( - "sha512-{}", - base64::engine::general_purpose::STANDARD.encode(Sha512::digest(&bytes)) - ) }, + builds.sort_by_key(|build| build["platform"].as_str().map(str::to_string)); + let key = &sha256_hex( + serde_json::Value::from(builds.clone()) + .to_string() + .as_bytes(), + )[..12]; + let registry = format!("https://patch.socket.dev/patch-registry/gem/grant-token/{uuid}/"); + let artifacts = artifacts(uuid, None); + let reference = |listed: bool| { + let mut identifiers = serde_json::json!({ + "name": PLAT, "version": PLAT_VERSION, "gemChecksumSha256": ruby_sha, }); - if let Some(platform) = platform { - artifact["platform"] = serde_json::json!(platform); + let mut index_url = registry.clone(); + if listed { + identifiers["gemBuilds"] = builds.clone().into(); + index_url = format!("{registry}s/{key}"); } - artifacts.push(artifact); + serde_json::json!({ + "status": "granted", + "purl": purl, + "url": artifacts[0]["url"], + "artifacts": artifacts, + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": index_url, + "identifiers": identifiers, + }, + }) + }; + let (with_list, plain) = (reference(true), reference(false)); + let gem_patch = uuid.to_string(); + Mock::given(method("POST")) + .and(path_regex(r"/(patch|patches)/package$")) + .respond_with(move |request: &wiremock::Request| { + let asked: serde_json::Value = + serde_json::from_slice(&request.body).unwrap_or_default(); + let mut results = serde_json::Map::new(); + for asked_uuid in asked["uuids"].as_array().into_iter().flatten() { + let Some(asked_uuid) = asked_uuid.as_str() else { + continue; + }; + let reference = match asked_uuid == gem_patch { + true if asked["gemBuilds"] == true => Some(&with_list), + true => Some(&plain), + false => references.get(asked_uuid), + }; + if let Some(reference) = reference { + results.insert(asked_uuid.to_string(), reference.clone()); + } + } + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": results })) + }) + .mount(&server) + .await; + for (route, bytes) in mounts { Mock::given(method("GET")) .and(path(route)) .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) .mount(&server) .await; } - Mock::given(method("POST")) - .and(path_regex(r"/(patch|patches)/package$")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { uuid: { - "status": "granted", - "purl": purl, - "url": artifacts[0]["url"], - "artifacts": artifacts, - }} - }))) - .mount(&server) - .await; server } @@ -2921,31 +3026,108 @@ async fn service_requests(server: &MockServer) -> usize { .count() } +/// The uuids each package reference request to `server` named, in arrival +/// order, each list sorted. Every request must have asked for the list of +/// the gem's builds. +async fn reference_requests(server: &MockServer) -> Vec> { + let requests = server.received_requests().await.unwrap_or_default(); + let mut asked = Vec::new(); + for request in requests + .iter() + .filter(|request| request.url.path().ends_with("/package")) + { + let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default(); + assert_eq!( + body["gemBuilds"], true, + "every package reference request asks for the list of the gem's builds: {body}" + ); + let uuids = body["uuids"].as_array().into_iter().flatten(); + let mut uuids: Vec = uuids + .filter_map(|uuid| uuid.as_str().map(str::to_string)) + .collect(); + uuids.sort(); + asked.push(uuids); + } + asked +} + +/// The events of `env` with `action` that are a platform gem's +/// (`details.gemFix`), as `(purl, uuid, gemFix, platform, errorCode)`, in +/// envelope order. +fn platform_gem_events( + env: &serde_json::Value, + action: &str, +) -> Vec<(String, String, String, String, String)> { + let text = |value: &serde_json::Value| value.as_str().unwrap_or_default().to_string(); + let events = env["events"].as_array().into_iter().flatten(); + events + .filter(|event| event["action"] == action && event["details"]["gemFix"].is_string()) + .map(|event| { + ( + text(&event["purl"]), + text(&event["uuid"]), + text(&event["details"]["gemFix"]), + text(&event["details"]["platform"]), + text(&event["errorCode"]), + ) + }) + .collect() +} + +/// One event per platform gem of `platforms` (in lock order), each under +/// that platform's own patch and naming the gem's patch as its fix. +fn per_platform_gem( + platforms: &[String], + code: &str, +) -> Vec<(String, String, String, String, String)> { + platforms + .iter() + .map(|platform| { + ( + platform_purl(platform), + build_uuid(UUID, platform), + UUID.to_string(), + platform.clone(), + code.to_string(), + ) + }) + .collect() +} + /// A gem bundler locks as PRECOMPILED PLATFORM gems (the shape of /// nokogiri: one lock entry per platform, no plain `name (version)`), which /// cannot be vendored as its own tree because bundler never builds a -/// `path:` gem's extensions. Vendor takes the patch service's prebuild of -/// EVERY locked platform instead: +/// `path:` gem's extensions. Vendor takes the patched platform gem of +/// EVERY locked platform instead, each from that platform's own patch: /// /// 1. the REAL bundler resolves the fixture gem from a local source that /// publishes it as platform gems only, and locks this machine's /// platform and two foreign ones; -/// 2. while the service lacks one platform's prebuild the gem is -/// skipped, by that platform's name: the run does not fail, downloads -/// no gem and writes nothing; -/// 3. with every prebuild served, `vendor` unpacks one tree per platform -/// (each with its stub gemspec), moves every platform block into one -/// `PATH` section and wires the Gemfile; -/// 4. `vex` attests the patch `(vendored)`, and `vendor --check` covers -/// every platform's tree (a tampered FOREIGN tree fails it); +/// 2. while one locked platform has no patched build (the service lists +/// upstream's own gem for it) the gem is not vendored: the run exits +/// 0, says so in ONE line that names the platform, asks for the gem +/// patch's reference alone, downloads no gem and writes nothing; +/// 3. with a patched build of every platform, `vendor` asks for the gem +/// patch's reference and then for the platform patches in ONE +/// request, unpacks one tree per platform from that platform's own +/// gem (each with its stub gemspec), moves every platform block into +/// one `PATH` section, wires the Gemfile, records each tree's patch +/// and digests in the ledger, and reports one event per platform gem; +/// 4. `vex` attests each platform gem `(vendored)` under its own patch, +/// and `vendor --check` covers every platform's tree (a tampered +/// FOREIGN tree fails it); /// 5. a fresh checkout — the committable files only, and no request to /// the patch service — installs frozen with a byte-stable lock, loads /// the PATCHED file from the tree of the running platform, and an /// unfrozen install and `bundle lock` regenerate the same lock; /// 6. a second `vendor` run changes nothing and asks the service nothing, -/// and a newer patch whose prebuild for one platform is not built yet -/// keeps the vendored one; -/// 7. `vendor --revert` restores the Gemfile and the lock byte for byte +/// and a newer patch that lacks one platform's patched build leaves +/// the vendored one in force; +/// 7. a ledger entry that names the platforms of its copy and no patch +/// for their trees (`gemPlatforms`, as a development build recorded +/// it) still checks and reverts, and the next `vendor` run records the +/// patch of each tree in its place; +/// 8. `vendor --revert` restores the Gemfile and the lock byte for byte /// (the registry CHECKSUMS tokens included) and removes the trees. /// /// Run for a gem the Gemfile declares, and for one it only reaches through @@ -3075,34 +3257,43 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) PLAT_PRISTINE.as_bytes(), patched.as_bytes(), ); - let vendor = |server: &MockServer| { + let vendor_in = |root: &Path, server: &MockServer, json: bool| { let uri = server.uri(); - run_socket( - &proj, - &[ - "vendor", - "--json", - "--cwd", - proj.to_str().unwrap(), - "--patch-server-url", - &uri, - ], - ) + let mut args = vec!["vendor"]; + if json { + args.push("--json"); + } + args.extend(["--cwd", root.to_str().unwrap(), "--patch-server-url", &uri]); + run_socket(root, &args) }; - - // 2. One locked platform without a prebuild (the service lists one - // only once it is built): the gem is skipped, by name, the run does - // not fail, no gem is downloaded and nothing is written. - let partial = - platform_patch_service(&fixture.join("service"), &purl, UUID, &platforms[..2]).await; + let vendor = |server: &MockServer| vendor_in(&proj, server, true); + // The project as it is before anything is vendored, for a person's run. + let unvendored = base.join("unvendored"); + common::fs_tree::copy_tree(&proj, &unvendored); + + // 2. One locked platform has no patched build yet: the gem is not + // vendored, in one line, the run does not fail, no gem is + // downloaded and nothing is written. + let (with_build, without_build) = platforms.split_at(2); + let partial = platform_patch_service(&fixture, &purl, UUID, with_build, without_build).await; + let mut have = with_build.to_vec(); + have.sort(); + let not_vendored = format!( + "{PLAT}@{PLAT_VERSION} is not vendored: no patched build yet for {} ({} and {} have \ + one). Vendored mode needs every locked platform; `scan --mode hosted` can patch the \ + others now.", + without_build[0], have[0], have[1] + ); let (code, stdout, stderr) = vendor(&partial); assert_eq!( code, 0, - "a prebuild that is not built yet is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" + "a platform with no patched build is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" ); let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "success", "envelope: {env}"); assert_eq!(env["summary"]["applied"], 0, "nothing vendored: {env}"); assert_eq!(env["summary"]["failed"], 0, "and nothing failed: {env}"); + assert_eq!(env["summary"]["skipped"], 1, "one counted skip: {env}"); let skipped = env["events"] .as_array() .unwrap() @@ -3110,26 +3301,42 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) .find(|e| e["errorCode"] == "vendor_prebuilt_platform_pending") .unwrap_or_else(|| panic!("a vendor_prebuilt_platform_pending event: {env}")); assert_eq!(skipped["action"], "skipped", "{skipped}"); - let said = skipped.to_string(); - assert!( - said.contains(&format!("`{PLAT}`")) && said.contains(&format!("`{}`", platforms[2])), - "the skip names the gem and the platform with no prebuild: {skipped}" - ); + assert_eq!(skipped["reason"], not_vendored.as_str(), "{skipped}"); assert_eq!( artifact_downloads(&partial).await, Vec::::new(), "the package reference says what is built: nothing is downloaded" ); + assert_eq!( + reference_requests(&partial).await, + [[UUID]], + "the reference of the gem's own patch, and nothing else" + ); assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_before); assert_eq!(std::fs::read(&lock_path).unwrap(), lock_before); + assert!(!proj.join(".socket/vendor").exists(), "nothing is written"); + // For a person: that one line, and no warning. (The other line of + // stderr is the note that this run names no API token.) + let (code, stdout, stderr) = vendor_in(&unvendored, &partial, false); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let said: Vec<&str> = stderr + .lines() + .filter(|line| !line.contains("SOCKET_API_TOKEN")) + .collect(); + assert_eq!( + said, + [not_vendored.as_str()], + "one line on stderr:\n{stderr}" + ); assert!( - !proj.join(".socket/vendor/gem").exists(), - "no vendored copy is written" + stdout.contains("Vendored 0 packages; 1 skipped."), + "{stdout}" ); + assert!(!unvendored.join(".socket/vendor").exists()); drop(partial); - // 3. Every prebuild served: vendor. - let server = platform_patch_service(&fixture.join("service"), &purl, UUID, &platforms).await; + // 3. A patched build of every platform: vendor. + let server = platform_patch_service(&fixture, &purl, UUID, &platforms, &[]).await; let (code, stdout, stderr) = vendor(&server); assert_eq!( code, 0, @@ -3137,20 +3344,34 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) ); let env = parse_json_envelope(&stdout); assert_eq!(env["status"], "success", "envelope: {env}"); - assert_eq!(env["summary"]["applied"], 1, "one package vendored: {env}"); assert_eq!(env["summary"]["failed"], 0, "no failures: {env}"); - // The prebuilds and their stubs are all that is downloaded: the ruby - // gem the same reference names is not. + assert_eq!( + platform_gem_events(&env, "applied"), + per_platform_gem(&sorted, ""), + "one `applied` event per platform gem, each under its own patch: {env}" + ); + assert_eq!(env["summary"]["applied"], 3, "each is counted: {env}"); + // The gem patch's reference, then ONE request for the platform patches. + let mut own_patches: Vec = platforms.iter().map(|p| build_uuid(UUID, p)).collect(); + own_patches.sort(); + assert_eq!( + reference_requests(&server).await, + [vec![UUID.to_string()], own_patches.clone()], + "one batched reference request for the platform patches" + ); + // The platform gems and their stubs are all that is downloaded: the + // ruby gem the gem patch's reference names is not. let mut downloaded = artifact_downloads(&server).await; downloaded.sort(); - let mut prebuilds: Vec = platforms + let mut platform_files: Vec = platforms .iter() .flat_map(|p| ["gem", "gemspec"].map(|ext| format!("{PLAT}-{PLAT_VERSION}-{p}.{ext}"))) .collect(); - prebuilds.sort(); - assert_eq!(downloaded, prebuilds); + platform_files.sort(); + assert_eq!(downloaded, platform_files); - // One prebuild tree per platform, each with its own stub gemspec. + // One tree per platform, each that platform's own patched gem with its + // own stub gemspec. let copy_rel = format!(".socket/vendor/gem/{UUID}/{PLAT}-{PLAT_VERSION}"); for platform in &platforms { let tree = proj.join(©_rel).join(platform); @@ -3159,6 +3380,11 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) patched, "{platform}: the vendored tree must hold the patched bytes" ); + assert_eq!( + &std::fs::read_to_string(tree.join("lib/sockplat/build")).unwrap(), + platform, + "{platform}: the tree is that platform's own gem" + ); let stub = std::fs::read_to_string(tree.join(format!("{PLAT}.gemspec"))) .unwrap_or_else(|e| panic!("{platform}: stub gemspec not materialized: {e}")); assert!( @@ -3203,20 +3429,53 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) !lock.contains(&format!("\n {PLAT} ({PLAT_VERSION}-{own}) sha256=")), "a path gem's CHECKSUMS entry is bare:\n{lock}" ); - let state = std::fs::read_to_string(proj.join(".socket/vendor/state.json")).unwrap(); - let state: serde_json::Value = serde_json::from_str(&state).unwrap(); - let entry = state["entries"] - .as_object() - .and_then(|entries| entries.values().next()) - .unwrap_or_else(|| panic!("a ledger entry: {state}")); + // The ledger records which patch built which tree, and the digests its + // downloads passed. + let state_path = proj.join(".socket/vendor/state.json"); + let ledger_entry = || { + let state = std::fs::read_to_string(&state_path).unwrap(); + let state: serde_json::Value = serde_json::from_str(&state).unwrap(); + let entries = state["entries"].as_object().cloned(); + entries + .and_then(|entries| entries.values().next().cloned()) + .unwrap_or_else(|| panic!("a ledger entry: {state}")) + }; + let entry = ledger_entry(); + let recorded: Vec = sorted + .iter() + .map(|platform| { + let file = |ext: &str| { + let leaf = format!("{PLAT}-{PLAT_VERSION}-{platform}.{ext}"); + std::fs::read(fixture.join("service").join(leaf)).unwrap() + }; + serde_json::json!({ + "platform": platform, + "uuid": build_uuid(UUID, platform), + "gemIntegrity": sri(&file("gem")), + "gemspecIntegrity": sri(&file("gemspec")), + }) + }) + .collect(); + assert_eq!(entry["uuid"], UUID, "the entry is the gem patch's: {entry}"); assert_eq!( - entry["gemPlatforms"], - serde_json::json!(sorted), - "the ledger records the platform trees: {entry}" + entry["gemBuilds"], + serde_json::Value::from(recorded), + "the ledger records each tree's patch: {entry}" + ); + assert!(entry.get("gemPlatforms").is_none(), "{entry}"); + // For a person: one package, then nothing to do. + let (code, stdout, stderr) = vendor_in(&unvendored, &server, false); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!(stdout.contains("Vendored 1 package."), "{stdout}"); + let (code, stdout, stderr) = vendor_in(&unvendored, &server, false); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "{stdout}" ); - // 4. VEX attests the patch against the committed trees, and `--check` - // covers every one of them. + // 4. VEX attests each platform gem against the committed trees, under + // the patch of its tree, and `--check` covers every one of them. let vex_path = proj.join("out.vex.json"); let (code, stdout, stderr) = run_socket( &proj, @@ -3237,13 +3496,17 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) assert_eq!(stmts.len(), 1, "the vendored patch must be attested: {doc}"); assert_eq!(stmts[0]["vulnerability"]["name"], GHSA); assert_eq!(stmts[0]["status"], "not_affected"); - assert!( - stmts[0]["impact_statement"] - .as_str() - .unwrap() - .contains("(vendored)"), - "vendored attestation must carry the (vendored) marker: {doc}" - ); + let impact = stmts[0]["impact_statement"].as_str().unwrap(); + for platform in &platforms { + let part = format!( + "Patched via Socket patch {} (vendored)", + build_uuid(UUID, platform) + ); + assert!( + impact.split("; ").any(|said| said == part), + "{platform}: attested under the patch of its tree: {doc}" + ); + } let check = |root: &Path| { let uri = server.uri(); run_socket( @@ -3264,6 +3527,11 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) code, 0, "vendor --check failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" ); + assert_eq!( + platform_gem_events(&parse_json_envelope(&stdout), "verified"), + per_platform_gem(&sorted, "vendor_check_ok"), + "one verdict per platform gem:\n{stdout}" + ); let tampered = base.join("tampered"); common::fs_tree::copy_tree(&proj, &tampered); std::fs::write( @@ -3305,7 +3573,9 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) "require \"{declared}\"\n\ abort \"probe constant missing after require\" unless defined?(Sockplat::SOCKET_PATCH_VENDOR_E2E)\n\ puts Sockplat::SOCKET_PATCH_VENDOR_E2E\n\ - puts $LOADED_FEATURES.grep(%r{{/sockplat\\.rb\\z}})" + loaded = $LOADED_FEATURES.grep(%r{{/sockplat\\.rb\\z}})\n\ + puts loaded\n\ + puts \"build=\" + File.read(File.join(File.dirname(loaded.first), \"sockplat/build\"))" ); let probe = bundle(&fresh, &["exec", "ruby", "-e", script.as_str()], false); assert!( @@ -3323,6 +3593,10 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) probe_out.contains(&format!("{copy_rel}/{own}/lib/sockplat.rb")), "the patched file must load from the tree of the running platform:\n{probe_out}" ); + assert!( + probe_out.contains(&format!("build={own}")), + "that tree is this machine's own platform gem:\n{probe_out}" + ); // The lock is the one bundler itself writes for this Gemfile: an // unfrozen install and a re-lock leave it byte-identical. for args in [&["install"][..], &["lock"][..]] { @@ -3347,12 +3621,14 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) "the fresh checkout installs with no request to the patch service" ); - // Manifest-less VEX over the fresh checkout: attested from the lock's - // PATH wiring and the vendor ledger, and, with the ledgers gone too, - // from the lock and the patch API alone (the platform trees are then - // read off the committed directory). On a plain thread: PatchApi runs - // its own runtime, which cannot be started (or dropped) from inside - // this test's async context. + // Manifest-less VEX over the fresh checkout: each platform gem is + // attested under the patch of its tree from the lock's PATH wiring and + // the vendor ledger, which records those patches. With the ledgers + // gone too nothing says which patch built which tree, and the gem is + // attested as itself from the lock and the patch API alone (the + // platform trees are then read off the committed directory). On a + // plain thread: PatchApi runs its own runtime, which cannot be started + // (or dropped) from inside this test's async context. std::thread::scope(|scope| { scope.spawn(|| { use vex_e2e_common::{ @@ -3372,11 +3648,19 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) product: Some(PRODUCT.into()), ..base }; - let base_purl = format!("pkg:gem/{PLAT}@{PLAT_VERSION}"); strip_manifest(&fresh); let out = run_vex(&binary(), &fresh, &run(VexRun::offline())); assert_eq!(out.code, Some(0), "manifest-less vex: {out}"); - assert_attested(out.doc(), &base_purl, UUID, Marker::Vendored, VULNS); + for platform in &platforms { + assert_attested( + out.doc(), + &platform_purl(platform), + &build_uuid(UUID, platform), + Marker::Vendored, + VULNS, + ); + } + let base_purl = format!("pkg:gem/{PLAT}@{PLAT_VERSION}"); strip_ledgers(&fresh); let out = run_vex(&binary(), &fresh, &run(VexRun::online(&api))); assert_eq!(out.code, Some(0), "ledger-less vex: {out}"); @@ -3386,7 +3670,7 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) // 6. A second run changes nothing and asks the service nothing. let gemfile_wired = std::fs::read(&gemfile_path).unwrap(); - let state_wired = std::fs::read(proj.join(".socket/vendor/state.json")).unwrap(); + let state_wired = std::fs::read(&state_path).unwrap(); let (code, stdout, stderr) = vendor(&server); assert_eq!( code, 0, @@ -3394,30 +3678,32 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) ); let env2 = parse_json_envelope(&stdout); assert_eq!(env2["summary"]["failed"], 0, "re-run must not fail: {env2}"); - assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_wired); - assert_eq!(std::fs::read(&lock_path).unwrap(), lock_wired); assert_eq!( - std::fs::read(proj.join(".socket/vendor/state.json")).unwrap(), - state_wired + platform_gem_events(&env2, "skipped"), + per_platform_gem(&sorted, "already_vendored"), + "{env2}" ); + assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_wired); + assert_eq!(std::fs::read(&lock_path).unwrap(), lock_wired); + assert_eq!(std::fs::read(&state_path).unwrap(), state_wired); assert_eq!( service_requests(&server).await, served_before, "an in-sync re-run downloads nothing" ); - // A newer patch of the gem whose prebuild for one platform is not - // built yet: the vendored patch stays in force, and the run says so + // A newer patch of the gem that lacks one platform's patched build: + // the vendored patch stays in force, and the run says so in one line // and does not fail. let manifest_path = proj.join(".socket/manifest.json"); let manifest = std::fs::read_to_string(&manifest_path).unwrap(); std::fs::write(&manifest_path, manifest.replace(UUID, UUID_NEXT)).unwrap(); let update = - platform_patch_service(&fixture.join("service"), &purl, UUID_NEXT, &platforms[..2]).await; + platform_patch_service(&fixture, &purl, UUID_NEXT, with_build, without_build).await; let (code, stdout, stderr) = vendor(&update); assert_eq!( code, 0, - "an update that is not built yet is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" + "an update that lacks a platform is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" ); let env3 = parse_json_envelope(&stdout); assert_eq!(env3["summary"]["failed"], 0, "nothing failed: {env3}"); @@ -3428,30 +3714,117 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) .find(|e| e["errorCode"] == "vendor_prebuilt_platform_pending") .unwrap_or_else(|| panic!("a vendor_prebuilt_platform_pending event: {env3}")); assert_eq!(kept["action"], "skipped", "{kept}"); - let said = kept.to_string(); - assert!( - said.contains(&format!("kept the vendored patch {UUID}")) - && said.contains(&format!("`{}`", platforms[2])) - && said.contains(UUID_NEXT), - "the skip names the kept patch, the new one and the platform: {kept}" + assert_eq!( + kept["reason"], + format!( + "{PLAT}@{PLAT_VERSION} was not brought up to date: no patched build yet for {} ({} \ + and {} have one). Vendored mode needs every locked platform; its vendored copy of \ + an earlier patch stays in force as it is.", + without_build[0], have[0], have[1] + ) + .as_str(), + "{kept}" ); assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_wired); assert_eq!(std::fs::read(&lock_path).unwrap(), lock_wired); - assert_eq!( - std::fs::read(proj.join(".socket/vendor/state.json")).unwrap(), - state_wired - ); + assert_eq!(std::fs::read(&state_path).unwrap(), state_wired); assert!( !proj .join(format!(".socket/vendor/gem/{UUID_NEXT}")) .exists(), - "nothing of the unbuilt patch is written" + "nothing of the newer patch is written" ); assert_eq!(artifact_downloads(&update).await, Vec::::new()); drop(update); std::fs::write(&manifest_path, manifest).unwrap(); - // 7. Revert: both files byte for byte, every tree gone. + // 7. An entry that names the platforms of its copy and no patch for + // their trees, as a development build recorded it: it still checks + // (one verdict, for the gem) and reverts, and the next vendor run + // records the patch of each tree in its place. + let mut state: serde_json::Value = serde_json::from_slice(&state_wired).unwrap(); + for entry in state["entries"].as_object_mut().unwrap().values_mut() { + let entry = entry.as_object_mut().unwrap(); + entry.remove("gemBuilds"); + entry.insert("gemPlatforms".into(), serde_json::json!(sorted)); + } + let earlier_state = serde_json::to_vec_pretty(&state).unwrap(); + std::fs::write(&state_path, &earlier_state).unwrap(); + let (code, stdout, stderr) = check(&proj); + assert_eq!( + code, 0, + "an entry that names platforms only still checks.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let checked = parse_json_envelope(&stdout); + assert_eq!(checked["summary"]["verified"], 1, "{checked}"); + assert_eq!( + platform_gem_events(&checked, "verified"), + Vec::new(), + "one verdict, for the gem: {checked}" + ); + let reverting = base.join("reverting"); + common::fs_tree::copy_tree(&proj, &reverting); + let (code, stdout, stderr) = run_socket( + &reverting, + &[ + "vendor", + "--revert", + "--json", + "--cwd", + reverting.to_str().unwrap(), + ], + ); + assert_eq!( + code, 0, + "an entry that names platforms only still reverts.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_eq!( + std::fs::read(reverting.join("Gemfile")).unwrap(), + gemfile_before + ); + assert_eq!( + std::fs::read(reverting.join("Gemfile.lock")).unwrap(), + lock_before + ); + assert!(!reverting.join(".socket/vendor").exists()); + let converting = service_requests(&server).await; + let (code, stdout, stderr) = vendor(&server); + assert_eq!( + code, 0, + "the run that converts the entry.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let converted = parse_json_envelope(&stdout); + assert_eq!( + platform_gem_events(&converted, "applied"), + per_platform_gem(&sorted, ""), + "{converted}" + ); + let rebuilt = converted["events"] + .as_array() + .unwrap() + .iter() + .find(|event| event["errorCode"] == "vendor_artifact_rebuilt") + .unwrap_or_else(|| panic!("a vendor_artifact_rebuilt event: {converted}")); + assert!( + rebuilt["reason"] + .as_str() + .unwrap_or_default() + .contains("was recorded with no patch named for its platform gems"), + "{rebuilt}" + ); + assert!( + service_requests(&server).await > converting, + "the trees are fetched again, each from its platform's patch" + ); + assert_eq!( + std::fs::read(&state_path).unwrap(), + state_wired, + "the ledger is the one a vendor run writes" + ); + assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_wired); + assert_eq!(std::fs::read(&lock_path).unwrap(), lock_wired); + + // 8. Revert: both files byte for byte, every tree gone. let (code, stdout, stderr) = run_socket( &proj, &[ From 802c5a122c251456d3fe6ae740b527c1f4db03ff Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 21:52:26 -0500 Subject: [PATCH 019/120] Check that an earlier registry snapshot keeps answering in the nokogiri script A hosted lock names the registry snapshot it was moved to, and installs from it until the next scan: the patch service keeps a snapshot answering as it did after a later one exists. The stand-in does that too, but nothing in the script looked. The hosted scenario now reads what the earlier snapshot lists before and after the missing builds are published, and requires the two to be the same and the newer snapshot to be another URL. Co-Authored-By: Claude Fable 5.2 --- tests/nokogiri/nokogiri_e2e.rb | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index 1dfb897cbd..363a1941da 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -58,6 +58,7 @@ require "digest" require "fileutils" require "json" +require "net/http" require "open3" require "optparse" require "rbconfig" @@ -668,9 +669,15 @@ def hosted(service, platforms, waiting, lock) rewritten = hosted_scan(service, platforms, lock, []) installs_frozen(service, "hosted", rewritten, patched.include?(own_platform)) end - # The builds that were missing are there: a newer registry snapshot. + # The builds that were missing are there: a newer registry snapshot, + # beside the earlier one, which lists what it listed. earlier = service.index_url + listed = Net::HTTP.get(URI(earlier + "info/nokogiri")) waiting.each { |platform| service.publish(platform) } + unless waiting.empty? + check(service.index_url != earlier && Net::HTTP.get(URI(earlier + "info/nokogiri")) == listed, + "the registry has a newer snapshot, and the earlier one answers as it did", service.index_url) + end rewritten = hosted_scan(service, platforms, lock, waiting.empty? ? [] : patched) unless waiting.empty? || patched.empty? check(!rewritten.include?(earlier) && rewritten.include?(service.index_url), From fc55e69dd567f21a38a2ece8d9612b3bbae25d42 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 21:52:32 -0500 Subject: [PATCH 020/120] Cover a platform the list leaves out in the vendored platform capstone A locked platform can lack a patched build in two ways: the patch registry lists upstream's own gem for it, or its build is still being made and no list names it yet. Vendored mode treats both the same (the gem is not vendored, one line, exit 0, nothing written), and the capstone only served the first. Its not-vendored step now runs against both. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_vendor_gem_build.rs | 117 +++++++++--------- 1 file changed, 61 insertions(+), 56 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs index e69a2df39e..327eb3a93f 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -2867,7 +2867,8 @@ fn platform_purl(platform: &str) -> String { /// (`registryOverride.identifiers.gemBuilds`): the ruby gem, each platform /// of `patched` with the patch of its patched build ([`build_uuid`]), and /// each of `upstream` with none (the registry hands on upstream's own gem -/// for it). Each of those patches serves that platform's gem (`tarball`) +/// for it); a platform in neither is one whose patched build is still being +/// made. Each of those patches serves that platform's gem (`tarball`) /// and stub gemspec, and one request answers for every uuid it names. The /// URLs name the production host, so the run reaches them only through /// `--patch-server-url`. @@ -3104,9 +3105,10 @@ fn per_platform_gem( /// publishes it as platform gems only, and locks this machine's /// platform and two foreign ones; /// 2. while one locked platform has no patched build (the service lists -/// upstream's own gem for it) the gem is not vendored: the run exits -/// 0, says so in ONE line that names the platform, asks for the gem -/// patch's reference alone, downloads no gem and writes nothing; +/// upstream's own gem for it, or does not list it yet) the gem is not +/// vendored: the run exits 0, says so in ONE line that names the +/// platform, asks for the gem patch's reference alone, downloads no +/// gem and writes nothing; /// 3. with a patched build of every platform, `vendor` asks for the gem /// patch's reference and then for the platform patches in ONE /// request, unpacks one tree per platform from that platform's own @@ -3273,9 +3275,10 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) // 2. One locked platform has no patched build yet: the gem is not // vendored, in one line, the run does not fail, no gem is - // downloaded and nothing is written. + // downloaded and nothing is written. The same whether the service + // lists upstream's own gem for that platform or, while its build is + // being made, does not list it at all. let (with_build, without_build) = platforms.split_at(2); - let partial = platform_patch_service(&fixture, &purl, UUID, with_build, without_build).await; let mut have = with_build.to_vec(); have.sort(); let not_vendored = format!( @@ -3284,56 +3287,58 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) others now.", without_build[0], have[0], have[1] ); - let (code, stdout, stderr) = vendor(&partial); - assert_eq!( - code, 0, - "a platform with no patched build is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" - ); - let env = parse_json_envelope(&stdout); - assert_eq!(env["status"], "success", "envelope: {env}"); - assert_eq!(env["summary"]["applied"], 0, "nothing vendored: {env}"); - assert_eq!(env["summary"]["failed"], 0, "and nothing failed: {env}"); - assert_eq!(env["summary"]["skipped"], 1, "one counted skip: {env}"); - let skipped = env["events"] - .as_array() - .unwrap() - .iter() - .find(|e| e["errorCode"] == "vendor_prebuilt_platform_pending") - .unwrap_or_else(|| panic!("a vendor_prebuilt_platform_pending event: {env}")); - assert_eq!(skipped["action"], "skipped", "{skipped}"); - assert_eq!(skipped["reason"], not_vendored.as_str(), "{skipped}"); - assert_eq!( - artifact_downloads(&partial).await, - Vec::::new(), - "the package reference says what is built: nothing is downloaded" - ); - assert_eq!( - reference_requests(&partial).await, - [[UUID]], - "the reference of the gem's own patch, and nothing else" - ); - assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_before); - assert_eq!(std::fs::read(&lock_path).unwrap(), lock_before); - assert!(!proj.join(".socket/vendor").exists(), "nothing is written"); - // For a person: that one line, and no warning. (The other line of - // stderr is the note that this run names no API token.) - let (code, stdout, stderr) = vendor_in(&unvendored, &partial, false); - assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); - let said: Vec<&str> = stderr - .lines() - .filter(|line| !line.contains("SOCKET_API_TOKEN")) - .collect(); - assert_eq!( - said, - [not_vendored.as_str()], - "one line on stderr:\n{stderr}" - ); - assert!( - stdout.contains("Vendored 0 packages; 1 skipped."), - "{stdout}" - ); - assert!(!unvendored.join(".socket/vendor").exists()); - drop(partial); + for listed in [without_build, &[]] { + let partial = platform_patch_service(&fixture, &purl, UUID, with_build, listed).await; + let (code, stdout, stderr) = vendor(&partial); + assert_eq!( + code, 0, + "a platform with no patched build is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!(env["summary"]["applied"], 0, "nothing vendored: {env}"); + assert_eq!(env["summary"]["failed"], 0, "and nothing failed: {env}"); + assert_eq!(env["summary"]["skipped"], 1, "one counted skip: {env}"); + let skipped = env["events"] + .as_array() + .unwrap() + .iter() + .find(|e| e["errorCode"] == "vendor_prebuilt_platform_pending") + .unwrap_or_else(|| panic!("a vendor_prebuilt_platform_pending event: {env}")); + assert_eq!(skipped["action"], "skipped", "{skipped}"); + assert_eq!(skipped["reason"], not_vendored.as_str(), "{skipped}"); + assert_eq!( + artifact_downloads(&partial).await, + Vec::::new(), + "the package reference says what is built: nothing is downloaded" + ); + assert_eq!( + reference_requests(&partial).await, + [[UUID]], + "the reference of the gem's own patch, and nothing else" + ); + assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_before); + assert_eq!(std::fs::read(&lock_path).unwrap(), lock_before); + assert!(!proj.join(".socket/vendor").exists(), "nothing is written"); + // For a person: that one line, and no warning. (The other line of + // stderr is the note that this run names no API token.) + let (code, stdout, stderr) = vendor_in(&unvendored, &partial, false); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let said: Vec<&str> = stderr + .lines() + .filter(|line| !line.contains("SOCKET_API_TOKEN")) + .collect(); + assert_eq!( + said, + [not_vendored.as_str()], + "one line on stderr:\n{stderr}" + ); + assert!( + stdout.contains("Vendored 0 packages; 1 skipped."), + "{stdout}" + ); + assert!(!unvendored.join(".socket/vendor").exists()); + } // 3. A patched build of every platform: vendor. let server = platform_patch_service(&fixture, &purl, UUID, &platforms, &[]).await; From 48185da64a72fd49388bb6410999d5ae3b18b8cd Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 21:52:39 -0500 Subject: [PATCH 021/120] Hold the converted platform capstones to the warnings they name The five converted capstones run on every bundler from 2.2 on, of which only 4.0.15 is on the machine they were converted on. Holding a run's warnings to an exact list there would turn a caveat another bundler line adds into a failure of a case that is about something else. They assert what they asserted before: the codes that must not appear, the one a lock with no `CHECKSUMS` section brings, and the refresh note. The cases added for `CHECKSUMS` locks keep the exact lists. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_redirect_gem_build.rs | 53 +++++++++++-------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs index 9700454aa5..2c8ae219e7 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -8110,21 +8110,26 @@ async fn platform_prebuilds_install_frozen_and_roll_back( reported(true).len(), "every patched build is counted: {env}" ); - // The platform copy bundler had installed is the patched build now, and - // nothing warns about platforms. - let caveats = |refreshed: bool| { - let mut codes = Vec::new(); - if refreshed { - codes.push("redirect_gem_install_refreshed".to_string()); - } - if !checksums_lock { - codes.push("redirect_gem_no_checksums_section".to_string()); - } - codes - }; - let mut codes = warning_codes(&env); - codes.sort(); - assert_eq!(codes, caveats(true), "{env}"); + // Nothing warns about platforms, and the platform copy bundler had + // installed is the patched build now. + let codes = warning_codes(&env); + let said = |code: &str| codes.iter().any(|said| said == code); + for code in [ + "redirect_gem_platform_unsupported", + "redirect_gem_stale_install", + "redirect_gem_frozen_install", + ] { + assert!(!said(code), "no {code}: {env}"); + } + assert_eq!( + said("redirect_gem_no_checksums_section"), + !checksums_lock, + "{env}" + ); + assert!( + said("redirect_gem_install_refreshed"), + "the warm platform install is refreshed: {env}" + ); assert_eq!( std::fs::read_to_string(&warm_lib).unwrap(), patched, @@ -8167,13 +8172,17 @@ async fn platform_prebuilds_install_frozen_and_roll_back( assert_eq!(p.lock(), lock, "a re-scan leaves the lock byte-identical"); assert_eq!(p.gemfile(), gemfile); assert_eq!(hosted_events(&env), reported(false), "{env}"); - let mut codes = warning_codes(&env); - codes.sort(); - assert_eq!( - codes, - caveats(false), - "a re-scan has nothing to refresh, warn about or skip: {env}" - ); + let codes = warning_codes(&env); + for code in [ + "redirect_gem_install_refreshed", + "redirect_gem_stale_install", + "redirect_gem_platform_unsupported", + ] { + assert!( + !codes.iter().any(|said| said == code), + "a re-scan has nothing to refresh, warn about or skip: {env}" + ); + } assert_eq!( env["updates"], serde_json::json!([]), From 46e30cd48789b208f1532de6b03a92b1e3c3f031 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 22:29:19 -0500 Subject: [PATCH 022/120] Wrap a gem's line without stranding a clause, in vendored mode too Seen on a terminal with real nokogiri at 80 and 100 columns. A clause wider than the terminal wraps at a word, and the clause after it was then put on a row of its own although the row had room: the "left on its upstream registry" line ended in a row holding one platform name and another holding the last three words. A clause now goes on from where the wrapped one left the row. The one line vendored mode prints for a gem with a platform that has no patched build was not wrapped at all (211 columns for three platforms), where the hosted line of the same gem breaks after a clause. It is wrapped the same way when a person is at the terminal, and stays one line in a pipe. Co-Authored-By: Claude Fable 5.2 --- .../socket-patch-cli/src/commands/vendor.rs | 5 +- crates/socket-patch-cli/src/ui/text.rs | 97 ++++++++++++++++--- 2 files changed, 88 insertions(+), 14 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index c54795c172..0806a1293a 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -731,7 +731,10 @@ pub(crate) fn format_advisory(code: &str, detail: &str, verbose: bool) -> Option /// names the gem itself and is the whole line. fn format_skip(purl: &str, code: &str, detail: &str) -> String { if code == vendor::VENDOR_PREBUILT_PLATFORM_PENDING { - detail.to_string() + // The one line of the gem, on stderr: wrapped for a person at a + // terminal, as the hosted line of such a gem is. + let width = crate::ui::attended(crate::ui::Stream::Stderr).then(crate::ui::stderr_width); + crate::ui::wrap_line(detail, width) } else { format!("Skipping {}: {detail}", normalize_purl(purl)) } diff --git a/crates/socket-patch-cli/src/ui/text.rs b/crates/socket-patch-cli/src/ui/text.rs index 38824c5e03..96be986c97 100644 --- a/crates/socket-patch-cli/src/ui/text.rs +++ b/crates/socket-patch-cli/src/ui/text.rs @@ -65,30 +65,58 @@ pub(crate) fn wrap_words( /// `line` as it prints for a person. With `width` (its stream is a /// terminal with a person at it) a line that does not fit breaks after a -/// clause (`; `) -/// under a two-space hanging indent, so no clause is cut in two unless it -/// is itself wider than the terminal, where it wraps at a word. Without -/// it the line is as it is, so a pipe or a log keeps one line. +/// clause (`; `) under a two-space hanging indent, so no clause is cut in +/// two unless it is itself wider than the terminal: such a clause wraps at +/// a word from where the row stands, and the clause after it goes on from +/// there. Without `width` the line is as it is, so a pipe or a log keeps +/// one line. pub(crate) fn wrap_line(line: &str, width: Option) -> String { const INDENT: &str = " "; let Some(width) = width else { return line.to_string(); }; - let mut rows: Vec = Vec::new(); + let len = |text: &str| text.chars().count(); + // What a row holds beside its indent: every row but the first has one. + let later = width.saturating_sub(INDENT.len()); + let room = |rows: &[String]| if rows.len() > 1 { later } else { width }; + // Put `text` on the row being filled, or on a new one when it is full. + fn place(rows: &mut Vec, text: &str, room: usize) { + let row = rows.last_mut().expect("one row at least"); + if row.is_empty() { + row.push_str(text); + } else if row.chars().count() + 1 + text.chars().count() <= room { + row.push(' '); + row.push_str(text); + } else { + rows.push(text.to_string()); + } + } + let mut rows: Vec = vec![String::new()]; for clause in line.split_inclusive("; ") { let clause = clause.trim_end(); - let room = if rows.len() > 1 { INDENT.len() } else { 0 }; - match rows.last_mut() { - Some(row) if room + row.chars().count() + 1 + clause.chars().count() <= width => { - row.push(' '); - row.push_str(clause); - } - _ => rows.push(clause.to_string()), + let row = rows.last().expect("one row at least"); + let here = if row.is_empty() { + len(clause) <= room(&rows) + } else { + len(row) + 1 + len(clause) <= room(&rows) + }; + if here || len(clause) <= later { + let room = room(&rows); + place(&mut rows, clause, room); + continue; + } + // Wider than a row: at a word, a code span kept whole. + for word in wrap_tokens(clause) { + let room = room(&rows); + place(&mut rows, &word, room); } } rows.iter() .enumerate() - .flat_map(|(at, row)| wrap_words(row, width, if at == 0 { "" } else { INDENT }, INDENT)) + .map(|(at, row)| match at { + 0 => row.clone(), + _ => format!("{INDENT}{row}"), + }) .collect::>() .join("\n") } @@ -431,6 +459,49 @@ pub(crate) fn shell_word(word: &str) -> String { mod tests { use super::*; + /// A line breaks after a clause, a clause is cut only when it is + /// wider than the terminal, and the clause after one that wrapped goes + /// on from where it left the row. A pipe keeps one line. + #[test] + fn wrap_line_breaks_after_clauses_and_goes_on_after_one_that_wrapped() { + let kept = + "nokogiri 1.19.3: patched for aarch64-linux-gnu, x86_64-linux-gnu; upstream gem \ + kept for arm64-darwin (no patched build yet)"; + assert_eq!(wrap_line(kept, None), kept); + assert_eq!(wrap_line(kept, Some(200)), kept); + assert_eq!( + wrap_line(kept, Some(80)), + "nokogiri 1.19.3: patched for aarch64-linux-gnu, x86_64-linux-gnu;\n upstream gem kept \ + for arm64-darwin (no patched build yet)" + ); + let waiting = "nokogiri 1.19.3: no patched build yet for aarch64-linux-gnu, arm64-darwin, \ + x86_64-linux-gnu; left on its upstream registry"; + assert_eq!( + wrap_line(waiting, Some(80)), + "nokogiri 1.19.3: no patched build yet for aarch64-linux-gnu, arm64-darwin,\n \ + x86_64-linux-gnu; left on its upstream registry" + ); + let vendored = "nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin \ + (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs \ + every locked platform; `scan --mode hosted` can patch the others now."; + assert_eq!( + wrap_line(vendored, Some(80)), + "nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin\n \ + (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs every\n \ + locked platform; `scan --mode hosted` can patch the others now." + ); + for width in [80, 100, 120] { + for line in [kept, waiting, vendored] { + let wrapped = wrap_line(line, Some(width)); + assert!( + wrapped.lines().all(|row| row.chars().count() <= width), + "{width}: {wrapped}" + ); + assert_eq!(wrapped.replace("\n ", " "), line, "nothing is lost"); + } + } + } + #[test] fn wrap_words_respects_width_prefix_and_long_words() { assert_eq!( From 287eccca7cffdaf5de01817941ed99f8b2409d7a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 22:48:38 -0500 Subject: [PATCH 023/120] Attest each locked build in the VEX step of the platform capstones The real-Bundler capstones of a gem locked as platform builds ended in the VEX matrix written for a gem locked as its ruby gem: one statement under the gem's own patch. `vex` attests such a lock per build, each patched build under that build's patch, so all five capstones failed on a correct document. Their VEX step is a matrix of its own. Over the fresh checkout the real bundler installed, `vex` and `apply --vex` must name each locked build under its own patch, and the ruby-platform entry under the gem's, from exactly the requests the lock's shape calls for: the gem patch's record and one package reference, plus the index of the lock's registry where the lock has no CHECKSUMS to say what it installs. `--offline` attests nothing (`record_unavailable`, no document) and asks nothing, and the pair reverted to its registry version names the patch nowhere. The scan's own `--vex` document is held to the same statements. The file's own `warning_codes` goes, for the one in `common::envelope`: the lint of the `cli` suite allows no private envelope reader. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_redirect_gem_build.rs | 308 ++++++++++++++++-- 1 file changed, 276 insertions(+), 32 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs index 2c8ae219e7..19048ddba2 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -83,15 +83,15 @@ //! real binary: byte-idempotent under the same grant, in-place URL refresh //! (the Gemfile option + the converged lock's remote) under a rotated one. //! -//! MANIFEST-LESS VEX (every installing arm, `manifestless_vex_matrix`): on -//! the fresh checkout the real bundler installed — hosted never writes a -//! `.socket/manifest.json` nor a ledger — `vex` attests `(redirected)` from -//! the lockfile wiring + the patch API (and so does the embedded -//! `apply --vex`); `--offline` is `record_unavailable` with zero requests; -//! the pair reverted to its registry version names the patch nowhere, even -//! under `--no-verify`. The main arm also proves the lock-only revert -//! (the Gemfile's option kept) re-converges on the next unfrozen install, -//! and on the next hosted scan. +//! MANIFEST-LESS VEX (every arm that installs a gem locked as its ruby +//! gem, `manifestless_vex_matrix`): on the fresh checkout the real bundler +//! installed — hosted never writes a `.socket/manifest.json` nor a ledger +//! — `vex` attests `(redirected)` from the lockfile wiring + the patch API +//! (and so does the embedded `apply --vex`); `--offline` is +//! `record_unavailable` with zero requests; the pair reverted to its +//! registry version names the patch nowhere, even under `--no-verify`. The +//! main arm also proves the lock-only revert (the Gemfile's option kept) +//! re-converges on the next unfrozen install, and on the next hosted scan. //! //! PLATFORM GEMS (the cases at the end of the file, on a lock the real //! bundler wrote for a gem published as precompiled platform gems): the @@ -106,7 +106,9 @@ //! patched (this machine in either role), none patched or one still being //! made (nothing moves, quietly), a newer snapshot, `bundle lock //! --add-platform` over a hosted lock, and a refresh whose download the -//! registry redirects. +//! registry redirects. Where every locked build is patched, VEX over the +//! fresh checkout the real bundler installed names each build under its own +//! patch (`platform_vex_matrix`). //! //! VERSION MATRIX: the arms run on bundler 1.17 → 4.x (the CHECKSUMS arm //! from 2.6, the CHECKSUMS-era floor; every other arm from 1.17). Pick the @@ -126,6 +128,7 @@ #[path = "common/mod.rs"] mod common; +use common::envelope::{event_triples, warning_codes}; use common::{binary, hermetic, hermetic_command}; use std::io::Write as _; @@ -2079,8 +2082,7 @@ async fn view_requests(fx: &RedirectFixture) -> usize { /// offline. async fn manifestless_vex_matrix(fx: &RedirectFixture, fresh: &Path) { use vex_e2e_common::{ - assert_absent, assert_attested, assert_not_attested, run_vex, strip_manifest, Marker, - VexVia, + assert_attested, assert_not_attested, run_vex, strip_manifest, Marker, VexVia, }; let bin = binary(); let lock = std::fs::read_to_string(fresh.join(fx.lock_name)).unwrap(); @@ -2127,15 +2129,24 @@ async fn manifestless_vex_matrix(fx: &RedirectFixture, fresh: &Path) { assert_not_attested(&out.envelope, PURL, "record_unavailable"); assert_eq!(request_count(fx).await, before, "--offline made requests"); - // 3. reverted to the registry pair (the patched install kept): no lock - // names the patch, and hosted mode keeps no ledger to remember it. + // 3. reverted to the registry pair (the patched install kept). + assert_reverted_pair_names_no_patch(fx, fresh); +} + +/// `fresh` with its manifest pair put back on the registry version, the +/// installed tree kept: no lock names the patch and hosted mode keeps no +/// ledger to remember it, so `vex` has nothing to attest +/// (`manifest_not_found`), with and without `--no-verify`, online and +/// offline. +fn assert_reverted_pair_names_no_patch(fx: &RedirectFixture, fresh: &Path) { + use vex_e2e_common::{assert_absent, run_vex}; std::fs::write(fresh.join(fx.gemfile_name), &fx.pristine_gemfile).unwrap(); std::fs::write(fresh.join(fx.lock_name), &fx.pristine_lock).unwrap(); for (offline, no_verify) in [(false, false), (false, true), (true, false), (true, true)] { let mut run = vex_run(fx); run.offline = offline; run.no_verify = no_verify; - let out = run_vex(&bin, fresh, &run); + let out = run_vex(&binary(), fresh, &run); let cell = format!("reverted offline={offline} no_verify={no_verify}"); assert_eq!(out.code, Some(2), "{cell}: {out}"); assert_eq!( @@ -7304,6 +7315,8 @@ struct PlatformProject { foreign: String, /// The lock has a `CHECKSUMS` section. checksums: bool, + /// The lock names the ruby-platform gem beside the platform builds. + ruby_entry: bool, } impl PlatformProject { @@ -7474,6 +7487,7 @@ impl PlatformProject { own, foreign, checksums, + ruby_entry, }; assert_eq!( std::fs::read_to_string(project.installed_lib(&project.fx.proj)) @@ -7972,14 +7986,6 @@ fn hosted_events(env: &serde_json::Value) -> Vec { events } -/// The warning codes of a run, in envelope order. -fn warning_codes(env: &serde_json::Value) -> Vec { - let warnings = env["warnings"].as_array().into_iter().flatten(); - warnings - .map(|w| w["code"].as_str().unwrap_or_default().to_string()) - .collect() -} - /// The event of a patched build: `applied`, under the build's own patch, /// with `newlyPatched` when the run put the build in place. fn patched_event(platform: &str, newly: bool) -> serde_json::Value { @@ -8025,6 +8031,237 @@ fn by_platform(mut events: Vec) -> Vec { events } +/// What one statement of a VEX document says of the fixture gem: its +/// status, the packages of the project it is about, the products it names +/// beside the project, and its impact statement (`not_affected`) or action +/// statement (`affected`). +#[derive(Debug, PartialEq)] +struct Said { + status: &'static str, + packages: Vec, + products: Vec, + words: String, +} + +/// Every statement of `doc`, each about the one vulnerability of the gem +/// patch's record ([`VULNS`]) in the project [`PRODUCT`]. +fn said(doc: &serde_json::Value) -> Vec { + let ids = |list: &serde_json::Value| -> Vec { + let items = list.as_array().into_iter().flatten(); + items + .filter_map(|item| item["@id"].as_str().map(str::to_string)) + .collect() + }; + let (vulnerability, aliases) = VULNS[0]; + let statements = doc["statements"].as_array().expect("statements"); + statements + .iter() + .map(|st| { + assert_eq!(st["vulnerability"]["name"], vulnerability, "{st}"); + assert_eq!( + st["vulnerability"]["aliases"], + serde_json::json!(aliases), + "{st}" + ); + assert_eq!(st["products"][0]["@id"], PRODUCT, "{st}"); + let (status, words) = match st["status"].as_str() { + Some("not_affected") => { + assert_eq!( + st["justification"], "inline_mitigations_already_exist", + "{st}" + ); + ("not_affected", &st["impact_statement"]) + } + Some("affected") => ("affected", &st["action_statement"]), + other => panic!("unexpected status {other:?}: {st}"), + }; + Said { + status, + packages: ids(&st["products"][0]["subcomponents"]), + products: ids(&st["products"])[1..].to_vec(), + words: words.as_str().unwrap_or_default().to_string(), + } + }) + .collect() +} + +/// What a document says of the gem where the lock names the platform +/// builds `locked`, each as the registry has it and at least one patched, +/// and with `ruby_entry` the ruby-platform gem beside them. ONE +/// `not_affected` statement names every patched build, each under its own +/// patch, and the ruby-platform gem under the gem's. Its products are the +/// forms a scanner reports a platform gem under, and the gem without a +/// platform only when no locked build is on upstream's gem: a scanner that +/// drops the platform matches every build by that form. Each build on +/// upstream's gem has an `affected` statement of its own. +fn build_statements(locked: &[(&str, Has)], ruby_entry: bool) -> Vec { + let having = |has: Has| -> Vec<&str> { + let builds = locked.iter().filter(|(_, how)| *how == has); + let mut platforms: Vec<&str> = builds.map(|(platform, _)| *platform).collect(); + platforms.sort(); + platforms + }; + let (patched, upstream) = (having(Has::Patched), having(Has::Upstream)); + // The form Grype and Syft report a platform gem under. + let grype_form = |platform: &&str| format!("{PURL}-{platform}"); + let purl = |platform: &&str| platform_purl(platform); + let gem = |named: bool| named.then(|| PURL.to_string()); + let mut patches: Vec = patched + .iter() + .map(|platform| build_uuid(platform)) + .collect(); + patches.extend(ruby_entry.then(|| UUID.to_string())); + patches.sort(); + let parts: Vec = patches + .iter() + .map(|patch| format!("Patched via Socket patch {patch} (redirected)")) + .collect(); + let mut statements = vec![Said { + status: "not_affected", + packages: gem(ruby_entry) + .into_iter() + .chain(patched.iter().map(purl)) + .collect(), + products: gem(upstream.is_empty()) + .into_iter() + .chain(patched.iter().map(grype_form)) + .chain(patched.iter().map(purl)) + .collect(), + words: parts.join("; "), + }]; + statements.extend(upstream.iter().map(|platform| Said { + status: "affected", + packages: vec![purl(platform)], + products: vec![grype_form(platform), purl(platform)], + words: format!( + "The patch registry has no patched build of this gem for {platform} yet and serves \ + upstream's own gem for it, so an install on that platform is without Socket patch \ + {UUID}. Run `socket-patch scan --mode hosted` again later: the lockfile takes the \ + patched build once it is published." + ), + })); + statements +} + +/// Manifest-less VEX over a fresh checkout the REAL bundler installed +/// (`fresh`) of a gem locked as the platform builds `locked`, each as the +/// registry has it ([`manifestless_vex_matrix`] is this for a gem locked as +/// its ruby gem alone, which is one pin under the gem's patch): +/// +/// 1. no `.socket/manifest.json` and no ledger: `vex` names each locked +/// build ([`build_statements`]) and exits 0, a build on upstream's gem +/// included. It asks for the gem patch's record and ONE package +/// reference, the gem patch's, whose list says which sha256 is a +/// patched build's; where the lock has no `CHECKSUMS` to say which +/// sha256 it installs, also for the index of the lock's registry. It +/// asks nothing else, and nothing of the upstream file host. The +/// embedded `apply --vex` writes the same statements from the same +/// requests; +/// 2. `--offline`: no local record, so nothing is attested +/// (`record_unavailable`, no document), with ZERO requests; +/// 3. the pair reverted to its registry version names the patch nowhere +/// ([`assert_reverted_pair_names_no_patch`]). +async fn platform_vex_matrix(p: &PlatformProject, fresh: &Path, locked: &[(&str, Has)]) { + use vex_e2e_common::{assert_omitted, run_vex, strip_manifest, VexVia}; + let bin = binary(); + let lock = std::fs::read_to_string(fresh.join("Gemfile.lock")).unwrap(); + assert!( + lock.contains(&format!("remote: {}", p.fx.index_url)), + "the installed checkout's lock must name the patch registry (bundler {}):\n{lock}", + p.fx.bundler.version + ); + assert_no_redirect_ledger(fresh); + strip_manifest(fresh); + let statements = build_statements(locked, p.ruby_entry); + let attested = &statements[0].packages; + let affected: Vec<&String> = statements[1..] + .iter() + .flat_map(|said| &said.packages) + .collect(); + let mut asked = vec![ + format!("/v0/orgs/{ORG}/patches/view/{UUID}"), + format!("/v0/orgs/{ORG}/patches/package"), + ]; + if !p.checksums { + asked.push(format!("{}info/{DEP}", &p.fx.index_url[p.api().len()..])); + } + + // 1. manifest-less, ledger-less: the lock, the patch API, and the + // lock's registry where the lock has no `CHECKSUMS`. + for via in [VexVia::Vex, VexVia::Apply] { + let mark = p.mark().await; + let out = run_vex(&bin, fresh, &vex_run(&p.fx).via(via)); + assert_eq!( + out.code, + Some(0), + "{via:?}: {out}\n--- Gemfile.lock\n{lock}" + ); + assert_eq!(said(out.doc()), statements, "{via:?}: {out}"); + let env = &out.envelope; + if via == VexVia::Vex { + assert_eq!(env["status"], "success", "{out}"); + let verified = attested.iter().map(|purl| (purl.as_str(), "verified", "")); + let kept = affected + .iter() + .map(|purl| (purl.as_str(), "skipped", "gem_upstream_build_kept")); + let events: Vec<(String, String, String)> = verified + .chain(kept) + .map(|(purl, action, code)| (purl.into(), action.into(), code.into())) + .collect(); + assert_eq!(event_triples(env), events, "{out}"); + assert_eq!( + (&env["summary"]["verified"], &env["summary"]["skipped"]), + (&serde_json::json!(attested.len()), &serde_json::json!(0)), + "a build on upstream's gem is counted nowhere: {out}" + ); + assert_eq!(warning_codes(env), Vec::::new(), "{out}"); + } else { + assert_eq!(env["status"], "noManifest", "{out}"); + assert_eq!(env["vex"]["statements"], statements.len(), "{out}"); + assert_eq!( + env["vex"]["affected"].as_u64().unwrap_or(0), + affected.len() as u64, + "{out}" + ); + } + assert_eq!( + request_paths(&p.fx._server, mark.0).await, + asked, + "{via:?}: the record, one reference and, without CHECKSUMS, the registry's index" + ); + assert_eq!( + p.references_since(mark).await, + [[UUID]], + "{via:?}: the reference of the gem's own patch, with the list of its builds" + ); + assert_eq!( + request_paths(&p.files, mark.1).await, + Vec::::new(), + "{via:?}: nothing of the upstream file host" + ); + } + assert!( + !fresh.join(".socket/manifest.json").exists(), + "vex / apply --vex must never write the manifest" + ); + + // 2. offline: no local record to build a statement from, no network. + let mark = p.mark().await; + let mut offline = vex_run(&p.fx); + offline.offline = true; + let out = run_vex(&bin, fresh, &offline); + assert_omitted(&out, PURL, "record_unavailable", "offline vex"); + assert_eq!( + event_triples(&out.envelope).len(), + 1, + "the gem's one pin is left out, and no build is reported beside it: {out}" + ); + assert_eq!(p.mark().await, mark, "--offline made requests"); + + // 3. reverted to the registry pair (the install kept). + assert_reverted_pair_names_no_patch(&p.fx, fresh); +} + /// A gem bundler locks as precompiled platform builds, with a patched build /// for every platform the lock names, against the REAL bundler end to end: /// @@ -8042,8 +8279,9 @@ fn by_platform(mut events: Vec) -> Vec { /// sets each entry to the sha256 the registry serves for it — the lock /// the real `bundle lock` writes for that Gemfile, byte for byte. It /// reports one `applied` event per locked build, each under that -/// build's own patch, and replaces the platform copy bundler had -/// installed with the patched platform gem; +/// build's own patch, as its own `--vex` document does, and replaces +/// the platform copy bundler had installed with the patched platform +/// gem; /// 3. a fresh checkout's FROZEN `bundle install` fetches exactly this /// machine's patched build from the patch registry (never the ruby /// gem, so nothing is compiled), leaves the lock byte-identical, and @@ -8052,8 +8290,8 @@ fn by_platform(mut events: Vec) -> Vec { /// search returns the platform gems' own patches beside the gem's; /// 5. `rollback` hands back the pre-scan pair byte for byte and puts the /// installed copy back on the upstream platform gem; -/// 6. standalone `vex` attests the gem from the lock, hash-verified -/// against the installed platform build. +/// 6. standalone `vex` over that fresh checkout attests each locked +/// build under its own patch ([`platform_vex_matrix`]). /// /// With `takeover`, a vendored run takes the gem over before step 5, each /// platform's tree from that platform's own patch (asked for in one @@ -8113,21 +8351,21 @@ async fn platform_prebuilds_install_frozen_and_roll_back( // Nothing warns about platforms, and the platform copy bundler had // installed is the patched build now. let codes = warning_codes(&env); - let said = |code: &str| codes.iter().any(|said| said == code); + let warned = |code: &str| codes.iter().any(|warned| warned == code); for code in [ "redirect_gem_platform_unsupported", "redirect_gem_stale_install", "redirect_gem_frozen_install", ] { - assert!(!said(code), "no {code}: {env}"); + assert!(!warned(code), "no {code}: {env}"); } assert_eq!( - said("redirect_gem_no_checksums_section"), + warned("redirect_gem_no_checksums_section"), !checksums_lock, "{env}" ); assert!( - said("redirect_gem_install_refreshed"), + warned("redirect_gem_install_refreshed"), "the warm platform install is refreshed: {env}" ); assert_eq!( @@ -8136,6 +8374,12 @@ async fn platform_prebuilds_install_frozen_and_roll_back( "the installed platform copy holds the patched file" ); assert_eq!(env["vex"]["statements"], 1, "vex block: {env}"); + let in_run = vex_e2e_common::read_doc(&p.fx.proj.join("out.vex.json")); + assert_eq!( + said(&in_run.expect("the run's document")), + build_statements(&every, ruby_entry), + "the run's own document names each locked build under its own patch" + ); let asked = p.references_since(scanned).await; assert!( !asked.is_empty() && asked.iter().all(|uuids| uuids == &[UUID]), @@ -8306,7 +8550,7 @@ async fn platform_prebuilds_install_frozen_and_roll_back( } // 6. Standalone VEX over the fresh checkout bundler installed. - manifestless_vex_matrix(&p.fx, &fresh).await; + platform_vex_matrix(&p, &fresh, &every).await; } #[tokio::test(flavor = "multi_thread")] From 4f0bde3dc07cfffaf24ea4875ff612416dd71c12 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 22:48:50 -0500 Subject: [PATCH 024/120] Check the VEX of a lock with one build patched and one on upstream's gem No real-Bundler case read the document of a lock the hosted scan moved with one patched build and one the registry passes through to upstream. That is the lock a wrong document over-claims on: the gem is one pin under one patch, and the build that installs upstream's gem must never be attested by it. The case takes the lock the real bundler wrote through the scan, a checkout with nothing installed and a frozen install, with this machine's platform as the patched build and as the one on upstream's gem. Each time the patched build is `not_affected` under its own patch and the other `affected`, with exit 0: the copy on the machine changes what is said of neither. A third run has a lock without CHECKSUMS, where the index of the lock's registry is what says which build is which. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_redirect_gem_build.rs | 105 +++++++++++++++++- 1 file changed, 102 insertions(+), 3 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs index 19048ddba2..3ad52067b1 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -106,9 +106,10 @@ //! patched (this machine in either role), none patched or one still being //! made (nothing moves, quietly), a newer snapshot, `bundle lock //! --add-platform` over a hosted lock, and a refresh whose download the -//! registry redirects. Where every locked build is patched, VEX over the -//! fresh checkout the real bundler installed names each build under its own -//! patch (`platform_vex_matrix`). +//! registry redirects. VEX names each locked build (`platform_vex_matrix`, +//! over the fresh checkout the real bundler installed): a patched build +//! under its own patch, a build on upstream's gem as affected, whichever of +//! the two this machine holds. //! //! VERSION MATRIX: the arms run on bundler 1.17 → 4.x (the CHECKSUMS arm //! from 2.6, the CHECKSUMS-era floor; every other arm from 1.17). Pick the @@ -8818,6 +8819,104 @@ async fn gem_hosted_machine_of_a_platform_with_no_patched_build_installs_upstrea one_platform_patched_and_one_on_upstream("platform-one-patched-other", false).await; } +/// VEX of a lock with ONE patched platform and one the registry still +/// serves as upstream's own gem, which the hosted scan moved and the REAL +/// bundler installed frozen. `own_patched` says which of the two this +/// machine is; `checksums_lock`, whether the lock says which sha256 it +/// installs or the registry's index has to. The patched build is attested +/// under its own patch and the other is said affected, never patched, with +/// exit 0: +/// +/// 1. by the scan's own `--vex`, over the copy bundler had installed; +/// 2. by a later `vex` over a checkout nothing is installed in; +/// 3. by a later `vex` over the checkout the frozen install put this +/// machine's gem in, the patched build or upstream's own: the copy on +/// this machine changes nothing of what is said of either build +/// ([`platform_vex_matrix`]). +async fn one_patched_build_is_attested_and_the_other_said_affected( + tag: &str, + own_patched: bool, + checksums_lock: bool, +) { + let floor = if checksums_lock { (2, 6) } else { (2, 2) }; + let Some(mut p) = PlatformProject::start(tag, floor, checksums_lock, false, &[]).await else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let (patched, upstream) = if own_patched { + (own.as_str(), foreign.as_str()) + } else { + (foreign.as_str(), own.as_str()) + }; + let locked = [(patched, Has::Patched), (upstream, Has::Upstream)]; + let index_url = p.serve(Some(&locked)).await; + let statements = build_statements(&locked, false); + + // 1. The scan, and its own document. + let env = p.scan(&["--vex", "out.vex.json", "--vex-product", PRODUCT]); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + hosted_events(&env), + by_platform(vec![patched_event(patched, true), upstream_event(upstream)]), + "{env}" + ); + p.assert_hosted_pair(&index_url, &[(patched, true), (upstream, false)]); + let in_run = vex_e2e_common::read_doc(&p.fx.proj.join("out.vex.json")); + assert_eq!(said(&in_run.expect("the run's document")), statements); + assert_eq!( + (&env["vex"]["statements"], &env["vex"]["affected"]), + (&serde_json::json!(2), &serde_json::json!(1)), + "{env}" + ); + + // 2. A checkout of the pair, nothing installed. + let checkout = stage_fresh_checkout(&p.fx, "checkout"); + let out = vex_e2e_common::run_vex(&binary(), &checkout, &vex_run(&p.fx)); + assert_eq!(out.code, Some(0), "nothing installed: {out}"); + assert_eq!(said(out.doc()), statements, "nothing installed: {out}"); + + // 3. The checkout a frozen install put this machine's gem in. + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, own_patched); + platform_vex_matrix(&p, &fresh, &locked).await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_vex_on_a_machine_of_the_patched_platform_says_the_other_build_is_affected() { + one_patched_build_is_attested_and_the_other_said_affected( + "platform-vex-one-patched-own", + true, + true, + ) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_vex_on_a_machine_of_a_platform_with_no_patched_build_attests_the_patched_one() { + one_patched_build_is_attested_and_the_other_said_affected( + "platform-vex-one-patched-other", + false, + true, + ) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.2); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_vex_tells_the_builds_of_a_lock_without_checksums_apart_by_its_registry() { + one_patched_build_is_attested_and_the_other_said_affected( + "platform-vex-one-patched-other-no-checksums", + false, + false, + ) + .await; +} + /// A gem is moved only once a locked build is patched and every locked /// platform is listed, and until then a run says so quietly. On the lock /// the real bundler wrote (with `CHECKSUMS`): From 4c2503bdf1ee3266b15f9f6b72e69d5c7ca0a924 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 22:30:10 -0500 Subject: [PATCH 025/120] docs: a gem locked as platform builds moves once one build is patched Describe hosted and vendored mode for a gem a Bundler lock names as precompiled platform builds as they are: the list of a version's gems on the gem patch's reference, the registry URL with its snapshot key, the one line and the per-build events, the two quiet cases, per-build VEX, all-or-nothing vendoring from each platform's own patch, and the codes that go with them. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 24 ++++---- docs/ecosystems.md | 75 +++++++++++++++++++------ 2 files changed, 71 insertions(+), 28 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 10b3aecec0..eee411f659 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -466,7 +466,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm **Non-UTF-8 candidate files (#721)**: the rewriters edit UTF-8 text only. A candidate file that exists but is not UTF-8 (for example a UTF-16 `requirements.txt`, which is what Windows PowerShell 5.1's `pip freeze >` writes and which pip installs from) is never read as absent. When a candidate of its ecosystem could rewrite it, the run is refused with `candidate_file_unreadable` (exit 1, `--dry-run` included), the message names the file, and nothing is written; the remedy is to re-save the file as UTF-8. Two exceptions keep their own refusals. A Gradle build file the Gradle planner reaches gets that planner's per-build refusal (`redirect_gradle_build_file_unreadable`, exit 0) and the rest of the run goes ahead, and with no readable Gradle build a stray Gradle file (a lock, a nested script) is never rewritten, so it does not refuse the run, while a non-UTF-8 root `settings.gradle(.kts)` or `build.gradle(.kts)` still refuses it (it may be the build itself). An unreadable `socket-patch.sbt` is refused with `redirect_sbt_owned_file_unreadable`. A vendored→hosted takeover checks this before it reverts anything, so a refused run leaves the vendored wiring, ledger entry and artifact byte-identical. Vendored mode likewise refuses a non-UTF-8 `requirements.txt` or `-r` include by name (`pypi_no_requirements`) instead of wiring around it. Lock-only discovery reads `requirements.txt` and its in-root `-r` includes the way pip decodes them (a UTF-16 or UTF-32 byte-order mark selects that encoding), so such a project's pins are still found instead of reporting "No packages found". -**Gem hosted wiring**: for a gem the manifest (`Gemfile` / `gems.rb`) declares, hosted mode appends ONE option to the user's own declaration, `, source: ""`, after its last argument, and changes nothing else of it: version requirement(s), quote style, other options, trailing comment, position, enclosing `group` / `platforms` / `install_if` block and indentation stay byte for byte. This covers a parenthesized call (the option goes inside the parentheses), a declaration continued over several lines (after the last argument, on its line), several version requirements, `%w` / symbol option values, a trailing `if` / `unless` / `while` / `until` / `rescue` modifier (the option goes before the modifier) and a declaration followed by another statement after a `;`. For a gem the manifest does not declare (a transitive dependency: the lock's `DEPENDENCIES` does not list it) hosted mode adds exactly one line at the end of the manifest, `gem "", "", source: "", require: false # added by socket-patch (transitive dependency)`, after one blank line, in the file's own line ending and keeping whether the file ends on one. `require: false` keeps `Bundler.require` from loading a gem it did not load before the line existed; the marker comment is what tells the unwind the whole line is socket-patch's. **The lock always follows** (the pair is what the Bundler that wrote the lock writes for that manifest, so frozen / deployment installs accept it as committed): on a lock written by Bundler ≥ 2.2 the gem's spec moves to a `GEM` section of its own whose `remote:` is the index URL (sections ordered as Bundler orders them); on a lock written by Bundler 1.17–2.1 the index URL joins the `remote:` lines of the one merged `GEM` section, in the order Bundler derives from the manifest's sources; the `DEPENDENCIES` entry keeps the requirement the manifest declares and gains `!` (a transitive gem gets ` (= )!`); and where the lock has a `CHECKSUMS` section the gem's entry is set to the patched artifact's sha256. A lock with no `CHECKSUMS` section (Bundler < 2.6) is converged the same way and pins the gem by source alone; the run reports that ONCE, naming the gems, as `redirect_gem_no_checksums_section`. **Precompiled platform gems**: a gem Bundler locks as platform builds has one lock entry per platform (`nokogiri (1.18.10-arm64-darwin)`, `nokogiri (1.18.10-x86_64-linux-gnu)`) and usually no ruby-platform `nokogiri (1.18.10)`. The patch registry serves a patched platform gem (a "prebuild": the upstream platform gem's name, gemspec and file list, with the patch's files replaced) for each platform the patch's grant lists (`registryOverride.identifiers.gemPlatforms`, `{platform, gemChecksumSha256}` each; absent or empty when it has none). When EVERY platform entry of the gem at the patched version has a prebuild there, the gem is wired like any other: the manifest edit is the same, every entry of that version (each spec line with its dependency sub-lines, verbatim and in the lock's order, plus a ruby-platform entry when one sits beside them) moves to the patch registry's `GEM` section, `DEPENDENCIES` is pinned the same way, and each `CHECKSUMS` entry of the gem is set to the sha256 of its own build (a platform entry to its prebuild's, the ruby-platform entry to `gemChecksumSha256`); a lock with no `CHECKSUMS` section gets none. A frozen `bundle install` of that pair fetches the one platform gem of the machine from the patch registry, compiles nothing and leaves the lock byte-identical (verified on Bundler 4.0.15). When a locked platform has no prebuild the gem is skipped with `redirect_gem_platform_unsupported`, which names the builds the lock holds, the ones the patch has no patched build for, and what the registry serves; so is a platform build in the merged layout of Bundler < 2.2. A lock does not record which Bundler installs it, only which one wrote it (`BUNDLED WITH`), so the pair is converged for that one; when it is the merged layout of Bundler < 2.2, which later Bundlers deprecate and from 2.5 on refuse under frozen / deployment mode, the run that writes the lock adds `redirect_gem_merged_lock_layout` naming the Bundler the pair is for. **Never a half-applied pair**: each gem is planned on a copy of the pair and committed only when the planned manifest and lock agree about it (the manifest gives it the index URL as its one source; the lock resolves it from a `GEM` section naming that remote, with a source-pinned `DEPENDENCIES` entry). A gem whose declaration cannot take the option, or whose lock cannot follow, is refused with neither file changed for it, and the warning's detail gives the reason and the way out: `redirect_gem_unrecognized_declaration` (the declaration cannot be edited in place — a heredoc or `do` block among its arguments, code before it on its line, a string spanning lines, a last argument that is not a literal and may be an options hash: it is taken for a version requirement only when the lock shows one requirement per positional argument, every other positional is a single quoted string, and the manifest has no `gemspec` directive, whose own requirement for the gem bundler folds into the lock entry, …), `redirect_gem_source_option` (it already selects a source: a `source:` / `git:` / `github:` / `path:` option or one a `**opts` splat may hold, a declaration inside a `source` / `git` / `github` / `path` block, a `DEPENDENCIES` entry that is already source-pinned, or a lock that resolves the gem from a `GIT` / `PATH` section), `redirect_gem_declared_more_than_once`, `redirect_gem_declaration_not_visible` (a direct dependency declared in an `eval_gemfile`d file, a loop or a gemspec; vendored mode refuses it for the same reason, so the way out is a literal `gem` line or `--mode agent`), `redirect_gem_dependency_not_locked` (declared, but the lock's `DEPENDENCIES` does not list it), `redirect_gem_lock_unconvergeable` (no `BUNDLED WITH` section to say which layout the lock's Bundler accepts, a merged Bundler < 2.2 section whose remotes the manifest's sources do not explain, or the one multi-remote `GEM` section Bundler 2.2 to 2.7 write for a manifest with more than one top-level `source` line, where the detail names that cause and the remedy: move each extra source into a `source "" do … end` block, then `bundle lock`), `redirect_gem_platform_unsupported` (a locked platform build the patch has no prebuild for, above) and `redirect_gem_inconsistent_plan` (the self-check above failed; a bug guard, never expected). A re-scan recognizes its own option (the grant-token and patch-uuid path levels of the URL rotate, so they are matched as wildcards) and refreshes the URL in place, in the manifest and the lock together; a re-scan of an unchanged project writes nothing. A lock reverted or regenerated without its manifest (the option still there, the lock back on the registry) is converged again by the next hosted scan. **Pins written by socket-patch 5.0 / 5.1** used a `source "" do … end` block in the declaration's place and, on a lock with no `CHECKSUMS` section, left the lock alone. That form is never written any more but stays recognized everywhere (re-scan, `list`, `vex`, `rollback` / `remove`, the takeovers): a re-scan keeps the block as it is, refreshes its URL like the option's, and converges a lock that never followed it; only where that lock cannot be converged does the run still warn `redirect_gem_frozen_install`. Human mode prints one line after the summary naming the declarations changed, e.g. ``Added `source:` to 3 gem declarations in Gemfile (puma, rack, and rexml); added 1 line for the transitive dependency nokogiri.`` **Update hold**: a gem wired this way has the patch registry as its only source, and that source serves the one patched version, so `bundle outdated` no longer lists the gem and `bundle update` cannot move it (a range requirement included) until its pin is rolled back. When a run newly wires at least one gem (an option appended or a line added, not a refreshed URL), human mode prints one more stdout line under that one, naming those gems once each: ``Bundler now takes rack from its Socket patch source only, which serves the patched version and no other: `bundle outdated` no longer lists it and `bundle update` cannot move it. To move it to a newer release, run `socket-patch rollback pkg:gem/rack@3.1.8`, then `bundle update rack`, then `socket-patch scan` again.`` The rollback step always names a purl (the gem's own for one gem, as `rollback` selects its pin: without the patch record's qualifiers such as `?platform=ruby`, so a shell passes it on whole; the shape `pkg:gem/@` for several), never a bare `rollback`, which would unwind every patch; after `get` the last step reads "then patch the new version the same way"; `--dry-run` words the first sentence as what the run would hold and prints no steps. `--json` and `--silent` output are unchanged (no warning code). Pinned against real Bundler by `tests/e2e_redirect_gem_build.rs`. See `docs/ecosystems.md` ("Ruby gems: hosted mode") for the user-facing description. +**Gem hosted wiring**: for a gem the manifest (`Gemfile` / `gems.rb`) declares, hosted mode appends ONE option to the user's own declaration, `, source: ""`, after its last argument, and changes nothing else of it: version requirement(s), quote style, other options, trailing comment, position, enclosing `group` / `platforms` / `install_if` block and indentation stay byte for byte. This covers a parenthesized call (the option goes inside the parentheses), a declaration continued over several lines (after the last argument, on its line), several version requirements, `%w` / symbol option values, a trailing `if` / `unless` / `while` / `until` / `rescue` modifier (the option goes before the modifier) and a declaration followed by another statement after a `;`. For a gem the manifest does not declare (a transitive dependency: the lock's `DEPENDENCIES` does not list it) hosted mode adds exactly one line at the end of the manifest, `gem "", "", source: "", require: false # added by socket-patch (transitive dependency)`, after one blank line, in the file's own line ending and keeping whether the file ends on one. `require: false` keeps `Bundler.require` from loading a gem it did not load before the line existed; the marker comment is what tells the unwind the whole line is socket-patch's. **The lock always follows** (the pair is what the Bundler that wrote the lock writes for that manifest, so frozen / deployment installs accept it as committed): on a lock written by Bundler ≥ 2.2 the gem's spec moves to a `GEM` section of its own whose `remote:` is the index URL (sections ordered as Bundler orders them); on a lock written by Bundler 1.17–2.1 the index URL joins the `remote:` lines of the one merged `GEM` section, in the order Bundler derives from the manifest's sources; the `DEPENDENCIES` entry keeps the requirement the manifest declares and gains `!` (a transitive gem gets ` (= )!`); and where the lock has a `CHECKSUMS` section the gem's entry is set to the patched artifact's sha256. A lock with no `CHECKSUMS` section (Bundler < 2.6) is converged the same way and pins the gem by source alone; the run reports that ONCE, naming the gems, as `redirect_gem_no_checksums_section`. **Precompiled platform gems**: a gem Bundler locks as platform builds has one lock entry per platform (`nokogiri (1.18.10-arm64-darwin)`, `nokogiri (1.18.10-x86_64-linux-gnu)`) and usually no ruby-platform `nokogiri (1.18.10)`. Its fix is still the one patch of the gem. That patch's package reference lists every gem of the version under `registryOverride.identifiers.gemBuilds`, `{platform, gemChecksumSha256, patchUuid}` each: the ruby gem (`platform: "ruby"`, the patch itself), each patched platform gem with the uuid of its own patch (the upstream platform gem's name, gemspec and file list, with the patch's files replaced), and each platform with no patched build with `patchUuid: null`, for which the patch registry lists upstream's own gem and answers its file with a redirect to the upstream registry. The list is asked for: every package reference request carries `"gemBuilds": true`, and the patch service answers a request without it with the ruby gem's registry alone. With a list, the index URL names the registry as it stood, `/s/` (an opaque key that changes when what the registry lists changes); it is recognised with any key or none, under any grant token, and written closed by a slash, as Bundler writes a remote. **The gem moves as soon as ONE build the lock names is patched** (a platform with a `patchUuid`, or the ruby-platform entry): the manifest edit is the same as for any gem, every entry of that version (each spec line with its dependency sub-lines, verbatim and in the lock's order, plus a ruby-platform entry when one sits beside them) moves to the patch registry's `GEM` section, `DEPENDENCIES` is pinned the same way, and each `CHECKSUMS` entry of the gem is set to the sha256 the list gives for its build (for a platform with no patched build that is the upstream gem's, which the entry already had); a lock with no `CHECKSUMS` section gets none. A frozen `bundle install` of that pair fetches the one gem of the machine through the patch registry, compiles nothing and leaves the lock byte-identical (verified on Bundler 4.0.15, frozen, deployment and unfrozen, and a `bundle lock` afterwards changes nothing): a machine of a patched platform installs the patched gem, any other installs what it installed before. No warning is given. Human output has one line per such gem, `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)` (a ruby-platform entry is named `ruby`; a dry run says `would be patched for`; on a terminal a line that does not fit breaks after a clause), and `--json` has one counted `applied` event (`verified` on a dry run) per patched build: `purl` `pkg:gem/@?platform=` (the gem's own purl for the ruby-platform entry), `uuid` that build's patch, `details.gemFix` the gem's patch, `details.platform`, and `details.newlyPatched: true` when this run put the build in place. A build on upstream's gem is an event that is NOT counted in `summary`: `action: "skipped"`, no `uuid`, `errorCode: "gem_upstream_build_kept"`, `details.gemFix`, `details.platform`. Every count of packages (the human totals, the rollout budget, the severity floor) takes the gem as one package with one patch. **VEX** is per build. The run's own `--vex` attests each patched build under its own patch (`not_affected`, subcomponent `pkg:gem/@?platform=`, impact `Patched via Socket patch (redirected)`; the ruby-platform entry under the gem's patch) and writes an `affected` statement for a build on upstream's gem, whose action statement says that the platform has no patched build yet; it needs no request beyond the run's own. A later `socket-patch vex` on such a lock makes at most two small requests per gem: the gem patch's package reference (for `gemBuilds`), and, only for a lock with no `CHECKSUMS` entry for a build, `info/` of the lock's own registry URL. A build is attested by its patch only when the sha256 the lock installs for it (its `CHECKSUMS` entry, else what the lock's registry lists) is that patch's; it is `affected` when that sha256 is the one listed for upstream's gem; and when neither can be told (the reference lists another archive than the lock pins, the request failed, or `--offline`) the build is left out of the document with `vex_gem_build_unknown`, never attested. A gem locked as its ruby-platform gem alone costs no extra request. `vex` prints the gem's line under its summary (`…: patched for x86_64-linux-gnu; not attested for arm64-darwin`), and its `--json` events of builds carry `details.gemFix` and `details.platform`. **Later runs**: the same reference changes nothing. A reference with another key (a patched build was published for another platform, or one was withdrawn) refreshes the URL in both files and rewrites the checksums that changed, and the line names what is new: `nokogiri 1.18.10: now also patched for arm64-darwin; already patched for x86_64-linux-gnu`. A platform added with `bundle lock --add-platform` is resolved by Bundler from the registry and reported by the next run. A lock already on the registry follows the reference even when no locked build is patched any more: a withdrawn build's entry goes back to the upstream gem's sha256. (A copy a machine already installed from the withdrawn build is not replaced by that run: the stale-install guard below does not judge a build the registry serves as upstream's gem.) **Two cases leave the gem as it is, quietly** (one counted `skipped` event with the code, one plain line on stdout, no warning, exit 0), and both pass by themselves: no build the lock names is patched yet (`redirect_gem_no_patched_build`: `nokogiri 1.18.10: no patched build yet for arm64-darwin, x86_64-linux-gnu; left on its upstream registry`), and the list leaves out a platform the lock names, which the patch service does while that platform's patched build is being made (`redirect_gem_build_pending`: `nokogiri 1.18.10: the patch registry does not list arm64-darwin yet (a patched build is still being made); left as it is until it does`). The gem is skipped with the warning `redirect_gem_platform_unsupported` only when the reference carries no list (the patch covers the ruby gem alone: the patch service does not know the version's platform gems, or the gem has none), or for a platform build in the merged layout of Bundler < 2.2. The patch service also has a patch record per patched platform gem (`pkg:gem/@?platform=`), which agent mode applies to an installed copy of that platform; a hosted or a vendored `scan` or `get ` never selects one as a fix of its own. A lock does not record which Bundler installs it, only which one wrote it (`BUNDLED WITH`), so the pair is converged for that one; when it is the merged layout of Bundler < 2.2, which later Bundlers deprecate and from 2.5 on refuse under frozen / deployment mode, the run that writes the lock adds `redirect_gem_merged_lock_layout` naming the Bundler the pair is for. **Never a half-applied pair**: each gem is planned on a copy of the pair and committed only when the planned manifest and lock agree about it (the manifest gives it the index URL as its one source; the lock resolves it from a `GEM` section naming that remote, with a source-pinned `DEPENDENCIES` entry). A gem whose declaration cannot take the option, or whose lock cannot follow, is refused with neither file changed for it, and the warning's detail gives the reason and the way out: `redirect_gem_unrecognized_declaration` (the declaration cannot be edited in place — a heredoc or `do` block among its arguments, code before it on its line, a string spanning lines, a last argument that is not a literal and may be an options hash: it is taken for a version requirement only when the lock shows one requirement per positional argument, every other positional is a single quoted string, and the manifest has no `gemspec` directive, whose own requirement for the gem bundler folds into the lock entry, …), `redirect_gem_source_option` (it already selects a source: a `source:` / `git:` / `github:` / `path:` option or one a `**opts` splat may hold, a declaration inside a `source` / `git` / `github` / `path` block, a `DEPENDENCIES` entry that is already source-pinned, or a lock that resolves the gem from a `GIT` / `PATH` section), `redirect_gem_declared_more_than_once`, `redirect_gem_declaration_not_visible` (a direct dependency declared in an `eval_gemfile`d file, a loop or a gemspec; vendored mode refuses it for the same reason, so the way out is a literal `gem` line or `--mode agent`), `redirect_gem_dependency_not_locked` (declared, but the lock's `DEPENDENCIES` does not list it), `redirect_gem_lock_unconvergeable` (no `BUNDLED WITH` section to say which layout the lock's Bundler accepts, a merged Bundler < 2.2 section whose remotes the manifest's sources do not explain, or the one multi-remote `GEM` section Bundler 2.2 to 2.7 write for a manifest with more than one top-level `source` line, where the detail names that cause and the remedy: move each extra source into a `source "" do … end` block, then `bundle lock`), `redirect_gem_platform_unsupported` (locked platform builds of a patch that covers the ruby gem alone, above) and `redirect_gem_inconsistent_plan` (the self-check above failed; a bug guard, never expected). A re-scan recognizes its own option (the grant-token and patch-uuid path levels of the URL rotate, so they are matched as wildcards) and refreshes the URL in place, in the manifest and the lock together; a re-scan of an unchanged project writes nothing. A lock reverted or regenerated without its manifest (the option still there, the lock back on the registry) is converged again by the next hosted scan. **Pins written by socket-patch 5.0 / 5.1** used a `source "" do … end` block in the declaration's place and, on a lock with no `CHECKSUMS` section, left the lock alone. That form is never written any more but stays recognized everywhere (re-scan, `list`, `vex`, `rollback` / `remove`, the takeovers): a re-scan keeps the block as it is, refreshes its URL like the option's, and converges a lock that never followed it; only where that lock cannot be converged does the run still warn `redirect_gem_frozen_install`. Human mode prints one line after the summary naming the declarations changed, e.g. ``Added `source:` to 3 gem declarations in Gemfile (puma, rack, and rexml); added 1 line for the transitive dependency nokogiri.`` **Update hold**: a gem wired this way has the patch registry as its only source, and that source serves the one patched version, so `bundle outdated` no longer lists the gem and `bundle update` cannot move it (a range requirement included) until its pin is rolled back. When a run newly wires at least one gem (an option appended or a line added, not a refreshed URL), human mode prints one more stdout line under that one, naming those gems once each: ``Bundler now takes rack from its Socket patch source only, which serves the patched version and no other: `bundle outdated` no longer lists it and `bundle update` cannot move it. To move it to a newer release, run `socket-patch rollback pkg:gem/rack@3.1.8`, then `bundle update rack`, then `socket-patch scan` again.`` The rollback step always names a purl (the gem's own for one gem, as `rollback` selects its pin: without the patch record's qualifiers such as `?platform=ruby`, so a shell passes it on whole; the shape `pkg:gem/@` for several), never a bare `rollback`, which would unwind every patch; after `get` the last step reads "then patch the new version the same way"; `--dry-run` words the first sentence as what the run would hold and prints no steps. `--json` and `--silent` output are unchanged (no warning code). Pinned against real Bundler by `tests/e2e_redirect_gem_build.rs`. See `docs/ecosystems.md` ("Ruby gems: hosted mode") for the user-facing description. **Gem stale-install guard (the canonical narrative; other mentions point here)**: the gem hosted rewrite is pure Gemfile/lock text, and Bundler keeps a gem it already holds whatever source the lock names. So after the rewrite a hosted run looks for the gems the project already has on disk, replaces the project's own stale copies with the patched gem itself, and warns about the rest. The unwind (`rollback`, `remove`, a withdrawn-patch restore) does the same in the other direction. Exit code and `status` never change: a refresh that cannot be done leaves everything as it was and falls back to the warning. @@ -487,7 +487,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm *How a copy is judged.* -- An installed dir is judged by the archive RubyGems installed it from, `/cache/.gem`: an archive whose sha256 is a patched artifact's (the grant's `gemChecksumSha256`, else its tarball sha256, or a prebuild's sha256 from `gemPlatforms`) is already patched and never warns, any other readable archive is stale, and a missing or unreadable one is never evidence by itself. A gem installed as a precompiled platform gem is judged the same way under its own leaf (`gems/nokogiri-1.18.10-arm64-darwin`, `cache/nokogiri-1.18.10-arm64-darwin.gem`): once its archive is the patched platform gem it is patched, never warned about again, and not withheld from `--vex`. +- An installed dir is judged by the archive RubyGems installed it from, `/cache/.gem`: an archive whose sha256 is a patched artifact's (the grant's `gemChecksumSha256`, else its tarball sha256, or a patched platform gem's sha256 from `gemBuilds`) is already patched and never warns, any other readable archive is stale, and a missing or unreadable one is never evidence by itself. A build the patch registry serves as upstream's own gem (`patchUuid: null`) is not judged at all: the upstream gem is what that platform installs, so it is never called stale, refreshed or downloaded, installed or committed to the cache dir. A gem installed as a precompiled platform gem is judged the same way under its own leaf (`gems/nokogiri-1.18.10-arm64-darwin`, `cache/nokogiri-1.18.10-arm64-darwin.gem`): once its archive is the patched platform gem it is patched, never warned about again, and not withheld from `--vex`. - When there is no readable archive (a pruned `cache/`, `gem cleanup`) or no patched sha to compare it with, and no agent-mode record (below), the scan fetches that patch's record (`…/patches/view/`, for that purl only) and judges the dir by its `afterHash` map; if that fetch fails too, the dir is unjudged: no warning, but the same run's `--vex` withholds the purl (`stale_install_unverified`) instead of assuming it patched. Otherwise hosted mode fetches no patch record. - An agent-mode manifest record of the same patch judges the dir's files by its `afterHash` file map instead. An in-place patch keeps the upstream archive in `/cache/`, and that archive is what `bundle pristine` and `bundle install --redownload` reinstall from (#2089): with a `CHECKSUMS` section in the lock Bundler removes the gem and fails on the pinned checksum (exit 37, and every later `bundle install` fails too), without one it reinstalls the unpatched gem. So files the record proves patched beside a readable archive that is not a patched artifact's are stale as well, by that archive alone: the refresh replaces the archive with the verified patched one under the same rules as an installed copy (project-local by default, a shared gem home only with `--gem-refresh-shared`) and never touches the gem dir, where agent mode keeps a native gem's original build; left alone, the warning says that the files are patched in place and names the archive as the one file to remove. With the patched archive beside them, with no readable archive, or with no patched sha256 to compare it with, the record's verdict stands and an agent→hosted migration stays quiet. - Which copies are judged is the lock's to say. Every build of the gem the project's lock names (the ruby-platform `-`, each `--`) is looked for under its own leaf in every gem home Bundler uses, and each one found is judged and refreshed on its own. A gem home can hold several builds of one version (the ruby-platform gem beside a precompiled one, another project's copy in a shared home): a build the lock does not name is never judged, reported or replaced, and it never stands in for one the lock does name. Only where no lock names the gem is the first installed copy of the version judged. @@ -500,7 +500,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm - **What is refreshed**: a stale installed gem whose gem home is the project's own and physically inside the project directory (`vendor/bundle`, a `BUNDLE_PATH` or `GEM_HOME` under the project root, compared on absolute paths so the default `--cwd .` counts) — its gem dir, its `/cache/.gem` and, for a gem that builds a native extension, its `/extensions///` — and a stale archive in bundler's cache dir inside the project. The installed `specifications` entry is kept: the patched gem carries the upstream gemspec byte for byte. After the run, with no further command, `bundle exec` loads the patched code, and `bundle install`, `bundle install --redownload`, `bundle pristine`, and a frozen, deployment or `--local` install all succeed and keep it. - **What is not, by default**: a gem home outside the project (the system gems, `~/.gem`, an rbenv or asdf home) — another project on the machine may pin the upstream bytes of the same `name-version`, and its `bundle pristine` would then fail on the replaced archive's checksum — and a project path that resolves outside the project directory (a `.bundle/config` `path` or `cache_path` naming another directory, a `vendor/bundle` that is a symlink), because the repository chooses that path. `--gem-refresh-shared` (env `SOCKET_GEM_REFRESH_SHARED`) refreshes both the same way. -- **The only source is the verified archive**: the patched `.gem`, whose sha256 must be one the grant pins (the lock's `CHECKSUMS` entry), checked before any byte of it is used. It is taken from disk when another materialization already holds it, else downloaded from the patch registry (`/gems/.gem`, the URL bundler itself would fetch, then the grant's own artifact URL). A platform copy (`--`) is refreshed from the patched platform gem the registry serves under that leaf, checked against that platform's own sha256 (`gemPlatforms`); a platform gem declares no extensions, so nothing is built. No `bundle` or `gem` command is run, and nothing else is contacted. `--offline` uses only an archive already on disk. With no verified archive, nothing is changed. +- **The only source is the verified archive**: the patched `.gem`, whose sha256 must be one the grant pins (the lock's `CHECKSUMS` entry), checked before any byte of it is used. It is taken from disk when another materialization already holds it, else downloaded from the patch registry (`/gems/.gem`, the URL bundler itself would fetch, then the grant's own artifact URL). A platform copy (`--`) is refreshed from the patched platform gem the registry serves under that leaf, checked against that platform's own sha256 (`gemBuilds`); a platform gem declares no extensions, so nothing is built. No `bundle` or `gem` command is run, and nothing else is contacted. `--offline` uses only an archive already on disk. With no verified archive, nothing is changed. - **The archive must be that gem**: its gemspec's name, version and platform must be the materialization's, it must agree with the installed gemspec on whether the gem builds extensions, and, when the archive the copy was installed from is still in the home's `cache/`, both must carry the same gemspec. An archive holding a symlink, hardlink or device entry is refused (RubyGems would create it; the refresh never writes one). - **Nothing is ever missing or half-done**: the new gem dir (and extension dir) is built in a stage dir inside the gem home (`/.socket-patch-refresh/`, removed afterwards) and exchanged with the installed one — one atomic exchange where the platform has it (Linux `renameat2`, macOS `renamex_np`), else two renames — and a step that fails puts the earlier ones back. The home's cached `.gem` is replaced together with the gem dir, never without it (that archive is what the next run judges the copy by), and is not created in a home whose `cache/` was pruned. No file is deleted before its verified replacement is in place. - **Native extensions**: RubyGems itself installs the verified archive into a stage home with the Ruby that owns the installed copy (found as agent mode finds it: the Ruby whose extension dir for the gem is the installed one; never a Ruby inside the project), compiling the extension from the archive's own sources and build scripts with the build arguments RubyGems recorded for the installed copy, and the gem dir and extension dir are swapped in together. The compiled extension therefore always matches its sources. With no such Ruby, a failed build, or `--no-gem-native-rebuild`, the copy is left exactly as it was, with the warning. @@ -519,7 +519,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm *What never refreshes.* A hosted → vendored takeover (`vendor`, `scan` / `get --mode vendored` over a hosted pin) puts the gem on its upstream entry only on its way to the vendored `path:` source, which is what Bundler loads from then on. The copies Bundler already holds are unused leftovers there, so the takeover changes none of them and downloads no gem for them: resetting the installed copy to the upstream build would cost a registry download in the mode that needs none, and would turn a patched leftover into an unpatched one that `vex` reports against the vendored artifact (`vendored_tree_out_of_sync`, whose gem wording names the copy and how to remove it). Its `upstream_gem_stale_cache` advisory about a patched cache-dir archive is as before. A vendored unwind (`remove`, `rollback`, `vendor --revert`, `scan --prune`, `vendor`'s reconcile of a vendored gem) likewise only names that archive, and never replaces it. -*A vendored unwind after a hosted or an agent scan.* Once a vendored gem is unwound, Bundler loads its installed copy again, so the leftover is in use: if a hosted scan made that copy the patched build before the gem was vendored, the patched code would keep running under the upstream lock, and on bundler ≥ 2.6 `bundle pristine` would fail on the upstream checksum. If agent mode patched that copy in place before the gem was vendored (#2093), the takeover moved its manifest record into the vendor ledger and kept the patched files, so the patched code would keep running with no record left that `rollback` or `apply --check` could act on. A gem `.socket/manifest.json` still has a record for is different: its in-place patch is agent mode's and on record (standalone `vendor` works from the manifest and keeps the record), so the vendored unwind does not judge its installed copy by a record. A wet `rollback`, `remove`, `vendor --revert` or `vendor` reconcile that put a vendored gem back on its upstream entry therefore applies the unwind direction's refresh to the gem's INSTALLED copies (of every build the restored lock names: a gem vendored from prebuilt platform gems is installed as `--`, #2174) when the lock now resolves the gem from rubygems.org (a gem from another remote is not judged: nothing proves its entry is the upstream one), under the same rules (staleness judged by `/cache/.gem` against the upstream sha256, and by the patch record of a detached ledger entry (`scan` / `get --mode vendored`) whose gem the manifest has no record for: a copy whose files all hash to the record's `afterHash` values is stale whatever archive its gem home holds, or when it holds none; a project-local gem home only, unless `--gem-refresh-shared`; `--no-gem-install-refresh`; an archive on disk, else rubygems.org unless `--offline`), with the same `upstream_gem_install_refreshed` note and `upstream_gem_stale_install` warning. `--json` carries them where the command carries a vendored revert's advisories (rollback `warnings[]`; `remove` / `vendor` advisory events); a human run prints the progress line after the gem's own line and one warning for the gems left on the patched build. The upstream sha256 is looked up only for a gem that has an installed copy with its archive, or one holding the record's patched files, so the unwind of a gem that is not installed needs no network. A gem that was only ever vendored has the upstream archive there: nothing is downloaded or changed. Rollback's "keep their patched bytes" note and its `reinstall_required` warning do not count a vendored gem whose installed copies are all proven to be the upstream build (#2214): each has, in its gem home, the archive with the verified upstream sha256, and every file the gem's ledger record lists is in its pre-patch state there (it hashes to its `beforeHash`, or the patch adds it and it is absent). Anything short of that proof keeps the gem in the count: a gem with no installed copy the run can find, a gem from another remote, a pruned `cache/`, no verified sha256, a ledger entry with no record (standalone `vendor` before v5), a file that is patched, edited or unreadable. A `--dry-run`, which does not judge the installed copies, counts every vendored gem it would unwind. A copy agent mode patched is reinstalled from the upstream archive RubyGems kept beside it, so nothing is downloaded for it either unless that archive is gone (a pruned `cache/`); the reinstall also removes what agent mode kept in the gem dir. When nothing proves the upstream sha256 for such a copy (`--offline` under a lock without `CHECKSUMS`), it is left as it is and named by `upstream_gem_stale_install`. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry is refused (a plain-`http` `SOCKET_RUBYGEMS_URL`, see the unwind direction), such an installed copy is reported as one that could not be checked, whichever of the two it is: nothing tells them apart. A `--dry-run` does not preview this (the lock on disk is still the vendored one), and `scan --prune` does not refresh. +*A vendored unwind after a hosted or an agent scan.* Once a vendored gem is unwound, Bundler loads its installed copy again, so the leftover is in use: if a hosted scan made that copy the patched build before the gem was vendored, the patched code would keep running under the upstream lock, and on bundler ≥ 2.6 `bundle pristine` would fail on the upstream checksum. If agent mode patched that copy in place before the gem was vendored (#2093), the takeover moved its manifest record into the vendor ledger and kept the patched files, so the patched code would keep running with no record left that `rollback` or `apply --check` could act on. A gem `.socket/manifest.json` still has a record for is different: its in-place patch is agent mode's and on record (standalone `vendor` works from the manifest and keeps the record), so the vendored unwind does not judge its installed copy by a record. A wet `rollback`, `remove`, `vendor --revert` or `vendor` reconcile that put a vendored gem back on its upstream entry therefore applies the unwind direction's refresh to the gem's INSTALLED copies (of every build the restored lock names: a gem vendored from patched platform gems is installed as `--`, #2174) when the lock now resolves the gem from rubygems.org (a gem from another remote is not judged: nothing proves its entry is the upstream one), under the same rules (staleness judged by `/cache/.gem` against the upstream sha256, and by the patch record of a detached ledger entry (`scan` / `get --mode vendored`) whose gem the manifest has no record for: a copy whose files all hash to the record's `afterHash` values is stale whatever archive its gem home holds, or when it holds none; a project-local gem home only, unless `--gem-refresh-shared`; `--no-gem-install-refresh`; an archive on disk, else rubygems.org unless `--offline`), with the same `upstream_gem_install_refreshed` note and `upstream_gem_stale_install` warning. `--json` carries them where the command carries a vendored revert's advisories (rollback `warnings[]`; `remove` / `vendor` advisory events); a human run prints the progress line after the gem's own line and one warning for the gems left on the patched build. The upstream sha256 is looked up only for a gem that has an installed copy with its archive, or one holding the record's patched files, so the unwind of a gem that is not installed needs no network. A gem that was only ever vendored has the upstream archive there: nothing is downloaded or changed. Rollback's "keep their patched bytes" note and its `reinstall_required` warning do not count a vendored gem whose installed copies are all proven to be the upstream build (#2214): each has, in its gem home, the archive with the verified upstream sha256, and every file the gem's ledger record lists is in its pre-patch state there (it hashes to its `beforeHash`, or the patch adds it and it is absent). Anything short of that proof keeps the gem in the count: a gem with no installed copy the run can find, a gem from another remote, a pruned `cache/`, no verified sha256, a ledger entry with no record (standalone `vendor` before v5), a file that is patched, edited or unreadable. A `--dry-run`, which does not judge the installed copies, counts every vendored gem it would unwind. A copy agent mode patched is reinstalled from the upstream archive RubyGems kept beside it, so nothing is downloaded for it either unless that archive is gone (a pruned `cache/`); the reinstall also removes what agent mode kept in the gem dir. When nothing proves the upstream sha256 for such a copy (`--offline` under a lock without `CHECKSUMS`), it is left as it is and named by `upstream_gem_stale_install`. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry is refused (a plain-`http` `SOCKET_RUBYGEMS_URL`, see the unwind direction), such an installed copy is reported as one that could not be checked, whichever of the two it is: nothing tells them apart. A `--dry-run` does not preview this (the lock on disk is still the vendored one), and `scan --prune` does not refresh. **Pipenv hosted redirect (`Pipfile.lock`, pipfile-spec 6)**: every category other than `_meta` (`default`, `develop`, and Pipenv 2022+ named categories) that pins the package at the patched version is rewritten to the hosted reference — `{"file" | "path": "#sha256=", "hashes": ["sha256:"]}` with `markers`/`extras`/`index` kept exactly as Pipenv wrote them (present or absent: whether Pipenv records `index` depends on its release, the Pipfile spelling and the locking environment, so only the entry itself knows) and `version` dropped; `_meta` (the Pipfile content hash) and the Pipfile itself are never touched, so `pipenv install --deploy`/`sync`/`verify` keep passing. The reference KEY depends on the installing Pipenv: releases 7–11 only install `path` references, 2018 and later `file` ones (0–6 write pipfile-spec < 6 and are refused). The release is probed once per command with `pipenv --version`, resolved on ABSOLUTE `PATH` entries only (a relative entry would run a `pipenv` planted in the scanned repository; `.bat`/`.cmd` shims are found through `PATHEXT` on Windows), only when a pypi patch actually targets an entry of the lock, and `SOCKET_PIPENV_MAJOR=` pins the answer without spawning anything. An unknown installer selects `file` and warns `redirect_pipenv_installer_unknown` only when the lock was rewritten. **Refusal scope**: a pin/source CONFLICT (another version pinned, a foreign `file`/`path` source, a VCS/editable dependency) refuses the whole dependency atomically across categories as `redirect_pipenv_refused` AND vetoes the sibling Python rewriters (requirements.txt / uv.lock / pyproject) for that patch — the project's Pipenv install could not pick the patch up, so a half-redirected checkout is refused; anything else (no entry for the package, an old pipfile-spec, an unparseable lock, a digest-less patch) is `redirect_pipenv_skipped` and leaves the siblings alone (a stale Pipfile.lock in a uv/Poetry/requirements project must not block them). The veto applies to a LIVE lock only: a `Pipfile.lock` with no `Pipfile` beside it is abandoned, so its conflict refuses that file but never the siblings. Hash enforcement at install time is split by era — the `#sha256=` URL fragment is what Pipenv 2023+ verifies, the `hashes` list what 2018–2022 verify, Pipenv 11 either — so both are load-bearing. **Pipenv stale-install guard**: Pipenv never reinstalls a release that is already present (`pipenv install`, `install --deploy` and `sync` all exit 0 and keep the installed bytes — measured on 11.10.4, 2018.11.26 and 2026.8.0, hosted and vendored), so after the rewrite the run probes the Python crawler's site-packages (VIRTUAL_ENV, `./.venv`, `./venv`, Pipenv's out-of-tree `WORKON_HOME` venv; `--global`/`--global-prefix` honoured) for each confirmed Pipfile.lock redirect with the Python stale-install guard's evidence (the pinned patched wheel, else the patch record; STALE needs positive evidence, read-only, skipped on `--dry-run`, stale purls excluded from the same-run `--vex` `assume_applied` set) and the Python stale-install guard (`redirect_pypi_stale_install`, see above) names the site-packages dir and the Pipenv-specific verified remedy: `pipenv run pip uninstall -y && pipenv sync` (or `pipenv --rm && pipenv sync`), with the `sync` arguments following the lock, since plain `pipenv sync` installs only `default`: the targeted form re-syncs the categories that pin the package (`--dev` for `develop`, `--categories ""` for a named category) and the `--rm` form re-syncs every non-empty category — NOT `pipenv uninstall`, which rewrites the Pipfile and re-locks the patch away. The vendored backend emits the twin `pypi_pipenv_stale_install` (`skipped` warning event). **Rollback** (v5.0, upstream restore): each hosted entry gets its registry shape back — `"version": "=="`, the entry's own `index` carried back unchanged (refused unless it — and the Pipfile's explicit `index`, if any — names a PyPI source in `_meta.sources`), and every release file's sha256 from PyPI's JSON API (`SOCKET_PYPI_JSON_API`), sorted by filename as Pipenv records them; an entry that pins another version beside the hosted reference is refused with the `git checkout` remedy (see "Hosted unwind coverage"). A Pipfile names no project, so a same-run `--vex` on a Pipenv project needs `--vex-product` (or a git remote) to detect a product purl. **Discovery**: `Pipfile.lock` is part of the lockfile inventory (every category's `==` pins, with the lock's digest set as `Sha256AnyOf` integrity so a lock-only checkout can be vendored by fetching the pure wheel through PyPI's JSON API — only when `_meta.sources` name the public index; a private-index lock stays discovery-only and never reaches pypi.org), and Socket's own hosted / vendored references stay discoverable as the package they replace, so a re-scan of an already-redirected or already-vendored lock-only checkout re-confirms it (`--vex` attests, vendored reports `already_vendored`) instead of finding nothing. @@ -1658,7 +1658,7 @@ path. Without hosted pins the no-manifest no-op below is unchanged. **Prebuilt vendor artifacts (`--vendor-source`)**: `service` is the default and `auto` is a compatibility alias. `build` is rejected at argument parsing. There is no local construction or fallback. Package-reference POSTs on the configured API/proxy (`--vendor-url` overrides it) return the download URL and integrity; `--patch-server-url` can override the download origin. The CLI verifies transfer integrity and patched-member afterHashes before writing. Pending builds, missing artifacts, service failures, wrong layouts and integrity mismatches fail closed. Fresh acquisition requires the network; healthy committed artifacts remain reusable offline. -Coverage includes npm (all lock flavors), Python wheels and source distributions, Cargo crates, Go module zips, Composer dist zips, RubyGems, NuGet packages and JVM jars. Directory artifacts are extracted and receive only the existing package-manager layout transformations. RubyGems requires the server's separately verified `gem-stub-gemspec`; a missing or invalid stub is a failure. A gem whose `Gemfile.lock` holds platform-suffixed entries (`nokogiri (1.18.10-x86_64-linux-gnu)`) is taken as the patch's prebuilt platform gems instead: for each locked platform the server's `gem-platform` artifact and its `gem-platform-stub-gemspec` (each carries its `platform`), both verified like the ruby gem and its stub. Which prebuilds exist is read from the package reference alone, and the ruby gem it also names is not downloaded. While the server lists no prebuild for a locked platform nothing is downloaded and the gem is skipped (`vendor_prebuilt_platform_pending`). A prebuild need not ship any of the patch's files (a patch of `patches/**` or `dependencies.yml` lives entirely in the rebuilt binaries): its integrity check against the digest the server states for that platform is mandatory and is what vouches for it, while a patched file it does ship that is not the patched one is a `vendor_prebuilt_required` failure. Yarn Berry checksums come from server metadata. Hosted Berry rollback retrieves upstream checksum metadata from `/upstream/npm/.json` and checks its package identity and upstream integrity against the registry; the CLI does not recreate the Berry zip. +Coverage includes npm (all lock flavors), Python wheels and source distributions, Cargo crates, Go module zips, Composer dist zips, RubyGems, NuGet packages and JVM jars. Directory artifacts are extracted and receive only the existing package-manager layout transformations. RubyGems requires the server's separately verified `gem-stub-gemspec`; a missing or invalid stub is a failure. A gem whose `Gemfile.lock` holds platform-suffixed entries (`nokogiri (1.18.10-x86_64-linux-gnu)`) is taken as its patched platform gems instead. The gem patch's package reference names the patch of each platform (`registryOverride.identifiers.gemBuilds`), which is all that is read to tell which platforms have a patched build; the ruby gem it also names is not downloaded. Each locked platform's tree then comes from that platform's own patch: its `tarball` (the patched platform gem) and its `gem-stub-gemspec`, the references of all of them asked for in ONE request, each download verified against the digest its own reference states, and the gem also against the sha256 the gem patch lists for that platform (a gem that is not the listed one is `vendor_prebuilt_integrity_mismatch`, with any existing copy untouched). While a locked platform has no patched build nothing is downloaded and the gem is not vendored (`vendor_prebuilt_platform_pending`). A patched platform gem need not ship any of the patch's files (a patch of `patches/**` or `dependencies.yml` lives entirely in the rebuilt binaries): its integrity check is mandatory and is what vouches for it, while a patched file it does ship that is not the patched one is a `vendor_prebuilt_required` failure. Yarn Berry checksums come from server metadata. Hosted Berry rollback retrieves upstream checksum metadata from `/upstream/npm/.json` and checks its package identity and upstream integrity against the registry; the CLI does not recreate the Berry zip. Agent runs fetch patch content as per-file blobs (v5.0 removed `--download-mode` and the diff archive path). Vendored runs retain patch records in memory and embed them in the vendor ledger, without staging blobs. N-API and the hosted in-memory engine remain supported for callers such as the future GitHub App. @@ -1740,7 +1740,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked prebuilt platform gem per locked platform, `-//`, each with its gemspec, plus `/.gitignore` (`!*`: re-includes the prebuilt binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a prebuilt platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patch's prebuilt platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. Every locked platform needs a prebuild: while the patch service lists none for one of them the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked patched platform gem per locked platform, `-//`, each from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. Every locked platform needs a patched build: while one has none the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity`, in lock order), and a restore fetches each tree by it. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event each (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; human lines and totals count the gem as one package. `vex` attests each vendored platform gem under its own patch, from the committed ledger alone. An entry that names only platforms (`gemPlatforms`, written by a development build) still verifies and reverts, and the next vendor run converts it; `repair` of such an entry asks for a vendor run. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | @@ -2519,7 +2519,7 @@ command's integration tests check its output. | `vendor_maven_selection_undetermined` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): what the build selects for the artifact cannot be read (the reason says why: typically a pom the local repository does not hold, because the project was never resolved) and no declaration names the patch's base version, so nothing is pinned on a guess and no file is written. The reason carries the remedy that fits its cause (resolve the project once and re-run when a pom is missing from the local repository; otherwise declare the artifact at the base version). The vendored twin of `redirect_maven_selection_undetermined`. | | `vendor_maven_pin_would_move_module` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven reactor): the only poms that resolve the artifact at the patch's base version are parent poms above a module that resolves another version. A `` pin in the parent is inherited by that module and would move it, and Maven has no management that reaches a parent and not its children, so nothing is pinned and no file is written; the reason names the parent, the module and its version. When a sibling module does select the base version it is pinned and the same sentence is the `vendor_jvm_degraded` reason `pin_would_move_module`. | | `vendor_prebuilt_pending` / `vendor_prebuilt_unavailable` | `skipped` | vendor / scan / get `--mode vendored` (every ecosystem, #954, #1235): the package is already vendored at another patch uuid, and the patch service has no prebuilt artifact for the selected (superseding) uuid — still building (`pending_build`) / not served (`build_failed`, `not_found`, `withdrawn`, no usable artifact). Nothing is touched: the older patch's artifact, wiring and ledger entry stay in force, the detail names both uuids (`kept the vendored patch : prebuilt is still building for patch `, where `` is the backend's artifact kind: `artifact` for the npm family, `.gem`, `crate`, `module zip`, `dist zip`, `wheel`, `.jar`, `.nupkg`, …), and the run does not fail (exit 0), the way hosted mode keeps its pin and lists the upgrade in `redirect.skipped[]`. A re-run picks the new patch up once the service serves it. A package with no vendored patch to keep still fails (`failed`, error `prebuilt is still building` / `prebuilt unavailable: `; outside the npm family under `vendor_prebuilt_required`), as does a request/transport failure. | -| `vendor_prebuilt_platform_pending` | `skipped` | vendor / scan / get `--mode vendored` (gem): `Gemfile.lock` pins the gem as precompiled platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the patch service lists no prebuilt platform gem (or no stub gemspec) for at least one locked platform. The service lists a prebuild only once it is built, so "not built yet" and "never built" look the same: the detail names the gem, the platforms with no prebuild and the ones that have one, nothing is downloaded or written, and the run does not fail (exit 0), with or without an older vendored patch. With one, it stays in force and the detail names both uuids (`kept the vendored patch : … for patch `). A re-run vendors the gem once every locked platform has a prebuild. Two cases stay failures (`vendor_prebuilt_required`): a copy the lock is already wired to that is missing or damaged and cannot be rebuilt, by a re-run or by `repair`; and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. | +| `vendor_prebuilt_platform_pending` | `skipped` | vendor / scan / get `--mode vendored` (gem): `Gemfile.lock` pins the gem as precompiled platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the gem patch's reference has no patched build for at least one locked platform: the platform is served as upstream's gem (`gemBuilds[].patchUuid` is null), is not listed yet, or the reference carries no list. Vendored mode is all-or-nothing for such a gem. Nothing is downloaded or written, the run does not fail (exit 0), and ONE line (stderr, no warning; one counted `skipped` event under the gem's purl) names the platforms without a patched build and the ones that have one (on a terminal it is wrapped like the hosted line of such a gem): `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs every locked platform; `scan --mode hosted` can patch the others now.` (with no platform patched, or no list: `… no patched build yet for arm64-darwin and x86_64-linux-gnu. Vendored mode needs every locked platform.`). A copy that is already vendored stays in force and the line says so: `… was not brought up to date: no patched build yet for java (… have one). Vendored mode needs every locked platform; its vendored copy stays in force as it is.`, or `…; its vendored copy of an earlier patch stays in force as it is.` when the copy is of an older patch. A gem pinned hosted (a takeover) stays hosted: `…; the gem stays hosted.` A re-run vendors the gem once every locked platform has a patched build. Two cases stay failures (`vendor_prebuilt_required`): a copy the lock is already wired to that is missing or damaged and cannot be rebuilt, by a re-run or by `repair` (`…; its vendored copy is missing or damaged and cannot be rebuilt until then.`); and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. | | `unsafe_coordinates` | `failed` | vendor: purl/uuid would escape `.socket/vendor/` (tampered manifest/state); refused before any write. | | `revert_failed` | `failed` | vendor --revert: a recorded entry could not be reverted. | | `vendor_ledger_missing` | `failed` (artifact-level: `uuid` + `details.{ecosystem,path}`, no purl) | repair (v5.0) and `vendor --check`: a lockfile references `.socket/vendor///` but the vendor ledger has no entry for it; repair no longer rebuilds ledger entries from lockfiles. Recovery: restore `.socket/vendor/state.json` from version control and re-run `repair`, or `git checkout -- ` and re-vendor. | @@ -2608,7 +2608,7 @@ command's integration tests check its output. | `vendor_dep_manifest_unlocked` | refused | vendor (yarn classic): the patch rewrites the package's own `package.json` to depend on a descriptor (`name@range`) no `yarn.lock` block is keyed by — an added dependency, or an existing one moved to a new range. A descriptor every wired block's sub-map already names is not counted: yarn keys those blocks by the registry packument's ranges, which can differ from the tarball's `package.json` (#1578). yarn 1 builds its install graph from the lock, so the rewired block would name a dependency it never resolves: online frozen installs fetch it unpinned, `--offline` installs fail and every plain `yarn install` re-saves the lock (#591). Refused after staging and before any wiring is written (the staged uuid dir is removed); the detail names the descriptors. Remedy: lock them first (for example `yarn add `), then re-run. A dry run, which stages nothing, does not foresee it. Also `failed` on `repair` (and `vendor_check_failed` on `vendor --check`) for a lock an older release already vendored that way, with a block wired to the entry naming a descriptor no block locks and the recorded pre-vendor block did not (#1379); the lock is left as it is. Remedy: `yarn install` (without `--frozen-lockfile`) to lock them, then commit `yarn.lock`. | | `redirect_yarn_classic_dep_manifest_unlocked` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` depends on a descriptor no `yarn.lock` block is keyed by and that the sub-maps of the registry blocks being pinned don't already name (yarn keys those by the packument's ranges, #1578). yarn 1 installs only what the lock names, so a pin would install the patched package without that dependency (#591). The dep is not pinned and never confirmed; the lock is left as it was. The served tarball is read on every run, so a pin an earlier release wrote without this check (#1462) gets the same warning and is never confirmed either; it stays in the lock until the dependency is locked or the pin is rolled back. Same remedy as `vendor_dep_manifest_unlocked`. | | `redirect_yarn_classic_dep_manifest_rewritten` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` declares other dependencies than the pinned block's sub-maps, every descriptor already locked; the block's `dependencies:` / `optionalDependencies:` sub-maps are rewritten to match, in the shape yarn 1 writes for that manifest (#591, #1558). | -| `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, a gem vendored as prebuilt platform gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel still reads as ignored, the run refuses and removes the uuid dir it created. | +| `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, a gem vendored as platform gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel still reads as ignored, the run refuses and removes the uuid dir it created. | | `vendor_artifact_gitignore_unchecked` | warning | vendor (vlt, the npm-family tarball flavors, NuGet and every PyPI flavor): git is installed but could not answer the ignore check for the written vendored directory (it failed to start, ran past 30 s, or `rev-parse` / `check-ignore` exited with an error); the package is vendored and the detail names what failed. Remedy: make sure no ignore rule covers `.socket/` before committing. Git absent, or a project outside any work tree, raises nothing. | | `vendor_ledger_gitignored` | top-level error (exit 1) | vendor / scan / get `--mode vendored` (every backend) and the hosted→vendored eject: inside a git work tree, `git check-ignore` reports the vendor ledger `.socket/vendor/state.json` as ignored by a file rule (such as `state.json`, `*.json` or `**/state.json`; the message names it), so the commit the run asks for would leave it out and no other checkout could `rollback`, `list` or `vendor --revert` the patches (#1638). A ledger git already tracks is never refused. Refused before any write, dry run included. Remedy: drop the rule or add `!.socket/vendor/state.json`. A rule that ignores `.socket/` or `.socket/vendor/` as a directory is `vendor_artifact_gitignored`: per package from the backends that check it themselves (the npm family, NuGet, PyPI, the JVM trees), and as this same run-level refusal when the run includes any other ecosystem. | | `vendor_ledger_entry_missing` | `failed` | vendor (vlt): the only installed copy is vlt's link to a committed vendored directory, but the vendor ledger has no entry for the package; restore `.socket/vendor/state.json` from version control (v5.0: `repair` no longer re-synthesizes it). Replaces the `package_not_installed` skip. | @@ -2623,7 +2623,7 @@ command's integration tests check its output. | `vendor_uuid_mismatch` | `skipped` | repair: the manifest's patch uuid moved past the vendored artifact — a re-vendor (`vendor` / `scan --mode vendored`) is pending; repair does not cross patch generations. | | `content_mismatch_overwritten` | `skipped` (warning) | apply (explicit `--allow-patch-conflicts` / `--force`): a file matched NEITHER beforeHash nor afterHash and was overwritten with the full verified patched content. This includes a file the patch adds (empty beforeHash) that already exists with other content. `--strict` turns this case into a `failed` event instead. Agent-mode `get` / `scan --json` carry it as a `(content_mismatch_overwritten) …` `warnings[]` entry (#1004). | | `vendor_lock_checksums_unsupported` / `vendor_stale_lock_checksum` | `failed` | vendor (gem): an ambiguous/platform CHECKSUMS entry, or a v1-wired lock whose stale token blocks the hot path (run `vendor --revert` + re-vendor). | -| `platform_gem_unsupported` | `failed` | vendor / scan / get `--mode vendored` (gem): a precompiled platform gem that cannot be vendored. `Gemfile.lock` pins the gem as platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and also holds the plain ` ()` entry of the `ruby` platform, which no prebuilt tree serves (the detail names it; `bundle lock --remove-platform ruby` drops it); or it pins the gem as platform gems and its `BUNDLED WITH` is absent or names a Bundler older than 2.3, the oldest the vendored layout is verified on (the detail names the version needed; `bundle update --bundler` re-locks); or the installed copy is a platform gem and the lock names no platform for the gem; or the patch record is for one platform's build (`?platform=`). Nothing is written. A locked platform the patch service has no prebuild for is not this failure: see `vendor_prebuilt_platform_pending`. | +| `platform_gem_unsupported` | `failed` | vendor / scan / get `--mode vendored` (gem): a precompiled platform gem that cannot be vendored. `Gemfile.lock` pins the gem as platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and also holds the plain ` ()` entry of the `ruby` platform, which no platform tree serves (the detail names it; `bundle lock --remove-platform ruby` drops it); or it pins the gem as platform gems and its `BUNDLED WITH` is absent or names a Bundler older than 2.3, the oldest the vendored layout is verified on (the detail names the version needed; `bundle update --bundler` re-locks); or the installed copy is a platform gem and the lock names no platform for the gem; or the patch record is for one platform's build (`?platform=`). Nothing is written. A locked platform with no patched build is not this failure: see `vendor_prebuilt_platform_pending`. | | `redirect_unattributable` | `skipped` (hosted event) | scan/get `--mode hosted`: the rewriters would pin the patch, but lockfile discovery over the result reads that pin as contested (another lock or requirements file resolves the same version elsewhere, or the pin is not one the package manager consumes), so `vex`, `rollback`, `remove` and `vendor` would refuse it. The candidate is left out of the rewrite, so nothing is written for it; the detail carries discovery's findings. Exit code unchanged. | | `redirect_mirror_unsupported` / `redirect_mirror_url_refused` | `skipped` (hosted event) + `warnings[]` | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the patch's ecosystem cannot be served through a mirror (`redirect_mirror_unsupported`: Cargo, NuGet; use `--mode vendored`), or its reference could not be moved onto the mirror (`redirect_mirror_url_refused`). Nothing is written for it. See "Patch mirror (experimental)". | | `redirect_mirror_unavailable` | `skipped` (hosted event) + `warnings[]` | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the mirror did not serve the reference the run asked it for, or could not be reached. That reference is skipped and nothing is written for it. One warning per package, or a single warning about the mirror when it served none of the references it was asked about. | @@ -2658,7 +2658,11 @@ command's integration tests check its output. | `redirect_gem_source_option` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the gem already has a source of its own (an option on its declaration, an enclosing `source` / `git` / `github` / `path` block, a source-pinned `DEPENDENCIES` entry, or a `GIT` / `PATH` lock section) and Bundler allows one per gem. The gem is skipped, nothing written for it. When the source is socket-patch's own vendored `path:`, the detail names the un-vendor step instead. | | `redirect_gem_dependency_not_locked` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the manifest declares the gem but the lock's `DEPENDENCIES` does not list it (an out-of-date lock, or a conditional declaration). The gem is skipped, nothing written for it; run `bundle lock` and re-run. | | `redirect_gem_lock_unconvergeable` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock cannot be edited into the one Bundler writes for the redirected manifest (no `BUNDLED WITH` section, or a merged Bundler < 2.2 `GEM` section whose remotes the manifest's sources do not explain), and Bundler refuses a manifest whose sources its lock does not record under frozen / deployment mode. The gem is refused whole: neither file changes for it. The detail names the lock shape and the way out (`bundle lock` with the current Bundler, then re-run; or `--mode vendored` / `--mode agent`). For a manifest with more than one top-level `source` line, which Bundler 2.2 to 2.7 lock into one `GEM` section naming every source and `bundle lock` does not change, the detail names that cause instead, and the way out is to keep the source that serves the gem as the one top-level `source`, move each other one into a `source "" do … end` block, run `bundle lock` (with Bundler 2.2.25 or later, which the detail says when the lock was written by an earlier 2.2 release, since those keep the one section) and re-run, or `--mode agent`; it does not print the source URLs. The gate counts block-less `source` calls outside every other construct, a computed URL included; a `source` inside a conditional is not counted and keeps the generic detail. | -| `redirect_gem_platform_unsupported` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock holds precompiled platform builds of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the patch has no patched platform gem ("prebuild", the grant's `gemPlatforms`) for at least one of them, or the lock is the merged layout of Bundler < 2.2. The detail names the locked builds, the ones with no prebuild and what the patch registry serves. The gem is skipped and the manifest and lock stay byte-identical for it. With a prebuild for every locked platform the gem is redirected and no warning is given. | +| `redirect_gem_platform_unsupported` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock holds precompiled platform builds of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the gem patch's reference carries no list of the version's gems (`gemBuilds`: the patch covers the ruby gem alone), or the lock is the merged layout of Bundler < 2.2. The detail names the locked builds and which of the two it is. The gem is skipped and the manifest and lock stay byte-identical for it. A platform with no patched build, or one the list does not name yet, is not this warning: see `gem_upstream_build_kept`, `redirect_gem_no_patched_build` and `redirect_gem_build_pending`. | +| `gem_upstream_build_kept` | `events[]` (`skipped`, NOT counted in `summary`, no `uuid`) | scan/get `--mode hosted` (gem): one platform build the lock names of a gem that was moved to (or is on) the patch registry, which the registry serves as upstream's own gem because that platform has no patched build yet. That platform installs what it installed before. `details.gemFix` is the gem's patch and `details.platform` the platform; the human line of the gem names it (`upstream gem kept for arm64-darwin (no patched build yet)`). Never a warning, never attested as patched. | +| `redirect_gem_no_patched_build` | `events[]` (`skipped`) | scan/get `--mode hosted` (gem): the lock holds the gem as precompiled platform builds and none of the builds it names has a patched build yet, so moving the gem would gain nothing: it is left on its upstream registry, byte-identical. One plain line on stdout (`nokogiri 1.18.10: no patched build yet for arm64-darwin, x86_64-linux-gnu; left on its upstream registry`), no warning, exit 0. A later run moves the gem once the patch service lists a patched build for a platform the lock names. | +| `redirect_gem_build_pending` | `events[]` (`skipped`) | scan/get `--mode hosted` (gem): the lock names a platform the gem patch's list (`gemBuilds`) leaves out, which the patch service does while that platform's patched build is being made. The gem is left as it is, byte-identical. One plain line on stdout (`nokogiri 1.18.10: the patch registry does not list arm64-darwin yet (a patched build is still being made); left as it is until it does`), no warning, exit 0. A later run moves the gem. | +| `vex_gem_build_unknown` | `vex.warnings[]` / `warnings[]` (one per gem and reason) and `events[]` (`skipped`, one per build) | vex, and the `--vex` of apply / vendor (gem): a Bundler lock takes the gem from a patch registry as precompiled platform builds, and whether a build it names is a patched one could not be told from what the lock installs: the gem patch's reference lists another archive for that platform than the lock pins (the lock is older than the reference: run `socket-patch scan --mode hosted`, then `vex` again), the reference or the registry's `info/` could not be read, or `--offline` forbids asking. The build is left out of the document, never attested as patched; the builds that can be told are attested, and the run is a partial failure (exit 1 with `no_applicable_patches` when nothing at all can be attested). The warning names the gem, the platforms and what to run. | | `redirect_gem_inconsistent_plan` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the rewriter's self-check found the planned manifest and lock disagreeing about the gem, a pair Bundler refuses frozen. Nothing is written for it. Not expected; report it. | | `redirect_gem_frozen_install` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): a pin socket-patch 5.0 / 5.1 wrote as a `source … do` block sits beside a lock that still records the upstream source and that this run changed but could not converge; Bundler rejects the pair under frozen / deployment mode until an unfrozen `bundle install` records the source. Never raised for the `source:` option form, whose lock always follows. | | `redirect_gem_no_lockfile` | `warnings[]` (warning) | scan `--mode hosted` (gem): the project has a `Gemfile` / `gems.rb` but no lock, so the version it resolves is unknown (#1125). Every gem is skipped and the Gemfile stays byte-identical; run `bundle lock` (or `bundle install`), commit the lock, and re-run. | diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 14dfbf8b6e..2610d695fe 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -22,7 +22,7 @@ below is about what a package manager installs and builds. | PyPI (`pypi`) — uv / poetry / pdm / pipenv / pip | ✅ in place | ✅ uv project/script locks, PEP 751 `pylock.toml` / `pylock..toml`, poetry, pdm, pipenv (Pipenv 2018 or later — every `Pipfile.lock` category is rewired, lock-only checkouts included; Pipenv 2023+ does not hash-check local wheels — `vendor_integrity_unverified`; Pipenv 2023.7.9+ exports the vendored wheel without a hash, so `pipenv requirements --hash` output fails pip's hash-checking mode — `pypi_pipenv_hash_export_unsupported`; a venv still holding the upstream release is reported as `pypi_pipenv_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)), and requirements.txt. Native uv vendoring requires uv ≥ 0.2.35 (the `[[package]]` lock grammar); hosted mode covers native `uv.lock` from uv 0.1.45 (the first release whose `uv lock` writes one) and requirements from uv 0.0.5; see [uv compatibility](testing/uv-compatibility.md). Declined where a rules_python hub of a Bazel workspace reads the file, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ requirements.txt including hash continuations, uv project/script locks, and PEP 751 locks. Version/source ambiguity is refused; see [uv compatibility](testing/uv-compatibility.md). Poetry 1.x and 2.x locks are supported; Poetry 0.x ignores URL sources and is refused. See [Poetry compatibility](testing/poetry-compatibility.md). Pipenv `Pipfile.lock` (pipfile-spec 6 — Pipenv 7 and later; `path` references for 7–11, `file` from 2018; lock-only checkouts and Pipenv's out-of-tree venv are discovered; a warm venv that Pipenv will not reinstall over warns `redirect_pypi_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)). `pdm.lock` is supported for the lock formats PDM 0.12–1.4 and 2.8.1+ write (`lock_version` 2 / 4.3–4.5.1); the identity-losing 3.1 / 4.0–4.2 formats (PDM 1.8–2.7) are refused. PDM 2.8.0 writes an indistinguishable `4.3` lock but shares that identity-loss bug, so a rewritten 2.8.0 lock crashes `pdm sync` — upgrade to ≥ 2.8.1. See [PDM compatibility](testing/pdm-compatibility.md). | | pixi (`pypi`) — the Python packages of a pixi project, from conda channels or PyPI | ✅ in place, in every environment under `.pixi/envs`: PyPI wheels and pure-Python conda packages (compiled conda packages are not supported yet and are skipped) — see [PyPI: pixi projects](#pypi-pixi-projects) | ❌ refused (`pypi_no_requirements` / `pypi_pyproject_only`, which name agent mode) | ❌ nothing rewritten (`redirect_pypi_pixi_project` names agent mode) | | Cargo (`cargo`) | ✅ in-place + `.cargo-checksum.json` rewrite (shared registry-cache caveat — see [Cargo: shared registry cache](#cargo-shared-registry-cache)) | ✅ `[patch.crates-io]` path entry in the root `Cargo.toml` (v5; per-version Socket keys; pre-v5 `.cargo/config*` wiring migrates on re-run) | ✅ per-patch sparse registry (`[registries.socket-patch-]` + Cargo.lock source/checksum); needs cargo 1.68+ (sparse registries) — a project whose `rust-version` or `rust-toolchain[.toml]` declares an older cargo is refused (`redirect_cargo_old_cargo`), use `--mode vendored`; direct dependencies only — a crate another dependency also pulls in is refused, use `--mode vendored`; a crate the user overrides with `[patch]` (path, git or another registry) is refused too, the override is left alone; a `cargo vendor` or `cargo local-registry` project (crates.io replaced by an on-disk source in the project's, a parent directory's or `$CARGO_HOME`'s `.cargo/config*`) is refused, use agent mode; with no `Cargo.lock` the graph is unknown, so only a project whose sole dependency is the patched crate is redirected; in a Bazel workspace a crate is not pinned while a rules_rust hub reads the project's Cargo files without its cargo config (`redirect_cargo_bazel_config_unread`), see [Bazel workspaces: Cargo](#bazel-workspaces-cargo) | -| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from prebuilt patched platform gems, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write); declined where a rules_ruby hub of a Bazel workspace reads the pair, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard"). In a Bazel workspace whose rules_ruby call holds the gem to another sha256 in `gem_checksums`, or has a `gem_checksums` that is not written out in the call, nothing is written for it (`redirect_bazel_gem_checksums_pinned`); see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems) | +| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from the patched platform gems, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write); declined where a rules_ruby hub of a Bazel workspace reads the pair, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard"). In a Bazel workspace whose rules_ruby call holds the gem to another sha256 in `gem_checksums`, or has a `gem_checksums` that is not written out in the call, nothing is written for it (`redirect_bazel_gem_checksums_pinned`); see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems) | | Go (`golang`) | ✅ `go.mod` `replace` → `.socket/go-patches/` — see [Go: directory replaces and go.sum](#go-directory-replaces-and-gosum) | ✅ `replace` → the committed vendor tree | ✅ (free tier) fork-style `replace` → `patch.socket.dev/gopatch/` + committed `go.sum` pin; see [Go notes](#go-directory-replaces-and-gosum). Paid hosted patches are unsupported; `redirect_golang_unsupported` names the vendored remedy | | Maven (`maven`) — Maven and Gradle | ✅ in place in every copy the build consumes: each `~/.m2` copy it reads and each Gradle `files-2.1` copy; `~/.m2` `.sha1`/`.md5` sidecars are rewritten, Gradle copies get advisories; jar-member records swap in the patch service's whole jar — prefer vendored / hosted, see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | ✅ suffixed Maven repository (`-socket.` pin + `.mvn/maven.config` + fallback file repository) for every pom root, single-module or reactor, or Gradle 6.8+ same-GAV repository with settings wiring and SHA-256 checks (a root with both `pom.xml` and a Gradle build wires both); see [JVM vendoring](design/maven-vendoring.md) and [Gradle](#gradle) | ✅ fail-closed by a Socket-only `-socket.` suffix: pom projects get a pinned `` (`${property}` versions are refused); Gradle 6.8+ builds get an owned settings script, lock-entry rewrites and a resolution tripwire — see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | | sbt / Mill / scala-cli (`maven`) | ✅ Coursier caches (sbt 1.3+, sbt 2, Mill, scala-cli) and Ivy caches (sbt 0.13–1.2, `useCoursier := false`) patched in place, Coursier checksum sidecars resynced — see [Scala build tools](#scala-build-tools-sbt-mill-scala-cli) | ✅ sbt 0.13.18+: generated `socket-patch-vendor.sbt` over the committed suffixed `.socket/vendor/maven2` tree; scala-cli directory builds: owned `socket-patch.scala` + same-GAV `.socket/vendor/coursier` tree (Linux / macOS); Mill: not wired (agent or hosted guidance) | ✅ sbt 0.13.18+: one generated `socket-patch.sbt`, gated on sbt's own `sbt update` records; Mill / scala-cli: paste-able snippets only (`redirect_mill_manual_snippet`, `redirect_scala_cli_manual_snippet`) | @@ -4892,7 +4892,7 @@ wire is skipped, neither file changes for it, and the warning says why and what | `redirect_gem_declaration_not_visible` | the lock lists it as a direct dependency, but it is declared where the scan cannot edit: an `eval_gemfile`d file, a loop, a gemspec. Declare it with a literal `gem ""` line in the Gemfile, in place of any other `gem` call that declares it (a gemspec's development dependency stays), or patch it with `--mode agent`. Vendored mode refuses it for the same reason. | | `redirect_gem_dependency_not_locked` | the Gemfile declares it and the lock's `DEPENDENCIES` does not list it. Run `bundle lock` and re-run. | | `redirect_gem_lock_unconvergeable` | the lock cannot be brought in line with the Gemfile: it has no `BUNDLED WITH` section to say which layout its Bundler accepts, or a Bundler < 2.2 lock lists its sources in an order the Gemfile's `source` lines do not explain. Run `bundle lock` with your current Bundler and re-run. Also a Gemfile with more than one top-level `source` line: Bundler 2.2 to 2.7 lock all its gems in one `GEM` section that names every source, which hosted mode does not rewrite, and `bundle lock` writes the same lock again. Keep the source that serves the gem as the one top-level `source` and move each other one into a `source "" do … end` block around the gems that come from it (Bundler's own deprecation warning asks for the same), then run `bundle lock` and re-run; or use `--mode agent`. A Bundler 2.2 release before 2.2.25 keeps the one section even then, so run that `bundle lock` with a later Bundler; the warning says so when the lock was written by one. | -| `redirect_gem_platform_unsupported` | the lock holds a platform-specific build of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) that the patch has no patched build for. The warning names the builds the lock holds, the ones that are missing, and what the patch registry serves. See "Precompiled platform gems" below. | +| `redirect_gem_platform_unsupported` | the lock holds platform-specific builds of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the patch covers the ruby gem alone, or the lock is the merged layout of a Bundler older than 2.2. The warning names the builds the lock holds and which of the two it is. See "Precompiled platform gems" below. | `--mode agent` can still patch a gem hosted mode skips. `--mode vendored` can too, unless it refuses the gem itself (see "Ruby gems: gems vendored mode refuses"). @@ -4908,20 +4908,59 @@ gem, and the lock then has one entry per platform the project supports, usually racc (~> 1.4) ``` -For such a gem the patch registry serves a patched platform gem (a "prebuild") per platform: the -upstream platform gem with the patch's files replaced, under the same file name. When the patch -has a prebuild for every platform the lock names, the scan wires the gem like any other. The -Gemfile edit is the same, every platform entry moves to the patch registry's `GEM` section with -its dependency lines (and a plain `nokogiri (1.18.10)` entry beside them moves too), -`DEPENDENCIES` gains the `!`, and each `CHECKSUMS` entry takes the sha256 of its own prebuild. -`bundle install` then fetches the one patched platform gem of the machine it runs on and -compiles nothing, in frozen and deployment mode too. - -When the patch has no prebuild for one of the locked platforms, the gem is skipped with -`redirect_gem_platform_unsupported` and neither file changes: a machine of that platform would -otherwise be sent to a registry that has no gem for it. Remove the platform from the lock if the -project does not need it (`bundle lock --remove-platform `) and re-run, or wait for the -prebuild. +For such a gem the patch registry lists every platform gem of the version: a patched platform +gem where one is built (the upstream platform gem with the patch's files replaced, under the same +file name), and upstream's own gem for a platform that has none yet, which the registry hands on +unchanged. So the scan moves the gem as soon as one platform the lock names has a patched build. +The Gemfile edit is the same as for any gem, every platform entry moves to the patch registry's +`GEM` section with its dependency lines (and a plain `nokogiri (1.18.10)` entry beside them moves +too), `DEPENDENCIES` gains the `!`, and each `CHECKSUMS` entry takes the sha256 the registry +serves for that build: the patched gem's where there is one, and the upstream gem's, which the +entry already had, where there is none. `bundle install` then fetches the gem of the machine it +runs on and compiles nothing, in frozen and deployment mode too. A machine of a patched platform +installs the patched gem; any other installs what it installed before. + +The run says which is which in one line, and warns about nothing: + +```text +nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet) +``` + +In `--json`, each patched build is one `applied` event under its own patch +(`pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu`, with the gem's patch in `details.gemFix`), +and a build that keeps upstream's gem is an event with `errorCode: "gem_upstream_build_kept"` +that `summary` does not count. Totals and the rollout budget count the gem as one package. + +VEX follows the builds. The scan's `--vex` attests each patched build under its own patch and +writes an `affected` statement for a build that keeps upstream's gem. A later `socket-patch vex` +reads the lock and asks the patch service which builds are patched (one request per such gem, +and one more for a lock with no `CHECKSUMS` section): a build is attested as patched only when +the lock installs exactly that patch's gem. When it cannot tell (`--offline`, a failed request, +a lock older than what the patch service lists now) it leaves the build out and says so with +`vex_gem_build_unknown`, naming what to run. + +The registry URL the scan writes names the registry as it stood (`…/s//`). When a patched +build is published for another platform, the next scan is given a URL with another key: it +refreshes the URL in both files, rewrites the one checksum that changed, and says what is new: + +```text +nokogiri 1.18.10: now also patched for arm64-darwin; already patched for x86_64-linux-gnu +``` + +Adding a platform is Bundler's own step: `bundle lock --add-platform ` resolves the gem +from its one source, the patch registry, and adds that platform's entry and checksum. The next +scan reports the new build. + +Two cases leave the gem as it is, with one plain line and no warning. Both pass by themselves, and +a later scan moves the gem: + +- no platform the lock names has a patched build yet (`redirect_gem_no_patched_build`). Moving the + gem would gain nothing, so it stays on its upstream registry; +- the patch registry does not list a platform the lock names yet (`redirect_gem_build_pending`). + Its patched build is still being made. + +The gem is skipped with the warning `redirect_gem_platform_unsupported` only when the patch covers +the ruby gem alone, or the lock is the merged layout of a Bundler older than 2.2. **Undoing it.** `rollback` and `remove` take the option (or the added line) off again and restore the lock: the pair is the pre-scan pair byte for byte, with LF or CRLF line endings. @@ -5100,8 +5139,8 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| -| Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed from the patched platform gem the registry serves for that platform, with nothing to compile; it is skipped with `redirect_gem_platform_unsupported` only while the patch has no patched build for one of the locked platforms. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from prebuilt patched platform gems. The patch service builds one for each platform, and the vendored directory holds each of them unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. Every platform in the lock needs one. While the patch service has none for one of them the gem is skipped with `vendor_prebuilt_platform_pending`, which names the platforms that have none: the run does not fail, nothing is written, a patch that is already vendored stays in place, and a later run vendors the gem once every platform has one. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the prebuilt binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed through the patch registry with nothing to compile: the patched platform gem where the platform has one, upstream's own gem where it has none yet. The gem moves as soon as one locked platform has a patched build, and the run names the platforms that are patched and the ones that keep upstream's gem. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. Every platform in the lock needs a patched build. While one has none the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) names the platforms without a patched build and says that hosted mode can patch the others now. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once every platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, From f11e926c7a7f3e7b830947a6f53596d4f5089493 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 26 Nov 2026 00:38:40 -0500 Subject: [PATCH 026/120] Keep the grant URL out of the Referer of a followed download redirect A serve URL holds its grant token in the path, and the client that downloads from one follows redirects: a patch registry may answer the file of a gem it has no patched build of with a redirect to the upstream registry. The HTTP client set a `Referer` on the redirected request, so the host it was sent to received the whole serve URL, token included. The plain client sets no `Referer`. The redirect is still followed. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/api/client.rs | 53 +++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index 3d56a9d419..9428cb8b03 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -2665,6 +2665,10 @@ fn api_client(api_token: Option<&str>, timeouts: &ApiTimeouts) -> reqwest::Clien /// public-proxy POST and the grant-tokenized serve GETs, where sending the /// Socket bearer would leak it to a third party. Bounded by `timeouts`, /// like the authenticated client. +/// +/// A serve URL holds its grant token in the path, and a serve route can +/// answer with a redirect to another host, which the client follows. No +/// `Referer` is set on the way: it would hand that URL to the next host. fn plain_client(timeouts: &ApiTimeouts) -> reqwest::Client { let mut headers = HeaderMap::new(); headers.insert( @@ -2672,7 +2676,11 @@ fn plain_client(timeouts: &ApiTimeouts) -> reqwest::Client { HeaderValue::from_static(USER_AGENT_VALUE), ); timeouts - .apply(crate::utils::http::client_builder().default_headers(headers)) + .apply( + crate::utils::http::client_builder() + .default_headers(headers) + .referer(false), + ) .build() .expect("failed to build plain reqwest client") } @@ -5905,6 +5913,49 @@ mod vendor_package_tests { } } + /// A serve URL can answer with a redirect to another host (a patch + /// registry may send a client to the upstream registry for a gem it + /// has no patched build of). The download follows it, and the request + /// to that host carries no `Referer`: the URL it came from holds the + /// grant token. + #[tokio::test] + async fn download_artifact_follows_a_redirect_without_naming_the_grant_url() { + const GRANT: &str = "grant-level"; + let registry = MockServer::start().await; + let elsewhere = MockServer::start().await; + let file = format!("/patch-registry/gem/{GRANT}/u/s/4f/gems/a-1.0.0-java.gem"); + Mock::given(method("GET")) + .and(path(file.as_str())) + .respond_with(ResponseTemplate::new(302).insert_header( + "Location", + format!("{}/gems/a.gem", elsewhere.uri()).as_str(), + )) + .mount(®istry) + .await; + Mock::given(method("GET")) + .and(path("/gems/a.gem")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"upstream".to_vec())) + .mount(&elsewhere) + .await; + let client = auth_client(registry.uri()); + let bytes = client + .download_artifact(&format!("{}{file}", registry.uri())) + .await + .expect("the redirect is followed"); + assert_eq!(bytes, b"upstream"); + let received = elsewhere.received_requests().await.unwrap_or_default(); + let [request] = received.as_slice() else { + panic!("one request to the other host: {received:?}"); + }; + assert!( + request.headers.get("referer").is_none(), + "the other host is told where the request came from: {:?}", + request.headers + ); + let sent = format!("{:?} {}", request.headers, request.url); + assert!(!sent.contains(GRANT), "the grant token: {sent}"); + } + /// A promised secondary that 404s must ERROR ("artifact not found"), /// and a still-building 408 maps to "artifact still building" — the /// arms encoding the no-soft-skip policy for promised artifacts. From 01b0ddc46d44a16596d88c1e94bb203c3b44945d Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 26 Nov 2026 00:43:07 -0500 Subject: [PATCH 027/120] State a gem build `vex` cannot tell as affected, and call the run a success For a gem a Bundler lock takes from a patch registry as platform builds, a build whose state could not be told (the lock pins another archive than the patch service lists, the reference or the registry's index could not be read, `--offline`) was left out of the document under a `skipped` event, the run became a partial failure, and it exited 1 when nothing else was attested. A reader of the document could not tell such a build from one the project does not have, and a scanner fed the document kept no statement about it. `vex` states what it knows. Such a build is in the document as `affected`, with an action statement that says it could not be shown that the lockfile installs a patched build for that platform, why, and what settles it. It names no patch. The run's status and exit code are what they are without it: `vex_gem_build_unknown` stays the warning (one per gem and reason) and becomes the code of the build's uncounted event, shaped like the one of a build on upstream's gem. The line for a person says `not shown patched for `. `--offline` with no local record is as it was: with no record there is no vulnerability to state anything of, and the gem is omitted as `record_unavailable`. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/vex.rs | 100 ++-- .../src/commands/vex_sources.rs | 545 ++++++++++++------ .../tests/e2e_redirect_gem_platform_builds.rs | 294 +++++++--- crates/socket-patch-core/src/vex/build.rs | 24 +- crates/socket-patch-core/src/vex/verify.rs | 3 +- 5 files changed, 648 insertions(+), 318 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index eac1d2dbe7..41f9196217 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -339,10 +339,11 @@ pub(crate) struct VexWriteSummary { pub statements: usize, /// How many of them say `affected`: of a package Bazel builds without /// its patch ([`unbuilt_by_bazel`]), or of a gem build the lockfile - /// takes from a patch registry as upstream's own gem - /// ([`GemBuildView::kept_upstream`]). + /// takes from a patch registry that is not shown patched: upstream's + /// own gem, or a build of which nothing shows what the lock installs + /// ([`GemBuildView::not_patched`]). /// - /// [`GemBuildView::kept_upstream`]: crate::commands::vex_sources::GemBuildView::kept_upstream + /// [`GemBuildView::not_patched`]: crate::commands::vex_sources::GemBuildView::not_patched pub affected: usize, /// The builds the document names in place of a gem (a gem vendored as /// platform gems, or taken from its patch registry as platform @@ -1568,8 +1569,9 @@ async fn generate_vex( // A gem vendored as platform gems, or taken from its patch registry as // platform builds, was judged above as the one copy or pin it is; the // document names each of its builds: a patched one under the patch - // that built it, and a hosted one the lock installs as upstream's own - // gem as affected (see `GemBuildView`). + // that built it, and a hosted one that is not shown patched as + // affected: one the lock installs as upstream's own gem, and one of + // which nothing shows what the lock installs (see `GemBuildView`). let mut affected = affected; let mut redirected = plan.redirected.clone(); let gem_builds = crate::commands::vex_sources::GemBuildView::of(&plan); @@ -1579,7 +1581,7 @@ async fn generate_vex( builds.expand(&mut outcome.code_not_present); builds.expand(&mut redirected); builds.expand_noted(&mut affected); - affected.extend(builds.kept_upstream().iter().cloned()); + affected.extend(builds.not_patched().iter().cloned()); } let manifest = gem_builds.as_ref().map_or(manifest, |builds| builds.view()); let redirected: &[String] = &redirected; @@ -2245,18 +2247,20 @@ fn vendored_out_of_sync_detail(purl: &str, copies: &[&Path], notes: &str) -> Str /// run told apart (the gems of [`Plan::hosted_gems`] the plan worked out), /// one line per gem, in the words of the hosted scan's own line: /// `nokogiri 1.19.3: patched for x86_64-linux-gnu; upstream gem kept for -/// arm64-darwin (no patched build yet)`. A build the document leaves out -/// (nothing shows what the lock installs for it, or the gem's installed -/// copy did not verify) is `not attested for `: the run's -/// warnings say why. The ruby-platform gem, where the lock names it beside -/// the platform builds, is the platform `ruby`. `applied` are the purls -/// the document attests as patched. +/// arm64-darwin (no patched build yet)`. A build of which nothing shows +/// what the lock installs is `not shown patched for `: the +/// document says `affected` of it, and the run's warning says why. A +/// build the document leaves out (the lock installs it patched, and the +/// gem's installed copy did not verify) is `not attested for `. +/// The ruby-platform gem, where the lock names it beside the platform +/// builds, is the platform `ruby`. `applied` are the purls the document +/// attests as patched. fn gem_build_lines(plan: &Plan, applied: &[String]) -> Vec { use socket_patch_core::vex::gem_builds::GemBuildState; - let attested = |build: &HostedGemBuild| { - matches!(build.state, GemBuildState::Patched { .. }) && applied.contains(&build.purl) - }; + let patched = |build: &HostedGemBuild| matches!(build.state, GemBuildState::Patched { .. }); + let attested = |build: &HostedGemBuild| patched(build) && applied.contains(&build.purl); let kept = |build: &HostedGemBuild| build.state == GemBuildState::Upstream; + let unshown = |build: &HostedGemBuild| build.unshown.is_some(); plan.hosted_gems .values() .filter(|gem| gem.resolved) @@ -2277,9 +2281,10 @@ fn gem_build_lines(plan: &Plan, applied: &[String]) -> Vec { platforms(&kept), " (no patched build yet)", ), + ("not shown patched for", platforms(&unshown), ""), ( "not attested for", - platforms(&|build| !attested(build) && !kept(build)), + platforms(&|build| patched(build) && !attested(build)), "", ), ]; @@ -3027,10 +3032,6 @@ fn omission_phrase(reason: &str) -> &'static str { "another package bundles its own copy, which no Socket wiring reaches (the \ warning above names it)" } - GEM_BUILD_UNKNOWN => { - "it is not shown whether the lockfile installs a patched build for this platform \ - (the warning above says why, and what to run)" - } _ => "the patch could not be verified", } } @@ -3299,31 +3300,37 @@ fn emit_envelope_success( if let Some(build) = build { gem_build_details(build, &mut details); } + // A gem build that is not shown patched: on upstream's + // gem (reported as the hosted run reports it), or one of + // which nothing shows what the lock installs. Nothing was + // skipped and nothing failed, so its event is counted + // nowhere. + let not_patched = build.and_then(|build| { + let platform = build.platform.as_deref().unwrap_or_default(); + match &build.unshown { + Some(why) => Some((GEM_BUILD_UNKNOWN, why.clone())), + None if build.kept_upstream => Some(( + GEM_UPSTREAM_BUILD_KEPT, + gem_upstream_build_kept_detail(platform), + )), + None => None, + } + }); // A package the document says is affected is not reported // as verified, nor counted as such: it is skipped, like a // patch the document leaves out, under its own code. - let event = match st.status { - Status::Affected => match build.filter(|build| build.kept_upstream) { - // A gem build on upstream's gem: nothing was - // skipped and nothing failed, that platform is as - // it was. Reported as the hosted run reports it, - // and counted nowhere. - Some(build) => { - let platform = build.platform.as_deref().unwrap_or_default(); - let event = PatchEvent::new(PatchAction::Skipped, sub.id.clone()) - .with_reason( - GEM_UPSTREAM_BUILD_KEPT, - gem_upstream_build_kept_detail(platform), - ); - env.events.push(event.with_details(details)); - continue; - } - None => { - unbuilt = true; - PatchEvent::new(PatchAction::Skipped, sub.id.clone()) - .with_reason(BAZEL_NOT_IN_BUILD, AFFECTED_REASON) - } - }, + let event = match (st.status, not_patched) { + (Status::Affected, Some((code, reason))) => { + let event = PatchEvent::new(PatchAction::Skipped, sub.id.clone()) + .with_reason(code, reason); + env.events.push(event.with_details(details)); + continue; + } + (Status::Affected, None) => { + unbuilt = true; + PatchEvent::new(PatchAction::Skipped, sub.id.clone()) + .with_reason(BAZEL_NOT_IN_BUILD, AFFECTED_REASON) + } _ => PatchEvent::new(PatchAction::Verified, sub.id.clone()), }; env.record(event.with_details(details)); @@ -3575,19 +3582,18 @@ mod tests { &[ failed( "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin", - GEM_BUILD_UNKNOWN + "not_applied" ), failed( "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", - GEM_BUILD_UNKNOWN + "not_applied" ), ], false ), [ - "Warning: omitting 2 packages from VEX: it is not shown whether the lockfile \ - installs a patched build for this platform (the warning above says why, and what \ - to run) (vex_gem_build_unknown): nokogiri@1.18.10 (arm64-darwin), nokogiri@1.18.10 \ + "Warning: omitting 2 packages from VEX: the patched files still hold the original \ + content (not_applied): nokogiri@1.18.10 (arm64-darwin), nokogiri@1.18.10 \ (x86_64-linux-gnu)" ] ); diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index bccdf1a1b7..ca31afae3b 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -81,9 +81,10 @@ //! lock and at most two requests per gem (the gem patch's reference, and //! the index of the lock's registry where the lock has no `CHECKSUMS`). //! The gem is judged as its one pin, and the document then names each -//! build ([`GemBuildView`]): a patched one under its own patch, one on -//! upstream's gem as affected, and one of which neither is shown not at -//! all (`vex_gem_build_unknown`). +//! build ([`GemBuildView`]): a patched one under its own patch, and one on +//! upstream's gem, or of which neither is shown, as affected. The latter +//! is no failure of the run: the statement says why and what settles it, +//! and one warning names the gem (`vex_gem_build_unknown`). use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; @@ -340,11 +341,13 @@ pub(crate) const GO_WORKSPACE_OVERRIDE: &str = "go_workspace_override"; /// package to the artifact; `vex::Unattested`, /// `UnattestedKind::LockNotRead`). const NOTE_LOCK_NOT_READ: &str = "vex_lock_not_read"; -/// Omission tag and note: a platform build of a gem the lockfile takes from -/// a patch registry, of which nothing shows whether the lock installs a -/// patched build or upstream's own gem ([`GemBuildState::Unknown`]). The -/// build is left out of the document, never attested on the strength of -/// the gem's one pin. +/// Note, and code of the uncounted event: a platform build of a gem the +/// lockfile takes from a patch registry, of which nothing shows whether the +/// lock installs a patched build or upstream's own gem +/// ([`GemBuildState::Unknown`]). The document says `affected` of the build, +/// with why and what settles it ([`GemBuildUnshown`]): it is never attested +/// on the strength of the gem's one pin, and never left out. Not an +/// omission: the run's status and exit code are what they are without it. pub(crate) const GEM_BUILD_UNKNOWN: &str = "vex_gem_build_unknown"; /// Largest compact-index document read for a gem's builds @@ -526,20 +529,23 @@ fn gate_unattested( /// platforms and upstream's own gem for the others, so the pin does not /// say that every locked build is patched ([`Plan::hosted_gems`]). The /// document names each locked build: a patched one under its own patch, -/// like a vendored one; one on upstream's gem as `affected` -/// ([`Self::kept_upstream`]), because the lock is known to install it -/// without the patch; and one of which neither is shown not at all (the -/// plan left it out, [`GEM_BUILD_UNKNOWN`]). The record of every build -/// stays in the view, so that no statement names a form of the gem that -/// also stands for a build the document does not call patched. +/// like a vendored one, and every other one as `affected` +/// ([`Self::not_patched`]). That is a build on upstream's gem, which the +/// lock is known to install without the patch, and a build of which +/// neither is shown ([`GEM_BUILD_UNKNOWN`]): nothing shows that the lock +/// installs a patched build for it, so the document does not say it does, +/// and says why and what settles it. The record of every build stays in +/// the view, so that no statement names a form of the gem that also +/// stands for a build the document does not call patched. pub(crate) struct GemBuildView { /// The record view with each such gem's key replaced by its builds' /// purls. view: PatchManifest, /// View purl of the gem → the purls of its builds that are patched. platform_gems: BTreeMap>, - /// The hosted builds on upstream's gem, each with what to do about it. - kept_upstream: Vec<(String, String)>, + /// The hosted builds that are not shown patched, each with what to do + /// about it. + not_patched: Vec<(String, String)>, /// Every build the view names in place of a gem, by purl. builds: BTreeMap, } @@ -554,6 +560,9 @@ pub(crate) struct GemBuildInfo { pub platform: Option, /// A hosted build the patch registry serves as upstream's own gem. pub kept_upstream: bool, + /// A hosted build of which nothing shows what the lock installs: why, + /// as its event says it ([`GemBuildUnshown::reason`]). + pub unshown: Option, } /// The action statement of a hosted gem build on upstream's gem @@ -596,7 +605,7 @@ impl GemBuildView { } let mut view = plan.view.clone(); let mut platform_gems = BTreeMap::new(); - let mut kept_upstream = Vec::new(); + let mut not_patched = Vec::new(); let mut builds = BTreeMap::new(); for (key, entry, record) in vendored { view.patches.remove(key); @@ -618,6 +627,7 @@ impl GemBuildView { gem_fix: entry.uuid.clone(), platform: Some(built.platform.clone()), kept_upstream: false, + unshown: None, }, ); purl @@ -646,15 +656,20 @@ impl GemBuildView { }, ); let upstream = build.state == GemBuildState::Upstream; + let unshown = build.unshown.as_ref().zip(build.platform.as_deref()); match (&build.state, build.platform.as_deref()) { (GemBuildState::Patched { .. }, _) => patched.push(build.purl.clone()), - (GemBuildState::Upstream, Some(platform)) => kept_upstream.push(( + (GemBuildState::Upstream, Some(platform)) => not_patched.push(( build.purl.clone(), upstream_build_action(platform, &gem.gem_fix), )), - // Left out by the plan; the ruby-platform gem of a - // patch's registry is never upstream's. - (GemBuildState::Upstream, None) | (GemBuildState::Unknown(_), _) => {} + (GemBuildState::Unknown(_), Some(_)) => { + let action = unshown.map(|(why, platform)| why.action(platform)); + not_patched.extend(action.map(|action| (build.purl.clone(), action))); + } + // The ruby-platform gem of a patch's registry is the + // gem's patch, never upstream's nor unknown. + (GemBuildState::Upstream | GemBuildState::Unknown(_), None) => {} } builds.insert( build.purl.clone(), @@ -662,6 +677,7 @@ impl GemBuildView { gem_fix: gem.gem_fix.clone(), platform: build.platform.clone(), kept_upstream: upstream, + unshown: unshown.map(|(why, platform)| why.reason(platform)), }, ); } @@ -670,7 +686,7 @@ impl GemBuildView { Some(Self { view, platform_gems, - kept_upstream, + not_patched, builds, }) } @@ -680,10 +696,12 @@ impl GemBuildView { &self.view } - /// The hosted builds the lock installs as upstream's own gem, each with - /// its action statement: what the document says `affected` of. - pub(crate) fn kept_upstream(&self) -> &[(String, String)] { - &self.kept_upstream + /// The hosted builds that are not shown patched, each with its action + /// statement: what the document says `affected` of. A build the lock + /// installs as upstream's own gem, and one of which nothing shows what + /// the lock installs. + pub(crate) fn not_patched(&self) -> &[(String, String)] { + &self.not_patched } /// Every build the view names in place of a gem, by purl. @@ -756,6 +774,115 @@ pub(crate) struct HostedGemBuild { pub purl: String, /// What the lock installs for it. pub state: GemBuildState, + /// For a build in [`GemBuildState::Unknown`]: why nothing shows what + /// the lock installs for it. + pub unshown: Option, +} + +/// Why nothing shows whether a lock installs a patched build or upstream's +/// own gem for a platform build of a hosted gem +/// ([`GemBuildState::Unknown`]), and what settles it. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum GemBuildUnshown { + /// `--offline` forbids asking the patch service for the gem's builds. + Offline, + /// The reference request failed; its error, safe to print. + Request(String), + /// The patch service gave no list of the patch's builds; why. + NoList(String), + /// The lock has no `CHECKSUMS` entry for the build, and the index of + /// its registry could not be read; the error, safe to print. + IndexUnread(String), + /// Neither the lock's `CHECKSUMS` nor the index of its registry names + /// an archive for the build. + Unpinned, + /// The list does not name the build's platform. + Unlisted, + /// The lock installs another archive than the list names: the list is + /// of a later state of the registry than the one the lock names. + Differs, +} + +impl From for GemBuildUnshown { + fn from(why: GemBuildUnknown) -> Self { + match why { + GemBuildUnknown::Unpinned => GemBuildUnshown::Unpinned, + GemBuildUnknown::Unlisted => GemBuildUnshown::Unlisted, + GemBuildUnknown::Differs => GemBuildUnshown::Differs, + } + } +} + +impl GemBuildUnshown { + /// The reason in words, said of `them` (`it` for one build, `them` + /// for several). `detail` adds the error of a read that failed: the + /// run's warning carries it, the document and the events do not. + fn why(&self, them: &str, detail: bool) -> String { + let failed = |what: String, error: &str| match detail { + true => format!("{what}: {error}"), + false => what, + }; + match self { + GemBuildUnshown::Offline => "--offline forbids asking the patch API".to_string(), + GemBuildUnshown::Request(error) => { + failed("the patch API request failed".to_string(), error) + } + GemBuildUnshown::NoList(why) => why.clone(), + GemBuildUnshown::IndexUnread(error) => failed( + format!( + "the lockfile has no CHECKSUMS entry for {them}, and its registry's index \ + could not be read" + ), + error, + ), + GemBuildUnshown::Unpinned => format!( + "neither the lockfile's CHECKSUMS nor its registry's index names an archive for \ + {them}" + ), + GemBuildUnshown::Unlisted => { + format!("the patch registry does not list {them} now") + } + GemBuildUnshown::Differs => format!( + "the lockfile installs another archive for {them} than the patch registry lists \ + now" + ), + } + } + + /// What to run to settle it: the request again where one failed, + /// without `--offline` where that forbade it, and the scan that brings + /// the lock up to date where the lock and the patch registry disagree. + fn remedy(&self) -> &'static str { + match self { + GemBuildUnshown::Offline => GEM_BUILD_ONLINE, + GemBuildUnshown::Request(_) | GemBuildUnshown::IndexUnread(_) => GEM_BUILD_RETRY, + GemBuildUnshown::NoList(_) + | GemBuildUnshown::Unpinned + | GemBuildUnshown::Unlisted + | GemBuildUnshown::Differs => GEM_BUILD_RESCAN, + } + } + + /// The action statement of the build for `platform`: what could not be + /// shown, why, and what settles it. It names no patch: none is shown + /// to be in what the lock installs. + fn action(&self, platform: &str) -> String { + format!( + "It could not be shown that the lockfile installs a patched build of this gem for \ + {platform} ({}), so it is stated as affected. {}", + self.why("it", false), + self.remedy() + ) + } + + /// What the uncounted [`GEM_BUILD_UNKNOWN`] event of the build for + /// `platform` says. + fn reason(&self, platform: &str) -> String { + format!( + "not shown patched for {platform}: {}", + self.why("it", false) + ) + } } impl HostedGem { @@ -776,6 +903,10 @@ impl HostedGem { Some(platform) => format!("{base}?platform={platform}"), None => key.to_string(), }, + unshown: match (&state, &platform) { + (GemBuildState::Unknown(why), Some(_)) => Some(GemBuildUnshown::from(*why)), + _ => None, + }, platform, state, }) @@ -1754,18 +1885,6 @@ async fn fetch_records( out } -/// Why nothing is known of the platform builds of a gem -/// ([`resolve_hosted_gems`]). -#[derive(Debug, Clone, PartialEq, Eq)] -enum BuildsUnread { - /// `--offline` forbids asking. - Offline, - /// The reference request failed; its error, safe to print. - Request(String), - /// The patch service gave no list of the patch's builds; why. - NoList(String), -} - /// A hosted gem whose builds the plan works out. struct PendingGem { /// Its view purl. @@ -1792,36 +1911,36 @@ impl PendingGem { /// What to run for a build whose state a later run can read. const GEM_BUILD_RETRY: &str = "Run `socket-patch vex` again to attest each build."; +/// What to run for a build `--offline` kept the run from asking about. +const GEM_BUILD_ONLINE: &str = "Run `socket-patch vex` without --offline to attest each build."; /// What to run for a build the lock and the patch registry disagree about. const GEM_BUILD_RESCAN: &str = "Run `socket-patch scan --mode hosted` to bring the lockfile up \ to date, then `socket-patch vex` again."; -/// The [`GEM_BUILD_UNKNOWN`] note of the gem at `key`: the builds for -/// `platforms` are left out, `why`, and `remedy` is what to run. -fn gem_build_note( - key: &str, - gem_fix: &str, - platforms: &[&str], - why: &str, - remedy: &str, -) -> PlanNote { +/// The [`GEM_BUILD_UNKNOWN`] note of the gem at `key`: nothing shows what +/// the lock installs for the builds of `platforms`, for the reason `why`, +/// so the document says `affected` of them. +fn gem_build_note(key: &str, gem_fix: &str, platforms: &[&str], why: &GemBuildUnshown) -> PlanNote { let one = platforms.len() == 1; + let them = if one { "it" } else { "them" }; PlanNote { code: GEM_BUILD_UNKNOWN, detail: format!( "{key}: the lockfile takes its {} for {} from the registry of Socket patch {gem_fix}, \ which serves a patched build for some platforms and upstream's own gem for the \ - others. Which it is for {} could not be told ({why}), so {} not attested. {remedy}", + others. Which it is for {} could not be told ({}), so the VEX document states \ + {them} as affected. {}", if one { "build" } else { "builds" }, platforms.join(", "), if one { "this one" } else { "these" }, - if one { "it is" } else { "they are" }, + why.why(them, true), + why.remedy(), ), } } -/// Work out [`Plan::hosted_gems`], and leave out the builds of which -/// nothing shows what the lock installs. +/// Work out [`Plan::hosted_gems`], and why nothing shows what the lock +/// installs for a build where nothing does. /// /// A gem `in_run` reports (a pin of the hosted run this plan is part of) /// takes its builds from there. Any other hosted gem is read from the lock @@ -1833,9 +1952,11 @@ fn gem_build_note( /// ([`gem_index`]). /// /// Under `--offline`, and where a request fails or the answers do not -/// settle a build, nothing is known of it: the build is omitted -/// ([`GEM_BUILD_UNKNOWN`]) and a note names the gem and what to run, once -/// per gem and reason. The ruby-platform gem a lock names beside the +/// settle a build, nothing is known of it: the build keeps the reason +/// ([`HostedGemBuild::unshown`]), which the document states it as +/// affected with, and a note names the gem and what to run, once per gem +/// and reason ([`GEM_BUILD_UNKNOWN`]). Nothing is gated: the run is no +/// less a success for it. The ruby-platform gem a lock names beside the /// platform builds is the gem's patch by the lock's wiring, whatever the /// requests say. async fn resolve_hosted_gems( @@ -1902,7 +2023,7 @@ async fn resolve_hosted_gems( // What each patch's reference lists, and what each lock's registry // serves where the lock does not say. let (lists, indexes) = if common.offline { - let unread = |_: &PendingGem| Err(BuildsUnread::Offline); + let unread = |_: &PendingGem| Err(GemBuildUnshown::Offline); let lists: Vec<_> = pending.iter().map(unread).collect(); (lists, pending.iter().map(|_| None).collect()) } else { @@ -1922,69 +2043,32 @@ async fn resolve_hosted_gems( let served = index.as_ref().and_then(|read| read.as_deref().ok()); let states = gem_build_states(&gem.version, &gem.pins, &gem.uuid, &listed, served); let builds = gem.pins.iter().map(|pin| pin.platform.clone()).zip(states); - let Some(hosted) = HostedGem::of(&gem.key, &gem.uuid, builds, true) else { + let Some(mut hosted) = HostedGem::of(&gem.key, &gem.uuid, builds, true) else { continue; }; - let mut unknown: BTreeMap> = BTreeMap::new(); + // What the reads say of a build beyond its state: with no list, + // why there is none; with no index, the error of that read. + for build in &mut hosted.builds { + let Some(why) = build.unshown.take() else { + continue; + }; + build.unshown = Some(match (&unread, why, &index) { + (Some(unread), _, _) => unread.clone(), + (None, GemBuildUnshown::Unpinned, Some(Err(error))) => { + GemBuildUnshown::IndexUnread(error.clone()) + } + (None, why, _) => why, + }); + } + let mut unshown: BTreeMap<&GemBuildUnshown, Vec<&str>> = BTreeMap::new(); for build in &hosted.builds { - if let (GemBuildState::Unknown(why), Some(platform)) = - (&build.state, build.platform.as_deref()) - { - plan.gated.push(failed(&build.purl, GEM_BUILD_UNKNOWN)); - unknown.entry(*why).or_default().push(platform); + if let (Some(why), Some(platform)) = (&build.unshown, build.platform.as_deref()) { + unshown.entry(why).or_default().push(platform); } } - let note = |platforms: &[&str], why: &str, remedy: &str| { - gem_build_note(&gem.key, &gem.uuid, platforms, why, remedy) - }; - if let Some(unread) = unread { - let platforms: Vec<&str> = unknown.into_values().flatten().collect(); - let (why, remedy) = match &unread { - BuildsUnread::Offline => ( - "--offline forbids asking the patch API".to_string(), - "Run `socket-patch vex` without --offline to attest each build.", - ), - BuildsUnread::Request(error) => ( - format!("the patch API request failed: {error}"), - GEM_BUILD_RETRY, - ), - BuildsUnread::NoList(why) => (why.clone(), GEM_BUILD_RESCAN), - }; - if !platforms.is_empty() { - plan.notes.push(note(&platforms, &why, remedy)); - } - } else { - for (why, platforms) in unknown { - let them = if platforms.len() == 1 { "it" } else { "them" }; - let (why, remedy) = match (why, &index) { - (GemBuildUnknown::Unpinned, Some(Err(error))) => ( - format!( - "the lockfile has no CHECKSUMS entry for {them}, and its registry's \ - index could not be read: {error}" - ), - GEM_BUILD_RETRY, - ), - (GemBuildUnknown::Unpinned, _) => ( - format!( - "neither the lockfile's CHECKSUMS nor its registry's index names an \ - archive for {them}" - ), - GEM_BUILD_RESCAN, - ), - (GemBuildUnknown::Unlisted, _) => ( - format!("the patch registry does not list {them} now"), - GEM_BUILD_RESCAN, - ), - (GemBuildUnknown::Differs, _) => ( - format!( - "the lockfile installs another archive for {them} than the patch \ - registry lists now" - ), - GEM_BUILD_RESCAN, - ), - }; - plan.notes.push(note(&platforms, &why, remedy)); - } + for (why, platforms) in unshown { + plan.notes + .push(gem_build_note(&gem.key, &gem.uuid, &platforms, why)); } plan.hosted_gems.insert(gem.key.clone(), hosted); } @@ -2001,7 +2085,7 @@ async fn read_gem_builds( gems: &[PendingGem], notes: &mut Vec, ) -> ( - Vec, BuildsUnread>>, + Vec, GemBuildUnshown>>, Vec>>, ) { use socket_patch_core::utils::redact::redact_urls_in; @@ -2029,10 +2113,10 @@ async fn read_gem_builds( .release(); } } - let lists: Vec, BuildsUnread>> = gems + let lists: Vec, GemBuildUnshown>> = gems .iter() .map(|gem| match &references { - Err(error) => Err(BuildsUnread::Request( + Err(error) => Err(GemBuildUnshown::Request( redact_urls_in(&error.to_string()).into_owned(), )), Ok(references) => { @@ -2043,7 +2127,7 @@ async fn read_gem_builds( .and_then(|reference| reference.registry_override.as_ref()) .and_then(|registry| registry.identifiers.gem_builds.clone()) .ok_or_else(|| { - BuildsUnread::NoList( + GemBuildUnshown::NoList( match reference.map(|reference| reference.status.as_str()) { Some("granted" | "reused") => { "the patch API lists no builds for that patch" @@ -3567,6 +3651,25 @@ mod tests { } } + /// What the document made from `plan` says of the gem: the purls it + /// attests as patched, and each purl it says `affected` of with the + /// action statement. + fn gem_statements(plan: &Plan) -> (Vec, Vec<(String, String)>) { + let builds = GemBuildView::of(plan).expect("a gem locked as platform builds"); + let mut applied = vec![GEM.to_string()]; + builds.expand(&mut applied); + (applied, builds.not_patched().to_vec()) + } + + /// The action statement of a build for `platform` that is not shown + /// patched for the reason `why`, with what to run. + fn unshown_action(platform: &str, why: &str, remedy: &str) -> String { + format!( + "It could not be shown that the lockfile installs a patched build of this gem for \ + {platform} ({why}), so it is stated as affected. {remedy}" + ) + } + const REFERENCE: &str = "/v0/orgs/acme/patches/package"; const ONE_PATCHED: [(&str, &str, Option<&str>); 2] = [ ("arm64-darwin", ARM_UPSTREAM, None), @@ -3649,11 +3752,13 @@ mod tests { ); } - /// The index of the lock's registry cannot be read: the builds are - /// omitted, and one note names the gem, the reason and what to run. + /// The index of the lock's registry cannot be read: nothing shows what + /// the lock installs, so the document says `affected` of both builds + /// and names no patch for them. Nothing is gated, and one note names + /// the gem, the reason (with the error of the read) and what to run. #[tokio::test] #[serial_test::serial] - async fn an_unreadable_index_omits_the_builds_of_a_lock_without_checksums() { + async fn an_unreadable_index_states_the_builds_of_a_lock_without_checksums_as_affected() { let server = wiremock::MockServer::start().await; mount_gem_reference(&server, "4f", &ONE_PATCHED).await; let tmp = tempfile::tempdir().unwrap(); @@ -3671,13 +3776,7 @@ mod tests { gem_states(&plan), [(GEM_ARM, &unpinned), (GEM_LINUX, &unpinned)] ); - assert_eq!( - plan.gated, - [ - failed(GEM_ARM, GEM_BUILD_UNKNOWN), - failed(GEM_LINUX, GEM_BUILD_UNKNOWN) - ] - ); + assert!(plan.gated.is_empty(), "{:?}", plan.gated); let [note] = plan.notes.as_slice() else { panic!("one note for the gem: {:?}", plan.notes); }; @@ -3687,20 +3786,39 @@ mod tests { "{GEM}: the lockfile takes its builds for arm64-darwin, x86_64-linux-gnu from \ the registry of Socket patch {U1}" )) && note.detail.contains( - "the lockfile has no CHECKSUMS entry for them, and its registry's index could \ - not be read" - ) && note.detail.ends_with(GEM_BUILD_RETRY), + "(the lockfile has no CHECKSUMS entry for them, and its registry's index could \ + not be read: " + ) && note.detail.ends_with(&format!( + "), so the VEX document states them as affected. {GEM_BUILD_RETRY}" + )), "{}", note.detail ); assert!(!note.detail.contains("/tok/"), "the grant token: {note:?}"); + + // The document: both builds as affected, without the error. + let why = "the lockfile has no CHECKSUMS entry for it, and its registry's index could \ + not be read"; + let action = |platform: &str| unshown_action(platform, why, GEM_BUILD_RETRY); + assert_eq!( + gem_statements(&plan), + ( + Vec::new(), + vec![ + (GEM_ARM.to_string(), action("arm64-darwin")), + (GEM_LINUX.to_string(), action("x86_64-linux-gnu")), + ] + ) + ); } /// The reference is of a later registry than the lock names: it lists /// a patched build for a platform the lock still pins upstream's gem /// for. That build is not attested as patched, on either way of - /// telling what the lock installs; the build the lock does pin patched - /// is. The note sends the reader to the scan. + /// telling what the lock installs: the document says `affected` of it, + /// and names the patch the list gives for it nowhere. The build the + /// lock does pin patched is attested. Nothing is gated, and the note + /// sends the reader to the scan. #[tokio::test] #[serial_test::serial] async fn a_reference_newer_than_the_lock_attests_no_build_the_lock_pins_otherwise() { @@ -3731,7 +3849,7 @@ mod tests { ], "checksums: {checksums}" ); - assert_eq!(plan.gated, [failed(GEM_ARM, GEM_BUILD_UNKNOWN)]); + assert!(plan.gated.is_empty(), "{:?}", plan.gated); let [note] = plan.notes.as_slice() else { panic!("one note for the gem: {:?}", plan.notes); }; @@ -3739,12 +3857,28 @@ mod tests { note.detail.contains("its build for arm64-darwin from") && note.detail.contains( "(the lockfile installs another archive for it than the patch registry \ - lists now), so it is not attested." + lists now), so the VEX document states it as affected." ) && note.detail.ends_with(GEM_BUILD_RESCAN), "{}", note.detail ); + let (applied, affected) = gem_statements(&plan); + assert_eq!(applied, [GEM_LINUX], "checksums: {checksums}"); + assert_eq!( + affected, + [( + GEM_ARM.to_string(), + unshown_action( + "arm64-darwin", + "the lockfile installs another archive for it than the patch registry \ + lists now", + GEM_BUILD_RESCAN + ) + )], + "checksums: {checksums}" + ); + assert!(!affected[0].1.contains(ARM_UUID) && !affected[0].1.contains(U1)); assert_eq!( asked(&server).await.len(), if checksums { 1 } else { 2 }, @@ -3754,12 +3888,12 @@ mod tests { } /// `--offline`: nothing is asked, so nothing says which locked build - /// is patched. The platform builds are omitted with one note; the - /// ruby-platform gem the lock names beside them is the gem's patch by - /// the lock's wiring alone. + /// is patched. The document says `affected` of the platform builds, + /// with one note and nothing gated; the ruby-platform gem the lock + /// names beside them is the gem's patch by the lock's wiring alone. #[tokio::test] #[serial_test::serial] - async fn offline_attests_no_platform_build_and_asks_nothing() { + async fn offline_states_the_platform_builds_as_affected_and_asks_nothing() { let server = wiremock::MockServer::start().await; mount_gem_reference(&server, "4f", &ONE_PATCHED).await; let tmp = tempfile::tempdir().unwrap(); @@ -3784,13 +3918,7 @@ mod tests { (GEM_LINUX, &unlisted) ] ); - assert_eq!( - plan.gated, - [ - failed(GEM_ARM, GEM_BUILD_UNKNOWN), - failed(GEM_LINUX, GEM_BUILD_UNKNOWN) - ] - ); + assert!(plan.gated.is_empty(), "{:?}", plan.gated); let [note] = plan.notes.as_slice() else { panic!("one note for the gem: {:?}", plan.notes); }; @@ -3800,26 +3928,42 @@ mod tests { "{GEM}: the lockfile takes its builds for arm64-darwin, x86_64-linux-gnu from \ the registry of Socket patch {U1}, which serves a patched build for some \ platforms and upstream's own gem for the others. Which it is for these could \ - not be told (--offline forbids asking the patch API), so they are not attested. \ - Run `socket-patch vex` without --offline to attest each build." + not be told (--offline forbids asking the patch API), so the VEX document \ + states them as affected. Run `socket-patch vex` without --offline to attest \ + each build." ) ); assert_eq!(asked(&server).await, Vec::::new()); - // The document: the ruby-platform gem alone, under the gem's patch. - let builds = GemBuildView::of(&plan).expect("a gem locked as platform builds"); - let mut applied = vec![GEM.to_string()]; - builds.expand(&mut applied); - assert_eq!(applied, [GEM]); - assert!(builds.kept_upstream().is_empty()); + // The document: the ruby-platform gem under the gem's patch, and + // each platform build as affected. + let action = |platform: &str| { + unshown_action( + platform, + "--offline forbids asking the patch API", + GEM_BUILD_ONLINE, + ) + }; + assert_eq!( + gem_statements(&plan), + ( + vec![GEM.to_string()], + vec![ + (GEM_ARM.to_string(), action("arm64-darwin")), + (GEM_LINUX.to_string(), action("x86_64-linux-gnu")), + ] + ) + ); } /// The reference request fails, or the reference carries no list: no - /// build is attested, the note says which it was, and the registry is - /// not asked for an index nothing could be held against. + /// build is attested as patched and the document says `affected` of + /// each, the note says which it was (with the error of a failed + /// request, which the document leaves out), nothing is gated, and the + /// registry is not asked for an index nothing could be held against. #[tokio::test] #[serial_test::serial] - async fn a_failed_or_listless_reference_attests_no_platform_build() { + async fn a_failed_or_listless_reference_states_the_platform_builds_as_affected() { use wiremock::matchers::{method, path as wm_path}; use wiremock::{Mock, ResponseTemplate}; let no_list = serde_json::json!({ "results": { U1: { @@ -3832,15 +3976,17 @@ mod tests { }, }, }}}); - for (answer, why, remedy) in [ + for (answer, why, stated, remedy) in [ ( ResponseTemplate::new(500), - "the patch API request failed: ", + "(the patch API request failed: ", + "the patch API request failed", GEM_BUILD_RETRY, ), ( ResponseTemplate::new(200).set_body_json(no_list), "(the patch API lists no builds for that patch)", + "the patch API lists no builds for that patch", GEM_BUILD_RESCAN, ), ] { @@ -3861,14 +4007,7 @@ mod tests { &RunApiClient::new(), ) .await; - assert_eq!( - plan.gated, - [ - failed(GEM_ARM, GEM_BUILD_UNKNOWN), - failed(GEM_LINUX, GEM_BUILD_UNKNOWN) - ], - "{why}" - ); + assert!(plan.gated.is_empty(), "{why}: {:?}", plan.gated); let [note] = plan.notes.as_slice() else { panic!("one note for the gem: {:?}", plan.notes); }; @@ -3884,11 +4023,19 @@ mod tests { !asked.is_empty() && asked.iter().all(|path| path == REFERENCE), "{asked:?}" ); - // Nothing of the gem is in the document. - let builds = GemBuildView::of(&plan).expect("a gem locked as platform builds"); - let mut applied = vec![GEM.to_string()]; - builds.expand(&mut applied); - assert!(applied.is_empty() && builds.kept_upstream().is_empty()); + // The document: no build as patched, each as affected. + let action = |platform: &str| unshown_action(platform, stated, remedy); + assert_eq!( + gem_statements(&plan), + ( + Vec::new(), + vec![ + (GEM_ARM.to_string(), action("arm64-darwin")), + (GEM_LINUX.to_string(), action("x86_64-linux-gnu")), + ] + ), + "{why}" + ); } } @@ -4004,10 +4151,10 @@ mod tests { /// A gem a lock takes from its patch registry as platform builds is /// named per locked build. A patched build goes under its own patch, /// with the gem patch's vulnerabilities, wherever the gem was; a build - /// on upstream's gem is in no list of attested purls and is handed - /// over as affected, with what to do; a build nothing is known of is - /// in neither. All three keep a record in the view, so no statement - /// names a form of the gem that stands for an unpatched build too. + /// on upstream's gem, and a build nothing is known of, are in no list + /// of attested purls and are handed over as affected, each with what + /// to do. All three keep a record in the view, so no statement names a + /// form of the gem that stands for an unpatched build too. #[test] fn a_hosted_gem_is_attested_per_locked_build() { const JAVA: &str = "pkg:gem/nokogiri@1.18.10?platform=java"; @@ -4045,20 +4192,30 @@ mod tests { builds.expand(&mut attested); assert_eq!(attested[others..], [GEM, GEM_LINUX]); } - let [(purl, action)] = builds.kept_upstream() else { - panic!("one build on upstream's gem: {:?}", builds.kept_upstream()); - }; - assert_eq!(purl, GEM_ARM); assert_eq!( - action, - &format!( - "The patch registry has no patched build of this gem for arm64-darwin yet and \ - serves upstream's own gem for it, so an install on that platform is without \ - Socket patch {U1}. Run `socket-patch scan --mode hosted` again later: the \ - lockfile takes the patched build once it is published." - ) + builds.not_patched(), + [ + ( + GEM_ARM.to_string(), + format!( + "The patch registry has no patched build of this gem for arm64-darwin \ + yet and serves upstream's own gem for it, so an install on that \ + platform is without Socket patch {U1}. Run `socket-patch scan --mode \ + hosted` again later: the lockfile takes the patched build once it is \ + published." + ) + ), + ( + JAVA.to_string(), + unshown_action( + "java", + "the patch registry does not list it now", + GEM_BUILD_RESCAN + ) + ), + ] ); - let described: Vec<(&str, Option<&str>, bool)> = builds + let described: Vec<(&str, Option<&str>, bool, Option<&str>)> = builds .builds() .iter() .map(|(purl, build)| { @@ -4067,16 +4224,22 @@ mod tests { purl.as_str(), build.platform.as_deref(), build.kept_upstream, + build.unshown.as_deref(), ) }) .collect(); assert_eq!( described, [ - (GEM, None, false), - (GEM_ARM, Some("arm64-darwin"), true), - (JAVA, Some("java"), false), - (GEM_LINUX, Some("x86_64-linux-gnu"), false), + (GEM, None, false, None), + (GEM_ARM, Some("arm64-darwin"), true, None), + ( + JAVA, + Some("java"), + false, + Some("not shown patched for java: the patch registry does not list it now") + ), + (GEM_LINUX, Some("x86_64-linux-gnu"), false, None), ] ); } diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs index daf6dabe5a..a8261b42a9 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs @@ -32,8 +32,10 @@ //! the lock's registry only when the lock has no `CHECKSUMS`; //! * a build is attested by its patch only on the sha256 the lock installs //! for it: one the lock pins otherwise, or that nothing could be read -//! about (`--offline`, a failed request), is left out and the run says -//! what to run (`vex_gem_build_unknown`); +//! about (`--offline`, a failed request, an unreadable index), is said +//! `affected`, with why and what to run. That is no failure: the run +//! exits 0 as a success, and one warning names the gem +//! (`vex_gem_build_unknown`); //! * a gem locked as its ruby-platform gem alone is one pin, with no //! request of its own. @@ -1049,6 +1051,53 @@ fn upstream_statement(platform: &str) -> Said { } } +/// The statement of the build for `platform`, of which nothing shows what +/// the lock installs: `why`, and `remedy` is what to run. It names no +/// patch. `shared` when no locked build is attested, so that the form +/// Trivy reports the gem under stands for affected builds alone. +fn unshown_statement(platform: &str, why: &str, remedy: &str, shared: bool) -> Said { + let mut products: Vec = Vec::new(); + products.extend(shared.then(|| PURL.to_string())); + products.extend([grype_form(platform), build_purl(platform)]); + Said { + status: "affected", + packages: vec![build_purl(platform)], + products, + words: format!( + "It could not be shown that the lockfile installs a patched build of this gem for \ + {platform} ({why}), so it is stated as affected. {remedy}" + ), + } +} + +/// What to run for a build the lock and the patch registry disagree about, +/// and for one a later run can read. +const RESCAN: &str = "Run `socket-patch scan --mode hosted` to bring the lockfile up to date, \ + then `socket-patch vex` again."; +const RETRY: &str = "Run `socket-patch vex` again to attest each build."; + +/// The uncounted events of the builds `platforms`, of which nothing shows +/// what the lock installs, after asserting that each says `affected` and +/// that the run counts none of them and is a success. +fn unshown_events(env: &Value, platforms: &[&str]) -> Vec<(String, String, String)> { + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + (&env["summary"]["skipped"], &env["summary"]["failed"]), + (&json!(0), &json!(0)), + "a build that is not shown patched is counted nowhere: {env}" + ); + for event in env["events"].as_array().into_iter().flatten() { + if event["errorCode"] == "vex_gem_build_unknown" { + assert_eq!(event["details"]["status"], "affected", "{event}"); + assert_eq!(event["uuid"], Value::Null, "no patch is named: {event}"); + } + } + platforms + .iter() + .map(|platform| event("skipped", platform, "vex_gem_build_unknown")) + .collect() +} + /// A `--json` hosted scan with `--vex`: exit code, envelope and document. fn scan_vex(proj: &Path, api: &str) -> (i32, Value, Option) { let out = proj.join("out.vex.json"); @@ -1339,8 +1388,10 @@ async fn a_later_vex_tells_the_builds_of_a_checksummed_lock_apart_in_one_request /// A later `vex` over a lock with no `CHECKSUMS`: the lock installs what /// its own registry serves, so a SECOND request reads that registry's -/// index. Two requests, the same document. With the index unreadable the -/// builds are left out, and the run says why and what to run. +/// index. Two requests, the same document. With the index unreadable +/// nothing shows what the lock installs: both builds are in the document +/// as affected, the run exits 0 as a success, and one warning says why +/// (with the error of the read) and what to run. #[tokio::test(flavor = "multi_thread")] async fn a_later_vex_asks_the_registry_of_a_lock_without_checksums() { let server = MockServer::start().await; @@ -1372,18 +1423,29 @@ async fn a_later_vex_asks_the_registry_of_a_lock_without_checksums() { let index = format!("{}/", index_url(&api, Some(4))); let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, false); let out = vex(proj.path(), &api); - assert_eq!(out.code, Some(1), "{out}"); + assert_eq!(out.code, Some(0), "{out}"); + let why = "the lockfile has no CHECKSUMS entry for it, and its registry's index could not be \ + read"; assert_eq!( - out.envelope["error"]["code"], "no_applicable_patches", + said(out.doc()), + [ + unshown_statement(ARM, why, RETRY, true), + unshown_statement(LINUX, why, RETRY, true) + ], "{out}" ); - assert!(out.doc.is_none(), "{out}"); + assert!( + !out.doc().to_string().contains(LINUX_UUID) && !out.doc().to_string().contains(UUID), + "no patch is named for a build that is not shown patched: {out}" + ); assert_eq!( build_events(&out.envelope), - [ - event("skipped", ARM, "vex_gem_build_unknown"), - event("skipped", LINUX, "vex_gem_build_unknown") - ], + unshown_events(&out.envelope, &[ARM, LINUX]), + "{out}" + ); + assert_eq!( + out.envelope["events"][0]["reason"], + format!("not shown patched for {ARM}: {why}"), "{out}" ); assert_eq!( @@ -1394,10 +1456,11 @@ async fn a_later_vex_asks_the_registry_of_a_lock_without_checksums() { let detail = out.envelope["warnings"][0]["detail"].as_str().unwrap(); assert!( detail.contains( - "the lockfile has no CHECKSUMS entry for them, and its registry's index could not \ - be read" - ) && detail.ends_with("Run `socket-patch vex` again to attest each build.") - && !detail.contains(TOKEN), + "(the lockfile has no CHECKSUMS entry for them, and its registry's index could not \ + be read: " + ) && detail.ends_with(&format!( + "), so the VEX document states them as affected. {RETRY}" + )) && !detail.contains(TOKEN), "{detail}" ); } @@ -1405,10 +1468,11 @@ async fn a_later_vex_asks_the_registry_of_a_lock_without_checksums() { /// The reference a later `vex` gets is of a newer registry than the lock /// names: it lists a patched build for the platform the lock still pins /// upstream's gem for. That build is NOT attested: the lock does not -/// install it. The build the lock does pin patched is, and the run sends -/// the reader to the scan that moves the lock. +/// install it. It is in the document as affected, with no patch named for +/// it, beside the build the lock does pin patched; the run exits 0 as a +/// success and sends the reader to the scan that moves the lock. #[tokio::test(flavor = "multi_thread")] -async fn a_later_vex_attests_no_build_a_newer_reference_lists_but_the_lock_does_not_pin() { +async fn a_later_vex_says_affected_of_a_build_a_newer_reference_lists_but_the_lock_does_not_pin() { for checksums in [true, false] { let server = MockServer::start().await; mount_api(&server, Some((&BOTH_PATCHED[..], 5))).await; @@ -1418,23 +1482,27 @@ async fn a_later_vex_attests_no_build_a_newer_reference_lists_but_the_lock_does_ let index = format!("{}/", index_url(&api, Some(4))); let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, checksums); + let why = "the lockfile installs another archive for it than the patch registry lists now"; let out = vex(proj.path(), &api); assert_eq!(out.code, Some(0), "checksums: {checksums}: {out}"); assert_eq!( said(out.doc()), - [patched_statement(&[(LINUX, LINUX_UUID)], false)], + [ + patched_statement(&[(LINUX, LINUX_UUID)], false), + unshown_statement(ARM, why, RESCAN, false) + ], "checksums: {checksums}" ); assert!(!out.doc().to_string().contains(ARM_UUID), "{out}"); + let mut events = vec![event("verified", LINUX, "")]; + events.extend(unshown_events(&out.envelope, &[ARM])); + assert_eq!(build_events(&out.envelope), events, "{out}"); assert_eq!( - build_events(&out.envelope), - [ - event("verified", LINUX, ""), - event("skipped", ARM, "vex_gem_build_unknown") - ], + out.envelope["events"][1]["reason"], + format!("not shown patched for {ARM}: {why}"), "{out}" ); - assert_eq!(out.envelope["status"], "partialFailure", "{out}"); + assert_eq!(out.envelope["summary"]["verified"], 1, "{out}"); assert_eq!( warning_codes(&out.envelope), ["vex_gem_build_unknown"], @@ -1446,9 +1514,8 @@ async fn a_later_vex_attests_no_build_a_newer_reference_lists_but_the_lock_does_ "{PURL}: the lockfile takes its build for {ARM} from the registry of Socket patch \ {UUID}, which serves a patched build for some platforms and upstream's own gem \ for the others. Which it is for this one could not be told (the lockfile \ - installs another archive for it than the patch registry lists now), so it is \ - not attested. Run `socket-patch scan --mode hosted` to bring the lockfile up to \ - date, then `socket-patch vex` again." + installs another archive for it than the patch registry lists now), so the VEX \ + document states it as affected. {RESCAN}" ), "{out}" ); @@ -1456,8 +1523,8 @@ async fn a_later_vex_attests_no_build_a_newer_reference_lists_but_the_lock_does_ assert_eq!(references, [[UUID.to_string()]], "one reference request"); assert_eq!(other.len(), usize::from(!checksums), "{other:?}"); - // A person reads the warning, the build left out, and which - // builds the document attests. + // A person reads the warning and what the document says of each + // build: nothing is left out, and nothing fails. let human = vex_e2e_common::VexRun { human: true, ..vex_run(&api) @@ -1466,7 +1533,9 @@ async fn a_later_vex_attests_no_build_a_newer_reference_lists_but_the_lock_does_ assert_eq!(out.code, Some(0), "{out}"); assert!( out.stdout.ends_with(&format!( - "\n{DEP} {DEP_VERSION}: patched for {LINUX}; not attested for {ARM}\n" + "Wrote OpenVEX document with 2 statements (1 affected) to {}\n{DEP} \ + {DEP_VERSION}: patched for {LINUX}; not shown patched for {ARM}\n", + out.output.display() )), "{out}" ); @@ -1474,14 +1543,15 @@ async fn a_later_vex_attests_no_build_a_newer_reference_lists_but_the_lock_does_ out.stderr.contains(&format!( "Warning: {PURL}: the lockfile takes its build for {ARM} from the registry of \ Socket patch {UUID}" - )) && out.stderr.contains(&format!( - "Warning: omitting {} from VEX: it is not shown whether the lockfile installs \ - a patched build for this platform (the warning above says why, and what to \ - run) (vex_gem_build_unknown)\n", - build_purl(ARM) )), "{out}" ); + assert!( + out.stderr.matches("Warning: ").count() == 1 + && !out.stderr.contains("omitting") + && !out.stderr.contains("Error"), + "one warning, and nothing left out: {out}" + ); // The scan the note names moves the lock, and the next document // attests both builds. @@ -1497,6 +1567,75 @@ async fn a_later_vex_attests_no_build_a_newer_reference_lists_but_the_lock_does_ } } +/// A hosted run's own `--vex` can meet a build it cannot tell too: a gem +/// an earlier run moved, whose patch this run's search does not return +/// (such a pin is kept, and the run pins nothing), on a lock older than +/// the reference lists. The run's document says `affected` of that build +/// beside the one the lock pins patched, the warning is among the +/// document's, and the run is a success. With every build untold it still +/// is: both are in the document as affected. +#[tokio::test(flavor = "multi_thread")] +async fn the_runs_vex_says_affected_of_a_build_of_a_gem_it_did_not_pin() { + let why = "the lockfile installs another archive for it than the patch registry lists now"; + for (linux_pin, statements, affected) in [ + ( + LINUX_PATCHED, + vec![ + patched_statement(&[(LINUX, LINUX_UUID)], false), + unshown_statement(ARM, why, RESCAN, false), + ], + 1, + ), + ( + LINUX_UPSTREAM, + vec![ + unshown_statement(ARM, why, RESCAN, true), + unshown_statement(LINUX, why, RESCAN, true), + ], + 2, + ), + ] { + let server = MockServer::start().await; + // The search finds no patch for the gem. + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "packages": [], "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(&server) + .await; + mount_api(&server, Some((&BOTH_PATCHED[..], 5))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, linux_pin, true); + let before = read(proj.path(), "Gemfile.lock"); + let (code, env, doc) = scan_vex(proj.path(), &api); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!(hosted_events(&env), Vec::::new(), "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + before, + "nothing is pinned" + ); + assert_eq!(said(&doc.expect("a document")), statements, "{env}"); + assert_eq!(env["vex"]["statements"], 2, "{env}"); + assert_eq!(env["vex"]["affected"], affected, "{env}"); + let vex_warnings: Vec<&str> = env["vex"]["warnings"] + .as_array() + .into_iter() + .flatten() + .filter_map(|warning| warning["code"].as_str()) + .collect(); + assert_eq!( + vex_warnings, + ["vex_hosted_unverified", "vex_gem_build_unknown"], + "the standing note of a hosted run's document, and the one warning for the gem: {env}" + ); + } +} + /// The record of the gem's patch as a pre-v5 hosted ledger holds it: the /// one way a hosted pin has a record with no request. fn write_record_ledger(proj: &Path) { @@ -1513,12 +1652,13 @@ fn write_record_ledger(proj: &Path) { vex_e2e_common::write_legacy_redirect_ledger(proj, PURL, &view); } -/// `--offline`: no request at all, so nothing says which locked build is -/// patched. With the record at hand the gem's one pin would have attested -/// every build; instead the platform builds are left out, and one warning +/// `--offline`, with the record of the gem's patch at hand: no request at +/// all, so nothing says which locked build is patched. The gem's one pin +/// would have attested every build; instead each platform build is in the +/// document as affected, the run exits 0 as a success, and one warning /// names the gem and what to run. #[tokio::test(flavor = "multi_thread")] -async fn an_offline_vex_attests_no_platform_build_and_says_so_once() { +async fn an_offline_vex_says_affected_of_each_platform_build_and_warns_once() { let server = MockServer::start().await; mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; let api = server.uri(); @@ -1531,18 +1671,26 @@ async fn an_offline_vex_attests_no_platform_build_and_says_so_once() { }; let out = vex_e2e_common::run_vex(&vex_e2e_common::binary(), proj.path(), &offline); - assert_eq!(out.code, Some(1), "{out}"); + assert_eq!(out.code, Some(0), "{out}"); + let (why, online) = ( + "--offline forbids asking the patch API", + "Run `socket-patch vex` without --offline to attest each build.", + ); assert_eq!( - out.envelope["error"]["code"], "no_applicable_patches", + said(out.doc()), + [ + unshown_statement(ARM, why, online, true), + unshown_statement(LINUX, why, online, true) + ], "{out}" ); - assert!(out.doc.is_none(), "{out}"); + assert!( + !out.doc().to_string().contains(LINUX_UUID) && !out.doc().to_string().contains(UUID), + "no patch is named for a build that is not shown patched: {out}" + ); assert_eq!( build_events(&out.envelope), - [ - event("skipped", ARM, "vex_gem_build_unknown"), - event("skipped", LINUX, "vex_gem_build_unknown") - ], + unshown_events(&out.envelope, &[ARM, LINUX]), "{out}" ); assert_eq!( @@ -1553,8 +1701,8 @@ async fn an_offline_vex_attests_no_platform_build_and_says_so_once() { "{PURL}: the lockfile takes its builds for {ARM}, {LINUX} from the registry of \ Socket patch {UUID}, which serves a patched build for some platforms and \ upstream's own gem for the others. Which it is for these could not be told \ - (--offline forbids asking the patch API), so they are not attested. Run \ - `socket-patch vex` without --offline to attest each build." + (--offline forbids asking the patch API), so the VEX document states them as \ + affected. {online}" ), }]), "{out}" @@ -1579,10 +1727,11 @@ async fn an_offline_vex_attests_no_platform_build_and_says_so_once() { } /// The reference request fails: the record is there, the list of the -/// gem's builds is not. No build is attested, the registry is not asked, -/// and the warning carries the failure. +/// gem's builds is not. No build is attested as patched: each is in the +/// document as affected, the run exits 0 as a success, the registry is +/// not asked, and the warning carries the failure (the document does not). #[tokio::test(flavor = "multi_thread")] -async fn a_failed_reference_request_attests_no_platform_build() { +async fn a_failed_reference_request_says_affected_of_each_platform_build() { let server = MockServer::start().await; Mock::given(method("POST")) .and(path(format!("/v0/orgs/{ORG}/patches/package"))) @@ -1596,16 +1745,21 @@ async fn a_failed_reference_request_attests_no_platform_build() { let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, true); let out = vex(proj.path(), &api); - assert_eq!(out.code, Some(1), "{out}"); - assert!(out.doc.is_none(), "{out}"); + assert_eq!(out.code, Some(0), "{out}"); + let why = "the patch API request failed"; assert_eq!( - build_events(&out.envelope), + said(out.doc()), [ - event("skipped", ARM, "vex_gem_build_unknown"), - event("skipped", LINUX, "vex_gem_build_unknown") + unshown_statement(ARM, why, RETRY, true), + unshown_statement(LINUX, why, RETRY, true) ], "{out}" ); + assert_eq!( + build_events(&out.envelope), + unshown_events(&out.envelope, &[ARM, LINUX]), + "{out}" + ); assert_eq!( warning_codes(&out.envelope), ["vex_gem_build_unknown"], @@ -1614,7 +1768,9 @@ async fn a_failed_reference_request_attests_no_platform_build() { let detail = out.envelope["warnings"][0]["detail"].as_str().unwrap(); assert!( detail.contains("could not be told (the patch API request failed: ") - && detail.ends_with("Run `socket-patch vex` again to attest each build."), + && detail.ends_with(&format!( + "), so the VEX document states them as affected. {RETRY}" + )), "{detail}" ); let (references, other) = requests(&server).await; @@ -1625,26 +1781,28 @@ async fn a_failed_reference_request_attests_no_platform_build() { assert_eq!(other, Vec::::new(), "no registry request"); // A person reads one warning for the gem and one line for its builds, - // each named with its platform. + // each named with its platform, and no error. let human = vex_e2e_common::VexRun { human: true, ..vex_run(&api) }; let out = vex_e2e_common::run_vex(&vex_e2e_common::binary(), proj.path(), &human); - assert_eq!(out.code, Some(1), "{out}"); - assert_eq!(out.stderr.matches("Warning: ").count(), 2, "{out}"); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!(out.stderr.matches("Warning: ").count(), 1, "{out}"); assert!( out.stderr.contains(&format!( - "Warning: omitting 2 packages from VEX: it is not shown whether the lockfile \ - installs a patched build for this platform (the warning above says why, and what \ - to run) (vex_gem_build_unknown): {DEP}@{DEP_VERSION} ({ARM}), {DEP}@{DEP_VERSION} \ - ({LINUX})\n" - )), + "Warning: {PURL}: the lockfile takes its builds for {ARM}, {LINUX} from the \ + registry of Socket patch {UUID}" + )) && !out.stderr.contains("omitting") + && !out.stderr.contains("Error"), "{out}" ); assert!( - out.stderr - .ends_with("Error: No applied patches with vulnerability metadata to attest.\n"), + out.stdout.ends_with(&format!( + "Wrote OpenVEX document with 2 statements (2 affected) to {}\n{DEP} {DEP_VERSION}: \ + not shown patched for {ARM}, {LINUX}\n", + out.output.display() + )), "{out}" ); } diff --git a/crates/socket-patch-core/src/vex/build.rs b/crates/socket-patch-core/src/vex/build.rs index 4a9b4e1276..49e60cb951 100644 --- a/crates/socket-patch-core/src/vex/build.rs +++ b/crates/socket-patch-core/src/vex/build.rs @@ -11,9 +11,9 @@ //! the latter become aliases. When two patches fix the same vuln ID //! they merge into one statement with both PURLs as subcomponents. //! -//! A package the caller knows the build takes without its patch gets -//! `affected` statements ([`build_document_with`] with -//! [`Attested::affected`]): one per +//! A package the caller knows the build takes without its patch, or +//! cannot show the build takes patched, gets `affected` statements +//! ([`build_document_with`] with [`Attested::affected`]): one per //! vulnerability ID, of its own, after the `not_affected` one of the same //! ID. Such statements are not merged, so that the action statement of //! each is about one subcomponent. @@ -136,8 +136,9 @@ pub struct Attested<'a> { /// installed build of the package /// ([`VerifyOutcome::code_not_present`](crate::vex::verify::VerifyOutcome::code_not_present)). pub code_not_present: &'a [String], - /// PURLs whose patch the caller knows the build does not take, each - /// with what to do about it. See [`build_document_with`]. + /// PURLs whose patch the caller knows the build does not take, or + /// cannot show it takes, each with what to do about it. See + /// [`build_document_with`]. pub affected: &'a [(String, String)], } @@ -159,12 +160,13 @@ pub const CODE_NOT_PRESENT_PREFIX: &str = /// is which. /// /// `attested.affected` names the PURLs whose patch the caller knows the -/// build does not take, each with what to do about it. Every vulnerability -/// of such a PURL's record gets a statement of the PURL's own with the -/// status `affected`: the PURL is the one subcomponent of the product, and -/// the action statement is what the caller gave for it, so a reader knows -/// which package to act on. It has no justification and no impact -/// statement, which belong to `not_affected`. +/// build does not take, or cannot show it takes (a gem build of which +/// nothing shows what the lockfile installs), each with what to do about +/// it. Every vulnerability of such a PURL's record gets a statement of the +/// PURL's own with the status `affected`: the PURL is the one subcomponent +/// of the product, and the action statement is what the caller gave for +/// it, so a reader knows which package to act on. It has no justification +/// and no impact statement, which belong to `not_affected`. /// /// A PURL is in `applied` or in `affected`, and `affected` wins for one /// in both. A vulnerability that PURLs of both kinds share has the diff --git a/crates/socket-patch-core/src/vex/verify.rs b/crates/socket-patch-core/src/vex/verify.rs index decda81f48..931310d469 100644 --- a/crates/socket-patch-core/src/vex/verify.rs +++ b/crates/socket-patch-core/src/vex/verify.rs @@ -8,7 +8,8 @@ //! on is "never emit `affected` or `under_investigation` — just omit". //! A failed check shows no more than that this copy is not the patched //! one. `affected` is for a package the caller knows the build takes -//! unpatched (`vex::build::build_document_with`). +//! unpatched, or cannot show it takes patched +//! (`vex::build::build_document_with`). //! //! The CLI is responsible for resolving PURL → on-disk package path //! (it already does this for `apply` / `scan` via the ecosystem From aba4d1cd75e5e3752bca7a143c7b7cf63cfd0571 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 26 Nov 2026 00:43:13 -0500 Subject: [PATCH 028/120] Replace the installed copy of a withdrawn gem build with upstream's gem A patched platform build can be withdrawn, because it is unsafe. The next hosted scan puts upstream's sha256 back into the lock for that platform, but a machine that had installed the build kept loading it: the stale-install guard passed over every build the patch registry serves as upstream's own gem, and `bundle install` keeps a gem it has installed. The guard judges the copy of such a build, and its archive in Bundler's cache dir, by the sha256 the reference lists for the platform. An archive that is upstream's gem is the right copy, as before: nothing is said, downloaded or fetched for it. A readable archive with another sha256 is replaced with upstream's gem, downloaded from the patch registry (which hands that file on) and verified against the listed sha256 before a byte is used, under the switches of every other refresh (`--no-gem-install-refresh`, `--gem-refresh-shared`, `--dry-run`). What cannot be replaced is warned about under the guard's own codes, in words that say a withdrawn build is still installed and how to remove it. The lines of a refresh name the upstream gem and never call the result patched, and so does the next step. Such a copy keeps nothing of the gem out of the run's VEX: the document says `affected` of that build whatever is installed, and still attests the other builds. A copy whose gem home holds no archive of it is not judged. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/gem_refresh.rs | 282 ++++++++- .../src/commands/scan/hosted.rs | 380 +++++++++--- .../tests/e2e_redirect_gem_stale_install.rs | 559 ++++++++++++++++++ 3 files changed, 1126 insertions(+), 95 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index f23b3f4d8c..80e11558ce 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -19,12 +19,21 @@ use socket_patch_core::patch::gem_refresh::{refresh, Source, Target, Wanted}; use crate::args::{GlobalArgs, RunApiClient}; use crate::ui::plural; -/// What the lock now pins: the hosted patch, or the upstream registry -/// entry an unwind put back. +/// What the lock now pins: the hosted patch, the upstream registry entry +/// an unwind put back, or, for one platform of a gem that stays on its +/// hosted patch, upstream's own gem again. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Direction { Patched, Upstream, + /// A hosted gem locked as platform builds, and a platform the patch + /// registry serves as upstream's own gem while a copy on disk holds + /// another build: the patched build that copy was installed from was + /// withdrawn, and the lock pins upstream's gem for that platform. The + /// hosted scan's guard finds it, so its codes and its retry are the + /// guard's ([`Direction::Patched`]); what replaces the copy is the + /// upstream gem. + Withdrawn, } impl Direction { @@ -32,7 +41,7 @@ impl Direction { fn wanted(self) -> &'static str { match self { Direction::Patched => "patched", - Direction::Upstream => "upstream", + Direction::Upstream | Direction::Withdrawn => "upstream", } } @@ -41,20 +50,43 @@ impl Direction { match self { Direction::Patched => "unpatched", Direction::Upstream => "patched", + Direction::Withdrawn => "withdrawn", } } - fn switched(self) -> &'static str { + /// What became of `gem`, before what is still stale of it. + fn switched(self, gem: &StaleGem) -> String { match self { - Direction::Patched => "was switched to its hosted patch", - Direction::Upstream => "is back on its upstream registry entry", + Direction::Patched => "was switched to its hosted patch".to_string(), + Direction::Upstream => "is back on its upstream registry entry".to_string(), + Direction::Withdrawn => { + let build = GemBuild::of_leaf(&gem.purl, &gem.leaf); + match build.and_then(|build| build.platform) { + Some(platform) => format!( + "is back on upstream's own gem for {platform}, whose patched build was \ + withdrawn" + ), + None => "is back on upstream's own gem, whose patched build was withdrawn" + .to_string(), + } + } + } + } + + /// Whether a re-run of the command can still refresh what this run + /// left: a scan finds the same copy again. An unwind can't be re-run: + /// its first run removed the wiring a second one would look for. + fn rerunnable(self) -> bool { + match self { + Direction::Patched | Direction::Withdrawn => true, + Direction::Upstream => false, } } /// The warning code of a materialization that is still stale. pub(crate) fn stale_code(self) -> &'static str { match self { - Direction::Patched => "redirect_gem_stale_install", + Direction::Patched | Direction::Withdrawn => "redirect_gem_stale_install", Direction::Upstream => "upstream_gem_stale_install", } } @@ -62,7 +94,7 @@ impl Direction { /// The `--json` note of a materialization this run refreshed. pub(crate) fn refreshed_code(self) -> &'static str { match self { - Direction::Patched => "redirect_gem_install_refreshed", + Direction::Patched | Direction::Withdrawn => "redirect_gem_install_refreshed", Direction::Upstream => "upstream_gem_install_refreshed", } } @@ -70,7 +102,7 @@ impl Direction { /// The `--json` note of a materialization a wet run would refresh. pub(crate) fn would_refresh_code(self) -> &'static str { match self { - Direction::Patched => "redirect_gem_install_would_refresh", + Direction::Patched | Direction::Withdrawn => "redirect_gem_install_would_refresh", Direction::Upstream => "upstream_gem_install_would_refresh", } } @@ -160,12 +192,12 @@ impl Policy { } if !self.shared && !resolves_inside(&self.root, path) { return Err(Why::OutOfTree( - match direction { - Direction::Patched => { + match direction.rerunnable() { + true => { "it is outside the project directory; `--gem-refresh-shared` refreshes \ it too" } - Direction::Upstream => "it is outside the project directory", + false => "it is outside the project directory", } .to_string(), )); @@ -475,16 +507,14 @@ fn display_list(paths: &[PathBuf]) -> String { /// every one of them does: a gem dir with no gemspec fails a re-run the /// same way, and a copy no Ruby owns needs its Ruby found first. fn retry_hint(direction: Direction, why: Option<&Why>, outlives: Option) -> &'static str { - match (why, direction) { - (Some(Why::Failed(_)), Direction::Patched) if outlives == Some(Outlives::NoGemspec) => "", - (Some(Why::Failed(_)), Direction::Patched) if outlives == Some(Outlives::ForeignRuby) => { + match (why, direction.rerunnable()) { + (Some(Why::Failed(_)), true) if outlives == Some(Outlives::NoGemspec) => "", + (Some(Why::Failed(_)), true) if outlives == Some(Outlives::ForeignRuby) => { "Re-run `socket-patch scan` with the Ruby that installed the gem first on `PATH` \ to retry, or " } - (Some(Why::Disabled), Direction::Patched) => { - "Re-run without `--no-gem-install-refresh`, or " - } - (Some(Why::Failed(_) | Why::OutOfTree(_)), Direction::Patched) => { + (Some(Why::Disabled), true) => "Re-run without `--no-gem-install-refresh`, or ", + (Some(Why::Failed(_) | Why::OutOfTree(_)), true) => { "Re-run `socket-patch scan` to retry, or " } _ => "", @@ -551,7 +581,7 @@ fn reason(why: Option<&Why>) -> String { /// The detail of one still-stale materialization (the `--json` warning). /// `why` is `None` where no refresh was attempted yet. pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Why>) -> String { - let (purl, switched) = (&gem.purl, direction.switched()); + let (purl, switched) = (&gem.purl, direction.switched(gem)); let (stale, wanted) = (direction.stale(), direction.wanted()); let reuse = format!("`bundle install` reuses an installed gem instead of fetching the {wanted} one"); @@ -614,11 +644,11 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh {}, and {reuse}. Other projects may load that gem home, so it was left alone. \ Install the {wanted} gem for this project only with `{LOCAL_PATH_REMEDY}`, or {}", dir.display(), - match direction { - Direction::Patched => { + match direction.rerunnable() { + true => { "re-run with `--gem-refresh-shared` to replace the shared copy".to_string() } - Direction::Upstream => format!( + false => format!( "replace the shared copy: remove {} and run `bundle install` ({})", display_list(&files_to_remove(gem)), other_projects_cost(1) @@ -743,6 +773,11 @@ pub(crate) fn report( } else { (direction.refreshed_code(), "replaced", "Replaced") }; + // Why the upstream gem takes the place of a copy on a hosted scan. + let because = match direction { + Direction::Withdrawn => " (its patched build was withdrawn)", + Direction::Patched | Direction::Upstream => "", + }; let (mut installed, mut archives, mut in_place) = (Vec::new(), Vec::new(), Vec::new()); for (purl, target) in &attempt.refreshed { let what = match target { @@ -769,7 +804,7 @@ pub(crate) fn report( } if !installed.is_empty() { out.progress.push(format!( - "{replaced} the installed copy of {} with the {wanted} build: {}.", + "{replaced} the installed copy of {} with the {wanted} build{because}: {}.", plural(installed.len(), "gem", "gems"), labels(installed.iter().copied()) )); @@ -784,7 +819,7 @@ pub(crate) fn report( } if !archives.is_empty() { out.progress.push(format!( - "{replaced} {} in Bundler's cache dir with the {wanted} gem: {}.", + "{replaced} {} in Bundler's cache dir with the {wanted} gem{because}: {}.", plural(archives.len(), "archive", "archives"), labels(archives.iter().copied()) )); @@ -845,6 +880,7 @@ pub(crate) fn report( let switch = match direction { Direction::Patched => "the switch to hosted patches", Direction::Upstream => "the switch back to the upstream registry", + Direction::Withdrawn => "the withdrawal of a patched build", }; let known = match direction { Direction::Patched if stale.iter().all(|gem| gem.in_place) => format!( @@ -867,6 +903,10 @@ pub(crate) fn report( "{} the patched build on disk after {switch}", plural(count, "gem still holds", "gems still hold") ), + Direction::Withdrawn => format!( + "{} a patched build on disk that was withdrawn", + plural(count, "gem still holds", "gems still hold") + ), }; let headline = match (count, unchecked.len()) { (_, 0) => known, @@ -907,14 +947,14 @@ pub(crate) fn report( place from the upstream archive beside it. ", ); } - bullets.push(match direction { - Direction::Patched => format!( + bullets.push(match direction.rerunnable() { + true => format!( "{why}To install {them} for this project only, run `{LOCAL_PATH_REMEDY}`, or \ re-run with `--gem-refresh-shared` to replace the shared {copies}." ), // An unwind can't be re-run (see `retry_hint`), so the shared // copies are replaced by hand (#2086). - Direction::Upstream => format!( + false => format!( "{why}To install {them} for this project only, run `{LOCAL_PATH_REMEDY}`. To \ replace the shared {copies}, run `{}`; {}.", reinstall_command(&shared_files, false), @@ -2673,6 +2713,192 @@ mod tests { ); } + /// The copy of a withdrawn build, where the lock pins upstream's gem + /// for the platform: the hosted scan's guard reports it under its own + /// codes and with its own retries (a scan can be re-run), and every + /// line says what the copy is and that the upstream gem takes its + /// place. Nothing calls the result patched. + #[tokio::test] + async fn the_copy_of_a_withdrawn_build_is_replaced_with_the_upstream_gem() { + let withdrawn = Direction::Withdrawn; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let platform_gem = |name: &str, home: &Path, project_local: bool| { + let mut gem = installed(name, home, project_local); + let (dir, _) = gem.installed.take().unwrap(); + let platform_dir = dir.with_file_name(format!("{name}-1.0.0-arm64-darwin")); + std::fs::rename(&dir, &platform_dir).unwrap(); + let specs = home.join("specifications"); + std::fs::rename( + specs.join(format!("{name}-1.0.0.gemspec")), + specs.join(format!("{name}-1.0.0-arm64-darwin.gemspec")), + ) + .unwrap(); + gem.leaf = format!("{name}-1.0.0-arm64-darwin"); + gem.installed = Some((platform_dir, project_local)); + gem + }; + let home = proj.join("vendor/bundle/ruby/3.4.0"); + let local = platform_gem("rexml", &home, true); + let (dir, _) = local.installed.clone().unwrap(); + + // Replaced: the notes and the progress line. + let replaced = Attempt { + refreshed: vec![ + ( + "pkg:gem/rexml@1.0.0".to_string(), + Target::Installed(dir.clone()), + ), + ( + "pkg:gem/rexml@1.0.0".to_string(), + Target::CacheArchive(PathBuf::from( + "vendor/cache/rexml-1.0.0-arm64-darwin.gem", + )), + ), + ], + ..Attempt::default() + }; + let out = report( + withdrawn, + &[], + &replaced, + &policy(&proj, true, false, false), + ); + assert!(out.summary.is_none()); + assert_eq!( + out.progress, + [ + "Replaced the installed copy of 1 gem with the upstream build (its patched build \ + was withdrawn): rexml 1.0.0.", + "Replaced 1 archive in Bundler's cache dir with the upstream gem (its patched \ + build was withdrawn): rexml 1.0.0.", + ] + ); + assert_eq!( + out.warnings, + [ + ( + "redirect_gem_install_refreshed", + format!( + "pkg:gem/rexml@1.0.0: replaced the withdrawn install at {} with the \ + upstream gem", + dir.display() + ) + ), + ( + "redirect_gem_install_refreshed", + "pkg:gem/rexml@1.0.0: replaced the withdrawn archive at \ + vendor/cache/rexml-1.0.0-arm64-darwin.gem with the upstream gem" + .to_string() + ), + ] + ); + let dry = report(withdrawn, &[], &replaced, &policy(&proj, true, false, true)); + assert!( + dry.progress[0].starts_with( + "Would replace the installed copy of 1 gem with the upstream build (its patched \ + build was withdrawn)" + ) && dry + .warnings + .iter() + .all(|(code, _)| *code == "redirect_gem_install_would_refresh"), + "{dry:?}" + ); + + // Left as it is: what it is, why, and how to remove it. A scan can + // be re-run, so the retry is offered. + let off = policy(&proj, false, false, false); + let stale = [local.clone()]; + let out = report(withdrawn, &stale, &pass(&stale, &off).await, &off); + let spec = home.join("specifications/rexml-1.0.0-arm64-darwin.gemspec"); + let archive = home.join("cache/rexml-1.0.0-arm64-darwin.gem"); + assert_eq!( + out.warnings, + [( + "redirect_gem_stale_install", + format!( + "pkg:gem/rexml@1.0.0 is back on upstream's own gem for arm64-darwin, whose \ + patched build was withdrawn, but its withdrawn install at {} was not \ + refreshed (`--no-gem-install-refresh` is set), and `bundle install` reuses \ + an installed gem instead of fetching the upstream one. Re-run without \ + `--no-gem-install-refresh`, or remove {}, {} and run `bundle install`", + dir.display(), + spec.display(), + archive.display() + ) + )] + ); + let summary = out.summary.expect("a summary"); + assert_eq!( + summary.headline, + "1 gem still holds a patched build on disk that was withdrawn" + ); + assert_eq!( + summary.bullets, + [format!( + "Not refreshed (`--no-gem-install-refresh` is set): rexml 1.0.0. Re-run without \ + `--no-gem-install-refresh`, or run `rm -f {} {} && bundle install`.", + shell_word(&spec), + shell_word(&archive) + )] + ); + + // A run that may not download (`--offline`) and holds no verified + // copy of the upstream gem: the same warning, with that reason. + let on = policy(&proj, true, false, false); + let upstream_gem = |gem: &StaleGem| { + Some(Wanted { + leaf: gem.leaf.clone(), + kind: "upstream", + sha256: BTreeSet::from(["0".repeat(64)]), + urls: vec!["http://127.0.0.1:9/gems/rexml.gem".to_string()], + on_disk: Vec::new(), + }) + }; + let tried = attempt(&stale, upstream_gem, &Source::DiskOnly, &on, withdrawn).await; + let out = report(withdrawn, &stale, &tried, &on); + assert_eq!( + out.summary.expect("a summary").bullets, + [format!( + "Not refreshed (this run is offline and no verified copy of the upstream gem is \ + on disk): rexml 1.0.0. Re-run `socket-patch scan` to retry, or run `rm -f {} {} \ + && bundle install`.", + shell_word(&spec), + shell_word(&archive) + )] + ); + + // In a gem home other projects load: left alone, with the flag + // that covers it. + let shared = platform_gem("rack", &tmp.path().join("gemhome"), false); + let stale = [shared]; + let out = report(withdrawn, &stale, &pass(&stale, &on).await, &on); + let detail = &out.warnings[0].1; + assert!( + detail.contains("but the shared gem home still holds its withdrawn install at") + && detail.ends_with( + "Install the upstream gem for this project only with `bundle config set \ + --local path vendor/bundle && bundle install`, or re-run with \ + `--gem-refresh-shared` to replace the shared copy" + ), + "{detail}" + ); + let summary = out.summary.expect("a summary"); + assert_eq!( + summary.headline, + "1 gem still holds a patched build on disk that was withdrawn" + ); + assert!( + summary.bullets[1].starts_with( + "`bundle install` reuses an installed gem instead of fetching the upstream one. \ + To install it for this project only, run" + ) && summary.bullets[1] + .ends_with("or re-run with `--gem-refresh-shared` to replace the shared copy."), + "{:?}", + summary.bullets + ); + } + /// What a pass may replace: the project's own copies; a shared home, or /// a project path that resolves outside the project, only with /// `--gem-refresh-shared`; nothing with `--no-gem-install-refresh`. diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index bc81806ba1..0d95863c8e 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -546,6 +546,13 @@ struct StaleInstallOutcome { /// The gem probe's stale materializations, one per warning, for the /// refresh that follows it ([`refresh_stale_gems`]). gems: Vec, + /// The gem probe's copies of a platform build the patch registry + /// serves as upstream's own gem that are another build: a patched + /// build that was withdrawn. The refresh puts upstream's gem in their + /// place. Not among `stale_purls`: the document says `affected` of + /// such a build whatever is installed, and its copy says nothing of + /// the gem's other builds. + withdrawn: Vec, } /// The gem and Python stale-install probes' fallback: when a confirmed @@ -632,7 +639,17 @@ fn stale_installed_gem( /// guard" section of CLI_CONTRACT.md). `why` is why the refresh did not fix /// it; `None` describes it before any refresh. fn gem_stale_warning(gem: &StaleGem, why: Option<&gem_refresh::Why>) -> serde_json::Value { - let direction = gem_refresh::Direction::Patched; + gem_stale_warning_of(gem_refresh::Direction::Patched, gem, why) +} + +/// [`gem_stale_warning`] for a materialization that is stale in +/// `direction`: an unpatched copy of a patched build, or the copy of a +/// withdrawn build where the lock pins upstream's gem. +fn gem_stale_warning_of( + direction: gem_refresh::Direction, + gem: &StaleGem, + why: Option<&gem_refresh::Why>, +) -> serde_json::Value { serde_json::json!({ "code": direction.stale_code(), "detail": gem_refresh::stale_detail(direction, gem, why), @@ -690,10 +707,15 @@ fn stale_cache_gem(purl: &str, cache_path: &Path) -> StaleGem { /// judged the same way, against the patched artifacts of the gem, which /// include its patched platform builds. /// * A platform build the patch registry serves as upstream's own gem (no -/// patched build yet; `gem_upstream_leaves` names it by leaf) is not -/// judged at all, installed or committed to the cache dir: its lock -/// entry pins upstream's gem, so a machine of that platform holds the -/// right copy, and there is nothing to report or to refresh. +/// patched build; `gem_upstream` gives the sha256 of that gem by leaf) +/// is pinned to upstream's gem by its lock entry. Its installed copy and +/// its archive in the cache dir are judged by that sha256 alone: an +/// archive that is upstream's gem is the right copy, and nothing is +/// reported, refreshed or downloaded for it. A readable archive with +/// another sha256 is a patched build that was withdrawn (`withdrawn`): +/// the lock does not install it, and `bundle install` keeps it. A copy +/// whose gem home holds no archive of it is not judged: no patch record +/// is fetched for a build that has no patch. /// * Which copies are judged is the lock's to say: every build of the gem /// the project's lock names is looked for under its own leaf, in every /// gem home. A gem home can hold several builds of one version (the @@ -716,7 +738,7 @@ async fn gem_stale_install_warnings( (String, String), std::collections::BTreeSet, >, - gem_upstream_leaves: &std::collections::BTreeSet, + gem_upstream: &std::collections::BTreeMap, views: &mut ViewFallback<'_>, ) -> StaleInstallOutcome { use socket_patch_core::crawlers::types::CrawlerOptions; @@ -825,6 +847,11 @@ async fn gem_stale_install_warnings( } let mut dir_state: std::collections::BTreeMap = std::collections::BTreeMap::new(); + // The installed copies of a build on upstream's gem that are another + // build: the candidate, the leaf, and whether the gem home is the + // project's own. + let mut withdrawn_dirs: std::collections::BTreeMap = + std::collections::BTreeMap::new(); // Bundler's configured cache dir (`cache_path`, default vendor/cache). let app_cache = socket_patch_core::crawlers::ruby_crawler::bundler_app_cache_dir(cwd).await; // Copies with no local evidence, judged by the view fallback below. @@ -840,8 +867,20 @@ async fn gem_stale_install_warnings( let Some(leaf) = dir.file_name().and_then(|n| n.to_str()) else { continue; }; - // Upstream's own gem is what the lock pins for this build. - if gem_upstream_leaves.contains(leaf) { + // Upstream's own gem is what the lock pins for this build: the + // archive RubyGems installed the copy from is that gem, or the + // copy is a build that was withdrawn. + if let Some(upstream_sha) = gem_upstream.get(leaf) { + let archive = gem_refresh::home_cache_archive(dir); + let installed_from = match &archive { + Some(archive) => file_sha256_hex(archive).await, + None => None, + }; + if installed_from.is_some_and(|sha| !sha.eq_ignore_ascii_case(upstream_sha)) { + withdrawn_dirs + .entry(dir.clone()) + .or_insert_with(|| ((*purl).to_string(), leaf.to_string(), *project_local)); + } continue; } let entry = dir_state.entry(dir.clone()).or_insert_with(|| DirJudgment { @@ -963,6 +1002,39 @@ async fn gem_stale_install_warnings( // qualifier-insensitively, so one left out would re-exempt the dir. out.stale_purls.extend(j.purls.iter().cloned()); } + // The copies of a withdrawn build, each with the project's cache-dir + // archive of that build unless it is proven to be upstream's gem: + // bundler installs from it first. + let withdrawn = gem_refresh::Direction::Withdrawn; + for (dir, (purl, leaf, project_local)) in &withdrawn_dirs { + let project_cache = app_cache.join(format!("{leaf}.gem")); + let folded_cache = if *project_local && project_cache.is_file() { + let proven_upstream = match ( + gem_upstream.get(leaf), + file_sha256_hex(&project_cache).await, + ) { + (Some(want), Some(got)) => got.eq_ignore_ascii_case(want), + _ => false, + }; + (!proven_upstream).then_some(project_cache) + } else { + None + }; + if let Some(archive) = &folded_cache { + cache_covered.insert(archive.clone()); + } + let gem = stale_installed_gem( + purl, + dir, + leaf, + *project_local, + folded_cache.as_deref(), + false, + ); + out.warnings + .push(gem_stale_warning_of(withdrawn, &gem, None)); + out.withdrawn.push(gem); + } // Pass 3: standalone vendor/cache staleness — a committed archive whose // sha256 is readable and differs from the patched artifact's, unless a @@ -971,18 +1043,13 @@ async fn gem_stale_install_warnings( // otherwise never warn). One archive per build the lock names: the // ruby gem's alone where no lock names the gem. for (index, (purl, _, _)) in candidates.iter().enumerate() { - let Some(want_shas) = gem_artifact_shas.get(&gem_sha_key(purl)) else { - continue; - }; + let want_shas = gem_artifact_shas.get(&gem_sha_key(purl)); let builds = match named[index].as_slice() { [] => GemBuild::ruby(purl).into_iter().collect(), builds => builds.to_vec(), }; - for cache_path in builds - .iter() - .filter(|build| !gem_upstream_leaves.contains(&build.leaf)) - .map(|build| app_cache.join(format!("{}.gem", build.leaf))) - { + for build in &builds { + let cache_path = app_cache.join(format!("{}.gem", build.leaf)); if cache_covered.contains(&cache_path) || !cache_path.is_file() { continue; } @@ -990,6 +1057,20 @@ async fn gem_stale_install_warnings( let Some(got) = file_sha256_hex(&cache_path).await else { continue; }; + // A build on upstream's gem: the archive is that gem, or a + // build that was withdrawn. + if let Some(upstream_sha) = gem_upstream.get(&build.leaf) { + if !got.eq_ignore_ascii_case(upstream_sha) { + let gem = stale_cache_gem(purl, &cache_path); + out.warnings + .push(gem_stale_warning_of(withdrawn, &gem, None)); + out.withdrawn.push(gem); + } + continue; + } + let Some(want_shas) = want_shas else { + continue; + }; if want_shas.contains(&got) { continue; // the PATCHED archive — healthy commit, nothing stale } @@ -1013,11 +1094,17 @@ struct GemRefreshed { progress: Vec, /// The one human warning for what is still stale. summary: Option, + /// The one human warning for the copies of a withdrawn build that are + /// still on disk. + withdrawn_summary: Option, /// The cache-dir archives replaced: files the project commits. replaced_archives: Vec, /// An installed copy was replaced with the patched gem, or the upstream /// archive beside one patched in place was. replaced_installs: bool, + /// An installed copy of a withdrawn build was replaced with upstream's + /// gem. + replaced_withdrawn: bool, } /// What became of the copies of the switched gems that Bundler already @@ -1031,12 +1118,23 @@ enum GemCopies { Refreshed, /// Some are still stale; the run's warning names the command. Stale, + /// Every stale one was brought in line with what the lock pins, and + /// for one of them that is upstream's gem: its patched build was + /// withdrawn. + Followed, + /// The copy of a withdrawn build is still installed, and nothing else + /// is stale; the run's warning names the command. + Withdrawn, } impl GemRefreshed { fn copies(&self) -> GemCopies { if self.summary.is_some() { GemCopies::Stale + } else if self.withdrawn_summary.is_some() { + GemCopies::Withdrawn + } else if self.replaced_withdrawn { + GemCopies::Followed } else if self.replaced_installs { GemCopies::Refreshed } else { @@ -1052,6 +1150,12 @@ impl GemRefreshed { /// stale says so (the `--vex` exclusions are the second probe's). A /// refresh that fails changes nothing and leaves the warning; it never /// fails the run. `locked` is whether the run holds the apply lock. +/// +/// The copy of a withdrawn build goes the other way under the same +/// policy: it is replaced with upstream's gem, which the patch registry +/// hands on for that platform (`/gems/.gem`), verified +/// against the sha256 the reference lists for it. A build that was +/// withdrawn may be unsafe to keep loading, and `bundle install` keeps it. #[allow(clippy::too_many_arguments)] async fn refresh_stale_gems( common: &crate::args::GlobalArgs, @@ -1066,13 +1170,14 @@ async fn refresh_stale_gems( (String, String), std::collections::BTreeSet, >, - gem_upstream_leaves: &std::collections::BTreeSet, + gem_upstream: &std::collections::BTreeMap, overrides: &[DepOverride], mirror_sources: &socket_patch_core::hosted::engine::MirrorSources, views: &mut ViewFallback<'_>, ) -> GemRefreshed { use socket_patch_core::patch::gem_refresh::{Source, Wanted}; let direction = gem_refresh::Direction::Patched; + let withdrawn = gem_refresh::Direction::Withdrawn; let first = gem_stale_install_warnings( &common.cwd, common.global, @@ -1080,11 +1185,11 @@ async fn refresh_stale_gems( confirmed, local_records, gem_artifact_shas, - gem_upstream_leaves, + gem_upstream, views, ) .await; - if first.gems.is_empty() { + if first.gems.is_empty() && first.withdrawn.is_empty() { return GemRefreshed { outcome: if common.dry_run { StaleInstallOutcome::default() @@ -1150,13 +1255,45 @@ async fn refresh_stale_gems( on_disk: Vec::new(), }) }; + // Upstream's gem for the platform of a withdrawn build: what bundler + // itself would download from the patch registry, which hands that + // file on, verified against the sha256 the reference lists for the + // platform before any byte of it is used. + let upstream_wanted = |gem: &StaleGem| { + let (name, version) = gem_sha_key(&gem.purl); + let sha256 = gem_upstream.get(&gem.leaf)?.to_ascii_lowercase(); + let file = format!("{}.gem", gem.leaf); + let mut urls: Vec = overrides + .iter() + .filter(|o| o.ecosystem == "gem" && o.name == name && o.version == version) + .filter_map(|o| o.registry_override.as_ref()) + .map(|ro| format!("{}/gems/{file}", ro.index_url.trim_end_matches('/'))) + .map(|url| mirror_sources.fetch_url(&url).into_owned()) + .collect(); + urls.dedup(); + Some(Wanted { + leaf: gem.leaf.clone(), + kind: "upstream", + sha256: std::collections::BTreeSet::from([sha256]), + urls, + on_disk: Vec::new(), + }) + }; let source = if common.offline { Source::DiskOnly } else { Source::PatchServer(api_client) }; let pass = gem_refresh::attempt(&first.gems, wanted, &source, &policy, direction).await; - let mut outcome = if pass.changed(&policy) { + let withdrawn_pass = gem_refresh::attempt( + &first.withdrawn, + upstream_wanted, + &source, + &policy, + withdrawn, + ) + .await; + let mut outcome = if pass.changed(&policy) || withdrawn_pass.changed(&policy) { gem_stale_install_warnings( &common.cwd, common.global, @@ -1164,7 +1301,7 @@ async fn refresh_stale_gems( confirmed, local_records, gem_artifact_shas, - gem_upstream_leaves, + gem_upstream, views, ) .await @@ -1172,25 +1309,34 @@ async fn refresh_stale_gems( first }; let report = gem_refresh::report(direction, &outcome.gems, &pass, &policy); + let withdrawn_report = + gem_refresh::report(withdrawn, &outcome.withdrawn, &withdrawn_pass, &policy); outcome.warnings = report .warnings .iter() + .chain(&withdrawn_report.warnings) .map(|(code, detail)| serde_json::json!({ "code": code, "detail": detail })) .collect(); if common.dry_run { outcome.stale_purls.clear(); outcome.unjudged_purls.clear(); } + let mut progress = report.progress; + progress.extend(withdrawn_report.progress); GemRefreshed { outcome, - progress: report.progress, + progress, summary: report.summary, + withdrawn_summary: withdrawn_report.summary, replaced_archives: if common.dry_run { Vec::new() } else { - pass.replaced_archives().map(Path::to_path_buf).collect() + let replaced = pass.replaced_archives(); + let replaced = replaced.chain(withdrawn_pass.replaced_archives()); + replaced.map(Path::to_path_buf).collect() }, replaced_installs: !common.dry_run && pass.refreshed_an_install(), + replaced_withdrawn: !common.dry_run && withdrawn_pass.refreshed_an_install(), } } @@ -2422,10 +2568,11 @@ async fn run_redirect_selected_untracked( std::collections::BTreeSet, > = std::collections::BTreeMap::new(); // The platform builds the patch registry serves as upstream's own gem - // (no patched build yet), by leaf: a machine of such a platform holds - // upstream's gem, which is what its lock entry pins. - let mut gem_upstream_leaves: std::collections::BTreeSet = - std::collections::BTreeSet::new(); + // (no patched build), by leaf, each with the sha256 of that gem: what + // its lock entry pins, and what a machine of such a platform holds + // unless it installed a patched build that was withdrawn since. + let mut gem_upstream: std::collections::BTreeMap = + std::collections::BTreeMap::new(); for o in done.overrides.iter().filter(|o| o.ecosystem == "gem") { let sha = o .registry_override @@ -2441,8 +2588,10 @@ async fn run_redirect_selected_untracked( match build.patch_uuid { Some(_) => patched_builds.push(build.gem_checksum_sha256.clone()), None => { - gem_upstream_leaves - .insert(format!("{}-{}-{}", o.name, o.version, build.platform)); + gem_upstream.insert( + format!("{}-{}-{}", o.name, o.version, build.platform), + build.gem_checksum_sha256.clone(), + ); } } } @@ -2462,7 +2611,7 @@ async fn run_redirect_selected_untracked( &confirmed, &local_records, &gem_artifact_shas, - &gem_upstream_leaves, + &gem_upstream, &done.overrides, &mirror_sources, &mut views, @@ -2996,7 +3145,8 @@ async fn run_redirect_selected_untracked( }; eprintln!("{}", format_warning(code, &detail, width)); } - if let Some(summary) = &gem_refreshed.summary { + let summaries = [&gem_refreshed.summary, &gem_refreshed.withdrawn_summary]; + for summary in summaries.into_iter().flatten() { eprintln!( "{}", render_warning(&format!("{}.", summary.headline), &summary.bullets, width) @@ -3948,6 +4098,18 @@ fn format_next_steps( install` keeps the gems it already has)", &extra, ), + GemCopies::Followed if bundler_only => crate::ui::next_steps_installed( + &commit, + "the installed gems already hold the builds the lockfile pins, so there is nothing \ + to reinstall", + &extra, + ), + GemCopies::Withdrawn if bundler_only => crate::ui::next_steps( + &commit, + "Replace the withdrawn gem build with the command in the warning above (a plain \ + `bundle install` keeps the gems it already has)", + &extra, + ), _ => crate::ui::next_steps( &commit, &format!("Reinstall from the updated lockfile{hint}"), @@ -4897,7 +5059,7 @@ mod tests { confirmed, records, &std::collections::BTreeMap::new(), - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await @@ -5177,7 +5339,7 @@ mod tests { &one_confirmed, &none, &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5195,7 +5357,7 @@ mod tests { &one_confirmed, &none, &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5209,7 +5371,7 @@ mod tests { &one_confirmed, &none, &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5245,7 +5407,7 @@ mod tests { &confirmed, &std::collections::BTreeMap::new(), &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5341,7 +5503,7 @@ mod tests { &one_confirmed(), &none, &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut views, ) .await; @@ -5362,7 +5524,7 @@ mod tests { &one_confirmed(), &none, &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut views, ) .await; @@ -5393,7 +5555,7 @@ mod tests { &one_confirmed(), &none, &std::collections::BTreeMap::new(), - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut views, ) .await; @@ -5431,7 +5593,7 @@ mod tests { &one_confirmed(), &std::collections::BTreeMap::new(), &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut views, ) .await; @@ -5547,7 +5709,7 @@ mod tests { &one_confirmed(), &one_record(), &std::collections::BTreeMap::new(), - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5621,7 +5783,7 @@ mod tests { &confirmed, &records, &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await @@ -5667,7 +5829,7 @@ mod tests { &confirmed, &records, &upper, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5714,7 +5876,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5758,7 +5920,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5787,7 +5949,7 @@ mod tests { &one_confirmed(), &one_record(), &patched_shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5811,7 +5973,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5854,7 +6016,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5880,7 +6042,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5908,7 +6070,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5998,7 +6160,7 @@ mod tests { &one_confirmed(), &one_record(), &shas, - &std::collections::BTreeSet::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -6018,15 +6180,18 @@ mod tests { } } - /// A lock that names two platform builds, on a machine of the platform - /// the patch registry serves as upstream's own gem: the installed copy - /// and the committed cache-dir archive are upstream's gem, which is - /// what that lock entry pins. Neither is judged, whatever evidence - /// there is: nothing is stale, nothing is unjudged, and so nothing is - /// handed to the refresh. The same copies of a platform that has a - /// patched build are stale. + /// The copies of a platform build the patch registry serves as + /// upstream's own gem are judged by the sha256 of that gem alone: the + /// installed copy by the archive RubyGems installed it from, the + /// committed cache-dir archive by its own. Upstream's gem is the right + /// copy: nothing is stale, nothing is unjudged, and nothing is handed + /// to the refresh. A readable archive with another sha256 is a build + /// that was withdrawn: it is handed to the refresh apart from the + /// unpatched copies, and never withholds the gem from the same run's + /// VEX. A copy with no archive is not judged. The same copies of a + /// platform that has a patched build are stale. #[tokio::test] - async fn gem_stale_probe_leaves_a_build_on_upstreams_gem_alone() { + async fn gem_stale_probe_judges_a_build_on_upstreams_gem_by_its_archive() { let tmp = tempfile::tempdir().unwrap(); let cwd = tmp.path(); std::fs::write( @@ -6058,7 +6223,7 @@ mod tests { /// the ruby gem and the other platform's build. async fn judge( cwd: &std::path::Path, - upstream_leaves: &std::collections::BTreeSet, + upstream: &std::collections::BTreeMap, ) -> super::StaleInstallOutcome { let shas = std::collections::BTreeMap::from([( ("stale-unit".to_string(), "1.0.0".to_string()), @@ -6071,33 +6236,101 @@ mod tests { &one_confirmed(), &std::collections::BTreeMap::new(), &shas, - upstream_leaves, + upstream, &mut super::ViewFallback::offline(), ) .await } - let upstream = std::collections::BTreeSet::from([leaf.clone()]); - let patched_platform = std::collections::BTreeSet::new(); + let upstream_sha = socket_patch_core::vendor::file_sha256_hex(&archive) + .await + .expect("the archive's sha256"); + let upstream = std::collections::BTreeMap::from([(leaf.clone(), upstream_sha)]); + let patched_platform = std::collections::BTreeMap::new(); + // Nothing of a build on upstream's gem is an unpatched copy, and + // nothing of it keeps the gem out of the run's VEX. + let never_unpatched = |out: &super::StaleInstallOutcome| { + assert!(out.gems.is_empty(), "no unpatched copy"); + assert!(out.stale_purls.is_empty() && out.unjudged_purls.is_empty()); + }; let out = judge(cwd, &upstream).await; assert!(out.warnings.is_empty(), "{:?}", out.warnings); - assert!(out.gems.is_empty(), "nothing to refresh"); - assert!(out.stale_purls.is_empty() && out.unjudged_purls.is_empty()); + assert!(out.withdrawn.is_empty(), "nothing to refresh"); + never_unpatched(&out); let out = judge(cwd, &patched_platform).await; assert_eq!(out.warnings.len(), 1, "{:?}", out.warnings); assert_eq!(out.gems.len(), 1); + assert!(out.withdrawn.is_empty()); assert_eq!( out.gems[0].cache_archive.as_deref(), Some(committed.as_path()), "the committed archive is stale with it" ); + // The copy was installed from another archive than upstream's + // gem: a patched build that was withdrawn since. + std::fs::write(&archive, b"withdrawn platform .gem").unwrap(); + let out = judge(cwd, &upstream).await; + never_unpatched(&out); + let [gem] = out.withdrawn.as_slice() else { + panic!("one withdrawn copy: {:?}", out.withdrawn); + }; + assert_eq!((gem.purl.as_str(), gem.leaf.as_str()), (GEM_PURL, &*leaf)); + assert_eq!(gem.installed, Some((gem_dir.clone(), true))); + assert_eq!( + gem.cache_archive, None, + "the committed archive is upstream's gem" + ); + let [warning] = out.warnings.as_slice() else { + panic!("one warning: {:?}", out.warnings); + }; + assert_eq!(warning["code"], "redirect_gem_stale_install"); + let detail = detail_of(warning); + assert!( + detail.starts_with(&format!( + "{GEM_PURL} is back on upstream's own gem for arm64-darwin, whose patched build \ + was withdrawn, but its withdrawn install at {} was not refreshed, and `bundle \ + install` reuses an installed gem instead of fetching the upstream one.", + gem_dir.display() + )), + "{detail}" + ); + + // So is the committed archive, which goes with the install. + std::fs::write(&committed, b"withdrawn platform .gem").unwrap(); + let out = judge(cwd, &upstream).await; + never_unpatched(&out); + assert_eq!(out.withdrawn.len(), 1, "{:?}", out.withdrawn); + assert_eq!( + out.withdrawn[0].cache_archive.as_deref(), + Some(committed.as_path()) + ); + // With no archive beside the install there is nothing to judge it - // by: unjudged for a patched platform, still nothing for this one. + // by, and the committed archive is reported alone. std::fs::remove_file(&archive).unwrap(); + let out = judge(cwd, &upstream).await; + never_unpatched(&out); + let [gem] = out.withdrawn.as_slice() else { + panic!("the committed archive: {:?}", out.withdrawn); + }; + assert_eq!(gem.installed, None); + assert_eq!(gem.cache_archive.as_deref(), Some(committed.as_path())); + let detail = detail_of(&out.warnings[0]); + assert!( + detail.contains(&format!( + "but Bundler's cache dir still holds its withdrawn archive at {}", + committed.display() + )), + "{detail}" + ); + + // Nothing at all to judge by: unjudged for a patched platform, + // nothing for this one. std::fs::remove_file(&committed).unwrap(); let out = judge(cwd, &upstream).await; - assert!(out.warnings.is_empty() && out.unjudged_purls.is_empty()); + assert!(out.warnings.is_empty() && out.withdrawn.is_empty()); + never_unpatched(&out); let out = judge(cwd, &patched_platform).await; assert_eq!( out.unjudged_purls, @@ -6794,6 +7027,19 @@ mod tests { `bundle install` keeps the gems it already has), then run `socket-patch vex` to \ verify the installed patches." ); + // A copy of a withdrawn build went back to upstream's gem: the + // installed gems are what the lock pins, and never called patched. + assert_eq!( + steps(&bundler, GemCopies::Followed)[2], + " 2. Run `socket-patch vex` to verify the installed patches (the installed gems \ + already hold the builds the lockfile pins, so there is nothing to reinstall)." + ); + assert_eq!( + steps(&bundler, GemCopies::Withdrawn)[2], + " 2. Replace the withdrawn gem build with the command in the warning above (a plain \ + `bundle install` keeps the gems it already has), then run `socket-patch vex` to \ + verify the installed patches." + ); // A replaced cache-dir archive is one of Bundler's files too. let with_cache = [ "Gemfile.lock".to_string(), diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index 78a4f8517a..2d956741c5 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -3199,6 +3199,565 @@ async fn a_platform_served_as_upstreams_gem_is_no_stale_install() { } } +/// The snapshot the registry URL names once the patched build of +/// [`PLATFORM`] was withdrawn. +const LATER_SNAPSHOT: u32 = 5; + +/// A machine of the platform [`PLATFORM`] that holds a patched build which +/// was withdrawn since. The lock was moved while both locked platforms had +/// a patched build, and the hosted scan put this machine's patched build +/// in place: the installed copy, the archive RubyGems keeps beside it and +/// the committed `bundle cache` archive are that build. After the +/// withdrawal the reference lists upstream's own gem for this platform (no +/// patch), under a later snapshot, beside the other platform's patched +/// build. +struct WithdrawnBuild { + _tmp: tempfile::TempDir, + proj: PathBuf, + home: PathBuf, + gem_dir: PathBuf, + home_archive: PathBuf, + committed: PathBuf, + /// Upstream's gem for this platform, and the build that was withdrawn. + upstream: Vec, + withdrawn: Vec, + /// The sha256 of the other platform's patched build. + other_patched: String, + /// The path the registry serves this platform's gem at after the + /// withdrawal. + file_route: String, +} + +impl WithdrawnBuild { + /// Stage the machine against `server`, which answers as the patch + /// service does after the withdrawal, except for this platform's gem + /// file: each case serves that its own way. + async fn stage(server: &MockServer) -> WithdrawnBuild { + let upstream = real_gem_for(UPSTREAM_LIB, PLATFORM); + let other_upstream = real_gem_for(UPSTREAM_LIB, OTHER_PLATFORM); + let withdrawn = real_gem_for(PATCHED_LIB, PLATFORM); + let other_patched = sha256_of(&real_gem_for(PATCHED_LIB, OTHER_PLATFORM)); + let ruby_sha = sha256_of(&real_gem(PATCHED_LIB)); + let leaf = format!("{DEP}-{DEP_VERSION}-{PLATFORM}"); + + // While both platforms had a patched build. + mount_api_with( + server, + None, + &ruby_sha, + &[ + (PLATFORM, sha256_of(&withdrawn), Some(ARM_UUID)), + (OTHER_PLATFORM, other_patched.clone(), Some(LINUX_UUID)), + ], + ) + .await; + Mock::given(method("GET")) + .and(path(format!( + "{}/gems/{leaf}.gem", + snapshot_registry_path() + ))) + .respond_with( + ResponseTemplate::new(200) + .set_body_raw(withdrawn.clone(), "application/octet-stream"), + ) + .mount(server) + .await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"), + ) + .unwrap(); + std::fs::write( + proj.join("Gemfile.lock"), + platform_lock(&sha256_of(&upstream), &sha256_of(&other_upstream)), + ) + .unwrap(); + let home = project_home(&proj); + let gem_dir = install_real_gem_for(&home, UPSTREAM_LIB, PLATFORM); + let home_archive = home.join("cache").join(format!("{leaf}.gem")); + let committed = proj + .join("vendor") + .join("cache") + .join(format!("{leaf}.gem")); + std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); + std::fs::write(&committed, &upstream).unwrap(); + let uri = server.uri(); + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "premise: the first scan\n{stdout}\n{stderr}"); + assert_eq!( + installed_lib(&gem_dir), + PATCHED_LIB, + "premise: this machine holds the patched build" + ); + for archive in [&home_archive, &committed] { + assert_eq!(std::fs::read(archive).unwrap(), withdrawn, "premise"); + } + + // The patched build of this platform is withdrawn. + server.reset().await; + mount_patch_api_with( + server, + UUID, + PATCHED_LIB, + None, + &ruby_sha, + &[ + (PLATFORM, sha256_of(&upstream), None), + (OTHER_PLATFORM, other_patched.clone(), Some(LINUX_UUID)), + ], + LATER_SNAPSHOT, + ) + .await; + let file_route = + format!("/patch-registry/gem/{TOKEN}/{UUID}/s/{LATER_SNAPSHOT}/gems/{leaf}.gem"); + WithdrawnBuild { + _tmp: tmp, + proj, + home, + gem_dir, + home_archive, + committed, + upstream, + withdrawn, + other_patched, + file_route, + } + } + + /// The registry hands this platform's gem on as `body`. + async fn relay(&self, server: &MockServer, body: &[u8]) { + Mock::given(method("GET")) + .and(path(self.file_route.clone())) + .respond_with( + ResponseTemplate::new(200).set_body_raw(body.to_vec(), "application/octet-stream"), + ) + .mount(server) + .await; + } + + /// `socket-patch scan --mode hosted` with `extra`: exit code, stdout + /// and stderr. + fn scan(&self, server: &MockServer, extra: &[&str]) -> (i32, String, String) { + let uri = server.uri(); + common::run_with_env(&self.proj, &scan_args(&self.proj, &uri, extra), &[]) + } + + /// A `--json` scan with `extra`, which must exit 0: its envelope. + fn scan_json(&self, server: &MockServer, extra: &[&str]) -> serde_json::Value { + let mut args = vec!["--json"]; + args.extend_from_slice(extra); + let (code, stdout, stderr) = self.scan(server, &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + env + } + + /// The lock follows the reference: the registry at the later snapshot, + /// upstream's sha256 for this platform, the other platform's patched + /// build as it was. + fn assert_lock_is_back_on_upstreams_gem(&self, server: &MockServer) { + let lock = std::fs::read_to_string(self.proj.join("Gemfile.lock")).unwrap(); + assert!( + lock.contains(&format!( + " remote: {}/patch-registry/gem/{TOKEN}/{UUID}/s/{LATER_SNAPSHOT}/\n", + server.uri() + )) && lock.contains(&format!( + "CHECKSUMS\n {DEP} ({DEP_VERSION}-{PLATFORM}) sha256={}\n {DEP} \ + ({DEP_VERSION}-{OTHER_PLATFORM}) sha256={}\n", + sha256_of(&self.upstream), + self.other_patched + )), + "{lock}" + ); + } + + /// The copy, the archive beside it and the committed archive are all + /// `gem`, whose `lib` Ruby loads. + fn assert_holds(&self, gem: &[u8], lib: &str) { + assert_eq!(installed_lib(&self.gem_dir), lib); + assert_eq!(std::fs::read(&self.home_archive).unwrap(), gem); + assert_eq!(std::fs::read(&self.committed).unwrap(), gem); + assert!( + !self.home.join(".socket-patch-refresh").exists(), + "no stage left" + ); + } + + /// What a VEX document says of the gem whatever this machine holds: + /// the other platform's build is attested under its own patch, and + /// this platform's build is affected. + fn assert_vex(&self, doc: &serde_json::Value) { + let text = |value: &serde_json::Value| value.as_str().unwrap_or_default().to_string(); + let said: Vec<(String, String, String)> = doc["statements"] + .as_array() + .expect("statements") + .iter() + .map(|st| { + let packages = st["products"][0]["subcomponents"].as_array(); + assert_eq!(packages.map(Vec::len), Some(1), "{st}"); + ( + text(&st["status"]), + text(&st["products"][0]["subcomponents"][0]["@id"]), + text(&st["impact_statement"]), + ) + }) + .collect(); + assert_eq!( + said, + [ + ( + "not_affected".to_string(), + format!("{PURL}?platform={OTHER_PLATFORM}"), + format!("Patched via Socket patch {LINUX_UUID} (redirected)"), + ), + ( + "affected".to_string(), + format!("{PURL}?platform={PLATFORM}"), + String::new(), + ), + ], + "{doc}" + ); + assert!( + !doc.to_string().contains(ARM_UUID), + "the withdrawn build's patch is named nowhere: {doc}" + ); + } + + /// A later `socket-patch vex` over the project: its outcome. + fn later_vex(&self, server: &MockServer) -> vex_e2e_common::VexOutcome { + let later = vex_e2e_common::VexRun { + api_url: Some(server.uri()), + api_token: Some("fake".into()), + org: Some(ORG.into()), + patch_server_url: Some(server.uri()), + product: Some("pkg:gem/app@1.0.0".into()), + ..vex_e2e_common::VexRun::default() + }; + vex_e2e_common::run_vex(&vex_e2e_common::binary(), &self.proj, &later) + } +} + +/// The paths of the gem files and patch records `server` was asked for +/// after its first `skip` requests. +async fn gems_and_views_since(server: &MockServer, skip: usize) -> Vec { + let requests = server.received_requests().await.unwrap_or_default(); + let routes = requests.iter().skip(skip).map(|r| r.url.path().to_string()); + routes + .filter(|route| route.contains("/gems/") || route.contains("/patches/view/")) + .collect() +} + +/// A patched build that was withdrawn must not stay installed. The next +/// scan puts upstream's sha256 back into the lock, and the guard judges +/// this machine's copy by the archive it was installed from: it is not +/// upstream's gem, so it is replaced, with the committed archive, by the +/// file the patch registry serves for the platform, verified against the +/// sha256 the reference lists. Whether the registry relays that file +/// (200) or redirects to the upstream registry (302), in which case the +/// other host learns nothing of the grant. One download, no patch record. +/// The run's VEX and a later one say `affected` of this platform's build +/// and still attest the other; a further scan changes nothing. +#[tokio::test(flavor = "multi_thread")] +async fn a_withdrawn_build_is_replaced_with_upstreams_gem_through_the_registry() { + for redirects in [false, true] { + let server = MockServer::start().await; + let elsewhere = MockServer::start().await; + let w = WithdrawnBuild::stage(&server).await; + let leaf = format!("{DEP}-{DEP_VERSION}-{PLATFORM}"); + if redirects { + let location = format!("{}/gems/{leaf}.gem", elsewhere.uri()); + Mock::given(method("GET")) + .and(path(w.file_route.clone())) + .respond_with( + ResponseTemplate::new(302) + .insert_header("Location", location.as_str()) + .insert_header("Cache-Control", "no-store"), + ) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!("/gems/{leaf}.gem"))) + .respond_with( + ResponseTemplate::new(200) + .set_body_raw(w.upstream.clone(), "application/octet-stream"), + ) + .mount(&elsewhere) + .await; + } else { + w.relay(&server, &w.upstream).await; + } + + let env = w.scan_json(&server, &[]); + assert_eq!( + hosted_pins(&env), + [( + format!("{PURL}?platform={OTHER_PLATFORM}"), + LINUX_UUID.to_string() + )], + "redirects={redirects}: {env}" + ); + w.assert_lock_is_back_on_upstreams_gem(&server); + assert!(stale_warnings(&env).is_empty(), "nothing is left: {env}"); + let mut notes = warnings_with_code(&env, "redirect_gem_install_refreshed"); + notes.sort(); + assert_eq!( + notes, + [ + format!( + "{PURL}: replaced the withdrawn archive at {} with the upstream gem", + w.committed.display() + ), + format!( + "{PURL}: replaced the withdrawn install at {} with the upstream gem", + w.gem_dir.display() + ), + ], + "redirects={redirects}: {env}" + ); + w.assert_holds(&w.upstream, UPSTREAM_LIB); + assert_eq!( + gems_and_views_since(&server, 0).await, + [w.file_route.clone()], + "redirects={redirects}: one download for both, and no patch record" + ); + let handed_on = elsewhere.received_requests().await.unwrap_or_default(); + assert_eq!(handed_on.len(), usize::from(redirects)); + for request in &handed_on { + let sent = format!("{:?}", request.headers); + assert!( + request.headers.get("referer").is_none() && !sent.contains(TOKEN), + "the other host learns nothing of the grant: {sent}" + ); + } + + // A further scan changes nothing and downloads nothing. + let lock = std::fs::read(w.proj.join("Gemfile.lock")).unwrap(); + let before = server.received_requests().await.unwrap_or_default().len(); + let vex_path = w.proj.join("run.vex.json"); + let with_vex = [ + "--vex", + vex_path.to_str().unwrap(), + "--vex-product", + "pkg:gem/app@1.0.0", + ]; + let env = w.scan_json(&server, &with_vex); + assert!( + stale_warnings(&env).is_empty() + && warnings_with_code(&env, "redirect_gem_install_refreshed").is_empty(), + "redirects={redirects}: {env}" + ); + assert_eq!(std::fs::read(w.proj.join("Gemfile.lock")).unwrap(), lock); + w.assert_holds(&w.upstream, UPSTREAM_LIB); + let asked = gems_and_views_since(&server, before).await; + assert!( + asked.iter().all(|route| !route.contains("/gems/")), + "redirects={redirects}: {asked:?}" + ); + + // VEX, from that run and from a later `vex`. + assert_eq!(env["vex"]["affected"], 1, "{env}"); + w.assert_vex(&vex_e2e_common::read_doc(&vex_path).expect("the run's document")); + let out = w.later_vex(&server); + assert_eq!(out.code, Some(0), "redirects={redirects}: {out}"); + w.assert_vex(out.doc()); + assert_eq!(out.envelope["status"], "success", "{out}"); + } +} + +/// For a person, the run that replaces the copy of a withdrawn build says +/// so in one line per kind, each naming the upstream gem and why, never a +/// patched one, and has nothing left to reinstall. +#[tokio::test(flavor = "multi_thread")] +async fn a_withdrawn_build_refresh_says_what_took_its_place() { + let server = MockServer::start().await; + let w = WithdrawnBuild::stage(&server).await; + w.relay(&server, &w.upstream).await; + + let (code, stdout, stderr) = w.scan(&server, &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + for line in [ + format!( + "Replaced the installed copy of 1 gem with the upstream build (its patched build \ + was withdrawn): {DEP} {DEP_VERSION}.\n" + ), + format!( + "Replaced 1 archive in Bundler's cache dir with the upstream gem (its patched build \ + was withdrawn): {DEP} {DEP_VERSION}.\n" + ), + ] { + assert!(stderr.contains(&line), "missing {line:?}:\n{stderr}"); + } + assert!( + !stderr.contains("still holds") && !stderr.contains("patched build:"), + "nothing is left to warn about, and nothing is called patched:\n{stderr}" + ); + assert!( + stdout.contains( + " 2. Run `socket-patch vex` to verify the installed patches (the installed gems \ + already hold the builds the lockfile pins, so there is nothing to reinstall).\n" + ), + "{stdout}" + ); + assert!( + stdout.contains(&format!("vendor/cache/{DEP}-{DEP_VERSION}-{PLATFORM}.gem")), + "the replaced archive is a file to commit:\n{stdout}" + ); + w.assert_holds(&w.upstream, UPSTREAM_LIB); +} + +/// The registry relays bytes that are not the gem the reference lists for +/// the platform: no byte of them is used. The withdrawn build stays, the +/// lock still goes back to upstream's sha256, and the run says, as a +/// warning and never as a failure, that a withdrawn build is still +/// installed and how to remove it. That copy keeps nothing of the gem out +/// of the VEX: the other platform's build is attested, this one affected. +#[tokio::test(flavor = "multi_thread")] +async fn a_withdrawn_build_is_not_replaced_with_a_gem_the_reference_does_not_list() { + let server = MockServer::start().await; + let w = WithdrawnBuild::stage(&server).await; + // The same gem with other bytes. + w.relay( + &server, + &real_gem_for("module StaleProbeGem\n EVIL = true\nend\n", PLATFORM), + ) + .await; + let spec = w + .home + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}-{PLATFORM}.gemspec")); + let files = [&spec, &w.home_archive, &w.committed]; + + // For a person: one warning, and what to run. + let (code, stdout, stderr) = w.scan(&server, &[]); + assert_eq!(code, 0, "a failed refresh never fails the scan:\n{stderr}"); + w.assert_lock_is_back_on_upstreams_gem(&server); + w.assert_holds(&w.withdrawn, PATCHED_LIB); + let words: Vec = files.iter().map(|path| shell_word(path)).collect(); + let warning = format!( + "Warning: 1 gem still holds a patched build on disk that was withdrawn.\n - Not \ + refreshed (the upstream gem the server sent does not have the pinned sha256): {DEP} \ + {DEP_VERSION}. Re-run `socket-patch scan` to retry, or run `rm -f {} && bundle \ + install`.\n", + words.join(" ") + ); + assert!(stderr.contains(&warning), "missing {warning:?}:\n{stderr}"); + assert_eq!(stderr.matches("still holds").count(), 1, "{stderr}"); + assert!(!stderr.contains("Replaced"), "{stderr}"); + assert!( + stdout.contains( + " 2. Replace the withdrawn gem build with the command in the warning above (a \ + plain `bundle install` keeps the gems it already has), then run `socket-patch vex` \ + to verify the installed patches.\n" + ), + "{stdout}" + ); + + // The same in `--json`, on every later run, with the run's own VEX. + let vex_path = w.proj.join("run.vex.json"); + let with_vex = [ + "--vex", + vex_path.to_str().unwrap(), + "--vex-product", + "pkg:gem/app@1.0.0", + ]; + let env = w.scan_json(&server, &with_vex); + let listed: Vec = files.iter().map(|p| p.display().to_string()).collect(); + assert_eq!( + stale_warnings(&env), + [format!( + "{PURL} is back on upstream's own gem for {PLATFORM}, whose patched build was \ + withdrawn, but its withdrawn install at {} was not refreshed (the upstream gem the \ + server sent does not have the pinned sha256), and `bundle install` reuses an \ + installed gem instead of fetching the upstream one. Re-run `socket-patch scan` to \ + retry, or remove {} and run `bundle install`", + w.gem_dir.display(), + listed.join(", ") + )], + "{env}" + ); + assert!( + warnings_with_code(&env, "redirect_gem_install_refreshed").is_empty(), + "{env}" + ); + w.assert_holds(&w.withdrawn, PATCHED_LIB); + assert_eq!(env["vex"]["statements"], 2, "{env}"); + assert_eq!(env["vex"]["affected"], 1, "{env}"); + w.assert_vex(&vex_e2e_common::read_doc(&vex_path).expect("the run's document")); + let out = w.later_vex(&server); + assert_eq!(out.code, Some(0), "{out}"); + w.assert_vex(out.doc()); + assert_eq!(out.envelope["status"], "success", "{out}"); +} + +/// The refresh is switched off, or only previewed: nothing is downloaded +/// and nothing replaced. A dry run says what a wet run would replace, and +/// `--no-gem-install-refresh` warns that the withdrawn build is still +/// installed, with the run that replaces it. That run then does. +#[tokio::test(flavor = "multi_thread")] +async fn a_withdrawn_build_is_left_with_a_warning_when_the_refresh_is_off() { + let server = MockServer::start().await; + let w = WithdrawnBuild::stage(&server).await; + w.relay(&server, &w.upstream).await; + + let env = w.scan_json(&server, &["--dry-run"]); + let mut would = warnings_with_code(&env, "redirect_gem_install_would_refresh"); + would.sort(); + assert_eq!( + would, + [ + format!( + "{PURL}: would replace the withdrawn archive at {} with the upstream gem", + w.committed.display() + ), + format!( + "{PURL}: would replace the withdrawn install at {} with the upstream gem", + w.gem_dir.display() + ), + ], + "{env}" + ); + assert!(stale_warnings(&env).is_empty(), "{env}"); + w.assert_holds(&w.withdrawn, PATCHED_LIB); + + let env = w.scan_json(&server, &["--no-gem-install-refresh"]); + w.assert_lock_is_back_on_upstreams_gem(&server); + let stale = stale_warnings(&env); + assert_eq!(stale.len(), 1, "{env}"); + assert!( + stale[0].starts_with(&format!( + "{PURL} is back on upstream's own gem for {PLATFORM}, whose patched build was \ + withdrawn, but its withdrawn install at {} was not refreshed \ + (`--no-gem-install-refresh` is set), and `bundle install` reuses an installed gem \ + instead of fetching the upstream one. Re-run without `--no-gem-install-refresh`, \ + or remove ", + w.gem_dir.display() + )) && stale[0].ends_with(" and run `bundle install`"), + "{}", + stale[0] + ); + w.assert_holds(&w.withdrawn, PATCHED_LIB); + assert_eq!( + gems_and_views_since(&server, 0).await, + Vec::::new(), + "neither run downloads a gem or fetches a record" + ); + + // The run the warning names. + let env = w.scan_json(&server, &[]); + assert!(stale_warnings(&env).is_empty(), "{env}"); + assert_eq!( + warnings_with_code(&env, "redirect_gem_install_refreshed").len(), + 2, + "{env}" + ); + w.assert_holds(&w.upstream, UPSTREAM_LIB); +} + /// A fresh checkout: nothing is installed, and the lock names the gem only /// as platform builds. The hosted scan reads the gem from the lock alone /// and pins every build to its patched build. Where the patch registry From e4f6c672b2f4ca6579db4f4f21bce8c647112bc1 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 26 Nov 2026 00:43:18 -0500 Subject: [PATCH 029/120] Drive a withdrawn build through real Bundler, on a registry that relays The patch registry answers the file of a platform with no patched build with upstream's own bytes. The stand-in of the real-Bundler suite redirected to a second server. It relays by default, and one case keeps the redirect, which Bundler and the refresh must still follow. The new case installs this machine's patched build, withdraws it, and shows what Bundler does by itself: `bundle install` succeeds, changes nothing, and Ruby keeps loading the withdrawn build. The scan then replaces the copy through the registry and `bundle exec ruby` loads upstream's code; a further scan changes nothing. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_redirect_gem_build.rs | 246 ++++++++++++++++-- 1 file changed, 228 insertions(+), 18 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs index 3ad52067b1..55536087a9 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -6767,11 +6767,14 @@ async fn gem_hosted_scan_says_the_gem_is_held_at_its_version() { // with its patch, each platform still on upstream's gem with none. A // request without it gets the plain URL and no list; // * the registry under a snapshot lists every gem of that list, serves -// the file of a patched build, and answers the file of a platform with -// none with a 302 to the upstream registry's own file: here a second -// wiremock, the stand-in of that registry's file host, so nothing leaves -// the machine. A platform whose build is still being made is in neither. -// A snapshot answers as it did once a later one exists. +// the file of a patched build, and hands on the file of a platform +// with none: it relays upstream's own bytes (a 200). Where a case says +// so ([`PlatformProject::redirects`]) it answers that file with a 302 +// to the upstream registry's own file, which a client must follow too: +// here a second wiremock, the stand-in of that registry's file host, +// so nothing leaves the machine. A platform whose build is still being +// made is in neither. A snapshot answers as it did once a later one +// exists. // // "A machine of platform X" is this machine: bundler installs the platform // gem of the host it runs on, so each case that turns on which platform is @@ -6954,8 +6957,9 @@ const API_TOKEN: &str = "sktsec_00000000000000000000000000000000000000000000_api enum Has { /// A patched build, under a patch of its own. Patched, - /// No patched build yet: the registry lists upstream's own gem and - /// answers its file with a redirect to the upstream registry. + /// No patched build: the registry lists upstream's own gem and hands + /// its file on (it relays the bytes, or redirects to the upstream + /// registry where the case says so). Upstream, /// A patched build is being made: no list names the platform yet. Building, @@ -7307,8 +7311,13 @@ struct PlatformProject { /// `index_url` is the registry of the listing served last. fx: RedirectFixture, /// The stand-in of the upstream registry's file host: where the patch - /// registry sends a client for a platform it has no patched build of. + /// registry sends a client for a platform it has no patched build of, + /// when it redirects. files: MockServer, + /// The registry answers the file of a platform with no patched build + /// with a 302 to [`Self::files`], for the snapshots served from now + /// on. Off: it relays upstream's bytes itself. + redirects: bool, service: std::sync::Arc, /// The registry snapshots mounted so far, by path. snapshots: std::collections::BTreeSet, @@ -7483,6 +7492,7 @@ impl PlatformProject { _server: server, }, files, + redirects: false, service, snapshots: std::collections::BTreeSet::new(), own, @@ -7553,7 +7563,9 @@ impl PlatformProject { Some(_) => (&self.service.builds, None), None => ( &self.service.upstream, - Some(format!("{}/gems/{DEP}-{token}.gem", self.service.files)), + self.redirects.then(|| { + format!("{}/gems/{DEP}-{token}.gem", self.service.files) + }), ), }; IndexBuild { @@ -8630,7 +8642,8 @@ async fn gem_vendored_unwind_restores_a_platform_install_without_checksums() { /// mode and unfrozen, and leaves the lock byte-identical: a machine of /// the patched platform gets the PATCHED gem from the registry, a /// machine of the other gets UPSTREAM's gem, which the registry -/// answers with a 302 that bundler follows to the upstream file host; +/// relays itself or, with `redirects`, answers with a 302 that +/// bundler follows to the upstream file host; /// 3. the scan itself downloads the patched build to refresh the copy /// bundler had installed on the patched platform, and nothing at all /// on the other, whose installed copy is upstream's gem as its lock @@ -8638,10 +8651,11 @@ async fn gem_vendored_unwind_restores_a_platform_install_without_checksums() { /// 4. a re-scan changes nothing, reports no build as newly patched and /// offers no newer patch; a person reads one plain line; /// 5. `rollback` hands back the pre-scan pair byte for byte. -async fn one_platform_patched_and_one_on_upstream(tag: &str, own_patched: bool) { +async fn one_platform_patched_and_one_on_upstream(tag: &str, own_patched: bool, redirects: bool) { let Some(mut p) = PlatformProject::start(tag, (2, 6), true, false, &[]).await else { return; }; + p.redirects = redirects; let (own, foreign) = (p.own.clone(), p.foreign.clone()); let (patched, upstream) = if own_patched { (own.as_str(), foreign.as_str()) @@ -8743,15 +8757,15 @@ async fn one_platform_patched_and_one_on_upstream(tag: &str, own_patched: bool) std::slice::from_ref(&own_file), "{name}: bundler asks the patch registry for this machine's platform gem alone" ); - let handed_on: &[String] = if own_patched { - &[] - } else { + let handed_on: &[String] = if redirects && !own_patched { &[format!("{}.gem", p.own_leaf())] + } else { + &[] }; assert_eq!( redirected, handed_on, - "{name}: the registry hands a platform with no patched build on to the upstream \ - file host, and serves a patched build itself" + "{name}: the registry serves a patched build itself, and relays the gem of a \ + platform with no patched build unless it redirects to the upstream file host" ); } @@ -8809,14 +8823,24 @@ async fn one_platform_patched_and_one_on_upstream(tag: &str, own_patched: bool) #[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] async fn gem_hosted_machine_of_the_patched_platform_installs_the_patched_gem() { - one_platform_patched_and_one_on_upstream("platform-one-patched-own", true).await; + one_platform_patched_and_one_on_upstream("platform-one-patched-own", true, false).await; } #[tokio::test(flavor = "multi_thread")] #[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] async fn gem_hosted_machine_of_a_platform_with_no_patched_build_installs_upstreams_gem() { - one_platform_patched_and_one_on_upstream("platform-one-patched-other", false).await; + one_platform_patched_and_one_on_upstream("platform-one-patched-other", false, false).await; +} + +/// The same machine against a registry that answers the file of a platform +/// with no patched build with a redirect to the upstream registry: bundler +/// follows it. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_machine_of_a_platform_with_no_patched_build_follows_a_redirect_to_upstream() { + one_platform_patched_and_one_on_upstream("platform-one-patched-other-302", false, true).await; } /// VEX of a lock with ONE patched platform and one the registry still @@ -9253,6 +9277,192 @@ async fn gem_hosted_bundle_lock_add_platform_resolves_from_the_patch_registry() p.assert_installed(&fresh, true); } +/// A patched build that was withdrawn must not stay installed, against the +/// REAL bundler, on a `CHECKSUMS` lock: +/// +/// 1. the scan moves the lock while this machine's platform has a +/// patched build and replaces the copy bundler had installed; `bundle +/// install` agrees, and Ruby loads the PATCHED code; +/// 2. the build is withdrawn: the list has upstream's sha256 for this +/// platform, with no patch. A scan that may not refresh puts that +/// sha256 back into the lock and warns that the withdrawn build is +/// still installed. Bundler does not replace it: `bundle install` +/// succeeds, changes nothing, and Ruby still loads the withdrawn +/// build; +/// 3. the scan replaces the copy with upstream's gem, downloaded once +/// from the patch registry (which relays it; nothing is asked of the +/// upstream file host) and reported as such. `bundle install` leaves +/// it, and `bundle exec ruby` loads UPSTREAM's code; +/// 4. a further scan changes nothing, downloads nothing and warns of +/// nothing; +/// 5. a fresh checkout installs upstream's gem frozen; +/// 6. the run's own document and a later `vex` say `affected` of this +/// machine's build and attest the other platform's under its patch. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_withdrawn_build_is_replaced_with_upstreams_gem() { + let Some(mut p) = PlatformProject::start("platform-withdrawn", (2, 6), true, false, &[]).await + else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let warm_lib = p.installed_lib(&p.fx.proj); + + // 1. Both platforms patched: this machine holds the patched build. + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let first = p.serve(Some(&every)).await; + let env = p.scan(&[]); + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + let first_lock = p.assert_hosted_pair(&first, &[(&own, true), (&foreign, true)]); + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), first_lock); + p.assert_installed(&p.fx.proj, true); + + // 2. The build of this machine's platform is withdrawn. + let after = [ + (own.as_str(), Has::Upstream), + (foreign.as_str(), Has::Patched), + ]; + let second = p.serve(Some(&after)).await; + assert_ne!(first, second, "a withdrawal is a newer snapshot"); + let withdrawing = p.mark().await; + let env = p.scan(&["--no-gem-install-refresh"]); + assert_eq!( + hosted_events(&env), + by_platform(vec![upstream_event(&own), patched_event(&foreign, false)]), + "{env}" + ); + let lock = p.assert_hosted_pair(&second, &[(&own, false), (&foreign, true)]); + let pin = |patched: bool| { + let token = build_token(Some(&own)); + let sha = p.service.sha(Some(&own), patched); + format!(" {DEP} ({token}) sha256={sha}\n") + }; + assert_eq!( + lock, + first_lock + .replace(&first, &second) + .replace(&pin(true), &pin(false)), + "the URL and the one checksum that changed" + ); + assert_eq!(warning_codes(&env), ["redirect_gem_stale_install"], "{env}"); + let gem_dir = warm_lib.parent().and_then(Path::parent).unwrap(); + let detail = env["warnings"][0]["detail"].as_str().unwrap_or_default(); + assert!( + detail.starts_with(&format!( + "{PURL} is back on upstream's own gem for {own}, whose patched build was withdrawn, \ + but its withdrawn install at {} was not refreshed (`--no-gem-install-refresh` is \ + set), and `bundle install` reuses an installed gem instead of fetching the upstream \ + one. Re-run without `--no-gem-install-refresh`, or remove ", + gem_dir.display() + )), + "{detail}" + ); + let (fetched, redirected) = p.fetched_since(withdrawing).await; + assert_eq!( + (fetched, redirected), + (Vec::new(), Vec::new()), + "nothing is downloaded" + ); + // Bundler keeps the gem it has installed. + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), lock, "`bundle install` leaves the lock alone"); + p.assert_installed(&p.fx.proj, true); + + // 3. The scan replaces it with upstream's gem, through the registry. + let replacing = p.mark().await; + let env = p.scan(&[]); + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + assert_eq!( + env["warnings"][0]["detail"], + format!( + "{PURL}: replaced the withdrawn install at {} with the upstream gem", + gem_dir.display() + ), + "{env}" + ); + assert_eq!(env["redirect"]["rewrittenFiles"], serde_json::json!([])); + assert_eq!(p.lock(), lock); + let (fetched, redirected) = p.fetched_since(replacing).await; + assert_eq!( + fetched, + [format!( + "{}gems/{}.gem", + &second[p.api().len()..], + p.own_leaf() + )], + "upstream's gem comes from the patch registry, once" + ); + assert_eq!(redirected, Vec::::new(), "which relays it"); + assert_eq!( + p.views_since(replacing).await, + Vec::::new(), + "no patch record is fetched" + ); + assert_eq!( + std::fs::read_to_string(&warm_lib).unwrap(), + p.service.orig, + "the installed copy is upstream's gem" + ); + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), lock, "`bundle install` leaves the lock alone"); + p.assert_installed(&p.fx.proj, false); + + // 4. A further scan changes nothing. + let again = p.mark().await; + let env = p.scan(&[]); + assert_eq!( + p.lock(), + lock, + "a further scan leaves the lock byte-identical" + ); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], serde_json::json!([])); + assert_eq!( + hosted_events(&env), + by_platform(vec![upstream_event(&own), patched_event(&foreign, false)]), + "{env}" + ); + let (fetched, redirected) = p.fetched_since(again).await; + assert_eq!( + (fetched, redirected), + (Vec::new(), Vec::new()), + "nothing is downloaded" + ); + p.assert_installed(&p.fx.proj, false); + + // 5. A fresh checkout installs upstream's gem. + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, false); + + // 6. VEX: this machine's build is affected, the other attested. + let statements = build_statements(&after, false); + let env = p.scan(&["--vex", "out.vex.json", "--vex-product", PRODUCT]); + let in_run = vex_e2e_common::read_doc(&p.fx.proj.join("out.vex.json")); + assert_eq!(said(&in_run.expect("the run's document")), statements); + assert_eq!( + (&env["vex"]["statements"], &env["vex"]["affected"]), + (&serde_json::json!(2), &serde_json::json!(1)), + "{env}" + ); + let out = vex_e2e_common::run_vex(&binary(), &p.fx.proj, &vex_run(&p.fx)); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!(said(out.doc()), statements, "{out}"); + assert_eq!(out.envelope["status"], "success", "{out}"); +} + /// The stale-install refresh downloads `gems/` from the patch /// registry, which may answer a file with a redirect (it does for every /// platform it has no patched build of). The download follows it: here From b71e4513f19bbe6cdedfabe5cdbfb33f91e31c2a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 26 Nov 2026 00:43:24 -0500 Subject: [PATCH 030/120] Relay a pass-through gem file from the stand-in patch service The stand-in of the nokogiri script answered the file of a platform with no patched build with a redirect to its upstream port. The patch registry relays such a file, so the stand-in does, and the script checks that nothing is asked of the upstream port. `:redirect => true` (`--pass-through-redirect`) keeps the redirect for a run that wants it. Co-Authored-By: Claude Fable 5.2 --- tests/nokogiri/nokogiri_e2e.rb | 26 ++++++++++++++++++-------- tests/nokogiri/patch_service.rb | 17 +++++++++++------ 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index 363a1941da..66ce519277 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -527,8 +527,9 @@ def scenario(name) # per locked build. A fresh checkout installs with the lock # frozen, as CI and a deploy do, and Ruby there loads the # patched gem where this machine's platform has one and - # upstream's own gem, which the registry answers with a - # redirect, where it has none yet. With no locked build + # upstream's own gem, which the registry relays (or, with + # `--pass-through-redirect`, answers with a redirect to the + # upstream registry), where it has none yet. With no locked build # patched nothing moves. Once the service has the builds that # were missing, the next scan moves the lock to the newer # registry snapshot and the install is the patched gem. @@ -572,7 +573,8 @@ def patch_service @patch_service.stop if @patch_service @patch_service = PatchService.new( "nokogiri", @version, locked_platforms, UUID, GHSA, File.join(File.dirname(@proj), "patch-service"), - "\nmodule Nokogiri\n #{RB_CONST} = 1\nend\n", :pass_through => pass_through + "\nmodule Nokogiri\n #{RB_CONST} = 1\nend\n", :pass_through => pass_through, + :redirect => @opts[:redirect] ) end @@ -810,10 +812,16 @@ def installs_frozen(service, mode, rewritten, patched) check(now[RB_CONST].nil?, "Ruby there loads upstream's nokogiri: this platform has no patched build yet", JSON.pretty_generate(now)) file = "nokogiri-#{@version}-#{own_platform}.gem" - redirected = service.requests.any? { |_, path, status| status == 302 && path.end_with?("/gems/#{file}") } - check(redirected && service.upstream_requests.include?(["GET", "/gems/#{file}", 200]), - "which the patch registry answers with a redirect to the upstream registry", - (service.requests + service.upstream_requests).inspect) + answers = service.requests.select { |_, path, _| path.end_with?("/gems/#{file}") }.map(&:last).uniq + if @opts[:redirect] + check(answers == [302] && service.upstream_requests.include?(["GET", "/gems/#{file}", 200]), + "which the patch registry answers with a redirect to the upstream registry", + (service.requests + service.upstream_requests).inspect) + else + check(answers == [200] && service.upstream_requests.empty?, + "which the patch registry relays itself, with nothing asked of the upstream registry", + (service.requests + service.upstream_requests).inspect) + end end check(now["binary_sha256"] == @baseline["binary_sha256"], "with the precompiled binary, nothing compiled") check(now["smoke"] == @baseline["smoke"], "and nokogiri parses, queries, transforms and validates") @@ -1114,7 +1122,7 @@ class SocketPatchE2E < Rails::Application end opts = { :install => "any", :build => "ok", :gem_home => "project", :scenarios => %w[ruby c libxml2], :gems => [], - :settings => [], :unread_check => true, :add_platforms => [], :pass_through => [] } + :settings => [], :unread_check => true, :add_platforms => [], :pass_through => [], :redirect => false } parser = OptionParser.new do |o| o.banner = "usage: ruby nokogiri_e2e.rb --socket-patch BIN --nokogiri VERSION [options]" o.on("--socket-patch BIN", "the socket-patch binary under test") { |v| opts[:socket_patch] = v } @@ -1142,6 +1150,8 @@ class SocketPatchE2E < Rails::Application o.on("--pass-through LIST", Array, "hosted and vendored: the locked platforms the stand-in patch service has no", "patched build of yet, so that it hands on upstream's own gem for them: platform names,", "`own` (this machine's) or `others` (every other locked one)") { |v| opts[:pass_through].concat(v) } + o.on("--pass-through-redirect", "the stand-in answers the file of such a platform with a redirect to the upstream", + "registry, which a client must follow, where by default it relays the file") { opts[:redirect] = true } o.on("--rails VERSION", "also install this Rails (a Gemfile requirement, for example '~> 7.1.0') and check", "that a booted application sanitizes HTML through the patched nokogiri") { |v| opts[:rails] = v } o.on("--bundle-setting KEY=VALUE", "one more Bundler setting for the install, for example", diff --git a/tests/nokogiri/patch_service.rb b/tests/nokogiri/patch_service.rb index 3b1d384500..500a254ee3 100644 --- a/tests/nokogiri/patch_service.rb +++ b/tests/nokogiri/patch_service.rb @@ -28,9 +28,11 @@ # `"patchUuid": null`. A request without it gets the plain URL and no # list. # * The registry under a snapshot lists every gem of that list. A -# pass-through platform is upstream's own line, and its file is a 302 to -# the upstream stand-in (`upstream_url`), which serves the real gem. A -# platform whose patched build is still being made is in neither the +# pass-through platform is upstream's own line, and its file is relayed: +# a 200 with upstream's own bytes. With `:redirect => true` it is a 302 +# to the upstream stand-in (`upstream_url`), which serves the real gem: +# an answer a client must follow too. +# A platform whose patched build is still being made is in neither the # list nor the registry. A snapshot answers as it did after `publish` # made a newer one. # @@ -40,8 +42,9 @@ # service.publish("arm64-darwin") # its patched build is there: a newer snapshot # # Options: `:pass_through` (platforms served as upstream's own gem), -# `:building` (platforms left out of the list), `:list => false` (a patch of -# the ruby gem alone: no list for any request). +# `:redirect => true` (their files are redirected to the upstream stand-in +# and not relayed), `:building` (platforms left out of the list), +# `:list => false` (a patch of the ruby gem alone: no list for any request). # # No gem dependencies, and nothing newer than Ruby 2.1 syntax: the file is # loaded on every leg, though its scenarios only run where nokogiri has @@ -75,6 +78,7 @@ def initialize(name, version, platforms, uuid, ghsa, work, mark, options = {}) @work = work @mark = mark @list = options.fetch(:list, true) + @redirect = options.fetch(:redirect, false) @requests = [] @upstream_requests = [] @reference_requests = [] @@ -474,8 +478,9 @@ def route(verb, path, body) when "info/#{@name}" then [200, "text/plain", info, index] when "names" then [200, "text/plain", "---\n#{@name}\n", index] else + # The row of a pass-through platform holds upstream's own gem. state, gem = rows.find { |_, g| "gems/#{g.file}" == rest } - if state == :pass_through + if state == :pass_through && @redirect [302, "text/plain", "", { "Location" => "#{upstream_url}/gems/#{gem.file}", "Cache-Control" => "no-store" }] elsif gem then [200, "application/octet-stream", gem.bytes] else [404, "text/plain", ""] From 2356336c9faf9f788dfa1f3981e26d07c270c07d Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 26 Nov 2026 00:35:36 -0500 Subject: [PATCH 031/120] Read the patch a platform gem's patch was built from off its reference The patch of one platform gem is built from the patch of the gem itself, and the patch service names that patch on the platform patch's package reference (`rebuiltFromUuid`). Nothing read it, so a run that was handed a platform gem's patch had no way to find the gem's. `PackageVendorResult` reads the field leniently: absent, null or any other shape is no patch named, and never fails the reference response it is part of. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/api/types.rs | 41 +++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/crates/socket-patch-core/src/api/types.rs b/crates/socket-patch-core/src/api/types.rs index 16b3edd548..37d0f2b693 100644 --- a/crates/socket-patch-core/src/api/types.rs +++ b/crates/socket-patch-core/src/api/types.rs @@ -330,6 +330,13 @@ pub struct PackageVendorResult { /// other shape reads as no address. #[serde(default)] pub npm_registry_url: Option, + /// For the patch of one platform gem: the UUID of the patch it was + /// built from, the patch of the gem itself. A hosted or a vendored run + /// patches a gem through that patch, so `get` takes it for a platform + /// gem's patch named by its UUID. Absent or null for every other + /// patch; any other shape reads as none ([`lenient`]). + #[serde(default, deserialize_with = "lenient")] + pub rebuilt_from_uuid: Option, } /// One served artifact: the native tarball (`kind: "tarball"`), or a @@ -618,6 +625,40 @@ mod tests { ); } + /// The reference of a platform gem's patch names the patch it was + /// built from (`rebuiltFromUuid`). A reference without the field, with + /// a null, or with a value that is no string names none, and still + /// reads: the field never fails the response it is part of. + #[test] + fn package_vendor_result_reads_the_patch_a_platform_gems_patch_was_built_from() { + let read = |built_from: Option| { + let mut json = serde_json::json!({ + "status": "granted", + "purl": "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + }); + if let Some(built_from) = built_from { + json["rebuiltFromUuid"] = built_from; + } + let result: PackageVendorResult = serde_json::from_value(json).unwrap(); + assert_eq!(result.status, "granted"); + result.rebuilt_from_uuid + }; + let gem_patch = "7b1e4f3a-2c5d-4e6f-8a9b-0c1d2e3f4a5b"; + assert_eq!( + read(Some(serde_json::json!(gem_patch))).as_deref(), + Some(gem_patch) + ); + assert_eq!(read(None), None); + for unreadable in [ + serde_json::Value::Null, + serde_json::json!(7), + serde_json::json!({ "uuid": gem_patch }), + serde_json::json!([gem_patch]), + ] { + assert_eq!(read(Some(unreadable.clone())), None, "{unreadable}"); + } + } + #[test] fn test_organizations_response_deserialize() { // Mirrors GET /v0/organizations: an object keyed by org id. `name` From d121b963bb82a4a62cb40735663db2098e15b952 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 26 Nov 2026 00:35:41 -0500 Subject: [PATCH 032/120] Let the PTY runner of the suites take a terminal width `pty_io::run_command` always opened an 80-column terminal, so a suite could not check output that is fitted to the terminal's width at any other width. `run_command_at` takes the width, and `run_command` is it at 80 columns. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/tests/common/pty_io.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/socket-patch-cli/tests/common/pty_io.rs b/crates/socket-patch-cli/tests/common/pty_io.rs index b0674d4db5..57cd52f3e8 100644 --- a/crates/socket-patch-cli/tests/common/pty_io.rs +++ b/crates/socket-patch-cli/tests/common/pty_io.rs @@ -129,6 +129,20 @@ pub fn run(args: &[&str], cwd: &Path, input: &str, timeout: Duration) -> (i32, S /// `TERM` is pinned: `console`/`dialoguer` derive key handling and /// rendering from it, and bare CI shells leave it unset or `dumb`. pub fn run_command( + cmd: portable_pty::CommandBuilder, + args: &[&str], + cwd: &Path, + env: &[(&str, &str)], + answers: &[&[u8]], + timeout: Duration, +) -> PtyRun { + run_command_at(80, cmd, args, cwd, env, answers, timeout) +} + +/// [`run_command`] on a PTY `cols` columns wide, for output that is +/// fitted to the terminal's width. +pub fn run_command_at( + cols: u16, mut cmd: portable_pty::CommandBuilder, args: &[&str], cwd: &Path, @@ -139,7 +153,7 @@ pub fn run_command( let pair = portable_pty::native_pty_system() .openpty(portable_pty::PtySize { rows: 24, - cols: 80, + cols, pixel_width: 0, pixel_height: 0, }) From e724e358137a20852148d0d38ddb0d55ee9b1ffb Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 26 Nov 2026 00:35:50 -0500 Subject: [PATCH 033/120] Take the gem's patch for a platform gem's patch named by its UUID In hosted and vendored mode a gem is patched through the patch of the gem itself, whose reference names the patched build of every platform. `get ` with the uuid of one platform gem's patch reached a refusal there: hosted mode pinned nothing under a warning about a missing registry override, and vendored mode failed `platform_gem_unsupported` with advice to use agent mode. The caller had to work out which patch to ask for instead. The run asks the patch service which patch the platform gem's patch was built from (one reference request), fetches that record, and goes on as `get ` does: the same ecosystem and plan checks, the same files written, the same output. One plain line on stderr says which patch it took, broken between words on a terminal, and under `--json` the envelope names the patch that was asked for (`platformGemPatch`: `uuid`, `purl`, `platform`, and `gemFix`, the gem's patch). The patch that is named has to be a patch uuid and the patch of that same gem, never one of its platform gems. Where no such patch can be taken (the reference names none, a request fails) the outcome is what it was, with the command to run instead. Hosted mode pins nothing and warns `platform_gem_patch_not_taken`. Vendored mode refuses `platform_gem_unsupported` before anything is downloaded, as the uuid path refuses any patch the project cannot vendor. Agent mode is untouched: it applies the platform gem's own record to the installed copy of that platform. A uuid that is no platform gem's patch costs no request. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/get.rs | 187 ++++- .../tests/get/get_platform_gem_uuid.rs | 757 ++++++++++++++++++ crates/socket-patch-cli/tests/get/main.rs | 3 + 3 files changed, 941 insertions(+), 6 deletions(-) create mode 100644 crates/socket-patch-cli/tests/get/get_platform_gem_uuid.rs diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index 8b9b565484..cff042ccff 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -15,7 +15,9 @@ use socket_patch_core::manifest::records::{build_patch_record, files_for_manifes use socket_patch_core::manifest::schema::PatchManifest; use socket_patch_core::telemetry::{track_patch_fetch_failed, track_patch_fetched, TelemetryAuth}; use socket_patch_core::utils::concurrent::{api_concurrency_for, ordered_concurrent}; -use socket_patch_core::utils::purl::{canonical_purl, normalize_purl, strip_purl_qualifiers}; +use socket_patch_core::utils::purl::{ + canonical_purl, normalize_purl, purl_parts, purl_qualifier, strip_purl_qualifiers, +}; use socket_patch_core::utils::purl_key::PurlKey; use socket_patch_core::utils::target::{Target, TargetKind}; use socket_patch_core::vendor::load_state; @@ -1226,6 +1228,102 @@ pub(crate) async fn download_patch_records_with( download_patch_records_reusing(selected, params, api_client, prefetched, None).await } +/// Warning code of a hosted `get ` whose UUID names the patch of one +/// platform gem, when no patch of the gem itself could be taken for it +/// ([`PlatformGemPatch`]): the run pins nothing, and the warning names the +/// command that patches the gem. +const PLATFORM_GEM_PATCH_NOT_TAKEN: &str = "platform_gem_patch_not_taken"; + +/// The patch of one platform gem (`pkg:gem/@?platform=…`) +/// that a hosted or a vendored `get` was given by its UUID. Such a run +/// patches a gem through the patch of the gem itself, whose reference +/// names the patched build of every platform: it takes the patch this one +/// was built from ([`Self::gem_patch`]) and goes on as it does for that +/// patch's UUID. +struct PlatformGemPatch { + uuid: String, + purl: String, + /// ` `, as the run's lines name a gem. + gem: String, + platform: String, + /// The gem's patch the run took in its place, once it has one. + gem_fix: Option, +} + +impl PlatformGemPatch { + /// `patch` as the patch of a platform gem; `None` for any other. + fn of(patch: &PatchResponse) -> Option { + if !super::scan::is_platform_gem_patch(&patch.purl) { + return None; + } + let (_, name, version) = purl_parts(&patch.purl)?; + Some(PlatformGemPatch { + uuid: patch.uuid.clone(), + purl: patch.purl.clone(), + gem: format!("{name} {version}"), + platform: purl_qualifier(&patch.purl, "platform")?.to_string(), + gem_fix: None, + }) + } + + /// The gem's patch: the one this patch's package reference names as + /// what it was built from (`rebuiltFromUuid`). One reference request, + /// then the fetch of that record. `None` when the reference names no + /// patch, a request fails, or the patch named is not the patch of this + /// gem itself. + async fn gem_patch(&self, api_client: &ApiClient) -> Option { + let references = api_client + .fetch_registry_references(std::slice::from_ref(&self.uuid)) + .await + .ok()?; + let built_from = references.get(&self.uuid)?.rebuilt_from_uuid.as_deref()?; + // The value goes into a request path: a patch UUID or nothing. + if Target::parse(built_from).kind() != TargetKind::Uuid { + return None; + } + let gem_patch = api_client.fetch_patch(built_from).await.ok()??; + (!super::scan::is_platform_gem_patch(&gem_patch.purl) + && canonical_purl(&gem_patch.purl) == canonical_purl(&self.purl)) + .then_some(gem_patch) + } + + /// The one line that says which patch the run took (stderr). + fn taken_line(&self, mode: &str) -> Option { + let gem_fix = self.gem_fix.as_deref()?; + Some(format!( + "{} is the patch of {}'s {} build; {mode} mode takes the gem's patch {gem_fix}, \ + which it was built from", + self.uuid, self.gem, self.platform + )) + } + + /// The same fact for the envelope (`platformGemPatch`). + fn taken_json(&self) -> Option { + let gem_fix = self.gem_fix.as_deref()?; + Some(serde_json::json!({ + "uuid": self.uuid, + "purl": self.purl, + "platform": self.platform, + "gemFix": gem_fix, + })) + } + + /// What a run that found no gem's patch to take says of this one: it + /// is no fix of its own in `mode`, and the command that patches the + /// gem there. + fn not_taken(&self, mode: &str) -> String { + format!( + "{} is the patch of {}'s {} build, which {mode} mode does not take by itself: it \ + patches a gem through the gem's own patch. Run `socket-patch get {} --mode {mode}` \ + instead", + self.uuid, + self.gem, + self.platform, + canonical_purl(&self.purl) + ) + } +} + pub async fn run(args: GetArgs) -> i32 { // Validate flags let type_flags = [args.id, args.cve, args.ghsa, args.package] @@ -1416,6 +1514,36 @@ pub async fn run(args: GetArgs) -> i32 { } } status.finish(); + // The patch of one platform gem is no fix of its own in hosted and + // vendored mode: the run takes the gem's patch, which it was built + // from, and goes on below as it does for that patch's UUID. (A + // patch outside the run's ecosystems, or a paid one on the public + // proxy, gets its own answer below and costs no request here.) + let mut platform_gem: Option = None; + if mode != super::scan::ScanMode::Agent { + let named = fetch_result.as_ref().ok().and_then(Option::as_ref); + let asked = named.and_then(PlatformGemPatch::of).filter(|_| { + named.is_some_and(|patch| { + args.common.purl_ecosystem_selected(&patch.purl) + && !(patch.tier == "paid" && use_public_proxy) + }) + }); + if let Some(mut asked) = asked { + status.set(format!("Fetching the patch of {}...", asked.gem)); + let gem_patch = asked.gem_patch(&api_client).await; + status.finish(); + if let Some(gem_patch) = gem_patch { + asked.gem_fix = Some(gem_patch.uuid.clone()); + fetch_result = Ok(Some(gem_patch)); + } + if let Some(line) = asked.taken_line(mode.cli_name()).filter(|_| !quiet) { + let width = crate::ui::attended(crate::ui::Stream::Stderr) + .then(crate::ui::stderr_width); + eprintln!("{}", crate::ui::wrap_line(&line, width)); + } + platform_gem = Some(asked); + } + } match fetch_result { Ok(Some(patch)) => { // The search path's selection rules hold here too: a patch @@ -1492,6 +1620,17 @@ pub async fn run(args: GetArgs) -> i32 { // (`policy_bypassed`). let mut uuid_warnings = super::scan::policy::policy_bypass_warnings(&args.common, &selected); + // A platform gem's patch that no gem's patch was taken for + // reaches the hosted engine, which pins nothing for it: + // say what to run. (The vendored refusal says it itself.) + if let Some(asked) = platform_gem.as_ref().filter(|asked| { + asked.gem_fix.is_none() && mode == super::scan::ScanMode::Hosted + }) { + uuid_warnings.push(( + PLATFORM_GEM_PATCH_NOT_TAKEN.to_string(), + asked.not_taken(mode.cli_name()), + )); + } if !args.common.silent { for (_, detail) in &uuid_warnings { eprintln!("Warning: {detail}"); @@ -1512,7 +1651,15 @@ pub async fn run(args: GetArgs) -> i32 { save_and_apply_patch(&args, &api_client, &patch, &uuid_warnings).await } super::scan::ScanMode::Hosted => { - run_get_hosted(&args, &api_client, &selected, &[], &uuid_warnings).await + run_get_hosted( + &args, + &api_client, + &selected, + platform_gem.as_ref(), + &[], + &uuid_warnings, + ) + .await } super::scan::ScanMode::Vendored => { run_get_vendored( @@ -1521,6 +1668,7 @@ pub async fn run(args: GetArgs) -> i32 { use_public_proxy, &selected, Some(&patch), + platform_gem.as_ref(), &[], &uuid_warnings, &telemetry, @@ -1719,8 +1867,7 @@ pub async fn run(args: GetArgs) -> i32 { // A hosted or a vendored run patches a gem through the patch of the // gem itself: the patch of one of its platform gems, which a search // returns beside it, is no fix of its own there. (One named by its - // UUID is the caller's exact intent, and reaches the backend's own - // refusal.) + // UUID stands for the gem's patch: see `PlatformGemPatch`.) if matches!( mode, super::scan::ScanMode::Vendored | super::scan::ScanMode::Hosted @@ -1995,6 +2142,7 @@ pub async fn run(args: GetArgs) -> i32 { &args, &api_client, &selected, + None, &narrow_skips, &narrow_warnings, ) @@ -2007,6 +2155,7 @@ pub async fn run(args: GetArgs) -> i32 { use_public_proxy, &selected, None, + None, &narrow_skips, &narrow_warnings, &telemetry, @@ -2509,11 +2658,14 @@ fn get_download_params(args: &GetArgs, save_only: bool, persist_blobs: bool) -> /// matches `scan --mode hosted` selecting the same patches. The engine owns /// all output (and honors `--dry-run` internally); in JSON mode it records /// its events (`details.mode: "hosted"`) into the get envelope passed as -/// `scan_result` and prints it. +/// `scan_result` and prints it. `platform_gem` is the platform gem's patch +/// the run was given by its UUID, when `selected` is the gem's patch taken +/// for it: the envelope names it (`platformGemPatch`). async fn run_get_hosted( args: &GetArgs, api_client: &ApiClient, selected: &[PatchSearchResult], + platform_gem: Option<&PlatformGemPatch>, narrow_skips: &[PatchEvent], narrow_warnings: &[(String, String)], ) -> i32 { @@ -2526,6 +2678,9 @@ async fn run_get_hosted( let scan_result = args.common.json.then(|| { let mut env = new_envelope(&args.common); fold_narrowing_into_result(&mut env, narrow_skips, narrow_warnings); + if let Some(taken) = platform_gem.and_then(PlatformGemPatch::taken_json) { + env.set_extra("platformGemPatch", taken); + } env }); // Embedded VEX stays a scan/vendor feature (get has no --vex): a @@ -2564,6 +2719,12 @@ async fn run_get_hosted( /// pre-record envelope, so a refused run writes nothing at all; the search /// path lets the download phase record the refusal per patch and still runs /// the vendor step (scan parity). +/// +/// `platform_gem` is the platform gem's patch the uuid path was given. With +/// the gem's patch taken for it (`prefetched`), the envelope names it +/// (`platformGemPatch`). With none taken, `prefetched` is that patch itself +/// and is refused `platform_gem_unsupported` before the engine, with the +/// command that vendors the gem. #[allow(clippy::too_many_arguments)] async fn run_get_vendored( args: &GetArgs, @@ -2571,12 +2732,16 @@ async fn run_get_vendored( use_public_proxy: bool, selected: &[PatchSearchResult], prefetched: Option<&PatchResponse>, + platform_gem: Option<&PlatformGemPatch>, narrow_skips: &[PatchEvent], narrow_warnings: &[(String, String)], telemetry: &TelemetryAuth, ) -> i32 { let mut env = new_envelope(&args.common); fold_narrowing_into_result(&mut env, narrow_skips, narrow_warnings); + if let Some(taken) = platform_gem.and_then(PlatformGemPatch::taken_json) { + env.set_extra("platformGemPatch", taken); + } // Dry run: ledger-classification preview only (scan's posture) — no // download, no vendor step, no writes. if args.common.dry_run { @@ -2616,13 +2781,23 @@ async fn run_get_vendored( // Human: `Error (): ` on stderr — an error, so it is // exempt from `--silent` like every other `Error (…)` line here. let vendor_state = load_state(&args.common.project_root()).await; - let refusals = Box::pin(vendored_download_refusals( + let mut refusals = Box::pin(vendored_download_refusals( ¶ms, selected, vendor_state.as_ref().map(|s| &s.entries), None, )) .await; + // A platform gem's patch that no gem's patch was taken for: what + // the project's own files refuse it for, if anything, comes first. + if let Some(asked) = platform_gem.filter(|asked| asked.gem_fix.is_none()) { + refusals + .entry(patch.purl.clone()) + .or_insert_with(|| VendorRefusal { + code: "platform_gem_unsupported", + detail: asked.not_taken("vendored"), + }); + } if let Some(VendorRefusal { code, detail }) = refusals.get(&patch.purl) { // An expected skip (a gem version this project doesn't lock) // is not an error: the same `skipped` event and `[skip]` line diff --git a/crates/socket-patch-cli/tests/get/get_platform_gem_uuid.rs b/crates/socket-patch-cli/tests/get/get_platform_gem_uuid.rs new file mode 100644 index 0000000000..be5ab5f28b --- /dev/null +++ b/crates/socket-patch-cli/tests/get/get_platform_gem_uuid.rs @@ -0,0 +1,757 @@ +//! `get ` where the uuid names the patch of ONE PLATFORM GEM (its +//! record's purl is `pkg:gem/@?platform=`), +//! against a stand-in patch service (the real binary; no Ruby or Bundler +//! runs here). +//! +//! In hosted and vendored mode a gem is patched through the patch of the +//! gem itself, whose reference names the patched build of every platform. +//! The patch of one platform gem is no fix of its own there, so the run +//! takes the patch it was built from, which that patch's package reference +//! names (`rebuiltFromUuid`), and goes on as `get ` does: +//! +//! * the project is left file for file as `get ` +//! leaves it, in both modes; +//! * one plain line says which patch was taken (stderr, once, fitted to a +//! terminal's width; nothing under `--silent`), and the `--json` +//! envelope names the patch that was asked for under `platformGemPatch`; +//! * it costs one reference request more, for the platform gem's patch; +//! * with no patch named for the build to come from, nothing is written +//! and the run names the command to run instead: hosted mode pins +//! nothing under a warning, vendored mode refuses +//! `platform_gem_unsupported`; +//! * agent mode applies the platform gem's own record to the installed +//! copy of that platform, with no reference request; +//! * the uuid of a patch of the gem itself, and of a patch of another +//! ecosystem, cost no request of this kind. + +use std::collections::BTreeMap; +use std::path::Path; + +use base64::Engine as _; +use serde_json::{json, Value}; +use sha2::{Digest, Sha512}; +use wiremock::matchers::{method, path as wm_path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +use crate::common::envelope::{ + envelope_error_code, envelope_error_message, event_triples, parse_json_envelope, +}; +use crate::common::{self, git_sha256, sha256_hex}; + +const ORG: &str = "test-org"; +/// A name nothing on the developer's machine can have installed. +const NAME: &str = "sockplatget"; +const VERSION: &str = "1.0.0"; +const PURL: &str = "pkg:gem/sockplatget@1.0.0"; +/// The gem's patch: the patch of its ruby gem, the one fix of the gem. +const UUID: &str = "6e7f0000-0000-4000-8000-000000000001"; +const DARWIN: &str = "arm64-darwin"; +const LINUX: &str = "x86_64-linux-gnu"; +/// The patches of its two patched platform gems. +const DARWIN_UUID: &str = "6e7f0000-0000-4000-8000-0000000000da"; +const LINUX_UUID: &str = "6e7f0000-0000-4000-8000-0000000000f1"; +const TOKEN: &str = "66666666-6666-4666-8666-666666666666"; +const LIB: &str = "lib/sockplatget.rb"; +const SO: &str = "lib/sockplatget/ext.so"; +const PRISTINE: &[u8] = b"module SockPlatGet; VERSION = '1.0.0'; end\n"; +const PATCHED: &[u8] = b"module SockPlatGet; VERSION = '1.0.0'; SAFE = true; end\n"; +const GHSA: &str = "GHSA-plat-form-gems"; +/// Shaped like a Socket API token, so no run warns about the token itself. +const API_TOKEN: &str = "sktsec_00000000000000000000000000000000000000000000_api"; + +const GEMFILE: &str = "source \"https://rubygems.org\"\n\ngem \"sockplatget\", \"~> 1.0\"\n"; + +/// Bundler's lock of a project that takes the gem as its two precompiled +/// platform gems. +fn lock() -> String { + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n {NAME} ({VERSION}-{DARWIN})\n \ + {NAME} ({VERSION}-{LINUX})\n\nPLATFORMS\n {DARWIN}\n {LINUX}\n\nDEPENDENCIES\n \ + {NAME} (~> 1.0)\n\nBUNDLED WITH\n 2.5.22\n" + ) +} + +/// A minimal `.gem`: an uncompressed tar whose `data.tar.gz` holds `files`. +fn make_gem(files: &[(&str, &[u8])]) -> Vec { + let mut data = tar::Builder::new(Vec::new()); + for (path, bytes) in files { + let mut header = tar::Header::new_gnu(); + header.set_size(bytes.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + data.append_data(&mut header, path, *bytes).unwrap(); + } + let data_tar = data.into_inner().unwrap(); + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut gz, &data_tar).unwrap(); + let data_tar_gz = gz.finish().unwrap(); + let mut gem = tar::Builder::new(Vec::new()); + let mut header = tar::Header::new_gnu(); + header.set_size(data_tar_gz.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + gem.append_data(&mut header, "data.tar.gz", data_tar_gz.as_slice()) + .unwrap(); + gem.into_inner().unwrap() +} + +/// The patched gem of `platform`: the patched Ruby file and the platform's +/// own binary. +fn platform_gem(platform: &str) -> Vec { + make_gem(&[(LIB, PATCHED), (SO, platform.as_bytes())]) +} + +fn stub(platform: &str) -> Vec { + format!( + "Gem::Specification.new do |s|\n s.name = \"{NAME}\"\n s.version = \"{VERSION}\"\n \ + s.platform = \"{platform}\"\n s.summary = \"a synthetic fixture gem\"\n \ + s.authors = [\"Socket\"]\n s.require_paths = [\"lib\"]\nend\n" + ) + .into_bytes() +} + +fn sri(bytes: &[u8]) -> String { + format!( + "sha512-{}", + base64::engine::general_purpose::STANDARD.encode(Sha512::digest(bytes)) + ) +} + +fn build_uuid(platform: &str) -> &'static str { + match platform { + DARWIN => DARWIN_UUID, + _ => LINUX_UUID, + } +} + +/// A patch record as the patch API's view serves it. +fn patch_view(uuid: &str, purl: &str) -> Value { + json!({ + "uuid": uuid, + "purl": purl, + "publishedAt": "2026-01-01T00:00:00Z", + "files": { + LIB: { + "beforeHash": git_sha256(PRISTINE), + "afterHash": git_sha256(PATCHED), + "blobContent": base64::engine::general_purpose::STANDARD.encode(PATCHED), + } + }, + "vulnerabilities": { + GHSA: { + "cves": ["CVE-2026-31337"], + "summary": "a synthetic vulnerability", + "severity": "high", + "description": "details" + } + }, + "description": "synthetic platform gem patch", + "license": "MIT", + "tier": "free" + }) +} + +/// What the reference of a platform gem's patch says of the patch it was +/// built from. +#[derive(Clone, Copy, Debug)] +enum BuiltFrom { + /// `rebuiltFromUuid`: the gem's patch. + Gem, + /// No such field. + Absent, + /// `rebuiltFromUuid: null`. + Null, + /// A value that is no patch uuid. + Malformed, + /// The uuid of a patch the service has no record of. + Unknown, + /// The patch of the gem's other platform gem. + PlatformPatch, + /// The reference request answers nothing for the patch. + NoResult, +} + +/// A uuid the stand-in has no record of. +const UNKNOWN_UUID: &str = "6e7f0000-0000-4000-8000-00000000dead"; +/// A second patch of the gem itself, whose record spells its purl with +/// `?platform=ruby`, and a patch of an npm package. The stand-in grants +/// neither a reference. +const RUBY_UUID: &str = "6e7f0000-0000-4000-8000-0000000000b1"; +const NPM_UUID: &str = "6e7f0000-0000-4000-8000-0000000000c2"; +const NPM_PURL: &str = "pkg:npm/sockplatget-js@1.0.0"; + +/// The patch service of the one gem: the gem's patch, whose reference +/// lists the version's gems (`gemBuilds`) under a registry snapshot, and +/// the patch of each platform gem, whose reference serves that gem and +/// its stub gemspec and names the gem's patch as `built_from` says. +async fn service(built_from: BuiltFrom) -> MockServer { + let server = MockServer::start().await; + let api = server.uri(); + let mut results = serde_json::Map::new(); + let ruby_gem = make_gem(&[(LIB, PATCHED)]); + let mut gem_builds = vec![json!({ + "platform": "ruby", "gemChecksumSha256": sha256_hex(&ruby_gem), "patchUuid": UUID + })]; + for platform in [DARWIN, LINUX] { + let own = build_uuid(platform); + let (gem, gemspec) = (platform_gem(platform), stub(platform)); + let base = format!("/patch/gem/{NAME}/{VERSION}/{TOKEN}/{own}/{NAME}-{VERSION}-{platform}"); + let mut artifacts = Vec::new(); + for (kind, ext, bytes) in [ + ("tarball", "gem", &gem), + ("gem-stub-gemspec", "gemspec", &gemspec), + ] { + let route = format!("{base}.{ext}"); + artifacts.push(json!({ + "kind": kind, + "url": format!("{api}{route}"), + "integrity": { "sha512": sri(bytes) } + })); + Mock::given(method("GET")) + .and(wm_path(route)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes.clone())) + .mount(&server) + .await; + } + gem_builds.push(json!({ + "platform": platform, "gemChecksumSha256": sha256_hex(&gem), "patchUuid": own + })); + let purl = format!("{PURL}?platform={platform}"); + let mut reference = json!({ + "status": "granted", + "purl": purl, + "url": format!("{api}{base}.gem"), + "artifacts": artifacts, + }); + match built_from { + BuiltFrom::Gem => reference["rebuiltFromUuid"] = json!(UUID), + BuiltFrom::Absent | BuiltFrom::NoResult => {} + BuiltFrom::Null => reference["rebuiltFromUuid"] = Value::Null, + BuiltFrom::Malformed => reference["rebuiltFromUuid"] = json!("../view/elsewhere"), + BuiltFrom::Unknown => reference["rebuiltFromUuid"] = json!(UNKNOWN_UUID), + BuiltFrom::PlatformPatch => reference["rebuiltFromUuid"] = json!(DARWIN_UUID), + } + if !matches!(built_from, BuiltFrom::NoResult) { + results.insert(own.to_string(), reference); + } + mount_view(&server, own, &purl).await; + } + gem_builds.sort_by_key(|build| build["platform"].as_str().map(str::to_string)); + let ruby_url = format!("{api}/patch/gem/{NAME}/{VERSION}/{TOKEN}/{UUID}/{NAME}-{VERSION}.gem"); + results.insert( + UUID.to_string(), + json!({ + "status": "granted", + "purl": PURL, + "url": ruby_url, + "artifacts": [{ "kind": "tarball", "url": ruby_url, + "integrity": { "sha512": sri(&ruby_gem), + "sha256": sha256_hex(&ruby_gem) } }], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": format!("{api}/patch-registry/gem/{TOKEN}/{UUID}/s/4f0a/"), + "identifiers": { + "name": NAME, "version": VERSION, + "gemChecksumSha256": sha256_hex(&ruby_gem), + "gemBuilds": gem_builds + } + } + }), + ); + Mock::given(method("POST")) + .and(wm_path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(move |request: &wiremock::Request| { + let asked: Value = serde_json::from_slice(&request.body).unwrap_or_default(); + let answered: serde_json::Map = asked["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|uuid| { + let uuid = uuid.as_str()?; + Some((uuid.to_string(), results.get(uuid)?.clone())) + }) + .collect(); + ResponseTemplate::new(200).set_body_json(json!({ "results": answered })) + }) + .mount(&server) + .await; + mount_view(&server, UUID, PURL).await; + mount_view(&server, RUBY_UUID, &format!("{PURL}?platform=ruby")).await; + mount_view(&server, NPM_UUID, NPM_PURL).await; + server +} + +async fn mount_view(server: &MockServer, uuid: &str, purl: &str) { + Mock::given(method("GET")) + .and(wm_path(format!("/v0/orgs/{ORG}/patches/view/{uuid}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(patch_view(uuid, purl))) + .mount(server) + .await; +} + +/// The patch API calls `server` has seen since its first `skip` requests: +/// the uuids each reference request named, and the uuid of each record +/// that was fetched, in arrival order. +async fn api_calls(server: &MockServer, skip: usize) -> (Vec>, Vec) { + let requests = server.received_requests().await.unwrap_or_default(); + let mut references = Vec::new(); + let mut views = Vec::new(); + for request in requests.iter().skip(skip) { + let route = request.url.path(); + if route.ends_with("/patches/package") { + let asked: Value = serde_json::from_slice(&request.body).unwrap_or_default(); + let uuids = asked["uuids"].as_array().into_iter().flatten(); + references.push( + uuids + .filter_map(|uuid| Some(uuid.as_str()?.to_string())) + .collect(), + ); + } else if let Some((_, uuid)) = route.rsplit_once("/patches/view/") { + views.push(uuid.to_string()); + } + } + (references, views) +} + +async fn request_count(server: &MockServer) -> usize { + server.received_requests().await.unwrap_or_default().len() +} + +/// A Bundler project that locks the gem as its two platform gems, in a +/// new temp dir. +fn project() -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("Gemfile"), GEMFILE).unwrap(); + std::fs::write(dir.path().join("Gemfile.lock"), lock()).unwrap(); + dir +} + +/// The arguments of `socket-patch get [--mode ]` against +/// `api`, with `extra` ones. +fn get_args<'a>( + api: &'a str, + uuid: &'a str, + mode: Option<&'a str>, + extra: &[&'a str], +) -> Vec<&'a str> { + let mut args = vec!["get", uuid, "--yes", "--api-url", api, "--proxy-url", api]; + args.extend_from_slice(&["--org", ORG, "--api-token", API_TOKEN]); + if let Some(mode) = mode { + args.extend_from_slice(&["--mode", mode]); + } + args.extend_from_slice(extra); + args +} + +/// `socket-patch get [--mode ]` at `root` against `api`, +/// with `extra` arguments. +fn get( + root: &Path, + api: &str, + uuid: &str, + mode: Option<&str>, + extra: &[&str], +) -> (i32, String, String) { + common::run_with_env(root, &get_args(api, uuid, mode, extra), &[]) +} + +/// [`get`] under `--json`: the exit code, the envelope and stderr. +fn get_json(root: &Path, api: &str, uuid: &str, mode: &str) -> (i32, Value, String) { + let (code, stdout, stderr) = get(root, api, uuid, Some(mode), &["--json"]); + (code, parse_json_envelope(&stdout), stderr) +} + +/// Every file under `root` with its content, by `/`-joined relative path. +/// A file reads as text (every file these runs write is text) with the +/// one thing that differs from run to run, the time a copy was vendored, +/// blanked. +fn tree(root: &Path) -> BTreeMap { + fn walk(dir: &Path, root: &Path, out: &mut BTreeMap) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + walk(&path, root, out); + continue; + } + let rel: Vec = path + .strip_prefix(root) + .unwrap() + .components() + .map(|part| part.as_os_str().to_string_lossy().into_owned()) + .collect(); + let text = String::from_utf8(std::fs::read(&path).unwrap()) + .unwrap_or_else(|_| panic!("{} is not text", path.display())); + let lines: Vec<&str> = text + .split_inclusive('\n') + .map( + |line| match line.trim_start().starts_with("\"vendoredAt\":") { + true => " \"vendoredAt\":