From be9f390b668a5343d9ac3e9383ec60d788000bb5 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 17:58:54 -0500 Subject: [PATCH 1/9] Redirect gems locked as platform builds to their prebuilds Bundler installs a native gem such as nokogiri as a precompiled platform gem, and the lock then has one entry per platform (`nokogiri (1.18.10-arm64-darwin)`) and usually no ruby-platform `nokogiri (1.18.10)`. Hosted mode skipped such a lock with `redirect_gem_platform_unsupported`, because the patch registry served the ruby gem alone. The registry can now serve a patched platform gem (a "prebuild") per platform, and the patch API lists them. API: a package artifact may carry `platform`, and the registry override's identifiers may carry `gemPlatforms` (`[{platform, gemChecksumSha256}]`). Both default to none. A grant's platform names and digests are held to the shape the lock takes before a grant becomes a candidate. Rewrite: when every platform entry of the gem at the patched version has a prebuild, every entry of that version (spec line and sub-lines, verbatim, plus a ruby-platform entry beside them) moves to the patch registry's `GEM` section, `DEPENDENCIES` is pinned as before, and each `CHECKSUMS` entry takes the sha256 of its own build. A lock with no `CHECKSUMS` section gets none. A locked platform with no prebuild keeps the skip, and the warning now names the missing builds and what the registry serves. A second scan of a moved lock is a no-op: the agreement check and the converge step look for the builds of the version, not for exactly one `name (version)` spec. Restore: every platform entry goes back to the upstream section where Bundler sorts it (by full name), and each `CHECKSUMS` entry is re-pinned to its own build's upstream sha256, the compact index's `-` line. One `info/` document is read per gem. Discovery: the platform specs of one gem version under a Socket `GEM` section of its own are one hosted pin, content-pinned only when `CHECKSUMS` holds a sha256 for every build. The engine drops a rewrite discovery cannot attribute, so this lands with the rewrite. Stale installs: an installed platform copy (`gems/nokogiri-1.18.10-arm64-darwin`) and its archive in Bundler's cache dir are judged against the patched artifacts, prebuilds included, and refreshed from `/gems/.gem` against that platform's own sha256. A platform gem declares no extensions, so nothing is built. After a rollback the same copy and archive go back to the upstream platform gem; a patched archive left in the cache dir would fail every install on the restored checksum. Lock-only discovery: the lock inventory lists a gem by its ruby-platform entry, so a gem locked only as platform builds was found only through an installed copy. A hosted run (the disk scan, `get --mode hosted` and the in-memory engine) now also reads those gems from the lock. Agent and vendored runs are unchanged. Nothing changes for a lock that names a gem by its ruby-platform entry alone. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/gem_refresh.rs | 253 +++++-- crates/socket-patch-cli/src/commands/get.rs | 6 +- .../src/commands/scan/discovery.rs | 47 +- .../src/commands/scan/hosted.rs | 90 ++- .../socket-patch-cli/src/commands/scan/mod.rs | 8 +- crates/socket-patch-core/src/api/types.rs | 80 ++- .../src/formats/gem/hosted.rs | 184 ++++- .../socket-patch-core/src/formats/gem/mod.rs | 162 +++++ crates/socket-patch-core/src/hosted/engine.rs | 76 +- .../src/hosted/memory/mod.rs | 11 +- .../src/patch/redirect/grant.rs | 70 ++ .../src/patch/redirect/mod.rs | 664 +++++++++++++++--- .../src/patch/redirect/upstream/client.rs | 116 ++- .../src/patch/redirect/upstream/gem.rs | 577 ++++++++++++--- .../src/patch/redirect/upstream/mod.rs | 24 +- .../src/vendor/lock_inventory/gem.rs | 16 + .../src/vendor/lock_inventory/mod.rs | 1 + .../socket-patch-core/src/vex/discover/gem.rs | 194 ++++- .../expected-edits.json | 1 + .../expected-warnings.json | 1 + .../platform-prebuild-missing/input/Gemfile | 4 + .../input/Gemfile.lock | 26 + .../platform-prebuild-missing/overrides.json | 28 + .../expected-edits.json | 1 + .../expected-warnings.json | 1 + .../platform-prebuilds-rerun/input/Gemfile | 4 + .../input/Gemfile.lock | 30 + .../platform-prebuilds-rerun/overrides.json | 32 + .../platform-prebuilds/expected-edits.json | 42 ++ .../platform-prebuilds/expected-warnings.json | 1 + .../platform-prebuilds/expected/Gemfile | 4 + .../platform-prebuilds/expected/Gemfile.lock | 30 + .../bundler/platform-prebuilds/input/Gemfile | 4 + .../platform-prebuilds/input/Gemfile.lock | 26 + .../bundler/platform-prebuilds/overrides.json | 32 + .../vex-discover-golden/redirect-gem.json | 90 +++ .../tests/upstream_restore_golden.rs | 123 ++++ 37 files changed, 2689 insertions(+), 370 deletions(-) create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-edits.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-warnings.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/input/Gemfile create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/input/Gemfile.lock create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/overrides.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/expected-edits.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/expected-warnings.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile.lock create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/overrides.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-edits.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-warnings.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile.lock create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/input/Gemfile create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/input/Gemfile.lock create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/overrides.json diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 5f54b1fe9..360ff8c23 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -768,9 +768,12 @@ pub(crate) fn report( out } -/// The installed copies (ruby platform) of `purls` in the gem homes Bundler -/// installs the project's gems into, each with the archive RubyGems -/// installed it from, `/cache/.gem`. +/// The installed copies of `purls` in the gem homes Bundler installs the +/// project's gems into, each with the archive RubyGems installed it from, +/// `/cache/.gem`. A copy is the ruby-platform build +/// (`-`) or, for a gem installed as a precompiled platform +/// gem, that build (`--`): its leaf says which, +/// and each build has an upstream archive of its own. async fn installed_with_archives(common: &GlobalArgs, purls: &[String]) -> Vec { use socket_patch_core::crawlers::types::CrawlerOptions; use socket_patch_core::crawlers::RubyCrawler; @@ -792,21 +795,15 @@ async fn installed_with_archives(common: &GlobalArgs, purls: &[String]) -> Vec/cache/.gem`, is -/// readable and is not the upstream one, and so is (in [`Scope::All`]) -/// such an archive in Bundler's cache dir. `upstream` is each purl's -/// upstream sha256; a purl without an entry is not judged. A purl whose -/// sha256 is `None` (the registry that would give it was refused) cannot -/// be judged either, and every installed copy of it is listed. +/// roles swapped: an installed copy is stale when the archive RubyGems +/// installed it from, `/cache/.gem`, is readable and is not +/// the upstream one, and so is (in [`Scope::All`]) such an archive in +/// Bundler's cache dir. `upstream` is the upstream sha256 of each build +/// ([`Build`]: a gem's ruby-platform gem, or one of its platform builds), +/// by leaf; a build without an entry is not judged. A build whose sha256 +/// is `None` (the registry that would give it was refused) cannot be +/// judged either, and every installed copy of it is listed. /// /// `records` holds the patch record of each gem that has one to judge by /// (a vendored unwind's ledger entry). An installed copy whose files are @@ -851,14 +849,15 @@ enum Scope { /// beside the upstream archive (#2093). async fn stale_after_restore( common: &GlobalArgs, - upstream: &BTreeMap>, + upstream: &BTreeMap, records: &BTreeMap, scope: Scope, ) -> Vec { use socket_patch_core::vendor::file_sha256_hex; let purls: Vec = upstream - .keys() + .values() + .map(|build| &build.purl) .chain(records.keys()) .collect::>() .into_iter() @@ -871,7 +870,7 @@ async fn stale_after_restore( // or not its archive is still in the home's cache. With one, // only a readable archive that is not the upstream gem makes // the copy stale. - let listed = match upstream.get(©.purl) { + let listed = match upstream.get(©.leaf).map(|build| &build.sha256) { None => false, Some(None) => true, Some(Some(sha)) => { @@ -895,19 +894,15 @@ async fn stale_after_restore( // restore's own `upstream_gem_stale_cache` to name.) let app_cache = socket_patch_core::crawlers::ruby_crawler::bundler_app_cache_dir(&common.cwd).await; - for (purl, sha) in upstream { - let Some(sha) = sha else { + for (leaf, build) in upstream { + let Some(sha) = &build.sha256 else { continue; }; - let Some((_, name, version)) = socket_patch_core::utils::purl::purl_parts(purl) else { - continue; - }; - let leaf = format!("{name}-{version}"); let archive = app_cache.join(format!("{leaf}.gem")); match file_sha256_hex(&archive).await { Some(got) if &got != sha => out.push(StaleGem { - purl: purl.clone(), - leaf, + purl: build.purl.clone(), + leaf: leaf.clone(), installed: None, cache_archive: Some(archive), in_place: false, @@ -918,6 +913,89 @@ async fn stale_after_restore( out } +/// One build of a restored gem, as [`stale_after_restore`] judges it by its +/// leaf (`-`, or `--` for a +/// precompiled platform gem). +#[derive(Debug, Clone)] +struct Build { + purl: String, + /// The upstream archive's sha256; `None` when the registry that would + /// give it was refused. + sha256: Option, +} + +/// The builds of the gem `purl` that may have a materialization to judge: +/// the ruby-platform gem, then each of `platforms` (the platform builds the +/// restored lock names) that is installed in a gem home Bundler uses or (in +/// [`Scope::All`]) archived in Bundler's cache dir. `(leaf, platform)` +/// each, the platform `None` for the ruby-platform gem. A lock names a +/// build for every platform the project supports, and this machine holds +/// one of them: only that one costs a lookup of its upstream archive. A +/// gem the lock names no platform build for is looked at nowhere. +async fn materialized_builds( + common: &GlobalArgs, + purl: &str, + platforms: &[String], + scope: Scope, +) -> Vec<(String, Option)> { + let Some((_, name, version)) = socket_patch_core::utils::purl::purl_parts(purl) else { + return Vec::new(); + }; + let mut builds = vec![(format!("{name}-{version}"), None)]; + if platforms.is_empty() { + return builds; + } + let mut held: BTreeSet = installed_with_archives(common, &[purl.to_string()]) + .await + .into_iter() + .map(|copy| copy.leaf) + .collect(); + if scope == Scope::All { + let app_cache = + socket_patch_core::crawlers::ruby_crawler::bundler_app_cache_dir(&common.cwd).await; + held.extend( + cached_platform_archives(&app_cache, &name, &version) + .await + .iter() + .filter_map(|archive| Some(archive.file_stem()?.to_str()?.to_string())), + ); + } + for platform in platforms { + let leaf = format!("{name}-{version}-{platform}"); + if held.contains(&leaf) { + builds.push((leaf, Some(platform.clone()))); + } + } + builds +} + +/// The archives of `name` `version`'s platform builds in Bundler's cache +/// dir, `--.gem`, in name order. A platform starts +/// with a letter: `foo-1.0-2.0.gem` is the gem `foo-1.0` at `2.0`. +pub(crate) async fn cached_platform_archives( + app_cache: &Path, + name: &str, + version: &str, +) -> Vec { + let prefix = format!("{name}-{version}-"); + let mut found = Vec::new(); + let Ok(mut entries) = tokio::fs::read_dir(app_cache).await else { + return found; + }; + while let Ok(Some(entry)) = entries.next_entry().await { + let file = entry.file_name(); + let platform = file + .to_str() + .and_then(|file| file.strip_suffix(".gem")) + .and_then(|leaf| leaf.strip_prefix(&prefix)); + if platform.is_some_and(|p| p.starts_with(|c: char| c.is_ascii_alphabetic())) { + found.push(entry.path()); + } + } + found.sort(); + found +} + /// Whether the files of the installed `copy` are the patched ones of its /// gem's record in `records`: every file the record lists hashes to its /// `afterHash`. `false` for a gem with no record. @@ -1143,6 +1221,13 @@ pub(crate) async fn after_vendored_unwind( ) -> RestoreRefresh { let mut installed: BTreeSet = BTreeSet::new(); for copy in installed_with_archives(common, unwound).await { + // A vendored gem is the ruby-platform gem: a platform build + // installed beside it was never the vendored copy's stand-in. + let ruby_platform = socket_patch_core::utils::purl::purl_parts(©.purl) + .is_some_and(|(_, name, version)| copy.leaf == format!("{name}-{version}")); + if !ruby_platform { + continue; + } if copy.archive.is_file() || holds_patch(©, records).await { installed.insert(copy.purl); } @@ -1171,17 +1256,20 @@ async fn refresh_restored( scope: Scope, ) -> RestoreRefresh { use socket_patch_core::patch::redirect::upstream::{ - gem_resolves_from_rubygems, gem_upstream_archive, UpstreamArchive, + gem_locked_platforms, gem_resolves_from_rubygems, gem_upstream_archive, UpstreamArchive, }; use socket_patch_core::vendor::registry_fetch::SecureRegistryClient; let policy = Policy::of(common); let direction = Direction::Upstream; - let mut shas: BTreeMap> = BTreeMap::new(); + // By leaf: a gem locked as precompiled platform builds is installed + // and cached as `--`, and each build has its + // own upstream archive. + let mut shas: BTreeMap = BTreeMap::new(); let mut urls: BTreeMap> = BTreeMap::new(); - // The gems whose upstream sha256 the registry is not asked for, each + // The builds whose upstream sha256 the registry is not asked for, each // with why: their installed copies are reported, not passed over. - let mut unverified: BTreeMap = BTreeMap::new(); + let mut unverified: BTreeMap = BTreeMap::new(); // The records an installed copy is judged by as well: those of the // gems the lock resolves from rubygems.org, which are back on their // upstream entries. A copy holding its record's patch is stale even @@ -1197,41 +1285,61 @@ async fn refresh_restored( .iter() .filter(|p| Ecosystem::from_purl(p) == Some(Ecosystem::Gem)) { - match gem_upstream_archive(&common.cwd, staged, purl, common.offline).await { - Some(UpstreamArchive::Known { sha256, url }) => { - // A vendored revert does not prove where the lock resolves - // the gem from: an entry vendored over hosted wiring before - // v5 reverts to its hosted pin, whose `CHECKSUMS` sha256 is - // the patched gem's (the hosted unwind restores that pin - // next, and refreshes then). Only a gem the lock resolves - // from rubygems.org is known to be back on its upstream - // entry. - if scope == Scope::Installed && url.is_none() { - continue; - } - shas.insert(purl.clone(), Some(sha256)); - urls.insert(purl.clone(), url); - if let Some(record) = records.get(purl) { - judged.insert(purl.clone(), record.clone()); - } - if pin_judge.is_some() { - pinned.push(purl.clone()); - } - } - // (Only a gem the lock resolves from rubygems.org comes back - // unverified, so the vendored unwind's rule holds for it too.) - Some(UpstreamArchive::Unverified(why)) => { - unverified.insert(purl.clone(), why); - } - None => { - if let Some(record) = records.get(purl) { - if gem_resolves_from_rubygems(&common.cwd, purl).await { + let platforms = gem_locked_platforms(&common.cwd, staged, purl).await; + for (leaf, platform) in materialized_builds(common, purl, &platforms, scope).await { + let archive = gem_upstream_archive( + &common.cwd, + staged, + purl, + platform.as_deref(), + common.offline, + ) + .await; + match archive { + Some(UpstreamArchive::Known { sha256, url }) => { + // A vendored revert does not prove where the lock + // resolves the gem from: an entry vendored over hosted + // wiring before v5 reverts to its hosted pin, whose + // `CHECKSUMS` sha256 is the patched gem's (the hosted + // unwind restores that pin next, and refreshes then). + // Only a gem the lock resolves from rubygems.org is + // known to be back on its upstream entry. + if scope == Scope::Installed && url.is_none() { + continue; + } + let build = Build { + purl: purl.clone(), + sha256: Some(sha256), + }; + shas.insert(leaf.clone(), build); + urls.insert(leaf, url); + if let Some(record) = records.get(purl) { judged.insert(purl.clone(), record.clone()); } + if pin_judge.is_some() && !pinned.contains(purl) { + pinned.push(purl.clone()); + } } - if pin_judge.is_some() { - pinned.push(purl.clone()); + // (Only a gem the lock resolves from rubygems.org comes + // back unverified, so the vendored unwind's rule holds for + // it too.) + Some(UpstreamArchive::Unverified(why)) => { + unverified.insert(leaf, (purl.clone(), why)); + } + // A platform build the lock does not name is not this + // project's: only the ruby-platform gem is judged by its + // record. + None if platform.is_none() => { + if let Some(record) = records.get(purl) { + if gem_resolves_from_rubygems(&common.cwd, purl).await { + judged.insert(purl.clone(), record.clone()); + } + } + if pin_judge.is_some() && !pinned.contains(purl) { + pinned.push(purl.clone()); + } } + None => {} } } } @@ -1247,7 +1355,16 @@ async fn refresh_restored( let pin_stale_any = !pin_stale.is_empty(); let mut stale = stale_after_restore(common, &shas, &judged, scope).await; stale.extend(pin_stale); - let unjudged = unverified.keys().map(|purl| (purl.clone(), None)).collect(); + let unjudged = unverified + .iter() + .map(|(leaf, (purl, _))| { + let build = Build { + purl: purl.clone(), + sha256: None, + }; + (leaf.clone(), build) + }) + .collect(); let unchecked = stale_after_restore(common, &unjudged, &BTreeMap::new(), Scope::Installed).await; if stale.is_empty() && unchecked.is_empty() && no_record.is_empty() { @@ -1257,8 +1374,8 @@ async fn refresh_restored( Some(Wanted { leaf: gem.leaf.clone(), kind: direction.wanted(), - sha256: BTreeSet::from([shas.get(&gem.purl)?.clone()?]), - urls: urls.get(&gem.purl)?.iter().cloned().collect(), + sha256: BTreeSet::from([shas.get(&gem.leaf)?.sha256.clone()?]), + urls: urls.get(&gem.leaf)?.iter().cloned().collect(), on_disk: Vec::new(), }) }; @@ -1295,7 +1412,7 @@ async fn refresh_restored( .map(|(purl, _)| purl.clone()) .collect(); for gem in unchecked { - if let (Some((dir, _)), Some(why)) = (&gem.installed, unverified.get(&gem.purl)) { + if let (Some((dir, _)), Some((_, why))) = (&gem.installed, unverified.get(&gem.leaf)) { pass.left .insert(dir.clone(), Why::Unverified(why.to_string())); installed.push(gem); diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index 8ea978ede..2a6701060 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -896,10 +896,14 @@ async fn filter_to_installed_purls( // project). let mut pnp_diags: Vec = Vec::new(); if !common.is_global() { - let supplement = super::scan::project_lockfile_supplement(&ctx, &[], None).await; + let hosted = mode == super::scan::ScanMode::Hosted; + let supplement = super::scan::project_lockfile_supplement(&ctx, &[], None, hosted).await; pnp_diags = supplement.unsupported; if mode != super::scan::ScanMode::Agent { present.extend(supplement.entries.iter().map(|e| PurlKey::new(&e.purl))); + // A hosted run's supplement also names the gems the lock + // resolves only as precompiled platform builds. + present.extend(supplement.purls.iter().cloned()); let vendored = super::scan::project_vendored_supplement(&ctx, &[], &ctx.loaded().await.vendor) .await; diff --git a/crates/socket-patch-cli/src/commands/scan/discovery.rs b/crates/socket-patch-cli/src/commands/scan/discovery.rs index eef505c0f..cbbe7e3d3 100644 --- a/crates/socket-patch-cli/src/commands/scan/discovery.rs +++ b/crates/socket-patch-cli/src/commands/scan/discovery.rs @@ -54,10 +54,18 @@ pub(crate) struct LockfileSupplement { /// crawled): an entry of an ecosystem the crawl skipped is never counted /// lockfile-only, since there is no crawl to tell whether it is installed. /// `entries` still holds the full inventory. +/// +/// `hosted`: the run is a hosted scan. The inventory leaves out a gem the +/// Bundler lock resolves only as precompiled platform builds (`nokogiri +/// (1.18.10-arm64-darwin)`: no one `.gem` stands for it, so it cannot be +/// vendored from the lock, and an in-place patch needs the installed copy). +/// Hosted mode redirects such a gem to its per-platform prebuilds from the +/// lock alone, so a hosted supplement names it too. pub(crate) async fn lockfile_supplement( ctx: &crate::commands::context::ProjectContext<'_>, crawled: &[socket_patch_core::crawlers::types::CrawledPackage], only: Option<&[String]>, + hosted: bool, ) -> LockfileSupplement { let common = ctx.common; let mut out = LockfileSupplement::default(); @@ -67,14 +75,49 @@ pub(crate) async fn lockfile_supplement( let locks = ctx.locks().await; out.unsupported = locks.unsupported.clone(); let entries = &locks.entries; - if entries.is_empty() { + let platform_gems = if hosted { + platform_only_gems(ctx).await + } else { + Vec::new() + }; + if entries.is_empty() && platform_gems.is_empty() { return out; } - (out.packages, out.purls) = lockfile_only_packages(entries, crawled, only, &common.cwd); + let discovered: Vec = entries.iter().cloned().chain(platform_gems).collect(); + (out.packages, out.purls) = lockfile_only_packages(&discovered, crawled, only, &common.cwd); out.entries = entries.clone(); out } +/// The gems the project's Bundler lock resolves only as precompiled +/// platform builds, as discovery-only lock entries (no archive URL, no +/// checksum: each platform build has its own). +async fn platform_only_gems( + ctx: &crate::commands::context::ProjectContext<'_>, +) -> Vec { + use socket_patch_core::vendor::lock_inventory::{ + gem_platform_only_purls_in, LockIntegrity, ProjectView, SourceKind, + }; + let view = ProjectView::Disk(&ctx.common.cwd); + gem_platform_only_purls_in(&view) + .await + .into_iter() + .filter_map(|purl| { + let (_, name, version) = socket_patch_core::utils::purl::purl_parts(&purl)?; + Some(LockfileEntry { + ecosystem: "gem", + source_kind: SourceKind::Unspecified, + pnpm_env: false, + purl, + resolved: None, + name, + version, + integrity: LockIntegrity::None, + }) + }) + .collect() +} + /// The lockfile entries with no crawled counterpart, fabricated as crawl /// entries, plus their [`PurlKey`]s. "Crawled" is by [`PurlKey`], the same /// relation [`lockfile_only_contains`] answers by: a lock spelling that diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 2cbaaaa08..1969fb15d 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -337,6 +337,10 @@ fn stale_cache_gem(purl: &str, cache_path: &Path) -> StaleGem { /// * A committed `vendor/cache/.gem` whose sha256 is not a patched /// artifact's is stale too (bundler installs from it first): folded into /// a project-local warning's delete list, or warned alone. +/// * 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. async fn gem_stale_install_warnings( cwd: &Path, global: bool, @@ -513,7 +517,8 @@ async fn gem_stale_install_warnings( // carries the committed vendor/cache archive when one is present and not // proven to be the patched artifact — bundler installs from it first, so // a remedy that leaves it behind silently reinstates the stale bytes. - let mut cache_covered: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new(); + let mut cache_covered: std::collections::BTreeSet = + std::collections::BTreeSet::new(); for (dir, j) in &dir_state { // Files patched in place beside the upstream archive (#2089). let in_place = j.patched && j.upstream_archive; @@ -541,8 +546,8 @@ async fn gem_stale_install_warnings( } else { None }; - if folded_cache.is_some() { - cache_covered.insert(j.purl.as_str()); + if let Some(archive) = &folded_cache { + cache_covered.insert(archive.clone()); } let gem = stale_installed_gem( &j.purl, @@ -560,35 +565,36 @@ async fn gem_stale_install_warnings( } // Pass 3: standalone vendor/cache staleness — a committed archive whose - // sha256 is readable and differs from the patched artifact's, for purls - // whose project-local install warning did not already fold it in (a - // fresh checkout with a committed stale cache has no installed dir at - // all, and would otherwise never warn). + // sha256 is readable and differs from the patched artifact's, unless a + // project-local install warning already folded it in (a fresh checkout + // with a committed stale cache has no installed dir at all, and would + // otherwise never warn). The ruby gem's archive, then the archive of + // each platform build bundler cached. for (purl, _, _) in &candidates { - if cache_covered.contains(purl) { - continue; - } let Some(want_shas) = gem_artifact_shas.get(&gem_sha_key(purl)) else { continue; }; let Some((_, name, version)) = purl_parts(purl) else { continue; }; - let cache_path = app_cache.join(format!("{name}-{version}.gem")); - if !cache_path.is_file() { - continue; - } - // Unreadable → no positive evidence, never a guess. - let Some(got) = file_sha256_hex(&cache_path).await else { - continue; - }; - if want_shas.contains(&got) { - continue; // the PATCHED archive — healthy commit, nothing stale + let mut archives = vec![app_cache.join(format!("{name}-{version}.gem"))]; + archives.extend(gem_refresh::cached_platform_archives(&app_cache, &name, &version).await); + for cache_path in archives { + if cache_covered.contains(&cache_path) || !cache_path.is_file() { + continue; + } + // Unreadable → no positive evidence, never a guess. + let Some(got) = file_sha256_hex(&cache_path).await else { + continue; + }; + if want_shas.contains(&got) { + continue; // the PATCHED archive — healthy commit, nothing stale + } + let gem = stale_cache_gem(purl, &cache_path); + out.warnings.push(gem_stale_warning(&gem, None)); + out.gems.push(gem); + out.stale_purls.insert((*purl).to_string()); } - let gem = stale_cache_gem(purl, &cache_path); - out.warnings.push(gem_stale_warning(&gem, None)); - out.gems.push(gem); - out.stale_purls.insert((*purl).to_string()); } out } @@ -686,14 +692,30 @@ async fn refresh_stale_gems( policy.enabled &= common.dry_run || locked; // 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. + // 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. let wanted = |gem: &StaleGem| { let (name, version) = gem_sha_key(&gem.purl); - let sha256 = gem_artifact_shas - .get(&(name.clone(), version.clone()))? + let platform = gem.leaf.strip_prefix(&format!("{name}-{version}-")); + let prebuilt: std::collections::BTreeSet = overrides .iter() - .map(|sha| sha.to_ascii_lowercase()) + .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) + .filter(|prebuild| Some(prebuild.platform.as_str()) == platform) + .map(|prebuild| prebuild.gem_checksum_sha256.to_ascii_lowercase()) .collect(); + let sha256 = if prebuilt.is_empty() { + gem_artifact_shas + .get(&(name.clone(), version.clone()))? + .iter() + .map(|sha| sha.to_ascii_lowercase()) + .collect() + } else { + prebuilt + }; let file = format!("{}.gem", gem.leaf); let mut urls: Vec = Vec::new(); for o in overrides @@ -1783,8 +1805,9 @@ async fn run_redirect_selected_untracked( // // purl-coordinate → every PATCHED .gem artifact's sha256 (registry // override identifier, tarball integrity fallback; one per platform - // variant) — judges the installed and committed archives, and verifies - // the archive a refresh installs. + // variant, and one per prebuild: the patched platform 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, @@ -1795,7 +1818,12 @@ async fn run_redirect_selected_untracked( .as_ref() .and_then(|ro| ro.identifiers.gem_checksum_sha256.clone()) .or_else(|| o.integrity.sha256.clone()); - if let Some(sha) = sha { + let prebuilds = o + .registry_override + .iter() + .flat_map(|ro| &ro.identifiers.gem_platforms) + .map(|prebuild| prebuild.gem_checksum_sha256.clone()); + for sha in sha.into_iter().chain(prebuilds) { gem_artifact_shas .entry((o.name.clone(), o.version.clone())) .or_default() diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 8f33bdb0f..c960e329f 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2095,7 +2095,13 @@ async fn scan_project( // that have NO installed copy (fresh clone, partial install). They join // discovery and are flagged "not yet installed". Scoped to the crawled // ecosystems. - let mut lockfile_only = lockfile_supplement(&ctx, &all_crawled, crawl_scope).await; + let mut lockfile_only = lockfile_supplement( + &ctx, + &all_crawled, + crawl_scope, + args.mode == Some(ScanMode::Hosted), + ) + .await; // Counted once: #604 adds the API's spellings of lockfile-only PyPI pins // to `lockfile_only.purls` after the batch query. let lockfile_only_count = lockfile_only.purls.len(); diff --git a/crates/socket-patch-core/src/api/types.rs b/crates/socket-patch-core/src/api/types.rs index c45cd5116..9218f0a27 100644 --- a/crates/socket-patch-core/src/api/types.rs +++ b/crates/socket-patch-core/src/api/types.rs @@ -182,15 +182,22 @@ 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"`) or -/// gem's path-source stub gemspec (`kind: "gem-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"`), +/// gem's path-source stub gemspec (`kind: "gem-stub-gemspec"`), or, per +/// built prebuild of a gem patch, 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). #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PackageVendorArtifact { pub kind: String, #[serde(default)] pub url: Option, + /// The gem platform (`x86_64-linux-gnu`, `arm64-darwin`) the artifact + /// is built for: present exactly on the two per-prebuild kinds. + #[serde(default)] + 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` @@ -490,4 +497,71 @@ mod tests { "HIGH" ); } + + /// 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. + #[test] + fn package_vendor_result_reads_gem_prebuilds() { + let sha = "ab".repeat(32); + let json = serde_json::json!({ + "status": "granted", + "purl": "pkg:gem/nokogiri@1.18.10?platform=ruby", + "url": "https://patch.socket.dev/patch/gem/nokogiri-1.18.10.gem", + "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", + "integrity": {} } + ], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/t/u/", + "identifiers": { + "name": "nokogiri", "version": "1.18.10", + "gemChecksumSha256": sha, + "gemPlatforms": [ + { "platform": "x86_64-linux-gnu", "gemChecksumSha256": sha } + ] + } + } + }); + let result: PackageVendorResult = serde_json::from_value(json.clone()).unwrap(); + 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 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 mut bare = json; + bare["registryOverride"]["identifiers"] + .as_object_mut() + .unwrap() + .remove("gemPlatforms"); + let result: PackageVendorResult = serde_json::from_value(bare).unwrap(); + assert!(result + .registry_override + .unwrap() + .identifiers + .gem_platforms + .is_empty()); + } } diff --git a/crates/socket-patch-core/src/formats/gem/hosted.rs b/crates/socket-patch-core/src/formats/gem/hosted.rs index 2e0de986c..2d484bf91 100644 --- a/crates/socket-patch-core/src/formats/gem/hosted.rs +++ b/crates/socket-patch-core/src/formats/gem/hosted.rs @@ -172,6 +172,14 @@ fn pin_dependency<'a>( /// and, on a `CHECKSUMS` lock, an unfrozen one exits 37 "mismatched /// checksums". /// +/// A gem locked as precompiled platform builds has one entry per platform +/// (`name (version-)`, with or without a ruby-platform `name +/// (version)` beside them): every entry of the version moves, in the +/// lock's order, since Bundler resolves all of them from the one source +/// the Gemfile gives the gem (a frozen install of that shape was verified +/// on bundler 4.0.15). The caller has checked that the patch registry +/// serves each of those builds. +/// /// Idempotent and rotation-aware: a section whose remote matches the /// token-wildcard pattern is recognized as ours (never duplicated) and its /// remote is refreshed under a rotated grant or superseding patch @@ -181,8 +189,9 @@ fn pin_dependency<'a>( /// /// `Ok` when the lock ends converged (already, or via edits recorded into /// `result`); `Err` with the reason when the dep cannot be attributed -/// safely — spec entry absent or duplicated, a legacy multi-remote `GEM` -/// section, or no DEPENDENCIES section — in which case nothing is touched. +/// safely — spec entry absent or duplicated, its builds spread over several +/// `GEM` sections, a legacy multi-remote `GEM` section, or no DEPENDENCIES +/// section — in which case nothing is touched. pub(crate) fn converge_gem_lock_source( lk: &mut String, dep: &DepOverride, @@ -199,27 +208,38 @@ pub(crate) fn converge_gem_lock_source( let model = super::parse(lk); let sections: Vec<&Section<'_>> = model.gem_sections().collect(); let spec_raw = format!("{} ({})", dep.name, dep.version); - let spec_at: Vec<(usize, usize)> = sections // (section idx, line idx) + // Every build of the version: (section idx, line idx, entry text). + let spec_at: Vec<(usize, usize, &str)> = sections .iter() .enumerate() .flat_map(|(k, section)| { section .specs .iter() - .filter(|spec| spec.raw == spec_raw) - .map(move |spec| (k, spec.line_no - 1)) + .filter(|spec| spec.locks(&dep.name, &dep.version)) + .map(move |spec| (k, spec.line_no - 1, spec.raw)) }) .collect(); let Some(deps) = &model.dependencies else { return Err("it has no DEPENDENCIES section".to_string()); }; - let &[(sec_idx, spec_idx)] = spec_at.as_slice() else { - return Err(if spec_at.is_empty() { - format!("no GEM section lists `{spec_raw}`") - } else { - format!("more than one GEM section lists `{spec_raw}`") - }); + let Some(&(sec_idx, _, _)) = spec_at.first() else { + return Err(format!("no GEM section lists `{spec_raw}`")); }; + if let Some((_, _, twice)) = spec_at + .iter() + .enumerate() + .find(|(at, (_, _, raw))| spec_at[..*at].iter().any(|(_, _, earlier)| earlier == raw)) + .map(|(_, entry)| entry) + { + return Err(format!("more than one GEM section lists `{twice}`")); + } + if spec_at.iter().any(|(k, _, _)| *k != sec_idx) { + return Err(format!( + "the builds of {} {} are spread over more than one GEM section", + dep.name, dep.version + )); + } // Exclusive of the header. let deps_start = deps.line_no; if sections[sec_idx].remotes.len() != 1 { @@ -290,13 +310,22 @@ pub(crate) fn converge_gem_lock_source( // patch registry (`https://patch.socket.dev/…`) sorts first would break // every converged hosted pair under `BUNDLE_FROZEN` / deployment // mode (verified: 4.0.15 installs it, 4.0.21 refuses it). - let mut last = spec_idx; - while last + 1 < lines.len() - && gem_lock_line_content(&lines[last + 1]).starts_with(" ") - { - last += 1; + // + // Each entry goes with its 6-space dependency sublines. Drained last + // entry first, so the earlier entries' line indices stay valid, and + // kept in the lock's order (Bundler's: by full name, the ruby + // build before its platform builds). + let mut moved: Vec> = Vec::new(); + for &(_, spec_idx, _) in spec_at.iter().rev() { + let mut last = spec_idx; + while last + 1 < lines.len() + && gem_lock_line_content(&lines[last + 1]).starts_with(" ") + { + last += 1; + } + let entry: Vec> = lines.drain(spec_idx..=last).collect(); + moved.splice(0..0, entry); } - let moved: Vec> = lines.drain(spec_idx..=last).collect(); let n = moved.len(); // Section bounds after the drain (every drained line sat inside // section `sec_idx`, which keeps its start). @@ -734,6 +763,127 @@ BUNDLED WITH 2.6.2 "; + /// A gem locked as precompiled platform builds: every entry of the + /// patched version moves, each with its own sub-lines and in the lock's + /// order, the ruby-platform entry included. Another version's build + /// stays upstream. + #[test] + fn platform_builds_of_the_version_move_together() { + let lock = "GEM + remote: https://rubygems.org/ + specs: + mini_portile2 (2.8.9) + nokogiri (1.15.0-java) + nokogiri (1.16.0) + mini_portile2 (~> 2.8.2) + racc (~> 1.4) + nokogiri (1.16.0-arm64-darwin) + racc (~> 1.4) + nokogiri (1.16.0-x86_64-linux) + racc (~> 1.4) + racc (1.7.3) + +PLATFORMS + arm64-darwin + ruby + x86_64-linux + +DEPENDENCIES + nokogiri (~> 1.16) + +BUNDLED WITH + 2.6.2 +"; + let expected = "GEM + remote: https://patch.test/gem/tok/uuid/ + specs: + nokogiri (1.16.0) + mini_portile2 (~> 2.8.2) + racc (~> 1.4) + nokogiri (1.16.0-arm64-darwin) + racc (~> 1.4) + nokogiri (1.16.0-x86_64-linux) + racc (~> 1.4) + +GEM + remote: https://rubygems.org/ + specs: + mini_portile2 (2.8.9) + nokogiri (1.15.0-java) + racc (1.7.3) + +PLATFORMS + arm64-darwin + ruby + x86_64-linux + +DEPENDENCIES + nokogiri (~> 1.16)! + +BUNDLED WITH + 2.6.2 +"; + let dep = dep("nokogiri", "1.16.0"); + let (ok, lk, edits) = converge_as(lock, &dep, DependencyPin::Keep); + assert!(ok); + assert_eq!(lk, expected); + assert_eq!( + edits, + [ + "redirect_gemfile_lock_dependency_pin:rewritten", + "redirect_gemfile_lock_gem_source:rewritten" + ] + ); + // Converged: a second pass finds every build in the section it + // names and changes nothing. + let (ok, again, edits) = converge_as(&lk, &dep, DependencyPin::Keep); + assert!(ok && again == lk && edits.is_empty(), "{edits:?}"); + // CRLF: each moved line keeps its ending. + let (ok, crlf, _) = converge_as(&lock.replace('\n', "\r\n"), &dep, DependencyPin::Keep); + assert!(ok); + assert_eq!(crlf, expected.replace('\n', "\r\n")); + } + + /// Builds of one version in two `GEM` sections (a hand-merged lock) are + /// not one source's to move: refused, nothing touched. + #[test] + fn platform_builds_spread_over_sections_are_refused() { + let lock = "GEM + remote: https://gems.mirror.example/ + specs: + nokogiri (1.16.0-arm64-darwin) + +GEM + remote: https://rubygems.org/ + specs: + nokogiri (1.16.0-x86_64-linux) + +DEPENDENCIES + nokogiri + +BUNDLED WITH + 2.6.2 +"; + let mut lk = lock.to_string(); + let mut changed = false; + let mut result = RewriteResult::default(); + let why = converge_gem_lock_source( + &mut lk, + &dep("nokogiri", "1.16.0"), + INDEX_URL, + "Gemfile.lock", + DependencyPin::Keep, + &mut changed, + &mut result, + ) + .unwrap_err(); + assert!( + why.contains("spread over more than one GEM section"), + "{why}" + ); + assert!(!changed && lk == lock && result.edits.is_empty()); + } + /// A transitive gem in the SECOND `GEM` section: located through the /// shared reader's section spans, moved into a patch-registry section /// sorted between the two remotes, and pinned in DEPENDENCIES before the diff --git a/crates/socket-patch-core/src/formats/gem/mod.rs b/crates/socket-patch-core/src/formats/gem/mod.rs index 0723cbbca..1e06a3a56 100644 --- a/crates/socket-patch-core/src/formats/gem/mod.rs +++ b/crates/socket-patch-core/src/formats/gem/mod.rs @@ -92,6 +92,25 @@ pub(crate) struct SpecLine<'t> { pub(crate) parsed: Option>, } +impl SpecLine<'_> { + /// Whether this entry locks a build of the gem `name` at `version`: the + /// ruby-platform entry `name (version)`, or a precompiled platform + /// build `name (version-)`. Bundler resolves one gem version + /// to one entry per platform the lock supports, so a redirect of the + /// version moves all of them together. + pub(crate) fn locks(&self, name: &str, version: &str) -> bool { + let ruby = self + .raw + .strip_prefix(name) + .and_then(|rest| rest.strip_prefix(" (")) + .and_then(|rest| rest.strip_suffix(')')) + == Some(version); + ruby || self.parsed.is_some_and(|spec| { + spec.platform.is_some() && spec.name == name && spec.version == version + }) + } +} + /// One source section (`GEM`, `PATH`, `GIT`, `PLUGIN SOURCE`). #[derive(Debug)] pub(crate) struct Section<'t> { @@ -242,6 +261,42 @@ impl<'t> GemfileLock<'t> { self.checksum_entries.is_some() } + /// The builds of `name` at `version` the lock names ([`LockedBuilds`]), + /// among the `GEM` sections' specs and the `CHECKSUMS` entries that pin + /// a sha256. A bare `CHECKSUMS` entry is what Bundler writes for a gem + /// it has no digest for (a `PATH` or `GIT` gem): it names no registry + /// build. + pub(crate) fn locked_builds(&self, name: &str, version: &str) -> LockedBuilds<'t> { + let mut builds = LockedBuilds::default(); + let specs = self + .gem_sections() + .flat_map(|section| section.specs.iter().map(|line| line.raw)); + // A `CHECKSUMS` entry up to its `)`: the spec it pins. + let checksums = self + .checksum_entries + .iter() + .flatten() + .copied() + .filter_map(|entry| { + let (name, token, tail) = split_checksum_entry(entry)?; + tail.contains("sha256=") + .then(|| &entry[..name.len() + " (".len() + token.len() + ")".len()]) + }); + for entry in specs.chain(checksums) { + let Some(spec) = parse_spec(entry).filter(|s| s.name == name && s.version == version) + else { + continue; + }; + match spec.platform { + Some(platform) => { + builds.platforms.insert(platform); + } + None => builds.ruby = true, + } + } + builds + } + /// [`Self::checksum`] as the lock pin readers record: the valid sha256 /// as [`LockIntegrity::Sha256Hex`], `None` when the lock pins nothing. pub(crate) fn integrity(&self, name: &'t str, token: &'t str) -> Option { @@ -250,6 +305,17 @@ impl<'t> GemfileLock<'t> { } } +/// The builds of one gem version a lock names +/// ([`GemfileLock::locked_builds`]). +#[derive(Debug, Default, PartialEq, Eq)] +pub(crate) struct LockedBuilds<'t> { + /// The platform of every `name (version-)` entry, sorted the + /// way Bundler orders them. + pub(crate) platforms: BTreeSet<&'t str>, + /// A ruby-platform `name (version)` entry is among them. + pub(crate) ruby: bool, +} + impl<'t> GemfileLock<'t> { /// Parse a lock text ([`parse`]). pub fn parse(text: &'t str) -> Self { @@ -305,6 +371,31 @@ impl<'t> GemfileLock<'t> { } } +impl GemfileLock<'_> { + /// The gems the lock resolves ONLY as precompiled platform builds: + /// `pkg:gem/@` for each gem version with `name + /// (version-)` specs in a `GEM` section and no ruby-platform + /// `name (version)` beside them, sorted. [`Self::entries`] leaves them + /// out (no single `.gem` stands for such a gem). Hosted mode patches + /// one through its per-platform prebuilds, so its discovery asks for + /// them here. + pub fn platform_only_purls(&self) -> Vec { + let specs = || { + self.gem_sections() + .flat_map(|section| section.specs.iter().filter_map(|line| line.parsed)) + }; + let ruby: HashSet<(&str, &str)> = specs() + .filter(|spec| spec.platform.is_none()) + .map(|spec| (spec.name, spec.version)) + .collect(); + let purls: BTreeSet = specs() + .filter(|spec| spec.platform.is_some() && !ruby.contains(&(spec.name, spec.version))) + .filter_map(|spec| simple_purl("gem", spec.name, spec.version)) + .collect(); + purls.into_iter().collect() + } +} + /// Where a rubygems-compatible registry at `base` (no trailing `/`) serves /// `name`-`version`'s `.gem` — the inventory's resolved URL and ledger /// recovery's fetch URL. `None` for a non-http(s) base. @@ -672,6 +763,77 @@ mod tests { ); } + /// The builds a lock names for one gem version: platform entries among + /// the specs and the sha256-pinned `CHECKSUMS` entries, and whether the + /// ruby-platform entry is one of them. Other versions, other gems, + /// non-`GEM` sections and bare `CHECKSUMS` entries do not count. + #[test] + fn locked_builds_of_a_gem_version() { + let sha = "a".repeat(64); + let text = format!( + "GEM\n remote: https://rubygems.org/\n specs:\n ffi (1.17.2-x86_64-linux-gnu)\n \ + nokogiri (1.18.10-x86_64-linux-gnu)\n racc (~> 1.4)\n nokogiri \ + (1.18.10-arm64-darwin)\n nokogiri (1.18.9-java)\n nokogiri-ext (1.18.10)\n\n\ + PATH\n remote: vendor/x\n specs:\n nokogiri (1.18.10-aarch64-linux-musl)\n\n\ + CHECKSUMS\n nokogiri (1.18.10-x64-mingw-ucrt)\n nokogiri (1.18.10-java) \ + sha256={sha}\n racc (1.8.1) sha256={sha}\n" + ); + let lock = parse(&text); + let builds = lock.locked_builds("nokogiri", "1.18.10"); + assert_eq!( + builds.platforms.iter().copied().collect::>(), + ["arm64-darwin", "java", "x86_64-linux-gnu"], + "the specs' platforms, and the one CHECKSUMS pins a sha256 for" + ); + assert!(!builds.ruby); + assert_eq!( + lock.locked_builds("racc", "1.8.1"), + LockedBuilds { + platforms: BTreeSet::new(), + ruby: true + }, + "a CHECKSUMS entry alone names the ruby gem" + ); + assert_eq!( + lock.locked_builds("nokogiri", "1.18"), + LockedBuilds::default() + ); + // The registry inventory lists only gems with a ruby-platform + // entry; hosted discovery asks for the platform-only ones apart. + assert_eq!( + lock.platform_only_purls(), + [ + "pkg:gem/ffi@1.17.2", + "pkg:gem/nokogiri@1.18.10", + "pkg:gem/nokogiri@1.18.9" + ] + ); + let inventoried: Vec = lock + .entries() + .unwrap_or_default() + .into_iter() + .map(|entry| entry.purl) + .collect(); + assert_eq!(inventoried, ["pkg:gem/nokogiri-ext@1.18.10"]); + + let section = lock.gem_sections().next().unwrap(); + let locking: Vec<&str> = section + .specs + .iter() + .filter(|line| line.locks("nokogiri", "1.18.10")) + .map(|line| line.raw) + .collect(); + assert_eq!( + locking, + [ + "nokogiri (1.18.10-x86_64-linux-gnu)", + "nokogiri (1.18.10-arm64-darwin)" + ] + ); + assert!(section.specs[4].locks("nokogiri-ext", "1.18.10")); + assert!(!section.specs[4].locks("nokogiri", "1.18.10")); + } + #[test] fn sections_specs_checksums_and_pins() { let sha = "A".repeat(64); diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index f492c64af..56f2c5ae9 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -6611,6 +6611,13 @@ snapshots: } async fn gem_rewrite_in(view: &ProjectView<'_>) -> (CandidateFiles, Rewritten) { + gem_rewrite_of(view, vec![gem_candidate()]).await + } + + async fn gem_rewrite_of( + view: &ProjectView<'_>, + candidates: Vec, + ) -> (CandidateFiles, Rewritten) { let outer = OuterAllowRemote::default; let options = RewriteOptions { dry_run: false, @@ -6629,12 +6636,79 @@ snapshots: patch_server_origins: Vec::new(), prior_discovery: None, }; - let candidates = vec![gem_candidate()]; let read = read_candidate_files(view, &BTreeSet::new(), &candidates).await; let done = rewrite(view, read.clone(), &candidates, BTreeMap::new(), options).await; (read, done) } + /// A gem locked as precompiled platform builds, with a prebuild for + /// each: the rewrite moves every build, and lockfile discovery (what + /// `vex`, `rollback` and `remove` read) attributes them to the one pin, + /// so the engine confirms it instead of dropping the rewrite as + /// unattributable. A second run over the result confirms the same pin + /// and writes nothing. + #[tokio::test] + async fn gem_platform_builds_are_confirmed_as_one_pin() { + use crate::patch::redirect::GemPlatformChecksum; + let mut candidate = gem_candidate(); + candidate + .dep + .registry_override + .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(); + 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 \ + rails (= 7.0.0)\n\nCHECKSUMS\n rails (7.0.0-arm64-darwin) sha256={}\n rails \ + (7.0.0-x86_64-linux-gnu) sha256={}\n\nBUNDLED WITH\n 4.0.15\n", + "1".repeat(64), + "2".repeat(64) + ); + let mut p = MemoryProject::new(); + p.insert_text("Gemfile", GEMFILE); + p.insert_text("Gemfile.lock", lock.as_str()); + let (_, done) = gem_rewrite_of(&ProjectView::Memory(&p), vec![candidate.clone()]).await; + assert!(done.unattributed.is_empty(), "{:?}", done.unattributed); + assert_eq!( + done.confirmed, + [("pkg:gem/rails@7.0.0".to_string(), FIXTURE_UUID.to_string())] + ); + let written = &done.rewrite.files["Gemfile.lock"]; + assert!( + written.contains( + " specs:\n rails (7.0.0-arm64-darwin)\n rails (7.0.0-x86_64-linux-gnu)\n\nGEM\n \ + remote: https://rubygems.org/\n specs:\n\nPLATFORMS" + ), + "{written}" + ); + assert!( + written.contains(&format!( + "CHECKSUMS\n rails (7.0.0-arm64-darwin) sha256={}\n rails (7.0.0-x86_64-linux-gnu) \ + sha256={}\n", + "a".repeat(64), + "b".repeat(64) + )), + "{written}" + ); + + 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; + assert!(again.rewrite.files.is_empty(), "{:?}", again.rewrite.edits); + assert_eq!(again.confirmed, done.confirmed); + assert!(again.unattributed.is_empty(), "{:?}", again.unattributed); + } + /// #390: `bundle config set --local gemfile Gemfile.next` makes bundler /// load `Gemfile.next`; the hosted redirect used to rewrite `Gemfile` /// (which bundler ignores) and attest the patch. Now no gem file is a diff --git a/crates/socket-patch-core/src/hosted/memory/mod.rs b/crates/socket-patch-core/src/hosted/memory/mod.rs index 8d3cd30ef..a4b3028b9 100644 --- a/crates/socket-patch-core/src/hosted/memory/mod.rs +++ b/crates/socket-patch-core/src/hosted/memory/mod.rs @@ -832,9 +832,18 @@ async fn engine( warnings.push(EngineWarning::new(code, detail, Some(&state.root))); } unsupported_ecosystem_warnings(&state.root, project, ecosystems, &mut warnings); + // The inventory's packages, and the gems the Bundler lock resolves + // only as precompiled platform builds, which it leaves out: hosted + // mode redirects those to their per-platform prebuilds. + let platform_gems = crate::vendor::lock_inventory::gem_platform_only_purls_in( + &ProjectView::Memory(project), + ) + .await; let purls: BTreeSet = entries .iter() - .filter_map(|e| discover::supplement_purl(&e.purl)) + .map(|e| e.purl.as_str()) + .chain(platform_gems.iter().map(String::as_str)) + .filter_map(discover::supplement_purl) .filter(|p| ecosystem_allowed(ecosystems, p)) .collect(); let mut admitted: Vec = Vec::with_capacity(purls.len()); diff --git a/crates/socket-patch-core/src/patch/redirect/grant.rs b/crates/socket-patch-core/src/patch/redirect/grant.rs index dbf7ea11a..da51253e9 100644 --- a/crates/socket-patch-core/src/patch/redirect/grant.rs +++ b/crates/socket-patch-core/src/patch/redirect/grant.rs @@ -267,6 +267,29 @@ 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` + // (`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() { + let platform = prebuild.platform.as_str(); + 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")); + } + if !is_hex(&prebuild.gem_checksum_sha256, 64) { + return Err(bad("gem platform checksum", "64 hex digits")); + } + if ids.gem_platforms[..at] + .iter() + .any(|earlier| earlier.platform == platform) + { + return Err(bad("gem platform list", "one entry per platform")); + } + } for (what, digest) in [ ("Maven pom sha256", &ids.maven_pom_sha256), ("Maven module sha256", &ids.maven_module_sha256), @@ -556,6 +579,53 @@ mod tests { let reason = malformed(&dep); assert!(reason.starts_with(&format!("its {field} ")), "{reason}"); } + // A gem patch's prebuilds: each platform and sha256 is written + // into the lock. + type Prebuilds = Vec<(&'static str, String)>; + let sha = "c".repeat(64); + let prebuilds: [(Option<&str>, Prebuilds); 6] = [ + ( + None, + vec![("x86_64-linux-gnu", sha.clone()), ("java", sha.clone())], + ), + (Some("gem platform "), vec![("ruby", sha.clone())]), + ( + Some("gem platform "), + vec![("arm64-darwin)\n evil (1.0", sha.clone())], + ), + (Some("gem platform "), vec![("21-darwin", sha.clone())]), + ( + Some("gem platform checksum "), + vec![("arm64-darwin", "abc".to_string())], + ), + ( + Some("gem platform list "), + vec![("arm64-darwin", sha.clone()), ("arm64-darwin", sha.clone())], + ), + ]; + for (field, list) in prebuilds { + let mut dep = maven(); + dep.registry_override + .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(); + match field { + None => assert_eq!(check(&dep, &[]), Ok(())), + Some(field) => { + let reason = malformed(&dep); + assert!(reason.starts_with(&format!("its {field}")), "{reason}"); + } + } + } // The sparse prefix is cargo's. let mut cargo = DepOverride { ecosystem: "cargo".into(), diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index ebcc01a76..0daf531c8 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -194,7 +194,31 @@ pub struct RegistryOverrideIdentifiers { /// `gradle/verification-metadata.xml`. #[cfg_attr(test, serde(skip_serializing_if = "Option::is_none"))] pub maven_module_sha256: Option, + /// 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)] + #[cfg_attr(test, serde(skip_serializing_if = "Vec::is_empty"))] + pub gem_platforms: Vec, +} + +/// 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`). +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[cfg_attr(test, derive(Serialize))] +#[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`. + pub platform: String, + /// sha256 hex of that platform's `.gem`. + pub gem_checksum_sha256: String, } #[derive(Debug, Clone, Deserialize)] @@ -7987,9 +8011,16 @@ fn gem_pair_agrees( } let model = crate::formats::gem::parse(lock); let spec = format!("{} ({})", dep.name, dep.version); + // The sections holding a build of the version: its ruby-platform entry, + // or the platform entries a precompiled gem is locked as. let holders: Vec<_> = model .gem_sections() - .filter(|section| section.specs.iter().any(|s| s.raw == spec)) + .filter(|section| { + section + .specs + .iter() + .any(|s| s.locks(&dep.name, &dep.version)) + }) .collect(); let [section] = holders.as_slice() else { return Err(format!( @@ -8014,14 +8045,17 @@ fn gem_pair_agrees( /// Plan the redirect of `dep` over the manifest pair (see [`GemPlan`]): the /// manifest gains the Socket source, and the lock is converged to what the -/// bundler that wrote it writes for that manifest. `Err` is the warning for +/// bundler that wrote it writes for that manifest. `checksums` is what the +/// lock's `CHECKSUMS` pins for the gem: `(token, sha256)` per build the +/// lock names, the token as the entry spells it (`` for the ruby +/// gem, `-` for a prebuild). `Err` is the warning for /// a gem that cannot be redirected; nothing is planned for it then. #[allow(clippy::too_many_arguments)] fn plan_gem_redirect( files: &BTreeMap, dep: &DepOverride, index_url: &str, - sha256: &str, + checksums: &[(String, String)], gemfile: Option<&str>, lock: &str, (gemfile_name, lock_name): (&str, &str), @@ -8285,49 +8319,56 @@ fn plan_gem_redirect( }; // ── The lock ──────────────────────────────────────────────────────── - let new_val = format!("{name} ({}) sha256={sha256}", dep.version); let mut unchecked = false; - // The entry for exactly `name (version)`, read with the shared - // Bundler-lock grammar the discovery reader uses — whatever digests it - // carries (bare, uppercase, several algorithms), so it is REPLACED, - // never shadowed by a second, conflicting entry. - if let Some((start, end)) = checksum_entry_span(&lk, name, &dep.version) { - let old_val = lk[start + 2..end].to_string(); - // Already redirected (re-run): the entry is at the target value. - if old_val != new_val { - lk.replace_range(start + 2..end, &new_val); + // One `CHECKSUMS` entry per build the lock names, each pinned to its + // own patched archive. The last one first: an entry the section lacks + // goes right under the header, so several end up in `checksums` order. + let mut checksum_edits: Vec = Vec::new(); + for (token, sha256) in checksums.iter().rev() { + let new_val = format!("{name} ({token}) sha256={sha256}"); + // The entry for exactly `name (token)`, read with the shared + // Bundler-lock grammar the discovery reader uses — whatever digests + // it carries (bare, uppercase, several algorithms), so it is + // REPLACED, never shadowed by a second, conflicting entry. + if let Some((start, end)) = checksum_entry_span(&lk, name, token) { + let old_val = lk[start + 2..end].to_string(); + // Already redirected (re-run): the entry is at the target value. + if old_val != new_val { + lk.replace_range(start + 2..end, &new_val); + lock_changed = true; + // The pre-edit entry is recorded verbatim as `original`. + checksum_edits.push(FileEdit { + path: lock_name.into(), + kind: "redirect_gemfile_lock_checksum".into(), + action: "rewritten".into(), + key: Some(dep.name.clone()), + original: Some(Value::String(old_val)), + new: Some(Value::String(new_val)), + }); + } + } else if GEM_CHECKSUMS_HEADER_RE.is_match(&lk) { + // A closure, not a template: the entry is written as it is, in + // the header's own line ending (the capture). + lk = GEM_CHECKSUMS_HEADER_RE + .replace(&lk, |header: ®ex::Captures<'_>| { + let cr = &header[1]; + format!("CHECKSUMS{cr}\n {new_val}{cr}") + }) + .to_string(); lock_changed = true; - // The pre-edit entry is recorded verbatim as `original`. - staged.edits.push(FileEdit { + checksum_edits.push(FileEdit { path: lock_name.into(), kind: "redirect_gemfile_lock_checksum".into(), - action: "rewritten".into(), + action: "added".into(), key: Some(dep.name.clone()), - original: Some(Value::String(old_val)), + original: None, new: Some(Value::String(new_val)), }); + } else { + unchecked = true; } - } else if GEM_CHECKSUMS_HEADER_RE.is_match(&lk) { - // A closure, not a template: the entry is written as it is, in - // the header's own line ending (the capture). - lk = GEM_CHECKSUMS_HEADER_RE - .replace(&lk, |header: ®ex::Captures<'_>| { - let cr = &header[1]; - format!("CHECKSUMS{cr}\n {new_val}{cr}") - }) - .to_string(); - lock_changed = true; - staged.edits.push(FileEdit { - path: lock_name.into(), - kind: "redirect_gemfile_lock_checksum".into(), - action: "added".into(), - key: Some(dep.name.clone()), - original: None, - new: Some(Value::String(new_val)), - }); - } else { - unchecked = true; } + staged.edits.extend(checksum_edits.into_iter().rev()); let mut mixed = false; match wiring { @@ -8589,17 +8630,6 @@ fn rewrite_gem( // The specs the lock resolves, read once from the lock as it was handed // in: the rewrites below only re-point specs, never change a version. let locked = files.get(lock_name).map(|lk| gem_locked_specs(lk)); - // The `name (version-platform)` specs it resolves besides. - let platform_specs: Vec<(&str, &str, &str)> = files - .get(lock_name) - .map(|lk| { - crate::formats::gem::parse(lk) - .gem_sections() - .flat_map(|s| s.specs.iter().filter_map(|l| l.parsed)) - .filter_map(|spec| Some((spec.name, spec.version, spec.platform?))) - .collect() - }) - .unwrap_or_default(); // Which lock layout the project's bundler writes and accepts. let layout = files.get(lock_name).and_then(|lk| lock_layout(lk)); @@ -8673,39 +8703,88 @@ fn rewrite_gem( continue; }; + // What `CHECKSUMS` pins for the gem: the ruby gem's sha256 under + // `name (version)`, unless the lock names platform builds. + let mut checksums = vec![(dep.version.clone(), sha256)]; // Platform-specific builds (`name (version-arm64-darwin)` among the - // specs or the CHECKSUMS entries) mean bundler resolves gems the - // patch registry does not serve — redirecting would pin the - // ruby-platform sha while installs keep fetching the upstream - // platform gem (guaranteed mismatch or a silently unpatched - // install). Fail closed: skip the dep entirely. + // 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. if let Some(lk) = lock.as_deref() { - let platform_re = Regex::new( - &(String::from(r"(?m)^ ") - + ®ex::escape(&dep.name) - + r" \(" - + ®ex::escape(&dep.version) - + r"-[^)]+\) sha256="), - ) - .expect("platform regex from the escaped name/version is valid"); - let spec = platform_specs - .iter() - .find(|(name, version, _)| *name == dep.name && *version == dep.version); - if platform_re.is_match(lk) || spec.is_some() { - result.warnings.push(RewriteWarning { - code: "redirect_gem_platform_unsupported".into(), - detail: format!( - "{lock_name} locks platform-specific builds of {} {}{} — the patch \ - registry serves only the ruby platform gem; redirect skipped", - dep.name, - dep.version, - spec.map(|(name, version, platform)| format!( - " (`{name} ({version}-{platform})`)" - )) - .unwrap_or_default() - ), - }); - continue; + let builds = crate::formats::gem::parse(lk).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) + }; + let entry = + |platform: &&str| format!("`{} ({}-{platform})`", dep.name, dep.version); + let missing: Vec = builds + .platforms + .iter() + .filter(|platform| prebuilt(platform).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(); + 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(", ")) + } + ) + } 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(), + detail: format!( + "{lock_name} locks platform-specific builds of {} {} ({}), and \ + {why}; redirect skipped", + dep.name, + dep.version, + builds + .platforms + .iter() + .map(entry) + .collect::>() + .join(", "), + ), + }); + continue; + } + // The ruby gem's entry stays only where the lock has one + // beside the platform builds (the registry serves it too). + if !builds.ruby { + checksums.clear(); + } + checksums.extend(builds.platforms.iter().filter_map(|platform| { + Some(( + format!("{}-{platform}", dep.version), + prebuilt(platform)?.gem_checksum_sha256.clone(), + )) + })); } } @@ -8755,7 +8834,7 @@ fn rewrite_gem( files, dep, &ov.index_url, - &sha256, + &checksums, gemfile.as_deref(), lk, (gemfile_name, lock_name), @@ -20043,6 +20122,431 @@ mod tests { ); } + /// [`gem_override`] with a prebuild (`(platform, sha256)`) per platform. + fn gem_override_prebuilt(name: &str, version: &str, prebuilds: &[(&str, &str)]) -> 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(); + dep + } + + const NOKOGIRI_GEMFILE: &str = + "source \"https://rubygems.org\"\n\ngem \"nokogiri\", \"1.18.10\"\n"; + + /// The upstream sha256 a fixture lock pins for a build of nokogiri. + fn upstream_sha(token: &str) -> String { + format!("{:0>64}", token.len()) + } + + /// A lock that resolves nokogiri 1.18.10 as the precompiled builds of + /// `platforms` (the shape bundler 4.0.15 writes), with the + /// ruby-platform entry beside them when `ruby`, and + /// each build's upstream sha256 under `CHECKSUMS` when `checksums`. + fn nokogiri_lock(platforms: &[&str], ruby: bool, checksums: bool) -> String { + let mut tokens: Vec = Vec::new(); + if ruby { + tokens.push("1.18.10".to_string()); + } + tokens.extend(platforms.iter().map(|p| format!("1.18.10-{p}"))); + let mut out = String::from("GEM\n remote: https://rubygems.org/\n specs:\n"); + for token in &tokens { + out.push_str(&format!(" nokogiri ({token})\n racc (~> 1.4)\n")); + } + out.push_str(" racc (1.8.1)\n\nPLATFORMS\n"); + for platform in platforms { + out.push_str(&format!(" {platform}\n")); + } + out.push_str("\nDEPENDENCIES\n nokogiri (= 1.18.10)\n"); + if checksums { + out.push_str("\nCHECKSUMS\n"); + for token in &tokens { + out.push_str(&format!( + " nokogiri ({token}) sha256={}\n", + upstream_sha(token) + )); + } + out.push_str(&format!(" racc (1.8.1) sha256={}\n", "9".repeat(64))); + } + out.push_str("\nBUNDLED WITH\n 4.0.15\n"); + out + } + + /// [`nokogiri_lock`] as the hosted rewrite leaves it: every build in + /// the patch registry's `GEM` section (which sorts before + /// rubygems.org), the dependency source-pinned, and each `CHECKSUMS` + /// entry at `pins`' sha256 for its token. + fn nokogiri_lock_hosted( + platforms: &[&str], + ruby: bool, + pins: Option<&[(&str, &str)]>, + ) -> String { + let mut tokens: Vec = Vec::new(); + if ruby { + tokens.push("1.18.10".to_string()); + } + tokens.extend(platforms.iter().map(|p| format!("1.18.10-{p}"))); + let mut out = format!("GEM\n remote: {GEM_TEST_URL}\n specs:\n"); + for token in &tokens { + out.push_str(&format!(" nokogiri ({token})\n racc (~> 1.4)\n")); + } + out.push_str( + "\nGEM\n remote: https://rubygems.org/\n specs:\n racc (1.8.1)\n\nPLATFORMS\n", + ); + for platform in platforms { + out.push_str(&format!(" {platform}\n")); + } + out.push_str("\nDEPENDENCIES\n nokogiri (= 1.18.10)!\n"); + if let Some(pins) = pins { + out.push_str("\nCHECKSUMS\n"); + for token in &tokens { + let sha = pins + .iter() + .find(|(t, _)| t == token) + .unwrap_or_else(|| panic!("no pin for {token}")) + .1; + out.push_str(&format!(" nokogiri ({token}) sha256={sha}\n")); + } + out.push_str(&format!(" racc (1.8.1) sha256={}\n", "9".repeat(64))); + } + out.push_str("\nBUNDLED WITH\n 4.0.15\n"); + out + } + + /// A gem bundler locks as precompiled platform builds, with a prebuild + /// for every one of them. + /// Each entry moves, block and sub-lines verbatim, into the patch + /// registry's `GEM` section; `DEPENDENCIES` is pinned; each `CHECKSUMS` + /// entry takes its own prebuild's sha256. The Gemfile edit is the one + /// a ruby gem gets, and a second scan changes nothing. + #[test] + fn gem_platform_builds_move_to_the_patch_registry_with_their_prebuilds() { + let (arm, linux) = ("a".repeat(64), "b".repeat(64)); + let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; + let dep = gem_override_prebuilt( + "nokogiri", + "1.18.10", + &[("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)], + ); + let (gemfile, lock, r) = gem_redirect( + NOKOGIRI_GEMFILE, + &nokogiri_lock(&platforms, false, true), + dep.clone(), + ); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert_eq!( + gemfile, + format!( + "source \"https://rubygems.org\"\n\ngem \"nokogiri\", \"1.18.10\", source: \ + \"{GEM_TEST_URL}\"\n" + ) + ); + assert_eq!( + lock, + nokogiri_lock_hosted( + &platforms, + false, + Some(&[ + ("1.18.10-arm64-darwin", &arm), + ("1.18.10-x86_64-linux-gnu", &linux) + ]) + ) + ); + let edits: Vec<(&str, &str, String)> = r + .edits + .iter() + .filter(|e| e.path == "Gemfile.lock") + .map(|e| { + let new = e.new.as_ref().and_then(Value::as_str).unwrap_or_default(); + (e.kind.as_str(), e.action.as_str(), new.to_string()) + }) + .collect(); + assert_eq!( + edits, + [ + ( + "redirect_gemfile_lock_checksum", + "rewritten", + format!("nokogiri (1.18.10-arm64-darwin) sha256={arm}") + ), + ( + "redirect_gemfile_lock_checksum", + "rewritten", + format!("nokogiri (1.18.10-x86_64-linux-gnu) sha256={linux}") + ), + ( + "redirect_gemfile_lock_dependency_pin", + "rewritten", + "nokogiri (= 1.18.10)!".to_string() + ), + ( + "redirect_gemfile_lock_gem_source", + "rewritten", + GEM_TEST_URL.to_string() + ), + ] + ); + + // The pair the scan left is the pair it wants: nothing to do. + let (_, _, again) = gem_redirect(&gemfile, &lock, dep); + assert!( + again.files.is_empty() && again.edits.is_empty() && again.warnings.is_empty(), + "a second scan is a no-op: files={:?} edits={:?} warnings={:?}", + again.files.keys(), + again.edits, + again.warnings + ); + } + + /// A lock with no `CHECKSUMS` section (bundler 2.2–2.5, or checksums + /// off) gets none: the builds move and are pinned by source alone, + /// which the run says once. Re-scanning it is a no-op too. + #[test] + fn gem_platform_builds_move_in_a_lock_without_checksums() { + let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; + let dep = gem_override_prebuilt( + "nokogiri", + "1.18.10", + &[ + ("arm64-darwin", &"a".repeat(64)), + ("x86_64-linux-gnu", &"b".repeat(64)), + ], + ); + let (gemfile, lock, r) = gem_redirect( + NOKOGIRI_GEMFILE, + &nokogiri_lock(&platforms, false, false), + dep.clone(), + ); + assert_eq!(lock, nokogiri_lock_hosted(&platforms, false, None)); + let codes: Vec<&str> = r.warnings.iter().map(|w| w.code.as_str()).collect(); + assert_eq!( + codes, + ["redirect_gem_no_checksums_section"], + "{:?}", + r.warnings + ); + let (_, _, again) = gem_redirect(&gemfile, &lock, dep); + assert!( + again.files.is_empty() && again.edits.is_empty(), + "a second scan changes nothing: {:?}", + again.edits + ); + } + + /// A ruby-platform `name (version)` entry beside the platform builds + /// (a lock whose PLATFORMS include `ruby`) moves with them, pinned to + /// the ruby gem's own sha256: the registry serves that gem too. + #[test] + fn gem_ruby_entry_beside_platform_builds_moves_with_them() { + let arm = "a".repeat(64); + let dep = gem_override_prebuilt("nokogiri", "1.18.10", &[("arm64-darwin", &arm)]); + let (gemfile, lock, r) = gem_redirect( + NOKOGIRI_GEMFILE, + &nokogiri_lock(&["arm64-darwin"], true, true), + dep.clone(), + ); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert_eq!( + lock, + nokogiri_lock_hosted( + &["arm64-darwin"], + true, + Some(&[("1.18.10", &"f".repeat(64)), ("1.18.10-arm64-darwin", &arm)]) + ) + ); + let (_, _, again) = gem_redirect(&gemfile, &lock, dep); + 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. + #[test] + fn gem_platform_without_a_prebuild_skips_the_gem_and_names_it() { + let lock = nokogiri_lock(&["arm64-darwin", "x86_64-linux-gnu"], false, true); + for (prebuilds, served) in [ + ( + vec![("arm64-darwin", "a".repeat(64))], + "the ruby platform gem and patched builds for arm64-darwin", + ), + (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(), + "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.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 + ); + } + } + + /// A platform build named only under `CHECKSUMS` counts as locked: with + /// its prebuild, the ruby entry moves and BOTH entries are re-pinned, + /// each to its own archive (never the platform line left on the + /// upstream sha256). + #[test] + fn gem_platform_checksum_entry_is_pinned_to_its_prebuild() { + let arm = "a".repeat(64); + let files = BTreeMap::from([ + ( + "Gemfile".to_string(), + "source \"https://rubygems.org\"\n\ngem \"rails\", \"7.0.0\"\n".to_string(), + ), + ( + "Gemfile.lock".to_string(), + gem_lock(&format!( + " rails (7.0.0) sha256={}\n rails (7.0.0-arm64-darwin) sha256={}", + "2".repeat(64), + "3".repeat(64) + )), + ), + ]); + let dep = gem_override_prebuilt("rails", "7.0.0", &[("arm64-darwin", &arm)]); + let r = rewrite_registry_redirect(&files, &[dep]); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let lock = &r.files["Gemfile.lock"]; + assert!( + lock.contains(&format!( + "CHECKSUMS\n rails (7.0.0) sha256={}\n rails (7.0.0-arm64-darwin) sha256={arm}\n", + "f".repeat(64) + )), + "{lock}" + ); + assert!( + lock.starts_with(&format!( + "GEM\n remote: {GEM_TEST_URL}\n specs:\n rails (7.0.0)\n\n" + )), + "{lock}" + ); + } + + /// CRLF line endings survive: the moved entries keep their own, and the + /// lines the rewrite writes take the file's. + #[test] + fn gem_platform_builds_move_in_a_crlf_lock() { + let (arm, linux) = ("a".repeat(64), "b".repeat(64)); + let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; + let dep = gem_override_prebuilt( + "nokogiri", + "1.18.10", + &[("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)], + ); + let crlf = |text: &str| text.replace('\n', "\r\n"); + let (gemfile, lock, r) = gem_redirect( + &crlf(NOKOGIRI_GEMFILE), + &crlf(&nokogiri_lock(&platforms, false, true)), + dep.clone(), + ); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert_eq!( + lock, + crlf(&nokogiri_lock_hosted( + &platforms, + false, + Some(&[ + ("1.18.10-arm64-darwin", &arm), + ("1.18.10-x86_64-linux-gnu", &linux) + ]) + )) + ); + let (_, _, again) = gem_redirect(&gemfile, &lock, dep); + assert!(again.files.is_empty() && again.edits.is_empty()); + } + + /// A gem the Gemfile does not declare (another gem depends on it): the + /// added line and `DEPENDENCIES` entry are the ones a ruby gem gets, + /// and the platform builds move the same way. + #[test] + fn gem_transitive_platform_builds_get_the_added_line() { + let arm = "a".repeat(64); + let gemfile = "source \"https://rubygems.org\"\n\ngem \"loofah\"\n"; + let lock = nokogiri_lock(&["arm64-darwin"], false, true) + .replace( + " specs:\n", + " specs:\n loofah (2.24.1)\n nokogiri (>= 1.12.0)\n", + ) + .replace(" nokogiri (= 1.18.10)\n", " loofah\n"); + let dep = gem_override_prebuilt("nokogiri", "1.18.10", &[("arm64-darwin", &arm)]); + let (gemfile_after, lock_after, r) = gem_redirect(gemfile, &lock, dep); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!( + gemfile_after.contains(&format!( + "\ngem \"nokogiri\", \"1.18.10\", source: \"{GEM_TEST_URL}\", require: false #" + )), + "{gemfile_after}" + ); + assert!( + lock_after.starts_with(&format!( + "GEM\n remote: {GEM_TEST_URL}\n specs:\n nokogiri (1.18.10-arm64-darwin)\n \ + racc (~> 1.4)\n\nGEM\n remote: https://rubygems.org/\n specs:\n loofah (2.24.1)\n" + )), + "{lock_after}" + ); + assert!( + lock_after.contains("DEPENDENCIES\n loofah\n nokogiri (= 1.18.10)!\n"), + "{lock_after}" + ); + assert!( + lock_after.contains(&format!(" nokogiri (1.18.10-arm64-darwin) sha256={arm}\n")), + "{lock_after}" + ); + } + + /// Bundler < 2.2 lists every source in ONE `GEM` section. Only a + /// ruby-platform entry is proven to converge there, so a platform build + /// keeps the skip even with a prebuild. + #[test] + fn gem_platform_builds_in_a_merged_lock_are_skipped() { + let lock = + "GEM\n remote: https://rubygems.org/\n specs:\n nokogiri (1.10.10-java)\n\n\ + PLATFORMS\n java\n\nDEPENDENCIES\n nokogiri (= 1.10.10)\n\n\ + BUNDLED WITH\n 2.1.4\n"; + let gemfile = "source \"https://rubygems.org\"\n\ngem \"nokogiri\", \"1.10.10\"\n"; + let dep = gem_override_prebuilt("nokogiri", "1.10.10", &[("java", &"a".repeat(64))]); + let (_, _, r) = gem_redirect(gemfile, lock, dep); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.edits); + let [warning] = r.warnings.as_slice() else { + panic!("one warning: {:?}", r.warnings); + }; + assert_eq!(warning.code, "redirect_gem_platform_unsupported"); + assert!( + warning.detail.contains("bundler (< 2.2)"), + "{}", + warning.detail + ); + } + /// Legal-but-non-canonical declarations (parenthesized call, tab or no /// space after `gem`) are declarations all the same: each takes the /// option where it is — treating one as undeclared would add a second diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs index c2cba5b41..cbc2f8844 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs @@ -159,14 +159,16 @@ fn packagist_base() -> String { } /// The `checksum:` (sha256 hex of the `.gem`) a compact-index `info/` -/// file records for the ruby-platform `version` — the value bundler writes -/// into `CHECKSUMS`. Lines are `[-] |`, the -/// requirement list carrying `checksum:`. -pub(crate) fn compact_index_checksum(info: &str, version: &str) -> Option { +/// file records for the build `token` — the value bundler writes into +/// `CHECKSUMS`. Lines are `[-] |`, the +/// requirement list carrying `checksum:`: `token` is `` for +/// the ruby-platform gem and `-` for a platform gem, +/// matched whole, so a version never answers for one of its platform +/// builds. +pub(crate) fn compact_index_checksum(info: &str, token: &str) -> Option { info.lines().find_map(|line| { let (head, reqs) = line.split_once('|')?; - let token = head.split(' ').next()?; - if token != version { + if head.split(' ').next()? != token { return None; } reqs.split(',') @@ -175,6 +177,20 @@ pub(crate) fn compact_index_checksum(info: &str, version: &str) -> Option Result { + compact_index_checksum(info, token).ok_or_else(|| { + let build = if token.contains('-') { + token.to_string() + } else { + format!("ruby-platform {token}") + }; + format!("{url} lists no {build} with a checksum") + }) +} + /// Expand a packagist `p2` version list. `minified: composer/2.0` documents /// (composer's `MetadataMinifier`) list each version as the DIFF against the /// previous expanded one: every key it carries replaces the inherited value, @@ -214,6 +230,10 @@ pub(crate) const OFFLINE: &str = type Cache = Mutex>>; +/// A compact-index `info/` document with the URL it was read from +/// (credentials redacted), or why it could not be read. +type GemInfo = Result<(String, String), String>; + /// [`Cache`] keyed by (registry base, `Authorization` sent, name, version). type RegistryCache = Mutex, String, String), Result>>; @@ -240,6 +260,11 @@ pub(crate) struct UpstreamClient { cargo: Cache, go: Cache, rubygems: Cache, + /// The compact-index `info/` documents already read, by gem + /// name, each with the URL it was read from: one lists every build of + /// the gem, and a gem locked as platform builds asks for the sha256 of + /// each. + rubygems_info: Mutex>, packagist: Cache>, pypi: Cache>, nuget: Cache, @@ -262,6 +287,7 @@ impl UpstreamClient { cargo: Mutex::default(), go: Mutex::default(), rubygems: Mutex::default(), + rubygems_info: Mutex::default(), packagist: Mutex::default(), pypi: Mutex::default(), nuget: Mutex::default(), @@ -579,8 +605,11 @@ impl UpstreamClient { result } - /// The rubygems.org sha256 of the ruby-platform `name-version.gem`, - /// from the compact index bundler itself reads (`info/`). + /// The rubygems.org sha256 of one build of a gem, from the compact + /// index bundler itself reads (`info/`). `token` names the build + /// as that index and the lock's `CHECKSUMS` do: `` for the + /// ruby-platform `name-version.gem`, `-` for a + /// platform gem. /// /// The lock's `CHECKSUMS` entry is re-pinned from it, and after an /// unwind the installed copy is replaced by the archive that has it @@ -588,31 +617,37 @@ impl UpstreamClient { /// native extension. So it is read over a transport nobody can rewrite /// ([`rubygems_secure_base`], [`SecureRegistryClient`]): a registry /// reached over plain http is not asked. - pub(crate) async fn rubygems_sha256( - &self, - name: &str, - version: &str, - ) -> Result { - let key = (name.to_string(), version.to_string()); + pub(crate) async fn rubygems_sha256(&self, name: &str, token: &str) -> Result { + let key = (name.to_string(), token.to_string()); if let Some(hit) = self.rubygems.lock().await.get(&key) { return hit.clone(); } - let result = self - .rubygems_sha256_at(rubygems_secure_base(), name, version) - .await; + // The document is read once per gem: the builds of one version + // (a gem locked for several platforms) are lines of the same one. + let info = self.rubygems_info.lock().await.get(name).cloned(); + let result = match info { + Some(info) => info.and_then(|(url, text)| checksum_in(&url, &text, token)), + None => { + let fetched = self.rubygems_info_at(rubygems_secure_base(), name).await; + let result = fetched + .clone() + .and_then(|(url, text)| checksum_in(&url, &text, token)); + self.rubygems_info + .lock() + .await + .insert(name.to_string(), fetched); + result + } + }; self.rubygems.lock().await.insert(key, result.clone()); result } - /// [`Self::rubygems_sha256`], uncached, from the registry at `base` - /// ([`rubygems_secure_base`]: its URL, or why it is not asked). The - /// base may carry a mirror's credentials: no error repeats them. - async fn rubygems_sha256_at( - &self, - base: Result, - name: &str, - version: &str, - ) -> Result { + /// The compact-index `info/` document of the registry at `base` + /// ([`rubygems_secure_base`]: its URL, or why it is not asked), with + /// the URL it was read from. Uncached. The base may carry a mirror's + /// credentials: neither the URL returned nor an error repeats them. + async fn rubygems_info_at(&self, base: Result, name: &str) -> GemInfo { if self.offline { return Err(OFFLINE.to_string()); } @@ -626,13 +661,13 @@ impl UpstreamClient { let _permit = self.permit().await; registry.download(&url).await? }; - let text = String::from_utf8(bytes).map_err(|_| format!("{url} is not UTF-8"))?; - compact_index_checksum(&text, version) - .ok_or_else(|| format!("{url} lists no ruby-platform {version} with a checksum")) + String::from_utf8(bytes).map_err(|_| format!("{url} is not UTF-8")) }; - looked_up - .await - .map_err(|why: String| crate::utils::redact::redact_urls_in(&why).into_owned()) + let redact = |text: &str| crate::utils::redact::redact_urls_in(text).into_owned(); + match looked_up.await { + Ok(text) => Ok((redact(&url), text)), + Err(why) => Err(redact(&why)), + } } /// Every version packagist serves for the composer package `name` @@ -1015,8 +1050,12 @@ mod tests { .await; let base = server.uri().replace("http://", "http://deploy:hunter2@"); let client = UpstreamClient::new(false); - let at = |name: &'static str, version: &'static str| { - client.rubygems_sha256_at(Ok(base.clone()), name, version) + let at = |name: &'static str, token: &'static str| { + let (client, base) = (&client, base.clone()); + async move { + let (url, info) = client.rubygems_info_at(Ok(base), name).await?; + checksum_in(&url, &info, token) + } }; assert_eq!(at("rails", "7.0.0").await, Ok(sha)); for (name, version, expected) in [ @@ -1025,6 +1064,7 @@ mod tests { "7.1.0", "lists no ruby-platform 7.1.0 with a checksum", ), + ("rails", "7.0.0-java", "lists no 7.0.0-java with a checksum"), ("garbled", "1.0.0", "is not UTF-8"), ("absent", "1.0.0", "HTTP 404"), ] { @@ -1039,10 +1079,7 @@ mod tests { let asked = server.received_requests().await.unwrap().len(); let refused = secure_gem_registry("http://deploy:hunter2@gems.example.test".to_string()); - let why = client - .rubygems_sha256_at(refused, "rails", "7.0.0") - .await - .unwrap_err(); + let why = client.rubygems_info_at(refused, "rails").await.unwrap_err(); assert!(why.contains("set it to an https URL"), "{why}"); assert!(!why.contains("hunter2"), "{why}"); assert_eq!(server.received_requests().await.unwrap().len(), asked); @@ -1057,6 +1094,9 @@ mod tests { 1.1.0-java |checksum:{other}\n" ); assert_eq!(compact_index_checksum(&info, "1.1.0"), Some(sha)); + // A platform build is named by its whole token, and only by it. + assert_eq!(compact_index_checksum(&info, "1.1.0-java"), Some(other)); + assert_eq!(compact_index_checksum(&info, "1.1.0-jav"), None); assert_eq!(compact_index_checksum(&info, "2.0.0"), None); assert_eq!(compact_index_checksum("1.0.0 |ruby:>= 2", "1.0.0"), None); } diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs b/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs index 3324cf632..5dea7b992 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs @@ -26,7 +26,10 @@ //! name order, into the upstream `GEM` section: the one remaining //! non-Socket single-remote section, or — when there are several — the //! one naming the manifest's global `source`, else the rubygems.org one; -//! anything else is ambiguous and refused. +//! anything else is ambiguous and refused. A gem locked as precompiled +//! platform builds has one spec per platform there (`name +//! (version-)`, with or without the ruby-platform one): each +//! goes back to where Bundler sorts it, by full name. //! * **Merged** (bundler ≤ 2.1 writes every rubygems source into ONE `GEM` //! section): the Socket `remote:` line is dropped from it. //! * **Mixed** (a block of 5.0 / 5.1 on a bundler < 2.6 lock those releases @@ -39,7 +42,9 @@ //! In every state a `CHECKSUMS` entry is re-pinned to the upstream sha256 //! from the rubygems.org compact index (`info/`, what bundler itself //! records; other upstream remotes are refused: their index may need -//! credentials and is not the default registry), and the `DEPENDENCIES` +//! credentials and is not the default registry) — each platform build's +//! entry to that build's own sha256, the index's `-` +//! line — and the `DEPENDENCIES` //! source pin (`name (…)!`) loses its `!` — unless the declaration sits //! inside the user's own `source … do` block, where bundler writes the `!` //! itself ([`in_source_block`], #1056). A `CHECKSUMS` entry the rewriter @@ -106,9 +111,24 @@ struct Entry { last: usize, name: String, version: String, + /// The parenthesized token: `version`, or `version-` for a + /// platform build. Empty for an entry that is no `name (token)`. + token: String, platform: bool, } +impl Entry { + /// `name-version[-platform]`, the key Bundler sorts a section's specs + /// by (`LockfileGenerator#add_specs`: `sort_by(&:full_name)`). + fn full_name(&self) -> String { + if self.token.is_empty() { + self.name.clone() + } else { + format!("{}-{}", self.name, self.token) + } + } +} + /// One `GEM` section: `[start, end)` runs from its header to the next /// header (its trailing blank separator included). struct GemSec { @@ -160,6 +180,13 @@ fn gem_sections(lines: &[&str]) -> Vec { last: k, name: spec.map(|s| s.name).unwrap_or(entry).to_string(), version: spec.map(|s| s.version).unwrap_or_default().to_string(), + token: match spec { + Some(s) => match s.platform { + Some(platform) => format!("{}-{platform}", s.version), + None => s.version.to_string(), + }, + None => String::new(), + }, platform: spec.is_none_or(|s| s.platform.is_some()), }); } else if line.starts_with(" ") { @@ -290,29 +317,32 @@ fn choose_upstream( } } -/// The line after which a spec named `name-version` sorts into `sec` -/// (bundler writes specs sorted by full name). +/// The line after which a spec of full name `full_name` +/// ([`Entry::full_name`]) sorts into `sec` (bundler writes specs sorted by +/// full name). fn insertion_point(sec: &GemSec, full_name: &str) -> Option { - let pred = sec.entries.iter().rfind(|e| { - let full = if e.version.is_empty() { - e.name.clone() - } else { - format!("{}-{}", e.name, e.version) - }; - full.as_str() < full_name - }); + let pred = sec + .entries + .iter() + .rfind(|e| e.full_name().as_str() < full_name); pred.map(|e| e.last).or(sec.specs_line) } /// A lock restore step's outcome. enum LockEdit { - /// The `CHECKSUMS` entry must be re-pinned from `remote` first. + /// The `CHECKSUMS` entries of the builds `tokens` (``, + /// `-`) must be re-pinned from `remote` first. NeedsSha { remote: Option, + tokens: Vec, }, Done(String), } +/// The upstream sha256 of each build of a gem, by its `CHECKSUMS` token +/// (``, `-`). +type UpstreamShas = BTreeMap; + /// One pin's coordinates. struct Gem<'p> { uuid: &'p str, @@ -333,13 +363,15 @@ enum DepEntry { } /// Restore `gem` in the LF lock text (module docs); `dep` says what becomes -/// of its `DEPENDENCIES` entry. +/// of its `DEPENDENCIES` entry, and `shas` holds the upstream sha256 of the +/// builds whose `CHECKSUMS` entries are re-pinned (asked for with +/// [`LockEdit::NeedsSha`]). fn lock_edit( lock: &str, gem: &Gem<'_>, globals: &[String], dep: DepEntry, - sha: Option<&str>, + shas: &UpstreamShas, ctx: &Ctx<'_>, ) -> Result { let lines: Vec<&str> = lock.split('\n').collect(); @@ -348,24 +380,39 @@ fn lock_edit( let mut drop: BTreeSet = BTreeSet::new(); let mut replace: BTreeMap = BTreeMap::new(); let mut insert_after: BTreeMap> = BTreeMap::new(); - let is_ours = |e: &Entry| e.name == gem.name && e.version == gem.version && !e.platform; + // A build of the gem's version: the ruby-platform entry or a platform + // one. + let is_build = |e: &Entry| e.name == gem.name && e.version == gem.version; + let is_ours = |e: &Entry| is_build(e) && !e.platform; let checksum_remote = match &wiring { Some(Wiring::Own(si)) => { let sec = &secs[*si]; - let entry = match sec.entries.as_slice() { - [e] if is_ours(e) => e, - _ => { - return Err(format!( - "its Socket GEM section does not lock exactly {} ({})", - gem.name, gem.version - )) - } - }; + // The section holds the builds of this one gem version and + // nothing else: its ruby-platform entry, the platform entries + // of its prebuilds, or both, each once. + let mut ours: Vec<&Entry> = sec.entries.iter().collect(); + ours.sort_by_key(|e| e.full_name()); + let exact = !ours.is_empty() + && ours.iter().all(|e| is_build(e)) + && ours.windows(2).all(|pair| pair[0].token != pair[1].token); + if !exact { + return Err(format!( + "its Socket GEM section does not lock exactly {} ({})", + gem.name, gem.version + )); + } let up = choose_upstream(&secs, *si, globals, ctx)?; - let at = insertion_point(&secs[up], &format!("{}-{}", gem.name, gem.version)) - .ok_or("the upstream GEM section has no `specs:` list")?; + // Each build back where Bundler sorts it. Builds that land + // after the same upstream line keep their own order. + for entry in ours { + let at = insertion_point(&secs[up], &entry.full_name()) + .ok_or("the upstream GEM section has no `specs:` list")?; + insert_after + .entry(at) + .or_default() + .extend_from_slice(&lines[entry.line..=entry.last]); + } drop.extend(sec.start..sec.end); - insert_after.insert(at, lines[entry.line..=entry.last].to_vec()); Some(secs[up].remotes[0].1.clone()) } Some(Wiring::Merged(si, line)) => { @@ -415,8 +462,20 @@ fn lock_edit( } } if let Some((s, e)) = named_section(&lines, "CHECKSUMS") { - let mut with_sha = Vec::new(); - let mut bare = false; + // A section of the gem's own holds every build the rewriter pinned, + // platform builds included; in any other state only the + // ruby-platform entry was ever the rewriter's. + let own = matches!(wiring, Some(Wiring::Own(_))); + let pinned_build = |token: &str| { + token == gem.version + || (own + && token + .strip_prefix(gem.version.as_str()) + .is_some_and(|platform| platform.starts_with('-'))) + }; + // Per build token: the entries carrying a sha256, and whether a + // bare one sits beside them. + let mut pinned: BTreeMap<&str, (Vec, bool)> = BTreeMap::new(); for (k, line) in lines.iter().enumerate().take(e).skip(s) { let Some(entry) = indented(line, 2) else { continue; @@ -424,33 +483,41 @@ fn lock_edit( let Some((name, token, tail)) = split_checksum_entry(entry.trim_end()) else { continue; }; - if name != gem.name || token != gem.version { + if name != gem.name || !pinned_build(token) { continue; } + let slot = pinned.entry(token).or_default(); if tail.contains("sha256=") { - with_sha.push(k); + slot.0.push(k); } else { - bare = true; + slot.1 = true; } } - match with_sha.as_slice() { - [] => {} - [k] if bare => { - drop.insert(*k); - } - [k] => { - let Some(sha) = sha else { - return Ok(LockEdit::NeedsSha { - remote: checksum_remote, - }); - }; - let re = Regex::new(r"sha256=[0-9A-Fa-f]*").expect("static sha256 regex is valid"); - replace.insert( - *k, - re.replace(lines[*k], format!("sha256={sha}")).into_owned(), - ); + let re = Regex::new(r"sha256=[0-9A-Fa-f]*").expect("static sha256 regex is valid"); + let mut unknown: Vec = Vec::new(); + for (token, (with_sha, bare)) in &pinned { + match with_sha.as_slice() { + [] => {} + [k] if *bare => { + drop.insert(*k); + } + [k] => match shas.get(*token) { + Some(sha) => { + replace.insert( + *k, + re.replace(lines[*k], format!("sha256={sha}")).into_owned(), + ); + } + None => unknown.push(token.to_string()), + }, + _ => return Err("CHECKSUMS pins it more than once".to_string()), } - _ => return Err("CHECKSUMS pins it more than once".to_string()), + } + if !unknown.is_empty() { + return Ok(LockEdit::NeedsSha { + remote: checksum_remote, + tokens: unknown, + }); } } let mut out: Vec = Vec::with_capacity(lines.len()); @@ -909,17 +976,26 @@ pub(crate) async fn restore( let Some((name, version)) = pin.name_version() else { continue; }; - if let Some(warning) = stale_cache_warning( - view.root(), - &pin.purl, - &name, - &version, - lock.as_deref(), - ctx.client, - ) - .await - { - result.warnings.push(warning); + // The ruby gem's archive, then one per platform build the + // restored lock names: `bundle cache` keeps each under its own + // `--.gem`. + let mut builds = vec![version.clone()]; + if let Some(lock) = lock.as_deref() { + builds.extend(platform_builds(lock, &name, &version)); + } + for build in builds { + if let Some(warning) = stale_cache_warning( + view.root(), + &pin.purl, + &name, + &build, + lock.as_deref(), + ctx.client, + ) + .await + { + result.warnings.push(warning); + } } } if let (Some(next), Some(endings)) = (lock, endings) { @@ -947,14 +1023,28 @@ pub(crate) const STALE_CACHE: &str = "upstream_gem_stale_cache"; /// declaration it replaced (module docs, "The block form"). pub(crate) const DECLARATION_PINNED: &str = "upstream_gem_declaration_pinned"; -/// The `CHECKSUMS` sha256 the lock pins for `name (version)`, if any. -fn lock_checksum(lock: &str, name: &str, version: &str) -> Option { +/// The tokens (`-`) of the platform builds of `name` +/// `version` the `GEM` sections of `lock` list, in lock order. +fn platform_builds(lock: &str, name: &str, version: &str) -> Vec { + let lines: Vec<&str> = lock.split('\n').collect(); + gem_sections(&lines) + .iter() + .flat_map(|sec| &sec.entries) + .filter(|e| e.name == name && e.version == version && e.token != version) + .map(|e| e.token.clone()) + .collect() +} + +/// The `CHECKSUMS` sha256 the lock pins for the build `name (token)`, if +/// any: `token` is ``, or `-` for a platform +/// build. +fn lock_checksum(lock: &str, name: &str, token: &str) -> Option { let lines: Vec<&str> = lock.split('\n').collect(); let (s, e) = named_section(&lines, "CHECKSUMS")?; lines[s..e].iter().find_map(|line| { let entry = indented(line, 2)?.trim_end(); - let (n, token, tail) = split_checksum_entry(entry)?; - if n != name || token != version { + let (n, entry_token, tail) = split_checksum_entry(entry)?; + if n != name || entry_token != token { return None; } tail.split_whitespace() @@ -963,7 +1053,8 @@ fn lock_checksum(lock: &str, name: &str, version: &str) -> Option { }) } -/// A restored gem whose `-.gem` still sits in Bundler's +/// A restored gem whose `-.gem` (`token`: ``, or +/// `-` for a platform build) still sits in Bundler's /// cache dir (`cache_path`, default `vendor/cache`) and is not proven to /// be the upstream archive: bundler installs from that dir before /// fetching, so the archive a `bundle cache` took while the hosted pin was @@ -977,19 +1068,19 @@ async fn stale_cache_warning( root: &std::path::Path, purl: &str, name: &str, - version: &str, + token: &str, lock: Option<&str>, client: &UpstreamClient, ) -> Option<(&'static str, String)> { let cache_dir = crate::crawlers::ruby_crawler::bundler_app_cache_dir(root).await; - let archive = cache_dir.join(format!("{name}-{version}.gem")); + let archive = cache_dir.join(format!("{name}-{token}.gem")); if !archive.is_file() { return None; } let got = crate::vendor::file_sha256_hex(&archive).await; - let upstream = match lock.and_then(|l| lock_checksum(l, name, version)) { + let upstream = match lock.and_then(|l| lock_checksum(l, name, token)) { Some(sha) => Ok(sha), - None => client.rubygems_sha256(name, version).await, + None => client.rubygems_sha256(name, token).await, }; let fix = "delete it, then run `bundle cache` to cache the upstream gem in its place \ (or `bundle install` if the project does not commit its cache)"; @@ -1065,10 +1156,11 @@ pub enum UpstreamArchive { Unverified(String), } -/// The upstream archive of the ruby-platform gem `purl`, as the lock at -/// `root` pins it once the gem is back on its registry entry: its sha256 -/// (the `CHECKSUMS` entry, else the rubygems.org compact index, unless -/// `offline`) and, when the lock resolves the gem from rubygems.org, the +/// The upstream archive of one build of the gem `purl` (the ruby-platform +/// gem, or the precompiled build for `platform`), as the lock at `root` +/// pins it once the gem is back on its registry entry: its sha256 (the +/// `CHECKSUMS` entry, else the rubygems.org compact index, unless +/// `offline`) and, when the lock resolves that build from rubygems.org, the /// URL it is served at. `restored` is the lock's text when the caller holds /// it (a restore's staged text; a dry run never wrote it), else the lock is /// read from disk. `None` when nothing proves the sha256: a gem from @@ -1079,9 +1171,16 @@ pub(super) async fn upstream_archive( root: &std::path::Path, restored: Option<&str>, purl: &str, + platform: Option<&str>, offline: bool, ) -> Option { let (_, name, version) = crate::utils::purl::purl_parts(purl)?; + // The build as the lock, the compact index and the gem's file name + // spell it. + let version = match platform { + Some(platform) => format!("{version}-{platform}"), + None => version, + }; let mut lock = restored.map(str::to_string); if lock.is_none() { for file in BUNDLER_LOCKS { @@ -1122,6 +1221,36 @@ pub(super) async fn upstream_archive( }) } +/// The platforms of the builds [`platform_builds`] finds for the gem +/// `purl` in the lock at `root`: `restored` when the caller holds its text, +/// else the lock on disk. Empty with no readable lock. +pub(super) async fn locked_platforms( + root: &std::path::Path, + restored: Option<&str>, + purl: &str, +) -> Vec { + let Some((_, name, version)) = crate::utils::purl::purl_parts(purl) else { + return Vec::new(); + }; + let mut lock = restored.map(str::to_string); + if lock.is_none() { + for file in BUNDLER_LOCKS { + if let Ok(text) = crate::utils::fs::read_regular_to_string(&root.join(file)).await { + lock = Some(text); + break; + } + } + } + let Some(lock) = lock else { + return Vec::new(); + }; + platform_builds(&to_lf(&lock), &name, &version) + .iter() + .filter_map(|token| token.strip_prefix(version.as_str())?.strip_prefix('-')) + .map(str::to_string) + .collect() +} + /// Whether the lock at `root` resolves the ruby-platform gem `purl` from /// rubygems.org ([`rubygems_locked`]). `false` with no readable lock. pub(super) async fn resolves_from_rubygems(root: &std::path::Path, purl: &str) -> bool { @@ -1136,14 +1265,16 @@ pub(super) async fn resolves_from_rubygems(root: &std::path::Path, purl: &str) - false } -/// Whether `lock` resolves `name (version)` from a `GEM` section whose -/// remote is rubygems.org (or the `SOCKET_RUBYGEMS_URL` stand-in). -fn rubygems_locked(lock: &str, name: &str, version: &str) -> bool { +/// Whether `lock` resolves the build `name (token)` (`token`: `` +/// for the ruby-platform gem, `-` for a platform build) +/// from a `GEM` section whose remote is rubygems.org (or the +/// `SOCKET_RUBYGEMS_URL` stand-in). +fn rubygems_locked(lock: &str, name: &str, token: &str) -> bool { let lines: Vec<&str> = lock.split('\n').collect(); gem_sections(&lines).iter().any(|sec| { sec.entries .iter() - .any(|e| e.name == name && e.version == version && !e.platform) + .any(|e| e.name == name && e.token == token) && sec .remotes .iter() @@ -1245,27 +1376,34 @@ async fn restore_one( }; let next_lock = match lock { None => None, - Some(text) => Some(match lock_edit(text, gem, globals, dep, None, ctx)? { - LockEdit::Done(next) => next, - LockEdit::NeedsSha { remote } => { - let remote = remote.ok_or("its upstream GEM remote is ambiguous")?; - if !same_remote(&remote, RUBYGEMS_REMOTE) { - return Err(format!( - "its upstream GEM remote {remote} is not rubygems.org, so its CHECKSUMS \ - sha256 cannot be re-derived" - )); - } - let sha = ctx - .client - .rubygems_sha256(&gem.name, &gem.version) - .await - .map_err(|why| format!("{} {}: {why}", gem.name, gem.version))?; - match lock_edit(text, gem, globals, dep, Some(&sha), ctx)? { - LockEdit::Done(next) => next, - LockEdit::NeedsSha { .. } => unreachable!("a sha was supplied"), + Some(text) => Some( + match lock_edit(text, gem, globals, dep, &UpstreamShas::new(), ctx)? { + LockEdit::Done(next) => next, + LockEdit::NeedsSha { remote, tokens } => { + let remote = remote.ok_or("its upstream GEM remote is ambiguous")?; + if !same_remote(&remote, RUBYGEMS_REMOTE) { + return Err(format!( + "its upstream GEM remote {remote} is not rubygems.org, so its CHECKSUMS \ + sha256 cannot be re-derived" + )); + } + // One `info/` document lists every build. + let mut shas = UpstreamShas::new(); + for token in tokens { + let sha = ctx + .client + .rubygems_sha256(&gem.name, &token) + .await + .map_err(|why| format!("{} {token}: {why}", gem.name))?; + shas.insert(token, sha); + } + match lock_edit(text, gem, globals, dep, &shas, ctx)? { + LockEdit::Done(next) => next, + LockEdit::NeedsSha { .. } => unreachable!("every sha was supplied"), + } } - } - }), + }, + ), }; let next_manifest = match (manifest, &wiring_in_manifest) { (Some(text), Some(wiring)) => Some(unwire_manifest(text, wiring, gem, &decl)), @@ -1373,11 +1511,31 @@ mod tests { ruby\n\nDEPENDENCIES\n puma\n rails (= 7.0.0)\n\nBUNDLED WITH\n 2.4.0\n"; // No CHECKSUMS (bundler 2.2–2.5): no registry lookup, offline works. assert_eq!( - done(lock_edit(&hosted, &gem(), &[], DepEntry::Unpin, None, &ctx).unwrap()), + done( + lock_edit( + &hosted, + &gem(), + &[], + DepEntry::Unpin, + &UpstreamShas::new(), + &ctx + ) + .unwrap() + ), want ); // Transitive: the DEPENDENCIES entry the rewriter added goes. - let out = done(lock_edit(&hosted, &gem(), &[], DepEntry::Drop, None, &ctx).unwrap()); + let out = done( + lock_edit( + &hosted, + &gem(), + &[], + DepEntry::Drop, + &UpstreamShas::new(), + &ctx, + ) + .unwrap(), + ); assert!(out.contains("DEPENDENCIES\n puma\n\n"), "{out}"); } @@ -1391,15 +1549,26 @@ mod tests { sha256={}\n", "d".repeat(64) ); - match lock_edit(&hosted, &gem(), &[], DepEntry::Unpin, None, &ctx).unwrap() { - LockEdit::NeedsSha { remote } => { - assert_eq!(remote.as_deref(), Some("https://rubygems.org/")) + match lock_edit( + &hosted, + &gem(), + &[], + DepEntry::Unpin, + &UpstreamShas::new(), + &ctx, + ) + .unwrap() + { + LockEdit::NeedsSha { remote, tokens } => { + assert_eq!(remote.as_deref(), Some("https://rubygems.org/")); + assert_eq!(tokens, ["7.0.0"]); } LockEdit::Done(_) => panic!("CHECKSUMS entry left patched"), } let sha = "2".repeat(64); + let shas = UpstreamShas::from([("7.0.0".to_string(), sha.clone())]); assert_eq!( - done(lock_edit(&hosted, &gem(), &[], DepEntry::Unpin, Some(&sha), &ctx).unwrap()), + done(lock_edit(&hosted, &gem(), &[], DepEntry::Unpin, &shas, &ctx).unwrap()), format!( "GEM\n remote: https://rubygems.org/\n specs:\n rails (7.0.0)\n\nDEPENDENCIES\n \ rails (= 7.0.0)\n\nCHECKSUMS\n rails (7.0.0) sha256={sha}\n" @@ -1407,12 +1576,172 @@ mod tests { ); // The rewriter's ADDED entry next to bundler's bare one is dropped. let added = hosted.replace("CHECKSUMS\n", "CHECKSUMS\n rails (7.0.0)\n"); - assert!( - done(lock_edit(&added, &gem(), &[], DepEntry::Unpin, None, &ctx).unwrap()) - .ends_with("CHECKSUMS\n rails (7.0.0)\n") + assert!(done( + lock_edit( + &added, + &gem(), + &[], + DepEntry::Unpin, + &UpstreamShas::new(), + &ctx + ) + .unwrap() + ) + .ends_with("CHECKSUMS\n rails (7.0.0)\n")); + } + + fn nokogiri() -> Gem<'static> { + Gem { + uuid: UUID, + name: "nokogiri".into(), + version: "1.18.10".into(), + } + } + + /// A gem locked as platform builds: every entry of the Socket section + /// goes back where Bundler sorts it (by full name, so before + /// `nokogiri-happymapper`), each with its sub-lines, and every + /// `CHECKSUMS` entry is re-pinned to its own build's upstream sha256. + #[test] + fn platform_builds_move_back_and_each_checksum_is_repinned() { + let client = super::super::UpstreamClient::new(true); + let ctx = ctx_with(&client); + let (arm, linux, other) = ("a".repeat(64), "b".repeat(64), "c".repeat(64)); + let lock = |socket: bool, arm: &str, linux: &str| { + let builds = " nokogiri (1.18.10-arm64-darwin)\n racc (~> 1.4)\n nokogiri \ + (1.18.10-x86_64-linux-gnu)\n racc (~> 1.4)\n"; + let (own, upstream, pin) = if socket { + ( + format!("GEM\n remote: {IDX}\n specs:\n{builds}\n"), + "", + "!", + ) + } else { + (String::new(), builds, "") + }; + format!( + "{own}GEM\n remote: https://rubygems.org/\n specs:\n mini_mime (1.1.5)\n{upstream} \ + nokogiri-happymapper (0.10.0)\n racc (1.8.1)\n\nPLATFORMS\n arm64-darwin\n \ + x86_64-linux-gnu\n\nDEPENDENCIES\n nokogiri (= 1.18.10){pin}\n\nCHECKSUMS\n mini_mime \ + (1.1.5) sha256={other}\n nokogiri (1.18.10-arm64-darwin) sha256={arm}\n nokogiri \ + (1.18.10-x86_64-linux-gnu) sha256={linux}\n racc (1.8.1) sha256={other}\n\nBUNDLED \ + WITH\n 4.0.15\n" + ) + }; + let hosted = lock(true, &"d".repeat(64), &"e".repeat(64)); + match lock_edit( + &hosted, + &nokogiri(), + &[], + DepEntry::Unpin, + &UpstreamShas::new(), + &ctx, + ) + .unwrap() + { + LockEdit::NeedsSha { remote, tokens } => { + assert_eq!(remote.as_deref(), Some("https://rubygems.org/")); + assert_eq!(tokens, ["1.18.10-arm64-darwin", "1.18.10-x86_64-linux-gnu"]); + } + LockEdit::Done(_) => panic!("CHECKSUMS entries left patched"), + } + // One sha is not enough: the other build is still asked for. + let mut shas = UpstreamShas::from([("1.18.10-arm64-darwin".to_string(), arm.clone())]); + match lock_edit(&hosted, &nokogiri(), &[], DepEntry::Unpin, &shas, &ctx).unwrap() { + LockEdit::NeedsSha { tokens, .. } => { + assert_eq!(tokens, ["1.18.10-x86_64-linux-gnu"]) + } + LockEdit::Done(_) => panic!("a CHECKSUMS entry left patched"), + } + shas.insert("1.18.10-x86_64-linux-gnu".to_string(), linux.clone()); + assert_eq!( + done(lock_edit(&hosted, &nokogiri(), &[], DepEntry::Unpin, &shas, &ctx).unwrap()), + lock(false, &arm, &linux) ); } + /// The ruby-platform entry beside the platform builds goes back with + /// them, first (Bundler's order). A lock without `CHECKSUMS` needs no + /// lookup, and a `CHECKSUMS` entry the rewriter added next to + /// bundler's own bare one is dropped, per build. + #[test] + fn ruby_entry_beside_platform_builds_moves_back_first() { + let client = super::super::UpstreamClient::new(true); + let ctx = ctx_with(&client); + let hosted = format!( + "GEM\n remote: {IDX}\n specs:\n nokogiri (1.18.10)\n mini_portile2 (~> 2.8.2)\n \ + nokogiri (1.18.10-java)\n\nGEM\n remote: https://rubygems.org/\n specs:\n \ + mini_portile2 (2.8.9)\n zeitwerk (2.6.0)\n\nDEPENDENCIES\n nokogiri!\n" + ); + let want = "GEM\n remote: https://rubygems.org/\n specs:\n mini_portile2 (2.8.9)\n \ + nokogiri (1.18.10)\n mini_portile2 (~> 2.8.2)\n nokogiri (1.18.10-java)\n \ + zeitwerk (2.6.0)\n\nDEPENDENCIES\n nokogiri\n"; + assert_eq!( + done( + lock_edit( + &hosted, + &nokogiri(), + &[], + DepEntry::Unpin, + &UpstreamShas::new(), + &ctx + ) + .unwrap() + ), + want + ); + let sha = "d".repeat(64); + let added = format!( + "{hosted}\nCHECKSUMS\n nokogiri (1.18.10)\n nokogiri (1.18.10) sha256={sha}\n nokogiri \ + (1.18.10-java)\n nokogiri (1.18.10-java) sha256={sha}\n" + ); + assert_eq!( + done( + lock_edit( + &added, + &nokogiri(), + &[], + DepEntry::Unpin, + &UpstreamShas::new(), + &ctx + ) + .unwrap() + ), + format!("{want}\nCHECKSUMS\n nokogiri (1.18.10)\n nokogiri (1.18.10-java)\n") + ); + } + + /// A Socket section is one gem version's builds. Another version's + /// build in it, or the same build twice, is not ours to split. + #[test] + fn socket_section_with_foreign_builds_is_refused() { + let client = super::super::UpstreamClient::new(true); + let ctx = ctx_with(&client); + for specs in [ + " nokogiri (1.18.10-java)\n nokogiri (1.18.9-java)\n", + " nokogiri (1.18.10-java)\n nokogiri (1.18.10-java)\n", + ] { + let lock = format!( + "GEM\n remote: https://rubygems.org/\n specs:\n\nGEM\n remote: {IDX}\n \ + specs:\n{specs}\nDEPENDENCIES\n nokogiri!\n" + ); + let why = lock_edit( + &lock, + &nokogiri(), + &[], + DepEntry::Unpin, + &UpstreamShas::new(), + &ctx, + ) + .err() + .expect("refused"); + assert!( + why.contains("does not lock exactly nokogiri (1.18.10)"), + "{why}" + ); + } + } + #[test] fn merged_section_drops_only_the_socket_remote() { let client = super::super::UpstreamClient::new(true); @@ -1422,7 +1751,7 @@ mod tests { rails (7.0.0)\n\nDEPENDENCIES\n puma\n rails (= 7.0.0)!\n\nBUNDLED WITH\n 2.1.4\n" ); assert_eq!( - done(lock_edit(&hosted, &gem(), &[], DepEntry::Unpin, None, &ctx).unwrap()), + done(lock_edit(&hosted, &gem(), &[], DepEntry::Unpin, &UpstreamShas::new(), &ctx).unwrap()), "GEM\n remote: https://rubygems.org/\n specs:\n puma (6.0.0)\n rails (7.0.0)\n\n\ DEPENDENCIES\n puma\n rails (= 7.0.0)\n\nBUNDLED WITH\n 2.1.4\n" ); @@ -1436,7 +1765,15 @@ mod tests { "GEM\n remote: https://gems.example/\n specs:\n\nGEM\n remote: https://mirror.example/\n \ specs:\n\nGEM\n remote: {IDX}\n specs:\n rails (7.0.0)\n\nDEPENDENCIES\n rails (= 7.0.0)!\n" ); - assert!(lock_edit(&two_upstreams, &gem(), &[], DepEntry::Unpin, None, &ctx).is_err()); + assert!(lock_edit( + &two_upstreams, + &gem(), + &[], + DepEntry::Unpin, + &UpstreamShas::new(), + &ctx + ) + .is_err()); // The manifest's global source singles one out. let globals = vec!["https://mirror.example".to_string()]; let out = done( @@ -1445,7 +1782,7 @@ mod tests { &gem(), &globals, DepEntry::Unpin, - None, + &UpstreamShas::new(), &ctx, ) .unwrap(), @@ -1459,11 +1796,27 @@ mod tests { "GEM\n remote: https://rubygems.org/\n specs:\n\nGEM\n remote: {IDX}\n specs:\n \ rack (3.0.0)\n rails (7.0.0)\n\nDEPENDENCIES\n rails (= 7.0.0)!\n" ); - assert!(lock_edit(&extra, &gem(), &[], DepEntry::Unpin, None, &ctx).is_err()); + assert!(lock_edit( + &extra, + &gem(), + &[], + DepEntry::Unpin, + &UpstreamShas::new(), + &ctx + ) + .is_err()); let none = format!( "GEM\n remote: {IDX}\n specs:\n rails (7.0.0)\n\nDEPENDENCIES\n rails!\n" ); - assert!(lock_edit(&none, &gem(), &[], DepEntry::Unpin, None, &ctx).is_err()); + assert!(lock_edit( + &none, + &gem(), + &[], + DepEntry::Unpin, + &UpstreamShas::new(), + &ctx + ) + .is_err()); } #[test] diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs index fb0054d4a..cadbc9f02 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs @@ -949,7 +949,10 @@ pub async fn gem_stale_cache_after_unwind( /// The upstream `.gem` of a gem `purl` that is back on its registry entry /// in the project at `root`: its sha256 and download url -/// ([`UpstreamArchive::Known`]). The sha256 is what the restored lock pins +/// ([`UpstreamArchive::Known`]). `platform` names the build: `None` for the +/// ruby-platform gem, else the platform of a precompiled build the lock +/// names (`--.gem`), which has a sha256 and a url +/// of its own. The sha256 is what the restored lock pins /// (its `CHECKSUMS` entry, else the rubygems.org compact index, unless /// `offline`); the url is set when the lock resolves the gem from /// rubygems.org. `staged` is a restore's [`RestoreOutcome::staged_text`]: @@ -962,12 +965,29 @@ pub async fn gem_upstream_archive( root: &Path, staged: &BTreeMap>, purl: &str, + platform: Option<&str>, offline: bool, ) -> Option { let restored = crate::formats::gem::BUNDLER_LOCKS .iter() .find_map(|lock| staged.get(*lock)?.as_deref()); - gem::upstream_archive(root, restored, purl, offline).await + gem::upstream_archive(root, restored, purl, platform, offline).await +} + +/// The platforms of the precompiled builds the lock at `root` names for +/// the gem `purl` (`arm64-darwin` for `name (version-arm64-darwin)`), in +/// lock order: empty for a gem locked as its ruby-platform gem alone. +/// `staged` is a restore's [`RestoreOutcome::staged_text`], read as +/// [`gem_upstream_archive`] reads it. +pub async fn gem_locked_platforms( + root: &Path, + staged: &BTreeMap>, + purl: &str, +) -> Vec { + let restored = crate::formats::gem::BUNDLER_LOCKS + .iter() + .find_map(|lock| staged.get(*lock)?.as_deref()); + gem::locked_platforms(root, restored, purl).await } /// Whether the lock on disk at `root` resolves the ruby-platform gem `purl` diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs b/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs index 8591d9907..6cab0cf12 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs @@ -58,6 +58,22 @@ pub(super) async fn inventory_gemfile_lock_raw_in( GemfileLock::parse(&text).entries() } +/// The gems the Bundler lock bundler loads resolves only as precompiled +/// platform builds ([`GemfileLock::platform_only_purls`]), which +/// [`inventory_gemfile_lock`] leaves out. Hosted mode's lockfile discovery +/// adds them: it redirects such a gem to its per-platform prebuilds, so a +/// lock that has no installed copy beside it (a fresh checkout, the +/// in-memory engine) must still name it. +pub async fn gem_platform_only_purls_in(view: &ProjectView<'_>) -> Vec { + let Some(lock) = bundler_loaded_lock_in(view).await else { + return Vec::new(); + }; + match view.read_text(lock).await { + Ok(text) => GemfileLock::parse(&text).platform_only_purls(), + Err(_) => Vec::new(), + } +} + /// Why the project's Bundler lock was not inventoried, when it holds gem /// files ([`GEM_FILES`]) but bundler loads no lock socket-patch reads /// ([`bundler_loaded_lock_diagnosed_in`]): an unsupported `BUNDLE_GEMFILE` diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs b/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs index e9d3c590d..1ea33e257 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs @@ -76,6 +76,7 @@ pub(crate) mod vlt; pub(crate) mod yarn; pub use self::bun::{bun_binary_lock_drives, bun_text_lock_drives}; +pub use self::gem::gem_platform_only_purls_in; pub(crate) use self::npm::{ npm_lock_bundled_nodes, npm_lock_entries, npm_lock_legacy_mirror_nodes, npm_lock_located_nodes, NpmLockEntry, NpmLockNode, NpmLockSection, diff --git a/crates/socket-patch-core/src/vex/discover/gem.rs b/crates/socket-patch-core/src/vex/discover/gem.rs index 6f1888c4e..3237dee1c 100644 --- a/crates/socket-patch-core/src/vex/discover/gem.rs +++ b/crates/socket-patch-core/src/vex/discover/gem.rs @@ -83,15 +83,36 @@ //! * several `remote:` lines in the section (a merged multi-source section) //! UNLESS the gem is source-pinned to the Socket remote — see "Merged //! sections" below; -//! * a platform-suffixed spec (`nokogiri (1.16.0-x86_64-linux)`): the patch -//! registry serves only the ruby-platform gem, and the rewriter refuses -//! deps with platform variants; //! * the same gem name locked in ANOTHER source section as well (the //! rewriter MOVES the spec; a duplicate is a hand-edit bundler would //! resolve ambiguously). //! +//! **Platform builds.** A gem bundler locks as precompiled platform gems +//! has one spec per platform, and the rewriter moves all of them (the +//! patch registry serves a patched build, a "prebuild", for each): +//! +//! ```text +//! GEM +//! remote: https://patch.socket.dev/patch-registry/gem/// +//! specs: +//! nokogiri (1.18.10-arm64-darwin) +//! racc (~> 1.4) +//! nokogiri (1.18.10-x86_64-linux-gnu) +//! racc (~> 1.4) +//! ``` +//! +//! The specs of one gem version under a Socket section of its own are ONE +//! hosted pin of `pkg:gem/@`, with or without the +//! ruby-platform `name (version)` beside them: one ref, as for a +//! ruby-platform gem. A platform spec anywhere else Socket wiring reaches +//! (a merged section, a vendored `PATH` section) is still +//! [`DIAG_REF_INVALID`]: no writer puts one there. +//! //! **Integrity.** `CHECKSUMS` ` name (version) sha256=` becomes //! [`Sha256Hex`](crate::vendor::lock_inventory::LockIntegrity::Sha256Hex). +//! A pin of several builds is pinned only when `CHECKSUMS` has a sha256 for +//! every one of them (each `name (version-)` entry holds its own +//! prebuild's); the ref then carries the first build's. //! `integrity_required` is true iff the lock HAS a `CHECKSUMS` section: in //! that era (bundler ≥ 2.6) the rewriter only converges the lock after //! writing the patched gem's sha256, so a pin-less @@ -173,8 +194,8 @@ use super::{ }; use crate::crawlers::ruby_crawler::bundler_loaded_lock_in; use crate::formats::gem::{ - bundler_manifest_for, declarations, gemfile, same_remote, GemfileLock, Section, SpecLine, - BUNDLER_LOCKS, + bundler_manifest_for, declarations, gemfile, same_remote, split_entry, GemfileLock, Section, + Spec, SpecLine, BUNDLER_LOCKS, }; use crate::patch::path_safety::is_canonical_uuid; use crate::vendor::gem::{gem_declaration_any, quoted_literal}; @@ -688,6 +709,11 @@ fn section_refs( _ => None, }; let mut matched = false; + // The gem versions a hosted section of its own already yielded: a gem + // locked as platform builds has one spec per platform, and they are one + // pin (module docs, "Platform builds"). + let own_hosted = matches!(wiring, Wiring::Hosted { only: None, .. }); + let mut pinned: BTreeSet<(&str, &str)> = BTreeSet::new(); for line in &sec.specs { // Merged section: only the gems source-pinned to the Socket remote // are its; the rest came from the other remotes. @@ -695,7 +721,12 @@ fn section_refs( continue; } matched = true; - spec_ref(file, lock, owners, line, wiring, manifest, out); + if let Some(spec) = line.parsed.filter(|_| own_hosted) { + if !pinned.insert((spec.name, spec.version)) { + continue; + } + } + spec_ref(file, lock, owners, sec, line, wiring, manifest, out); } if let Some(only) = only.filter(|_| !matched) { out.diag( @@ -851,11 +882,39 @@ fn vendored_wiring<'t>(file: &str, sec: &Section<'t>, out: &mut Discovery) -> Op } } -/// Validate one spec under a Socket-wired section and push its ref. +/// The content pin the lock records for the hosted gem version `spec` +/// names in `sec`: the `CHECKSUMS` sha256 of its one build, or, for a gem +/// locked as several builds (module docs, "Platform builds"), of the first +/// one when every build has one. `None` when any build is unpinned: bundler +/// installs whichever build matches the machine, so one bare entry leaves +/// the bytes of that platform open. +fn hosted_integrity( + lock: &GemfileLock<'_>, + sec: &Section<'_>, + spec: Spec<'_>, +) -> Option { + let mut pins = sec + .specs + .iter() + .filter(|line| { + line.parsed + .is_some_and(|s| s.name == spec.name && s.version == spec.version) + }) + .map(|line| { + let (name, token, _) = split_entry(line.raw)?; + lock.integrity(name, token) + }); + let first = pins.next()??; + pins.all(|pin| pin.is_some()).then_some(first) +} + +/// Validate one spec under a Socket-wired section `sec` and push its ref. +#[allow(clippy::too_many_arguments)] fn spec_ref( file: &str, lock: &GemfileLock<'_>, owners: &HashMap<&str, BTreeSet>, + sec: &Section<'_>, line: &SpecLine<'_>, wiring: &Wiring<'_>, manifest: &ManifestSources, @@ -874,13 +933,16 @@ fn spec_ref( ); return; }; - if let Some(platform) = spec.platform { + // A platform build is hosted wiring only in a Socket section of the + // gem's own, where the rewriter moves every build of the version. + let own_hosted = matches!(wiring, Wiring::Hosted { only: None, .. }); + if let Some(platform) = spec.platform.filter(|_| !own_hosted) { out.diag( DIAG_REF_INVALID, file, format!( - "{at}: {} {} is locked for platform {platform:?}; Socket patches wire only the \ - ruby-platform gem", + "{at}: {} {} is locked for platform {platform:?}; Socket patches wire a \ + platform build only through a patch-registry GEM section of its own", spec.name, spec.version ), ); @@ -918,7 +980,11 @@ fn spec_ref( uuid.clone(), file, Some(*remote), - lock.integrity(spec.name, spec.version), + if own_hosted { + hosted_integrity(lock, sec, spec) + } else { + lock.integrity(spec.name, spec.version) + }, lock.has_checksums(), ); if manifest_confirms(file, &at, coords, wiring, manifest, out) { @@ -1593,7 +1659,7 @@ mod tests { #[tokio::test] async fn invalid_socket_specs_are_diagnosed() { let lock = format!( - "GEM\n remote: {}\n specs:\n nokogiri (1.16.0-x86_64-linux)\n \ + "GEM\n remote: {}\n specs:\n \ bad name (1.0.0)\n ../x (1.0.0)\n .. (1.0.0)\n weird (abc)\n\n\ PATH\n remote: {}\n specs:\n rack (3.2.6)\n\n\ PATH\n remote: ../.socket/vendor/gem/{UUID_B}/puma-6.4.2\n specs:\n puma (6.4.2)\n\n\ @@ -1610,7 +1676,7 @@ mod tests { assert!(out.refs.is_empty(), "{:#?}", out.refs); assert_eq!( diag_codes(&out), - vec![DIAG_REF_INVALID; 10], + vec![DIAG_REF_INVALID; 9], "{:#?}", out.diagnostics ); @@ -1620,6 +1686,108 @@ mod tests { .all(|d| d.detail.starts_with("Gemfile.lock"))); } + /// A lock whose Socket section holds the platform builds of nokogiri + /// (and the ruby-platform entry when `ruby`), `checksums` under + /// `CHECKSUMS` when given. + fn platform_builds_lock(ruby: bool, checksums: Option<&str>) -> String { + let ruby = if ruby { + " nokogiri (1.18.10)\n racc (~> 1.4)\n" + } else { + "" + }; + let checksums = checksums + .map(|entries| format!("\nCHECKSUMS\n{entries} racc (1.8.1) sha256={SHA_UP}\n")) + .unwrap_or_default(); + format!( + "GEM\n remote: {}\n specs:\n{ruby} nokogiri (1.18.10-arm64-darwin)\n racc (~> \ + 1.4)\n nokogiri (1.18.10-x86_64-linux-gnu)\n racc (~> 1.4)\n\nGEM\n remote: \ + https://rubygems.org/\n specs:\n racc (1.8.1)\n\nPLATFORMS\n arm64-darwin\n \ + x86_64-linux-gnu\n\nDEPENDENCIES\n nokogiri (= 1.18.10)!\n{checksums}\nBUNDLED WITH\n \ + 4.0.15\n", + index(UUID_A) + ) + } + + /// The hosted rewriter moves every platform build of a precompiled gem + /// into the patch registry's section. They are ONE hosted pin of the + /// gem version — one ref, no diagnostic — or the engine would drop the + /// rewrite as unattributable. The pin is content-pinned only when + /// `CHECKSUMS` has a sha256 for every build. + #[tokio::test] + async fn hosted_platform_builds_are_one_pin() { + const SHA_B: &str = "feedfacefeedfacefeedfacefeedfacefeedfacefeedfacefeedfacefeedface"; + let arm = format!(" nokogiri (1.18.10-arm64-darwin) sha256={SHA_A}\n"); + let linux = format!(" nokogiri (1.18.10-x86_64-linux-gnu) sha256={SHA_B}\n"); + let plain = format!(" nokogiri (1.18.10) sha256={SHA_B}\n"); + // (ruby entry beside the builds, CHECKSUMS entries, the pin, required) + let cases: [(bool, Option, Option<&str>, bool); 5] = [ + (false, Some(format!("{arm}{linux}")), Some(SHA_A), true), + ( + true, + Some(format!("{plain}{arm}{linux}")), + Some(SHA_B), + true, + ), + // One build bare: the bytes of that platform are open. + ( + false, + Some(format!("{arm} nokogiri (1.18.10-x86_64-linux-gnu)\n")), + None, + true, + ), + (false, Some(arm.clone()), None, true), + // Bundler < 2.6: no CHECKSUMS section, nothing to require. + (false, None, None, false), + ]; + for (ruby, checksums, pin, required) in cases { + let p = Project::new(); + p.write( + "Gemfile.lock", + platform_builds_lock(ruby, checksums.as_deref()), + ); + p.write("Gemfile", manifest(&[hosted_decl("nokogiri", UUID_A)])); + let out = run(&p).await; + assert_refs( + &out, + &[("pkg:gem/nokogiri@1.18.10", UUID_A, WiringMode::Hosted)], + ); + assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); + let r = only(&out); + assert_eq!( + r.locked_integrity, + pin.map(|sha| LockIntegrity::Sha256Hex(sha.to_string())), + "{checksums:?}" + ); + assert_eq!(r.integrity_required, required); + assert_eq!(r.lockfile_basis_ok(), pin.is_some() || !required); + assert_eq!( + out.hosted_claim("pkg:gem/nokogiri@1.18.10", UUID_A), + Some(true) + ); + } + } + + /// A platform build is hosted wiring only in a Socket section of the + /// gem's own. In a merged section (bundler <= 2.1), where the rewriter + /// refuses platform builds, it is still diagnosed and never attested. + #[tokio::test] + async fn platform_build_in_a_merged_section_is_diagnosed() { + let p = Project::new(); + p.write( + "Gemfile.lock", + merged_lock(&index(UUID_A), "!").replace("vuln-gem (1.0.0)", "vuln-gem (1.0.0-java)"), + ); + p.write("Gemfile", block_gemfile(&index(UUID_A))); + let out = run(&p).await; + assert!(out.refs.is_empty(), "{:#?}", out.refs); + assert_eq!(diag_codes(&out), vec![DIAG_REF_INVALID]); + assert!( + out.diagnostics[0].detail.contains("platform \"java\""), + "{:?}", + out.diagnostics + ); + } + /// Ambiguous attributions: a legacy multi-remote GEM section, a patched /// gem ALSO locked by the upstream section, and a Socket section with no /// specs. 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-prebuild-missing/expected-edits.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-edits.json @@ -0,0 +1 @@ +[] 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 new file mode 100644 index 000000000..57ef0136a --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-warnings.json @@ -0,0 +1 @@ +["redirect_gem_platform_unsupported"] 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-prebuild-missing/input/Gemfile new file mode 100644 index 000000000..bbbe99128 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/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-prebuild-missing/input/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/input/Gemfile.lock new file mode 100644 index 000000000..7064b964b --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/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-prebuild-missing/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/overrides.json new file mode 100644 index 000000000..293fadc61 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/overrides.json @@ -0,0 +1,28 @@ +[ + { + "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/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", + "gemPlatforms": [ + { + "platform": "arm64-darwin", + "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } + ] + } + }, + "integrity": { + "sha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/expected-edits.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/expected-edits.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/expected-warnings.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/expected-warnings.json @@ -0,0 +1 @@ +[] 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 new file mode 100644 index 000000000..9c7fb0765 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/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/" +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 new file mode 100644 index 000000000..8f9165e97 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/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/ + 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=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + 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-prebuilds-rerun/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/overrides.json new file mode 100644 index 000000000..1d3992b06 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/overrides.json @@ -0,0 +1,32 @@ +[ + { + "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/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", + "gemPlatforms": [ + { + "platform": "arm64-darwin", + "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + { + "platform": "x86_64-linux-gnu", + "gemChecksumSha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + } + ] + } + }, + "integrity": { + "sha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + } + } +] 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 new file mode 100644 index 000000000..db5635906 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-edits.json @@ -0,0 +1,42 @@ +[ + { + "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/\"" + }, + { + "path": "Gemfile.lock", + "kind": "redirect_gemfile_lock_checksum", + "action": "rewritten", + "key": "nokogiri", + "original": "nokogiri (1.18.10-arm64-darwin) sha256=3333333333333333333333333333333333333333333333333333333333333333", + "new": "nokogiri (1.18.10-arm64-darwin) sha256=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + { + "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/" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-warnings.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-warnings.json @@ -0,0 +1 @@ +[] 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 new file mode 100644 index 000000000..9c7fb0765 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/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/" +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 new file mode 100644 index 000000000..8f9165e97 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/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/ + 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=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + 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-prebuilds/input/Gemfile b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/input/Gemfile new file mode 100644 index 000000000..bbbe99128 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/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-prebuilds/input/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/input/Gemfile.lock new file mode 100644 index 000000000..7064b964b --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/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-prebuilds/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/overrides.json new file mode 100644 index 000000000..1d3992b06 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/overrides.json @@ -0,0 +1,32 @@ +[ + { + "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/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", + "gemPlatforms": [ + { + "platform": "arm64-darwin", + "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + { + "platform": "x86_64-linux-gnu", + "gemChecksumSha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + } + ] + } + }, + "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 444526748..c843d7a11 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 @@ -43,5 +43,95 @@ "unlocked_pins": [], "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": [ + { + "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(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", + "integrity_required": true, + "url": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", + "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-prebuilds/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/gem/bundler/platform-prebuilds-rerun/input": { + "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(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", + "integrity_required": true, + "url": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", + "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" + } + ] } } diff --git a/crates/socket-patch-core/tests/upstream_restore_golden.rs b/crates/socket-patch-core/tests/upstream_restore_golden.rs index edcaf1989..fe6867ff0 100644 --- a/crates/socket-patch-core/tests/upstream_restore_golden.rs +++ b/crates/socket-patch-core/tests/upstream_restore_golden.rs @@ -609,6 +609,129 @@ 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. +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 + .iter() + .map(|platform| { + serde_json::json!({"platform": platform, "gemChecksumSha256": "ab".repeat(32)}) + }) + .collect(); + overrides +} + +/// A bundler 4 lock that resolves nokogiri as precompiled platform builds: +/// one entry per platform, and no ruby-platform `nokogiri (1.18.10)`. +const GEM_PLATFORM_LOCK: &str = "GEM\n remote: https://rubygems.org/\n specs:\n nokogiri (1.18.10-arm64-darwin)\n racc (~> 1.4)\n nokogiri (1.18.10-x86_64-linux-gnu)\n racc (~> 1.4)\n nokogiri-happymapper (0.10.0)\n puma (6.0.0)\n nio4r (~> 2.0)\n racc (1.8.1)\n\nPLATFORMS\n arm64-darwin\n x86_64-linux-gnu\n\nDEPENDENCIES\n nokogiri (= 1.18.10)\n puma\n\nCHECKSUMS\n nokogiri (1.18.10-arm64-darwin) sha256=4444444444444444444444444444444444444444444444444444444444444444\n nokogiri (1.18.10-x86_64-linux-gnu) sha256=5555555555555555555555555555555555555555555555555555555555555555\n nokogiri-happymapper (0.10.0) sha256=6666666666666666666666666666666666666666666666666666666666666666\n puma (6.0.0) sha256=1111111111111111111111111111111111111111111111111111111111111111\n racc (1.8.1) sha256=3333333333333333333333333333333333333333333333333333333333333333\n\nBUNDLED WITH\n 4.0.15\n"; + +/// A gem locked as precompiled platform builds, redirected to its +/// prebuilds and restored: every platform entry is back in the upstream +/// section where Bundler sorts it, the `DEPENDENCIES` pin (or added entry) +/// is gone, and each `CHECKSUMS` entry is back on its own build's upstream +/// sha256 — the pre-scan pair, byte for byte. +#[tokio::test] +#[serial] +async fn gem_platform_prebuilds_round_trip() { + let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; + let gemfile = + "source \"https://rubygems.org\"\n\ngem \"nokogiri\", \"1.18.10\"\ngem \"puma\"\n"; + let (checksums_at, bundled_at) = ( + GEM_PLATFORM_LOCK.find("CHECKSUMS\n").unwrap(), + GEM_PLATFORM_LOCK.find("BUNDLED WITH").unwrap(), + ); + let no_checksums = format!( + "{}{}", + &GEM_PLATFORM_LOCK[..checksums_at], + &GEM_PLATFORM_LOCK[bundled_at..] + ); + // The ruby-platform entry beside the platform builds. + let with_ruby = GEM_PLATFORM_LOCK + .replace( + " specs:\n", + " specs:\n nokogiri (1.18.10)\n mini_portile2 (~> 2.8.2)\n racc (~> 1.4)\n", + ) + .replace("PLATFORMS\n", "PLATFORMS\n ruby\n") + .replace( + "CHECKSUMS\n", + "CHECKSUMS\n nokogiri (1.18.10) sha256=7777777777777777777777777777777777777777777777777777777777777777\n", + ); + // Not declared: puma depends on it, and the rewriter adds the line. + let transitive_gemfile = "source \"https://rubygems.org\"\n\ngem \"puma\"\n"; + let transitive = GEM_PLATFORM_LOCK + .replace( + " nio4r (~> 2.0)\n", + " nio4r (~> 2.0)\n nokogiri (>= 1.18)\n", + ) + .replace(" nokogiri (= 1.18.10)\n", ""); + let overrides = || gem_override_prebuilt("nokogiri", "1.18.10", &platforms); + let cases = [ + synthetic( + "platform-builds", + &[("Gemfile", gemfile), ("Gemfile.lock", GEM_PLATFORM_LOCK)], + overrides(), + ), + synthetic( + "platform-builds-no-checksums", + &[("Gemfile", gemfile), ("Gemfile.lock", &no_checksums)], + overrides(), + ), + synthetic( + "platform-builds-beside-ruby", + &[("Gemfile", gemfile), ("Gemfile.lock", &with_ruby)], + overrides(), + ), + synthetic( + "platform-builds-crlf", + &[ + ("Gemfile", &gemfile.replace('\n', "\r\n")), + ("Gemfile.lock", &GEM_PLATFORM_LOCK.replace('\n', "\r\n")), + ], + overrides(), + ), + synthetic( + "platform-builds-transitive", + &[ + ("Gemfile", transitive_gemfile), + ("Gemfile.lock", &transitive), + ], + overrides(), + ), + ]; + for case in &cases { + let hosted = &case.expected[if case.expected.contains_key("gems.locked") { + "gems.locked" + } else { + "Gemfile.lock" + }]; + assert!( + hosted.contains(&format!( + " remote: {GEM_INDEX}\n specs:\n nokogiri (1.18.10" + )) || hosted.contains(&format!( + " remote: {GEM_INDEX}\r\n specs:\r\n nokogiri (1.18.10" + )), + "{}: the rewrite moved the builds:\n{hosted}", + case.dir.display() + ); + let server = gem_mock(case).await; + let _env = EnvGuard::set("SOCKET_RUBYGEMS_URL", server.uri()); + let (after, statuses) = run_case(case).await; + assert_round_trip(case, &after, &statuses); + // One `info/nokogiri` document lists every build: it is read once + // however many `CHECKSUMS` entries are re-pinned from it. + let asked = server + .received_requests() + .await + .unwrap() + .iter() + .filter(|request| request.url.path() == "/info/nokogiri") + .count(); + let pinned = case.input.values().any(|text| text.contains("CHECKSUMS")); + assert_eq!(asked, usize::from(pinned), "{}", case.dir.display()); + } +} + #[tokio::test] #[serial] async fn gem_pre_checksums_states() { From a312ac6bf06c943ed97a518f81b732f00192f0eb Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 17:58:55 -0500 Subject: [PATCH 2/9] Test hosted platform prebuilds against the real Bundler Three real-Bundler capstones in e2e_redirect_gem_build (`#[ignore]`, like their neighbours). The fixture gem is published as a ruby gem and as platform gems for this machine and for a foreign platform; a platform gem needs no binary, a pure-Ruby gem with `s.platform` set is one. The real Bundler locks the platform builds, the hosted scan moves them, and the lock is compared byte for byte with what `bundle lock` writes for the redirected Gemfile. A fresh checkout's frozen `bundle install` fetches exactly this machine's prebuild, leaves the lock untouched, and Ruby loads the patched file from the platform build. A re-scan changes nothing, `rollback` restores the pair byte for byte and the installed copy, and standalone `vex` attests the installed platform build. The arms: a `CHECKSUMS` lock holding the platform builds alone, the same without `CHECKSUMS`, and a lock that keeps the ruby-platform entry beside them (what Bundler 4 writes by default for a gem that also ships a ruby gem). Two hermetic tests need no Ruby: a stale platform install and its committed cache archive are replaced with the prebuild and put back by `rollback`; and a fresh checkout is pinned from the lock alone, or left untouched when a locked platform has no prebuild. The in-memory and disk engines are compared on the new golden fixture. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_redirect_gem_build.rs | 724 ++++++++++++++++++ .../tests/e2e_redirect_gem_stale_install.rs | 366 ++++++++- .../tests/hosted_memory_parity.rs | 9 + 3 files changed, 1091 insertions(+), 8 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 99a6e6b6f..d4722593c 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -6317,3 +6317,727 @@ async fn gem_hosted_scan_says_the_gem_is_held_at_its_version() { std::fs::read_to_string(&lock_path).unwrap() ); } + +// ── precompiled platform gems ("prebuilds") ─────────────────────────── + +/// One build a compact index serves: its gem, the token the index lists it +/// under (`` for the ruby gem, `-` for a +/// platform gem), its runtime deps, and the `.gem` the download route +/// returns. +struct IndexBuild { + name: &'static str, + token: String, + deps: Vec, + gem: Vec, +} + +/// [`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]) { + let mut names: Vec<&str> = Vec::new(); + for build in builds { + if !names.contains(&build.name) { + names.push(build.name); + } + } + let mut versions_body = String::from("created_at: 2026-01-01T00:00:00Z\n---\n"); + let mut names_body = String::from("---\n"); + for name in names { + let mut info_body = String::from("---\n"); + let mut tokens: Vec<&str> = Vec::new(); + for build in builds.iter().filter(|build| build.name == name) { + info_body.push_str(&format!( + "{} {}|checksum:{}\n", + build.token, + build.deps.join(","), + sha256_hex(&build.gem) + )); + tokens.push(&build.token); + 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"), + ) + .mount(server) + .await; + } + versions_body.push_str(&format!( + "{name} {} {}\n", + tokens.join(","), + md5_hex(info_body.as_bytes()) + )); + names_body.push_str(&format!("{name}\n")); + Mock::given(method("GET")) + .and(path(format!("{base}/info/{name}"))) + .respond_with(compact_index_body(info_body)) + .mount(server) + .await; + } + Mock::given(method("GET")) + .and(path(format!("{base}/versions"))) + .respond_with(compact_index_body(versions_body)) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path(format!("{base}/names"))) + .respond_with(compact_index_body(names_body)) + .mount(server) + .await; +} + +/// `lib/vuln_gem.rb` of the platform fixture: [`orig_lib`] / [`patched_lib`] +/// plus a `require` of the build marker beside it. +fn build_marked(lib: String) -> String { + lib.replace( + "require \"tiny_dep\"\n", + "require \"tiny_dep\"\nrequire \"vuln_gem/build\"\n", + ) +} + +/// Author and `gem build` one build of the fixture gem: the ruby gem, or, +/// with `platform`, a platform gem. A platform gem needs no binary: a +/// 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 +/// 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"); + let dir = stage.join(format!("{DEP}-{tag}-{build}-src")); + std::fs::create_dir_all(dir.join("lib/vuln_gem")).unwrap(); + std::fs::write(dir.join("lib/vuln_gem.rb"), lib).unwrap(); + std::fs::write( + dir.join("lib/vuln_gem/build.rb"), + format!("module VulnGem\n BUILD = \"{build}\"\nend\n"), + ) + .unwrap(); + let platform_line = platform + .map(|p| format!(" s.platform = \"{p}\"\n")) + .unwrap_or_default(); + std::fs::write( + 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.files = [\"lib/vuln_gem.rb\", \"lib/vuln_gem/build.rb\"]\n s.require_paths = [\"lib\"]\n \ + s.add_dependency \"{TRANSITIVE}\", \">= 0\"\nend\n" + ), + ) + .unwrap(); + let mut cmd = Command::new("gem"); + cmd.args(["build", &format!("{DEP}.gemspec")]) + .current_dir(&dir); + cache_env::isolate(&mut cmd); + let out = cmd.output().expect("failed to run gem build"); + assert!( + out.status.success(), + "gem build {DEP} ({build}) failed:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); + let leaf = match platform { + Some(p) => format!("{DEP}-{DEP_VERSION}-{p}"), + None => format!("{DEP}-{DEP_VERSION}"), + }; + std::fs::read(dir.join(format!("{leaf}.gem"))) + .unwrap_or_else(|e| panic!("built {leaf}.gem: {e}")) +} + +/// The platform of this machine's precompiled gems as their file names and +/// `Gemfile.lock` spell it (`arm64-darwin`, `x86_64-linux`): the local +/// platform without its OS version, which a gem built for it matches on +/// every release of the OS. With it, a platform this machine is not. +fn own_and_foreign_platform() -> (String, String) { + let mut ruby = Command::new("ruby"); + ruby.args([ + "-e", + "p = Gem::Platform.local; print [p.cpu, p.os].join(\"-\")", + ]); + cache_env::isolate(&mut ruby); + let out = ruby.output().expect("failed to run ruby"); + assert!(out.status.success(), "local platform probe failed"); + let own = String::from_utf8_lossy(&out.stdout).trim().to_string(); + let foreign = if own.ends_with("-linux") { + "arm64-darwin" + } else { + "x86_64-linux" + }; + (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. +async fn platform_prebuilds_install_frozen_and_roll_back( + tag: &str, + checksums_lock: bool, + ruby_entry: bool, +) { + // Bundler locks the specific platform's gem from 2.2; `CHECKSUMS` from 2.6. + let floor = if checksums_lock { (2, 6) } else { (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}"); + + // 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 })); + } + 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, + } + } + } + } + }))) + .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, + "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()), + } + }, + "vulnerabilities": { + GHSA: { + "cves": ["CVE-2026-3333"], + "summary": "gem redirect capstone vuln", + "severity": "high", + "description": "d" + } + }, + "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), + ); + }; + 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"], + ); + } + 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"]); + } + if checksums_lock { + 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", token(platform))), + "the fixture lock must pin the {platform} build:\n{pristine_lock}" + ); + } + 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, + &[ + "scan", + "--mode", + "hosted", + "--json", + "--yes", + "--cwd", + proj_str, + "--api-url", + &api, + "--org", + ORG, + "--api-token", + "fake", + "--vex", + "out.vex.json", + "--vex-product", + PRODUCT, + ], + ) + }; + let (code, stdout, stderr) = scan(); + assert_eq!( + code, 0, + "scan failed.\nstdout:\n{stdout}\nstderr:\n{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"] + .as_array() + .into_iter() + .flatten() + .filter_map(|w| w["code"].as_str()) + .collect(); + for code in [ + "redirect_gem_platform_unsupported", + "redirect_gem_stale_install", + "redirect_gem_frozen_install", + ] { + assert!(!warning_codes.contains(&code), "no {code}: {env}"); + } + 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}" + ); + 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}" + ); + } + assert!( + lock.contains(&format!("\nDEPENDENCIES\n {DEP}!\n")), + "DEPENDENCIES is source-pinned:\n{lock}" + ); + // 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(), + "the scan's lock must be what bundler {} writes for the redirected Gemfile", + 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, + }; + + // 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(); + assert_eq!( + fetched, + [format!("{own_leaf}.gem")], + "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}" + ); + + // 4. A re-scan changes nothing. + let (code, stdout, stderr) = scan(); + assert_eq!( + code, 0, + "re-scan failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + 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}" + ); + + // 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 this 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(); + } + 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" + ); + assert_eq!( + std::fs::read_to_string(&warm_lib).unwrap(), + 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}" + ); + + // 6. Standalone VEX over the fresh checkout bundler installed. + manifestless_vex_matrix(&fx, &fresh).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_platform_prebuilds_install_frozen_and_roll_back() { + platform_prebuilds_install_frozen_and_roll_back("platform-prebuilds-checksums", 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_platform_prebuilds_beside_the_ruby_entry_install_frozen_and_roll_back() { + platform_prebuilds_install_frozen_and_roll_back("platform-prebuilds-ruby-entry", true, 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_platform_prebuilds_without_checksums_install_frozen_and_roll_back() { + platform_prebuilds_install_frozen_and_roll_back("platform-prebuilds", false, false).await; +} 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 65ff715e9..f2003ba0c 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 @@ -84,6 +84,31 @@ async fn mount_api(server: &MockServer, view_budget: Option) { /// [`mount_api`] with the grant naming `patched_sha` as the patched /// archive's sha256. async fn mount_api_for(server: &MockServer, view_budget: Option, patched_sha: &str) { + 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). +async fn mount_api_with( + server: &MockServer, + view_budget: Option, + patched_sha: &str, + prebuilds: &[(&str, String)], +) { + 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() @@ -135,11 +160,7 @@ async fn mount_api_for(server: &MockServer, view_budget: Option, patched_sh "registryOverride": { "kind": "rubygems-compact-index", "indexUrl": index_url, - "identifiers": { - "name": DEP, - "version": DEP_VERSION, - "gemChecksumSha256": patched_sha, - } + "identifiers": identifiers, } } } @@ -2034,6 +2055,12 @@ async fn gem_hosted_standalone_vex_ignores_unused_system_home_copy() { /// (`metadata.gz`, the same bytes for every build, as the patch service /// keeps it) and the package tree (`data.tar.gz`). fn real_gem(lib: &str) -> Vec { + real_gem_for(lib, "ruby") +} + +/// [`real_gem`] built for `platform`: `ruby`, or the platform of a +/// precompiled gem (`--.gem`). +fn real_gem_for(lib: &str, platform: &str) -> Vec { use std::io::Write as _; fn gz(bytes: &[u8]) -> Vec { let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); @@ -2053,7 +2080,7 @@ fn real_gem(lib: &str) -> Vec { } let metadata = format!( "--- !ruby/object:Gem::Specification\nname: {DEP}\nversion: \ - !ruby/object:Gem::Version\n version: {DEP_VERSION}\nplatform: ruby\nauthors:\n- \ + !ruby/object:Gem::Version\n version: {DEP_VERSION}\nplatform: {platform}\nauthors:\n- \ e2e\nbindir: bin\ndependencies: []\nexecutables: []\nextensions: []\nfiles:\n- \ lib/stale_probe_gem.rb\nrequire_paths:\n- lib\nrubygems_version: 3.6.9\n" ); @@ -2085,14 +2112,23 @@ async fn serve_patched_gem(server: &MockServer, body: Vec) { /// A real install of the fixture gem under `home`: the gem dir, the /// archive RubyGems installed it from, and a gemspec that builds nothing. fn install_real_gem(home: &Path, lib: &str) -> PathBuf { - let leaf = format!("{DEP}-{DEP_VERSION}"); + install_real_gem_for(home, lib, "ruby") +} + +/// [`install_real_gem`] of the build for `platform`: RubyGems names a +/// platform gem's dir, archive and gemspec `--`. +fn install_real_gem_for(home: &Path, lib: &str, platform: &str) -> PathBuf { + let leaf = match platform { + "ruby" => format!("{DEP}-{DEP_VERSION}"), + platform => format!("{DEP}-{DEP_VERSION}-{platform}"), + }; 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_probe_gem.rb"), lib).unwrap(); std::fs::create_dir_all(home.join("cache")).unwrap(); std::fs::write( home.join("cache").join(format!("{leaf}.gem")), - real_gem(lib), + real_gem_for(lib, platform), ) .unwrap(); std::fs::create_dir_all(home.join("specifications")).unwrap(); @@ -2237,6 +2273,320 @@ async fn refresh_replaces_a_stale_project_install_and_its_archives() { ); } +/// The machine's platform in the platform-build arm, and one the lock also +/// names (another machine's). +const PLATFORM: &str = "arm64-darwin"; +const OTHER_PLATFORM: &str = "x86_64-linux-gnu"; + +/// A gem bundler locks as precompiled platform builds, each pinned to its +/// upstream archive: one entry per platform, no ruby-platform one. +fn platform_lock(arm_sha: &str, linux_sha: &str) -> String { + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n {DEP} ({DEP_VERSION}-{PLATFORM})\n \ + {DEP} ({DEP_VERSION}-{OTHER_PLATFORM})\n\nPLATFORMS\n {PLATFORM}\n {OTHER_PLATFORM}\n\n\ + DEPENDENCIES\n {DEP} (= {DEP_VERSION})\n\nCHECKSUMS\n {DEP} ({DEP_VERSION}-{PLATFORM}) \ + sha256={arm_sha}\n {DEP} ({DEP_VERSION}-{OTHER_PLATFORM}) sha256={linux_sha}\n\n\ + BUNDLED WITH\n 4.0.15\n" + ) +} + +/// A gem locked as precompiled platform builds, with a prebuild for every +/// one: the scan moves both lock entries to the patch registry, each +/// pinned to its own prebuild, and the platform copy this machine +/// installed (`gems/--`) is replaced with the +/// patched platform gem the registry serves under that name, verified +/// against that platform's sha256 — as is the committed `bundle cache` +/// archive. A platform gem declares no extensions, so nothing is built. +/// The same run's `--vex` attests the gem, a re-scan has nothing left to +/// do, and `rollback` hands back the pre-scan pair byte for byte and puts +/// the installed copy and the archive back on the upstream platform gem. +#[tokio::test(flavor = "multi_thread")] +async fn refresh_replaces_a_stale_platform_install_with_its_prebuild() { + let server = MockServer::start().await; + let build = |lib: &str, platform: &str| real_gem_for(lib, platform); + let (prebuilt, other_prebuilt) = ( + build(PATCHED_LIB, PLATFORM), + build(PATCHED_LIB, OTHER_PLATFORM), + ); + let (upstream, other_upstream) = ( + build(UPSTREAM_LIB, PLATFORM), + build(UPSTREAM_LIB, OTHER_PLATFORM), + ); + mount_api_with( + &server, + None, + &sha256_of(&real_gem(PATCHED_LIB)), + &[ + (PLATFORM, sha256_of(&prebuilt)), + (OTHER_PLATFORM, sha256_of(&other_prebuilt)), + ], + ) + .await; + let leaf = format!("{DEP}-{DEP_VERSION}-{PLATFORM}"); + // 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" + ))) + .respond_with( + ResponseTemplate::new(200).set_body_raw(prebuilt.clone(), "application/octet-stream"), + ) + .mount(&server) + .await; + // rubygems.org's stand-in: the index lists each build under its own + // `-` token. + Mock::given(method("GET")) + .and(path(format!("/upstream/info/{DEP}"))) + .respond_with(ResponseTemplate::new(200).set_body_string(format!( + "---\n{DEP_VERSION} |checksum:{}\n{DEP_VERSION}-{PLATFORM} |checksum:{}\n\ + {DEP_VERSION}-{OTHER_PLATFORM} |checksum:{}\n", + sha256_of(&real_gem(UPSTREAM_LIB)), + sha256_of(&upstream), + sha256_of(&other_upstream), + ))) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!("/upstream/gems/{leaf}.gem"))) + .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(); + let gemfile = format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"); + let lock = platform_lock(&sha256_of(&upstream), &sha256_of(&other_upstream)); + std::fs::write(proj.join("Gemfile"), &gemfile).unwrap(); + 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); + assert!(gem_dir.ends_with(&leaf)); + // A committed `bundle cache` of the upstream platform 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 vex_path = proj.join("out.vex.json"); + let uri = server.uri(); + let args = scan_args( + &proj, + &uri, + &[ + "--json", + "--vex", + vex_path.to_str().unwrap(), + "--vex-product", + "pkg:gem/app@1.0.0", + ], + ); + 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}"); + assert!( + !stdout.contains("redirect_gem_platform_unsupported"), + "every locked platform has a prebuild: {env}" + ); + + // 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 hosted_lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + assert!( + hosted_lock.contains(&format!( + "GEM\n remote: {index}\n specs:\n {DEP} ({DEP_VERSION}-{PLATFORM})\n {DEP} \ + ({DEP_VERSION}-{OTHER_PLATFORM})\n\n" + )), + "{hosted_lock}" + ); + assert!( + hosted_lock.contains(&format!( + "DEPENDENCIES\n {DEP} (= {DEP_VERSION})!\n\nCHECKSUMS\n {DEP} \ + ({DEP_VERSION}-{PLATFORM}) sha256={}\n {DEP} ({DEP_VERSION}-{OTHER_PLATFORM}) \ + sha256={}\n", + sha256_of(&prebuilt), + sha256_of(&other_prebuilt) + )), + "{hosted_lock}" + ); + + // The installed platform copy and both archives are the prebuild. + assert!( + stale_warnings(&env).is_empty(), + "nothing is left stale: {env}" + ); + let notes = warnings_with_code(&env, "redirect_gem_install_refreshed"); + assert_eq!( + notes.len(), + 2, + "the install and the committed archive: {env}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + assert_eq!( + std::fs::read(home.join("cache").join(format!("{leaf}.gem"))).unwrap(), + prebuilt, + "the archive RubyGems reinstalls from is the prebuild" + ); + assert_eq!(std::fs::read(&committed).unwrap(), prebuilt); + assert!( + !home.join(".socket-patch-refresh").exists(), + "no stage left" + ); + let doc = std::fs::read_to_string(&vex_path).expect("VEX written"); + assert!(doc.contains(PURL), "the refreshed copy is attested:\n{doc}"); + + // A re-scan: the pair is as the scan wants it, the install is patched. + 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, "{env}\nstderr:\n{stderr}"); + assert!( + stale_warnings(&env).is_empty() + && warnings_with_code(&env, "redirect_gem_install_refreshed").is_empty(), + "a re-scan has nothing to refresh or to warn about: {env}" + ); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + hosted_lock, + "a re-scan leaves the lock byte-identical" + ); + + // Rollback: every platform entry back upstream, each `CHECKSUMS` entry + // back on its upstream sha256, the Gemfile as it was. + let rubygems = format!("{uri}/upstream"); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &[ + "rollback", + PURL, + "--json", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + uri.as_str(), + ], + &[("SOCKET_RUBYGEMS_URL", rubygems.as_str())], + ); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + lock, + "rollback restores the lock byte for byte" + ); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + gemfile + ); + // The lock pins the upstream platform gem again, so what Bundler holds + // goes back to it too: a patched archive left in its cache dir would + // fail every install on the restored checksum. + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB); + assert_eq!( + std::fs::read(home.join("cache").join(format!("{leaf}.gem"))).unwrap(), + upstream + ); + assert_eq!(std::fs::read(&committed).unwrap(), upstream); + assert_eq!( + warnings_with_code(&env, "upstream_gem_install_refreshed").len(), + 2, + "the install and the committed archive: {env}" + ); + assert!( + warnings_with_code(&env, "upstream_gem_stale_cache").is_empty() + && warnings_with_code(&env, "upstream_gem_stale_install").is_empty(), + "nothing is left on the patched build: {env}" + ); +} + +/// 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. +#[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)); + let (arm_sha, linux_sha) = ( + sha256_of(&real_gem_for(PATCHED_LIB, PLATFORM)), + sha256_of(&real_gem_for(PATCHED_LIB, OTHER_PLATFORM)), + ); + for complete in [true, false] { + let server = MockServer::start().await; + let mut prebuilds = vec![(PLATFORM, arm_sha.clone())]; + if complete { + prebuilds.push((OTHER_PLATFORM, linux_sha.clone())); + } + mount_api_with(&server, None, &ruby_sha, &prebuilds).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + let gemfile = + format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"); + let lock = platform_lock(&"1".repeat(64), &"2".repeat(64)); + std::fs::write(proj.join("Gemfile"), &gemfile).unwrap(); + std::fs::write(proj.join("Gemfile.lock"), &lock).unwrap(); + + let (code, stdout, stderr) = hosted_scan_json(&proj, &server.uri()); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + 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!(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" + )), + "{after}" + ); + assert!( + after.contains(&format!( + " {DEP} ({DEP_VERSION}-{PLATFORM}) sha256={arm_sha}\n {DEP} \ + ({DEP_VERSION}-{OTHER_PLATFORM}) sha256={linux_sha}\n" + )), + "{after}" + ); + assert!( + stale_warnings(&env).is_empty(), + "nothing is installed: {env}" + ); + } else { + assert_eq!(hosted_pinned(&env), 0, "{env}"); + let [detail] = skipped.as_slice() else { + panic!("one platform skip: {env}"); + }; + assert!( + detail.contains(&format!( + "no patched build for `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})`" + )) && detail.contains(&format!("patched builds for {PLATFORM}")), + "{detail}" + ); + assert_eq!(after, lock, "the lock is untouched"); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + gemfile, + "the Gemfile is untouched" + ); + } + } +} + /// Human output of the run that refreshes: one progress line per kind, /// no warning, and the committed archive in the files to commit. #[tokio::test(flavor = "multi_thread")] diff --git a/crates/socket-patch-cli/tests/hosted_memory_parity.rs b/crates/socket-patch-cli/tests/hosted_memory_parity.rs index cc6dc03b0..bb14874b0 100644 --- a/crates/socket-patch-cli/tests/hosted_memory_parity.rs +++ b/crates/socket-patch-cli/tests/hosted_memory_parity.rs @@ -290,6 +290,15 @@ async fn parity_gemfile() { assert_parity(case("gem/bundler/basic")).await; } +/// A gem the lock resolves only as precompiled platform builds. The lock +/// inventory has no ruby-platform entry to list it by, so both hosted +/// engines find it through the lock's platform specs (nothing is +/// installed here), and both move every build to its prebuild. +#[tokio::test] +async fn parity_gemfile_platform_prebuilds() { + assert_parity(case("gem/bundler/platform-prebuilds")).await; +} + #[tokio::test] async fn parity_golang() { assert_parity(case("golang/gomod/basic")).await; From aff06da790e324e049238fb759a8365400a2c18e Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 17:58:55 -0500 Subject: [PATCH 3/9] Describe hosted platform prebuilds in the docs The CLI contract and the ecosystems guide said a gem locked as precompiled platform builds is always skipped in hosted mode. They now say when it is redirected (a prebuild for every locked platform), what the lock looks like afterwards, how an installed platform copy is judged and refreshed in both directions, how the lock is restored, and that the skip is left for a locked platform with no prebuild. `redirect_gem_platform_unsupported` gets its row in the warning table. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 17 +++++++------- docs/ecosystems.md | 30 +++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 0b8d58656..e960d4c35 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -364,7 +364,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Throttling: bounded retry, then a reported failure.** Every patch-API JSON call (the batch query, the per-package patch lists, patch views and VEX record fetches, hosted package references) retries an HTTP `429` or `503` answer up to 3 times (`SOCKET_API_MAX_RETRIES=`, `0`-`10`; `0` = no retry). The wait honors `Retry-After` (delta-seconds or HTTP-date); a `Retry-After` over 30 s is not waited out — the answer is final at once — and one under the jittered first backoff step (`0`, a past date) waits that step instead. Without one it backs off 0.5 s / 1 s / 2 s (each step up to 8 s, with jitter in its upper half). All retries in one run share a 60 s wall-clock window that opens with the run's first retry: a retry whose wait would end after it closes is refused and the answer is final. Parallel requests wait in parallel, so each still gets its retries while the run adds at most about 60 s. Nothing else is retried (401/403 still drive the proxy fallback on the first answer; the public proxy's permanent `503 "Patch API is not configured"` is never retried on any path — the batch query still degrades to the per-package path at once, and a per-package lookup or patch view answering it is the same non-throttle failure it always was, which on the legacy per-package path leaves that package unanswered, see above), and a retried answer folds exactly where the first attempt's would have, so output is identical to an unthrottled run's. A request still throttled after that is a failure in the channel its siblings use: a failed batch is the human `Warning: API batch of failed: ` line and, under `--json`, a run-level `warnings[]` entry `{code: "api_batch_failed", detail: "API batch of failed: "}` (additive; `status` stays `success`, exit 0 — the other batches' packages are reported); a failed per-package patch-list query in the agent / hosted / vendored flows is the human `Warning: could not fetch details for : ` line and, under `--json`, `{code: "patch_details_failed", detail: "could not fetch details for : "}`. When every batch (or every patch-list query) fails, the existing all-failed error envelope and exit 1 apply. The error names the exhausted retry: `Rate limit exceeded (HTTP 429, gave up after 3 retries). Please try again later.` / `API request failed with status 503: (gave up after 3 retries)` (or `(Retry-After s exceeds the 30 s retry cap)` / `(the run's 60 s retry window has closed)`); with retries off it is the pre-retry text. On the token-less legacy per-package proxy path (a proxy without `POST /patch/batch`), a package still throttled (429 / over-capacity 503) after its retries is an unanswered package (see "No patches" needs an answer above): the batch's answered packages are used and it is reported as `patch_lookup_failed` (`partialFailure`, exit 1); when it leaves no package of its batch answered, the batch fails through the batch-failure channel above. Only a PURL the service itself refuses (its own `400`) is skipped individually. Pinned by `tests/scan_api_retry_e2e.rs` and the core crate's `tests/api_retry_e2e.rs`. -**Lockfile supplement (v3.4)**: `scan` discovery is no longer limited to installed trees. The project's lockfiles (`package-lock.json`/`npm-shrinkwrap.json`, `pnpm-lock.yaml` v9, `yarn.lock` classic + berry, `bun.lock`, `vlt-lock.json` (registry nodes, Socket-hosted pins included; vendored `file` nodes are left to the vendor ledger), `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`, `uv.lock`/`poetry.lock`/pinned `requirements.txt`) are inventoried and dependencies with NO installed copy join discovery — counts, the API lookup, the table (flagged ` [NOT INSTALLED]`, plus a stderr note), and the prune "scanned" set (a wiped node_modules no longer prunes lockfile-listed entries). JSON gains a top-level `lockfileOnlyPackages` count and an additive `notInstalled: true` on matching `packages[]` entries. Agent mode partitions lockfile-only patches out BEFORE download (calm `skipped`/`package_not_installed` events — never an error exit, never a manifest write); vendored mode passes them through to the vendor engine's server download. Vendored-ledger entries likewise stay discoverable on a fresh clone (the committed artifact is the dependency). Global scans (`--global`) get no supplement. **Rush monorepos** (no root lockfile, `rush.json` present): the npm-lock inventory falls back to the Rush source-of-truth locks — `common/config/rush/pnpm-lock.yaml` plus every `common/config/subspaces/*/pnpm-lock.yaml` (`read_dir`-sorted, repo-relative paths preserved) — so a Rush repo's dependencies still join discovery. **Plug'n'Play layouts are an explicit refusal, not an empty inventory**: a `.pnp.*` loader means the npm packages are structurally unreachable in EVERY mode (under yarn PnP the installed-tree crawl is empty too — no `node_modules/`), so `scan` surfaces an additive top-level `warnings[]` array (`{code, detail}` objects, omitted when empty) carrying `yarn_pnp_unsupported` (same code as apply's refusal; remedy `yarn patch `) or `pnpm_pnp_unsupported` (pnpm's `node-linker=pnp` twin; pnpm remedies), plus a stderr `Warning: …` line on the human path. Exit code and `status` are deliberately unchanged (exit 0 / `success` — the same posture as hosted refusals, which exit 0 with no `applied` event); the warning is the machine-readable signal that nothing was checked. Pinned by `tests/e2e_safety_yarn_pnp.rs`. **A Bundler lock socket-patch cannot read is likewise a warning, not an empty inventory**: when the project holds gem files but bundler loads no `Gemfile.lock` / `gems.locked` socket-patch reads (`BUNDLE_GEMFILE` or bundler 4's `BUNDLE_LOCKFILE` naming another file, or a `Gemfile` + `gems.rb` twin, whose loaded pair depends on the bundler major that runs), `warnings[]` carries the additive `gem_lock_unsupported` (detail names the setting or the twin) and its lockfile-only gems are not discovered. Same exit-0 / `success` posture. +**Lockfile supplement (v3.4)**: `scan` discovery is no longer limited to installed trees. The project's lockfiles (`package-lock.json`/`npm-shrinkwrap.json`, `pnpm-lock.yaml` v9, `yarn.lock` classic + berry, `bun.lock`, `vlt-lock.json` (registry nodes, Socket-hosted pins included; vendored `file` nodes are left to the vendor ledger), `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`, `uv.lock`/`poetry.lock`/pinned `requirements.txt`) are inventoried and dependencies with NO installed copy join discovery — counts, the API lookup, the table (flagged ` [NOT INSTALLED]`, plus a stderr note), and the prune "scanned" set (a wiped node_modules no longer prunes lockfile-listed entries). JSON gains a top-level `lockfileOnlyPackages` count and an additive `notInstalled: true` on matching `packages[]` entries. Agent mode partitions lockfile-only patches out BEFORE download (calm `skipped`/`package_not_installed` events — never an error exit, never a manifest write); vendored mode passes them through to the vendor engine's server download. Vendored-ledger entries likewise stay discoverable on a fresh clone (the committed artifact is the dependency). The `Gemfile.lock` inventory lists a gem by its ruby-platform entry; a gem the lock resolves ONLY as precompiled platform builds (`nokogiri (1.18.10-arm64-darwin)`, no `nokogiri (1.18.10)`) joins the supplement of a hosted run alone (`scan` / `get --mode hosted`, and the in-memory hosted engine), which can redirect it to its per-platform prebuilds from the lock; agent and vendored runs see it only through an installed copy, as before. Global scans (`--global`) get no supplement. **Rush monorepos** (no root lockfile, `rush.json` present): the npm-lock inventory falls back to the Rush source-of-truth locks — `common/config/rush/pnpm-lock.yaml` plus every `common/config/subspaces/*/pnpm-lock.yaml` (`read_dir`-sorted, repo-relative paths preserved) — so a Rush repo's dependencies still join discovery. **Plug'n'Play layouts are an explicit refusal, not an empty inventory**: a `.pnp.*` loader means the npm packages are structurally unreachable in EVERY mode (under yarn PnP the installed-tree crawl is empty too — no `node_modules/`), so `scan` surfaces an additive top-level `warnings[]` array (`{code, detail}` objects, omitted when empty) carrying `yarn_pnp_unsupported` (same code as apply's refusal; remedy `yarn patch `) or `pnpm_pnp_unsupported` (pnpm's `node-linker=pnp` twin; pnpm remedies), plus a stderr `Warning: …` line on the human path. Exit code and `status` are deliberately unchanged (exit 0 / `success` — the same posture as hosted refusals, which exit 0 with no `applied` event); the warning is the machine-readable signal that nothing was checked. Pinned by `tests/e2e_safety_yarn_pnp.rs`. **A Bundler lock socket-patch cannot read is likewise a warning, not an empty inventory**: when the project holds gem files but bundler loads no `Gemfile.lock` / `gems.locked` socket-patch reads (`BUNDLE_GEMFILE` or bundler 4's `BUNDLE_LOCKFILE` naming another file, or a `Gemfile` + `gems.rb` twin, whose loaded pair depends on the bundler major that runs), `warnings[]` carries the additive `gem_lock_unsupported` (detail names the setting or the twin) and its lockfile-only gems are not discovered. Same exit-0 / `success` posture. **Server artifact acquisition (v5.0)**: vendoring downloads the patched artifact for the selected UUID, including on a fresh checkout with no installed package. The CLI no longer downloads pristine packages, stages patch blobs, applies patches to vendor copies, or constructs archives. Backend lock and package-identity checks still run before acquisition; git and custom-registry Cargo sources are refused with `vendor_source_unsupported`. Healthy committed artifacts are reused offline. A changed UUID downloads a fresh server artifact; an unhealthy artifact at the recorded UUID uses the exact redownload procedure below, except that a directory copy whose ledger entry has no file inventory (vendored before v5.0) is rebuilt by its backend from a fresh verified download, and a missing or stale Bun workspace mirror over a healthy canonical tarball is rewritten from that tarball by the backend; those cases report the backend's own failure codes. @@ -408,7 +408,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`. 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), `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, or a merged Bundler < 2.2 section whose remotes the manifest's sources do not explain) 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, 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)`. 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), `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, or a merged Bundler < 2.2 section whose remotes the manifest's sources do not explain), `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, 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. @@ -429,19 +429,19 @@ 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) is already patched and never warns, any other readable archive is stale, and a missing or unreadable one is never evidence by itself. +- 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`. - 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. - When several confirmed variant purls resolve to one installed dir, ANY of them judging it patched keeps it quiet. - Staleness needs **positive evidence** — bytes actually read that are not the patched state — so missing or unreadable files never mark a copy stale. -- A committed cache-dir archive whose sha256 is readable and differs from the patched artifact's is stale by itself, even with no installed dir at all (a fresh checkout with a committed stale cache). +- A committed cache-dir archive whose sha256 is readable and differs from the patched artifact's is stale by itself, even with no installed dir at all (a fresh checkout with a committed stale cache). That covers the ruby gem's `-.gem` and each platform build's `--.gem`. - Standalone `vex` and `apply --check` judge gem copies by the same rule (#1098): when Bundler doesn't use system gems, a copy in a `gem env` home is not one the project loads and is not verified, unless it is a default gem (its spec under `specifications/default/`), which Bundler loads from the system home under any path. *The refresh* (default; `--no-gem-install-refresh`, env `SOCKET_NO_GEM_INSTALL_REFRESH`, turns it off). - **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). 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 (`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 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. @@ -456,7 +456,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm - A human run prints ONE warning for all of them: how many gems, which gems in which gem home (or why they were not refreshed), why in one sentence, and the remedy as a command. Its headline is `N gems are still unpatched on disk after the switch to hosted patches` when none of the gems it covers was patched in place; when every one was, `N gems patched in place still have their upstream archives on disk after the switch to hosted patches`; and with both kinds, `N gems still have unpatched files or archives on disk after the switch to hosted patches`. - A stale-flagged purl is additionally **excluded from the same run's `--vex` `assume_applied` set** — the envelope must never attest a CVE its own warning says is live; the purl falls back to normal installed-tree verification (a patched install still attests, a stale one is omitted). A same-run `--vex` may still fail on "nothing to attest" per the embedded-VEX contract. -*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive (ruby-platform gems only: the lock's checksum names that archive). A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of each patch the gem was pinned to (`…/patches/view/`, for that gem only, through the run's API client) and the copy is stale when every file a record lists hashes to its `afterHash`. Each such copy is judged on its own files, and it is then replaced from the upstream archive like any other; no `cache/` dir is created for it. When no record proves the copy patched and one of them could not judge it (`--offline`, a failed fetch, a patch the API has no record of, record files missing from the copy), nothing tells it from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. After a request the API does not answer (a network error), no other record is asked for. Such a copy is judged the same way when nothing proves the upstream sha256 (a lock without `CHECKSUMS`, with `--offline` or a registry error): one proven patched is then reported as left on the patched build, since there is no verified archive to replace it with. An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. +*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive. A platform build the restored lock names (`nokogiri (1.18.10-arm64-darwin)`) is judged and refreshed under its own leaf, against that build's own upstream sha256 (its `CHECKSUMS` entry, else the compact index's `-` line) and from `/gems/--.gem`; so is its archive in bundler's cache dir. A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of each patch the gem was pinned to (`…/patches/view/`, for that gem only, through the run's API client) and the copy is stale when every file a record lists hashes to its `afterHash`. Each such copy is judged on its own files, and it is then replaced from the upstream archive like any other; no `cache/` dir is created for it. When no record proves the copy patched and one of them could not judge it (`--offline`, a failed fetch, a patch the API has no record of, record files missing from the copy), nothing tells it from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. After a request the API does not answer (a network error), no other record is asked for. Such a copy is judged the same way when nothing proves the upstream sha256 (a lock without `CHECKSUMS`, with `--offline` or a registry error): one proven patched is then reported as left on the patched build, since there is no verified archive to replace it with. An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. *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. @@ -697,7 +697,7 @@ Discovery is read-only, never touches the network, and never fails the run: a ma | cargo | `Cargo.lock`, `Cargo.toml`, `.cargo/config` (else `.cargo/config.toml`) | `Cargo.lock` `source = "sparse+…//index/"`, confirmed by `Cargo.toml`: a declaration cargo honors must route that version to the patch, either a dependency in the root manifest or a workspace member's with `registry = "socket-patch-"` and a requirement that accepts the locked version, or a `[patch.]` entry carrying that registry (in the root manifest, or the project config). Cargo resolves a dependency from the source its declaration names, so without one cargo takes the crate from crates.io and rewrites the lock, or fails under `--locked` (#2045). A reverted pin is diagnosed (`patched_ref_invalid`), no ref. A crate only registry dependents declare, a registry named only on a `[patch]` entry cargo ignores or a `[workspace.dependencies]` entry nothing inherits, and a lock with no readable root `Cargo.toml` withhold the ref (`patched_ref_unattributable`, never attested) while `rollback` / `remove` still unwind the lock entry. Run from a workspace member (an ancestor `[workspace]` that does not `exclude` the directory, or `package.workspace`; the check hosted scan and `vendor` refuse a project by), nothing there attests: cargo ignores a member's `[patch]` and reads `Cargo.lock` only at the workspace root, so each member file naming a Socket patch is diagnosed (`patched_ref_unattributable`, naming the workspace root to run from), a vendored `[patch]` copy is no reference, and a hosted pin is only one `rollback` / `remove` unwind. Another `[[package]]` of the same `name@version` from a non-Socket source (crates.io, git), which cargo locks beside the pin for a dependent added later and builds unpatched (#679), withholds the ref (`patched_ref_unattributable`, never attested) while `rollback` / `remove` still unwind it. | `[patch.] = { path = ".socket/vendor/cargo//-" }` — primarily the root `Cargo.toml` (v5 `vendor`; key-agnostic: `` is `package` when renamed, else the key, so `-socket-` keys count), also the project config (pre-v5 wiring), live only while the lock holds a sourceless entry for it that is not in `[[patch.unused]]`; a manifest entry cargo ignores — the project config redefines its key with another path, or a `[patch."https://github.com/rust-lang/crates.io-index"]` table replaces `[patch.crates-io]` — is diagnosed (`patched_ref_invalid`), no ref | `checksum` (v1: `[metadata]`), required | | golang | `go.mod`, `go.work`, `go.sum`, `go.work.sum` | `replace M v => patch.socket.dev/gopatch/ ` | `replace M v => ./.socket/vendor/golang//M@v` | the socket module's `/go.mod` go.sum line, required. The zip line (`h1:` of the module tree) is the locked integrity when present; `go mod tidy` prunes it when no package of the module is loaded and the build stays green, so the `/go.mod` line alone still attests from the lockfile, unless the main modules' `require`s or go.sum show the build selects another version (MVS keeps the `/go.mod` line of versions it only reads): then the replace is inert. With a `go.work` the main modules are its `use` members and the build selects by MVS over their module graph: each member's `require`s and the `go.mod` of every dependency go loads (read from its replacement directory or the module cache when the root is on disk). go keeps no member's `go.mod` tidy in workspace mode, so a member's dependency can raise the module past every `require`. A pin, zip line or not, whose replaced version a member's or a dependency's `require` raises is inert, as is one of a module that is itself a `use` member (go builds it from that directory). Sum-file zip lines are no evidence of the selection (go only appends to `go.work.sum`), and a `/go.mod`-only pin is never the lockfile basis in a workspace (`integrity_required = true`). Any mode writes the replace of a module a workspace shares into the root `go.work` (source `go.work`); a `go.work` root without a `go.mod` also reads each in-root member's `go.mod` replaces (source `/go.mod`). On disk the workspace is the one go resolves, read as hosted and vendored modes read it: `GOWORK`, else the nearest `go.work` at or above the project, with `use` members anywhere (in memory: the root `go.work` and its in-root members). The sum files are the ones go reads: the root `go.sum`, or with a `go.work`, its `go.work.sum` and each `use` member's `go.sum` (the root's only when `.` is a member), those outside the project only when inside the repository; under `GOWORK=off`, `go.work` and its replaces are ignored. A Socket replace that workspace keeps from the build, exactly where hosted and vendored modes refuse to write one (its `go.work` is an ancestor's or another file `GOWORK` names, so the root `go.work` is never read; it overrides the replace; it doesn't `use` the module; another member replaces the same `module@version` elsewhere), stays a reference but is unattested (`go_workspace_override`) for that file only: the root `go.mod`'s mirror of a `go.work` replace go never reads still attests. A replace of a module that is itself a `use` member is inert, diagnosed, never a reference. A `GOWORK` go rejects (a relative path, a file it cannot read or parse) reports each Go ref as `patched_ref_invalid` instead, as does a `GOFLAGS` `-modfile` other than the root `go.mod`. A conflicting hash or a malformed `h1:` for the socket module+version, or a line of other than three tokens anywhere in a sum file, is no pin. A replace that `require` no longer selects (`require M v'`) is inert: diagnosed, no ref. | | pypi | `uv.lock` (confirmed by `pyproject.toml` `[tool.uv.sources]` when present), PEP 723 `