diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 6338d568b..cbcef0001 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -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). 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 (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. *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. @@ -2269,7 +2269,7 @@ command's integration tests check its output. | `redirect_gem_stale_install` | `warnings[]` (warning) | scan / get `--mode hosted` (gem): a stale UNPATCHED materialization (installed gem, or committed archive in bundler's cache dir — `vendor/cache` unless `cache_path` moves it) that `bundle install` will reuse instead of fetching the redirected patch, and that the run did not refresh: it is in a shared gem home, or the refresh could not be done (the detail says why) or is turned off. The detail carries the remedy. A human run prints one warning for all of them. Full rules and flavors: the "Gem stale-install guard" section. | | `redirect_gem_install_refreshed` | `warnings[]` (note) | scan / get `--mode hosted` (gem): a stale materialization the run replaced with the sha256-verified patched gem (the detail names the purl and the path). A human run prints a progress line instead. See the "Gem stale-install guard" section. | | `redirect_gem_install_would_refresh` | `warnings[]` (note) | scan / get `--mode hosted --dry-run` (gem): a stale materialization a wet run would replace. Nothing was written or downloaded. | -| `upstream_gem_stale_install` | `warnings[]` (warning); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem), and a wet vendored gem unwind (`rollback`, `remove`, `vendor --revert`, `vendor`'s reconcile; #2083, and a copy agent mode patched in place before the gem was vendored, #2093): an installed copy of a gem that is back on its upstream entry still holds the PATCHED gem and was not refreshed (a shared gem home, a failed or disabled refresh). Bundler keeps using it. Also: the copy could not be checked against the upstream gem, because the registry that would say what that is was refused (plain-http `SOCKET_RUBYGEMS_URL`); it still holds the patched build if it was installed before the unwind. The detail carries the reason and the remedy; a human run prints one warning for all of them. | +| `upstream_gem_stale_install` | `warnings[]` (warning); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem), and a wet vendored gem unwind (`rollback`, `remove`, `vendor --revert`, `vendor`'s reconcile; #2083, and a copy agent mode patched in place before the gem was vendored, #2093): an installed copy of a gem that is back on its upstream entry still holds the PATCHED gem and was not refreshed (a shared gem home, a failed or disabled refresh). Bundler keeps using it. Also: the copy could not be checked against the upstream gem, because the registry that would say what that is was refused (plain-http `SOCKET_RUBYGEMS_URL`), or because its gem home has no archive of it and the pin's patch record could not be fetched (#2092); it still holds the patched build if it was installed before the unwind. The detail carries the reason and the remedy; a human run prints one warning for all of them. | | `upstream_gem_install_refreshed` | `warnings[]` (note); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem): an installed copy or cache-dir archive the unwind replaced with the sha256-verified upstream gem. A wet vendored gem unwind (#2083, #2093): an installed copy only. A human run prints a progress line instead. | | `upstream_gem_install_would_refresh` | `warnings[]` (note) | the same on `--dry-run`: what a wet unwind would replace. | | `redirect_gem_version_not_locked` | `warnings[]` (warning) | scan `--mode hosted` (gem): the crawled gem version is installed on the machine but no `GEM` section of the project's lock resolves it (another project's copy in the shared gem home). The gem is skipped and the Gemfile and lock stay byte-identical. | diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 9f0a78ff5..db3311adf 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -15,7 +15,7 @@ use socket_patch_core::manifest::schema::PatchRecord; use socket_patch_core::patch::gem_ext::RubyEnv; use socket_patch_core::patch::gem_refresh::{refresh, Source, Target, Wanted}; -use crate::args::GlobalArgs; +use crate::args::{GlobalArgs, RunApiClient}; use crate::ui::plural; /// What the lock now pins: the hosted patch, or the upstream registry @@ -657,18 +657,24 @@ pub(crate) fn report( } } // A gem whose copy could not be checked is not known to be stale: it - // is counted apart from the ones that are. - let unchecked: BTreeSet<&str> = local - .iter() - .filter(|(why, _)| matches!(why, Why::Unverified(_))) - .flat_map(|(_, gems)| gems.iter().map(|gem| gem.purl.as_str())) + // is counted apart from the ones that are. A gem with a copy of each + // kind (two gem homes) is known to be stale. + let purls_where = |unverified: bool| { + local + .iter() + .filter(move |(why, _)| matches!(why, Why::Unverified(_)) == unverified) + .flat_map(|(_, gems)| gems.iter().map(|gem| gem.purl.as_str())) + }; + let known_stale: BTreeSet<&str> = shared + .values() + .flatten() + .copied() + .chain(purls_where(false)) .collect(); - let count = stale - .iter() - .map(|gem| gem.purl.as_str()) - .filter(|purl| !unchecked.contains(purl)) - .collect::>() - .len(); + let unchecked: BTreeSet<&str> = purls_where(true) + .filter(|purl| !known_stale.contains(purl)) + .collect(); + let count = known_stale.len(); let switch = match direction { Direction::Patched => "the switch to hosted patches", Direction::Upstream => "the switch back to the upstream registry", @@ -768,13 +774,17 @@ async fn installed_with_archives(common: &GlobalArgs, purls: &[String]) -> Vec, } -/// After a hosted unwind restored the gems `restored` to their upstream +/// After a hosted unwind restored the gems of `pins` to their upstream /// entries: bring their installed copies and cached archives back to the /// upstream gem, and report what is still the patched build. `staged` is /// the restore's staged text (the restored lock). Only installed copies /// are reported as still stale here: the restore itself names an archive /// left in Bundler's cache dir (`upstream_gem_stale_cache`). +/// +/// `pins` is the patch uuids each restored gem was pinned to, by purl. An +/// installed copy whose gem home keeps no archive of it (a pruned `cache/`: +/// Bundler 4.1's `prune`, a slim image, `gem cleanup`) is judged by those +/// patches' records, as the hosted scan judges it (#2092): see +/// [`PinJudge`]. `api` is the run's API client, built only if such a copy +/// needs a record. pub(crate) async fn after_restore( common: &GlobalArgs, - restored: &[String], staged: &BTreeMap>, + pins: &BTreeMap>, + api: &RunApiClient, ) -> RestoreRefresh { - refresh_restored(common, restored, staged, &BTreeMap::new(), Scope::All).await + let judge = PinJudge { + common, + api, + pins, + fetched: BTreeMap::new(), + unreachable: false, + }; + let restored: Vec = pins.keys().cloned().collect(); + refresh_restored( + common, + &restored, + staged, + &BTreeMap::new(), + Some(judge), + Scope::All, + ) + .await +} + +/// The patch record a `/patches/view/` response gives for `uuid`; +/// `None` when it has none to judge by (no such patch, another patch's +/// record, or one listing no files). +pub(crate) fn view_record( + view: Option, + uuid: &str, +) -> Option { + view.map(|view| socket_patch_core::manifest::records::record_from_patch_response(&view).1) + .filter(|record| record.uuid == uuid && !record.files.is_empty()) +} + +/// Why a hosted unwind has no patch record to judge an installed copy by. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum NoRecord { + /// `--offline`: nothing is fetched. + Offline, + /// The fetch failed, or was not tried after one the API did not answer. + Unfetched, + /// The API answered, with no record of that patch to judge by (a + /// withdrawn patch, one listing no files). + NotServed, +} + +/// What judges the installed copies a hosted unwind's archive check cannot +/// (#2092): those whose gem home keeps no readable `/cache/.gem`. +/// Nothing else tells such a copy from the patched build the hosted scan +/// may have replaced it with, and no later `bundle install` replaces it. +/// Each is judged on its own files, by the record of a patch its gem was +/// pinned to (`pins`): a copy whose files all hash to a record's +/// `afterHash` values holds that patch. +struct PinJudge<'a> { + common: &'a GlobalArgs, + api: &'a RunApiClient, + pins: &'a BTreeMap>, + /// The record fetched for each uuid asked for so far, or why there is + /// none. + fetched: BTreeMap>, + /// A request got no answer from the API (a network error, a timeout): + /// no other is sent, so an API out of reach costs one timeout, not one + /// per gem. + unreachable: bool, +} + +impl PinJudge<'_> { + /// `uuid`'s patch record, fetched at most once. + async fn record(&mut self, uuid: &str) -> Result<&PatchRecord, NoRecord> { + use socket_patch_core::api::client::ApiError; + if !self.fetched.contains_key(uuid) { + let record = if self.common.offline { + Err(NoRecord::Offline) + } else if self.unreachable { + Err(NoRecord::Unfetched) + } else { + let api = self.common.api_client(self.api).await; + match api.fetch_patch(uuid).await { + Ok(view) => view_record(view, uuid).ok_or(NoRecord::NotServed), + Err(e) => { + self.unreachable = matches!(e, ApiError::Network(_)); + Err(NoRecord::Unfetched) + } + } + }; + self.fetched.insert(uuid.to_string(), record); + } + match self.fetched.get(uuid) { + Some(Ok(record)) => Ok(record), + Some(Err(why)) => Err(*why), + None => Err(NoRecord::Unfetched), + } + } + + /// The installed copies of `purls` with no readable archive in their + /// gem home: those that hold a pinned patch (stale), and those nothing + /// could judge, each with why (the reason completes "could not be + /// checked against the upstream gem (…)"). A copy is neither when a + /// record judged it and found files that are not its patch's, and no + /// other pin of its gem is left unjudged. A run with no such copy + /// fetches nothing. + async fn probe(&mut self, purls: &[String]) -> (Vec, Vec<(StaleGem, String)>) { + use socket_patch_core::vendor::file_sha256_hex; + use socket_patch_core::vex::verify::judge_installed_record; + + let (mut stale, mut unjudged) = (Vec::new(), Vec::new()); + for copy in installed_with_archives(self.common, purls).await { + // The same test as `stale_after_restore`'s: an archive it can + // hash is its to judge the copy by. + if file_sha256_hex(©.archive).await.is_some() { + continue; + } + // Why the copy is not known to be free of a pinned patch: a pin + // with no record, or a record whose files could not be read. + let (mut patched, mut open) = (false, None); + for uuid in self.pins.get(©.purl).into_iter().flatten() { + match self.record(uuid).await { + Ok(record) => { + let judged = judge_installed_record(©.dir, record).await; + if judged.patched { + patched = true; + break; + } + if !judged.stale_evidence { + open.get_or_insert( + "the files its patch record lists could not be read", + ); + } + } + Err(why) => { + open.get_or_insert(match why { + NoRecord::Offline => { + "`--offline` is set, so its patch record was not fetched" + } + NoRecord::Unfetched => "its patch record could not be fetched", + NoRecord::NotServed => "the patch API has no record of its patch", + }); + } + } + } + let gem = StaleGem { + purl: copy.purl, + leaf: copy.leaf, + installed: Some((copy.dir, copy.project_local)), + cache_archive: None, + in_place: false, + }; + match (patched, open) { + (true, _) => stale.push(gem), + (false, Some(why)) => { + unjudged.push((gem, format!("its gem home has no archive of it and {why}"))) + } + (false, None) => {} + } + } + (stale, unjudged) + } } /// After a wet vendored unwind put the gems `unwound` back on their @@ -985,6 +1155,7 @@ pub(crate) async fn after_vendored_unwind( &installed, &BTreeMap::new(), records, + None, Scope::Installed, ) .await @@ -995,6 +1166,7 @@ async fn refresh_restored( restored: &[String], staged: &BTreeMap>, records: &BTreeMap, + mut pin_judge: Option>, scope: Scope, ) -> RestoreRefresh { use socket_patch_core::patch::redirect::upstream::{ @@ -1016,6 +1188,10 @@ async fn refresh_restored( // error, under a lock without `CHECKSUMS`): it is then reported, not // refreshed. let mut judged: BTreeMap = BTreeMap::new(); + // The gems a hosted unwind's [`PinJudge`] covers. Each is back on its + // upstream entry, whatever remote that is and whether or not anything + // proves the upstream sha256: the restore that ran says so. + let mut pinned: Vec = Vec::new(); for purl in restored .iter() .filter(|p| Ecosystem::from_purl(p) == Some(Ecosystem::Gem)) @@ -1037,6 +1213,9 @@ async fn refresh_restored( 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.) @@ -1049,17 +1228,28 @@ async fn refresh_restored( judged.insert(purl.clone(), record.clone()); } } + if pin_judge.is_some() { + pinned.push(purl.clone()); + } } } } - if shas.is_empty() && unverified.is_empty() && judged.is_empty() { + if shas.is_empty() && unverified.is_empty() && judged.is_empty() && pinned.is_empty() { return RestoreRefresh::default(); } - let stale = stale_after_restore(common, &shas, &judged, scope).await; + // A hosted unwind's copies with no archive to judge them by: stale + // when they hold a pinned patch, reported when no record says (#2092). + let (pin_stale, no_record) = match &mut pin_judge { + Some(judge) => judge.probe(&pinned).await, + None => Default::default(), + }; + 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 unchecked = stale_after_restore(common, &unjudged, &BTreeMap::new(), Scope::Installed).await; - if stale.is_empty() && unchecked.is_empty() { + if stale.is_empty() && unchecked.is_empty() && no_record.is_empty() { return RestoreRefresh::default(); } let wanted = |gem: &StaleGem| { @@ -1080,7 +1270,12 @@ async fn refresh_restored( }; let mut pass = attempt(&stale, wanted, &source, &policy, direction).await; let still = if pass.changed(&policy) { - stale_after_restore(common, &shas, &judged, scope).await + let mut still = stale_after_restore(common, &shas, &judged, scope).await; + // (A copy no record judged is not one the pass could change.) + if let Some(judge) = pin_judge.as_mut().filter(|_| pin_stale_any) { + still.extend(judge.probe(&pinned).await.0); + } + still } else { stale }; @@ -1092,7 +1287,9 @@ async fn refresh_restored( .refreshed .iter() .filter(|(purl, target)| { - matches!(target, Target::Installed(_)) && !installed.iter().any(|gem| &gem.purl == purl) + matches!(target, Target::Installed(_)) + && !installed.iter().any(|gem| &gem.purl == purl) + && !no_record.iter().any(|(gem, _)| &gem.purl == purl) }) .map(|(purl, _)| purl.clone()) .collect(); @@ -1103,6 +1300,12 @@ async fn refresh_restored( installed.push(gem); } } + for (gem, why) in no_record { + if let Some((dir, _)) = &gem.installed { + pass.left.insert(dir.clone(), Why::Unverified(why)); + installed.push(gem); + } + } RestoreRefresh { refreshed_installs, report: report(direction, &installed, &pass, &policy), @@ -1302,6 +1505,171 @@ mod tests { assert!(out.summary.is_none()); } + /// A gem with a copy known to be stale in one gem home and a copy + /// that could not be checked in another is counted once, as stale: + /// the headline never drops a copy known to hold the patched build. + #[tokio::test] + async fn a_gem_with_a_stale_copy_and_an_unchecked_one_counts_as_stale() { + let tmp = tempfile::tempdir().unwrap(); + let stale = installed("rack", &tmp.path().join("vendor/bundle/ruby/3.4.0"), true); + let unchecked = installed("rack", &tmp.path().join("gems/ruby/3.4.0"), true); + let policy = policy(tmp.path(), true, false, false); + let mut pass = attempt( + std::slice::from_ref(&stale), + unobtainable, + &Source::DiskOnly, + &policy, + Direction::Upstream, + ) + .await; + let (dir, _) = unchecked.installed.clone().unwrap(); + pass.left + .insert(dir, Why::Unverified("no record".to_string())); + + let out = report(Direction::Upstream, &[stale, unchecked], &pass, &policy); + assert_eq!(out.warnings.len(), 2); + let summary = out.summary.expect("a summary"); + assert_eq!( + summary.headline, + "1 gem still holds the patched build on disk after the switch back to the upstream \ + registry" + ); + assert_eq!(summary.bullets.len(), 2, "{:?}", summary.bullets); + } + + /// #2092: [`PinJudge`] judges each installed copy with no archive in + /// its gem home on its own files, by the record of any patch its gem + /// was pinned to. A copy with its archive is the archive check's. + #[tokio::test] + async fn pin_judge_judges_an_archiveless_copy_by_any_of_its_pins() { + use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes as git_sha; + use socket_patch_core::manifest::schema::PatchFileInfo; + + const PURL: &str = "pkg:gem/rack@1.0.0"; + let record = |uuid: &str, after: &str| PatchRecord { + uuid: uuid.to_string(), + exported_at: String::new(), + files: [( + "lib/rack.rb".to_string(), + PatchFileInfo { + before_hash: git_sha(b"upstream\n"), + after_hash: git_sha(after.as_bytes()), + }, + )] + .into(), + vulnerabilities: Default::default(), + description: String::new(), + license: String::new(), + tier: String::new(), + }; + // A project whose own gem home holds `rack 1.0.0` with `lib`. + let project = |lib: &str, archive: bool| { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("vendor/bundle/ruby/3.4.0"); + let gem = home.join("gems/rack-1.0.0"); + std::fs::create_dir_all(gem.join("lib")).unwrap(); + std::fs::write(gem.join("lib/rack.rb"), lib).unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write( + home.join("specifications/rack-1.0.0.gemspec"), + "Gem::Specification.new do |s|\n s.name = \"rack\"\n s.version = \"1.0.0\"\nend\n", + ) + .unwrap(); + if archive { + std::fs::create_dir_all(home.join("cache")).unwrap(); + std::fs::write(home.join("cache/rack-1.0.0.gem"), b"archive").unwrap(); + } + tmp + }; + let pins = BTreeMap::from([( + PURL.to_string(), + vec!["uuid-a".to_string(), "uuid-b".to_string()], + )]); + // `--offline`: only the records seeded below are there to judge by. + let probe = |tmp: &tempfile::TempDir, fetched: Vec<(&str, Option)>| { + let fetched = fetched + .into_iter() + .map(|(uuid, record)| (uuid, record.ok_or(NoRecord::NotServed))); + let common = GlobalArgs { + cwd: tmp.path().to_path_buf(), + offline: true, + ..GlobalArgs::default() + }; + let pins = pins.clone(); + let fetched: BTreeMap> = fetched + .map(|(uuid, record)| (uuid.to_string(), record)) + .collect(); + async move { + let api = RunApiClient::new(); + let mut judge = PinJudge { + common: &common, + api: &api, + pins: &pins, + fetched, + unreachable: false, + }; + let (stale, unjudged) = judge.probe(&[PURL.to_string()]).await; + assert!(api.get().is_none(), "an offline probe builds no client"); + (stale.len(), unjudged) + } + }; + let (a, b) = (record("uuid-a", "patch a\n"), record("uuid-b", "patch b\n")); + let both = || vec![("uuid-a", Some(a.clone())), ("uuid-b", Some(b.clone()))]; + + // The copy holds the second pin's patch. + let tmp = project("patch b\n", false); + let (stale, unjudged) = probe(&tmp, both()).await; + assert_eq!((stale, unjudged.len()), (1, 0)); + + // Every record judged it, and it holds neither patch. + let tmp = project("upstream\n", false); + let (stale, unjudged) = probe(&tmp, both()).await; + assert_eq!((stale, unjudged.len()), (0, 0)); + + // One pin has no record, and the other's patch is not the copy's: + // nothing says the copy is not the first pin's patched build. + let (stale, unjudged) = probe(&tmp, vec![("uuid-b", Some(b.clone()))]).await; + assert_eq!((stale, unjudged.len()), (0, 1)); + assert_eq!( + unjudged[0].1, + "its gem home has no archive of it and `--offline` is set, so its patch record \ + was not fetched" + ); + + // A record that proves the patch settles it, whatever is missing. + let tmp = project("patch b\n", false); + let (stale, unjudged) = probe(&tmp, vec![("uuid-b", Some(b.clone()))]).await; + assert_eq!((stale, unjudged.len()), (1, 0)); + + // The API has no record of one pin's patch: the reason says so. + let tmp = project("upstream\n", false); + let (_, unjudged) = probe(&tmp, vec![("uuid-a", None), ("uuid-b", Some(b.clone()))]).await; + assert_eq!( + unjudged[0].1, + "its gem home has no archive of it and the patch API has no record of its patch" + ); + + // A record judges only files it could read: a copy without the file + // the record lists is not known to be free of the patch. + std::fs::remove_file( + tmp.path() + .join("vendor/bundle/ruby/3.4.0/gems/rack-1.0.0/lib/rack.rb"), + ) + .unwrap(); + let (stale, unjudged) = probe(&tmp, both()).await; + assert_eq!(stale, 0); + assert_eq!( + unjudged[0].1, + "its gem home has no archive of it and the files its patch record lists could not \ + be read" + ); + + // A copy with its archive is judged by the archive, not here. + let tmp = project("patch b\n", true); + let (stale, unjudged) = probe(&tmp, both()).await; + assert_eq!((stale, unjudged.len()), (0, 0)); + } + /// A project-local copy the refresh could not fix says why and names /// the two files whose removal makes Bundler fetch the gem. #[tokio::test] diff --git a/crates/socket-patch-cli/src/commands/hosted_unwind.rs b/crates/socket-patch-cli/src/commands/hosted_unwind.rs index 20c451fdb..cfe31abfd 100644 --- a/crates/socket-patch-cli/src/commands/hosted_unwind.rs +++ b/crates/socket-patch-cli/src/commands/hosted_unwind.rs @@ -5,7 +5,7 @@ use socket_patch_core::patch::redirect::upstream::HostedPin; -use crate::args::GlobalArgs; +use crate::args::{GlobalArgs, RunApiClient}; /// What the hosted leg did. #[derive(Default)] @@ -65,6 +65,8 @@ pub(crate) fn patch_server_origins_of(patch_server_url: Option<&str>) -> Vec = outcome + // Each restored gem with the patches it was pinned to. + let mut pins: std::collections::BTreeMap> = Default::default(); + for pin in outcome .restored() .filter(|pin| pin.purl.starts_with("pkg:gem/")) - .map(|pin| pin.purl.clone()) - .collect(); - if restored.is_empty() { + { + pins.entry(pin.purl.clone()) + .or_default() + .push(pin.uuid.clone()); + } + if pins.is_empty() { return; } - let refresh = after_restore(common, &restored, &outcome.staged_text).await; + let refresh = after_restore(common, &outcome.staged_text, &pins, api).await; out.warnings.retain(|(code, detail)| { code != GEM_STALE_CACHE || !refresh @@ -128,8 +136,14 @@ async fn refresh_restored_gems( /// Restore the in-scope hosted pins to their default upstream registry /// entries (core `patch::redirect::upstream`): v5 hosted mode keeps no /// ledger, so each pin's lock entry is re-resolved from the registry, and a -/// pin that cannot be is refused with the `git checkout` remedy. -pub(crate) async fn run_hosted_leg(common: &GlobalArgs, pins: &[HostedPin]) -> HostedLegOutcome { +/// pin that cannot be is refused with the `git checkout` remedy. `api` is +/// the run's API client, built only when the gem leg needs a patch record +/// (see `refresh_restored_gems`). +pub(crate) async fn run_hosted_leg( + common: &GlobalArgs, + pins: &[HostedPin], + api: &RunApiClient, +) -> HostedLegOutcome { use socket_patch_core::patch::redirect::upstream::{ restore_upstream, PinStatus, RestoreOptions, }; @@ -267,7 +281,7 @@ pub(crate) async fn run_hosted_leg(common: &GlobalArgs, pins: &[HostedPin]) -> H // names: bring the project's installed copies and cached archives // of the restored gems back to the upstream gem, and say what is // still the patched build. - refresh_restored_gems(common, &outcome, &mut out).await; + refresh_restored_gems(common, &outcome, &mut out, api).await; } let unwound: Vec<_> = vlt_targets .into_iter() diff --git a/crates/socket-patch-cli/src/commands/remove.rs b/crates/socket-patch-cli/src/commands/remove.rs index 1a79c5247..d5fcbbd3e 100644 --- a/crates/socket-patch-cli/src/commands/remove.rs +++ b/crates/socket-patch-cli/src/commands/remove.rs @@ -577,7 +577,14 @@ pub async fn run(args: RemoveArgs) -> i32 { // per-purl exit path (restoring the upstream entry IS the removal). let hosted_matches = hosted_pins_matching(&hosted_pins, &target, &[]); if !hosted_matches.is_empty() { - return remove_hosted_only(&args, hosted_matches, &telemetry, commit_recovery).await; + return remove_hosted_only( + &args, + hosted_matches, + &telemetry, + commit_recovery, + &api_client, + ) + .await; } let msg = format!("No patch found matching identifier: {}", args.identifier); @@ -943,7 +950,7 @@ pub async fn run(args: RemoveArgs) -> i32 { if !args.skip_rollback { let hosted_matches = hosted_pins_matching(&hosted_pins, &target, &matched_keys); if !hosted_matches.is_empty() { - let leg = match unwind_hosted(&args.common, &hosted_matches).await { + let leg = match unwind_hosted(&args.common, &hosted_matches, &api_client).await { Ok(leg) => { hosted_leg_warnings.extend(leg.warnings.iter().cloned()); leg @@ -1603,8 +1610,9 @@ async fn sweep_target_orphans( async fn unwind_hosted( common: &GlobalArgs, hosted_matches: &[HostedPin], + api_client: &RunApiClient, ) -> Result { - let leg = run_hosted_leg(common, hosted_matches).await; + let leg = run_hosted_leg(common, hosted_matches, api_client).await; // Printed as soon as the leg returns, so a human run that then fails // still says what it did to the files. print_run_warnings(common, &leg.warnings); @@ -1674,6 +1682,7 @@ async fn remove_hosted_only( hosted_matches: Vec, telemetry: &TelemetryAuth, commit_recovery: Option, + api_client: &RunApiClient, ) -> i32 { let loud = !args.common.json && !args.common.silent; if args.skip_rollback { @@ -1726,7 +1735,7 @@ async fn remove_hosted_only( return 0; } - let leg = match unwind_hosted(&args.common, &hosted_matches).await { + let leg = match unwind_hosted(&args.common, &hosted_matches, api_client).await { Ok(leg) => leg, Err(err) => { track_patch_remove_failed("hosted redirect revert failed", telemetry).await; diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index a146c5bbd..1822eb803 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -2389,7 +2389,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { .filter(|pin| hosted_scope.contains(&pin.purl)) .cloned() .collect(); - let hosted_leg = run_hosted_leg(&args.common, &in_scope).await; + let hosted_leg = run_hosted_leg(&args.common, &in_scope, &api_client).await; // An unscoped rollback promises to unwind EVERY hosted patch: // contested wiring it cannot restore fails the leg (a scoped run // names its own targets and leaves unrelated wiring alone). diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index b60266f5c..2cbaaaa08 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -245,11 +245,7 @@ impl<'a> ViewFallback<'a> { .fetch_patch(uuid) .await .ok() - .flatten() - .map(|view| { - socket_patch_core::manifest::records::record_from_patch_response(&view).1 - }) - .filter(|record| record.uuid == uuid && !record.files.is_empty()), + .and_then(|view| gem_refresh::view_record(view, uuid)), None => None, }; self.fetched.insert(uuid.to_string(), record); diff --git a/crates/socket-patch-cli/src/commands/scan/withdrawn.rs b/crates/socket-patch-cli/src/commands/scan/withdrawn.rs index c9b711797..7c65359b6 100644 --- a/crates/socket-patch-cli/src/commands/scan/withdrawn.rs +++ b/crates/socket-patch-cli/src/commands/scan/withdrawn.rs @@ -246,7 +246,10 @@ pub(super) async fn sweep( }; let to_restore: Vec = gone.iter().map(|(pin, _)| pin.clone()).collect(); - let leg = crate::commands::hosted_unwind::run_hosted_leg(common, &to_restore).await; + // The scan's own client, for a patch record the gem leg may need. + let run_client = crate::args::RunApiClient::new_with(Some(api_client.clone())); + let leg = + crate::commands::hosted_unwind::run_hosted_leg(common, &to_restore, &run_client).await; out.half_restored = leg.half_applied().map(str::to_string); let action = if common.dry_run { diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 19c3557ef..8a9469eb2 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -4910,7 +4910,12 @@ async fn run_revert(args: &VendorArgs, env: &mut Envelope) -> i32 { .filter(|pin| reverted.contains(&PurlKey::new(&pin.purl))) .collect(); if !rehosted.is_empty() { - let leg = crate::commands::hosted_unwind::run_hosted_leg(common, &rehosted).await; + let leg = crate::commands::hosted_unwind::run_hosted_leg( + common, + &rehosted, + &crate::args::RunApiClient::new(), + ) + .await; for purl in &leg.reverted { record_warning( env, 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 f4d1b93f5..099c72bd1 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -5270,6 +5270,103 @@ async fn gem_hosted_unwind_names_a_patched_archive_in_vendor_cache() { } } +/// #2092 against a real Bundler: the gem home has no `cache/` dir (Bundler +/// 4.1's `prune` setting, the `rm -rf "${BUNDLE_PATH}"/ruby/*/cache` of the +/// Dockerfile Rails generates), so the unwind has no archive to judge the +/// installed patched gem by. It judges the copy by the pin's patch record +/// and puts the upstream gem back. Left alone, `bundle install` would call +/// the bundle complete and keep the patched copy under the upstream lock. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 1.17; CHECKSUMS arm >= 2.6); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_unwind_restores_an_install_whose_home_cache_was_pruned() { + let Some(fx) = redirect_scanned_project( + "pruned-unwind", + Spelling::Gemfile, + false, + true, + None, + Driver::ScanVex, + ) + .await + else { + return; + }; + for command in ["rollback", "remove"] { + let dir = stage_fresh_checkout(&fx, &format!("pruned-{command}")); + let install = bundle(&dir, &["install"]); + assert!( + install.status.success(), + "{command}: hosted install:\n{}", + String::from_utf8_lossy(&install.stderr) + ); + let installed = fresh_installed_lib(&dir, &format!("{DEP}-{DEP_VERSION}"), "vuln_gem.rb"); + assert_eq!( + std::fs::read(&installed).unwrap(), + fx.patched, + "{command}: the patched gem is installed (test premise)" + ); + // /gems//lib/ + let home = installed.ancestors().nth(4).unwrap(); + std::fs::remove_dir_all(home.join("cache")).unwrap(); + + let api = fx._server.uri(); + let upstream = format!("{api}/upstream"); + let cwd = dir.to_str().expect("utf8 tmp path"); + let mut argv = vec![command, PURL, "--json", "--cwd", cwd]; + if command == "remove" { + argv.push("--yes"); + } + argv.extend([ + "--api-url", + &api, + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + &api, + ]); + let (code, stdout, stderr) = + run_socket_env(&dir, &argv, &[("SOCKET_RUBYGEMS_URL", &upstream)]); + let env: serde_json::Value = serde_json::from_str(&stdout).unwrap_or_else(|e| { + panic!("{command}: not JSON: {e}\nstdout:\n{stdout}\nstderr:\n{stderr}") + }); + assert_eq!(code, 0, "{command}: {env}\nstderr:\n{stderr}"); + let lock = std::fs::read_to_string(dir.join(fx.lock_name)).unwrap(); + assert!( + !lock.contains(&fx.index_url), + "{command}: the lock is back on upstream:\n{lock}" + ); + assert_eq!( + std::fs::read(&installed).unwrap(), + orig_lib().into_bytes(), + "{command}: the installed gem is the upstream one again: {env}" + ); + assert!( + env.to_string().contains("upstream_gem_install_refreshed") + && !env.to_string().contains("upstream_gem_stale_install"), + "{command}: {env}" + ); + assert!( + !home.join("cache").exists(), + "{command}: a pruned cache dir is not created" + ); + // The restored project installs as it is, and keeps the upstream gem. + let install = bundle(&dir, &["install"]); + assert!( + install.status.success(), + "{command}: bundle install after the unwind:\n{}", + String::from_utf8_lossy(&install.stderr) + ); + assert_eq!( + std::fs::read(&installed).unwrap(), + orig_lib().into_bytes(), + "{command}: bundle install keeps the upstream bytes" + ); + } +} + /// A warm project: the pre-redirect pair installed from the mock upstream /// into the project's `vendor/bundle`, as on a developer machine or a CI /// job with a restored bundle cache. 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 e1045f6ec..65ff715e9 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 @@ -2663,6 +2663,322 @@ async fn refused_registry_leaves_the_copy_reported(cached_archive: bool) { ); } +/// The commands that unwind a hosted gem. +const HOSTED_UNWINDS: [&[&str]; 2] = [&["rollback", "--yes"], &["remove", PURL, "--yes"]]; + +/// A project whose gem a hosted scan pinned, with the lock as `bundle +/// install` leaves it, in a gem home that has no `cache/` dir (Bundler +/// 4.1's `prune` setting, the `rm -rf "${BUNDLE_PATH}"/ruby/*/cache` of the +/// Dockerfile Rails generates, `gem cleanup`). With `refreshed` the scan +/// replaced the installed copy with the patched build; without, it was told +/// not to (`--no-gem-install-refresh`) and the copy is still the upstream +/// one. Returns the installed gem dir and the gem home. +async fn hosted_with_pruned_home_cache( + server: &MockServer, + proj: &Path, + refreshed: bool, +) -> (PathBuf, PathBuf) { + std::fs::create_dir_all(proj).unwrap(); + write_manifest_pair(proj); + let home = project_home(proj); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let uri = server.uri(); + let flags: &[&str] = if refreshed { + &["--json"] + } else { + &["--json", "--no-gem-install-refresh"] + }; + let (code, _, stderr) = common::run_with_env(proj, &scan_args(proj, &uri, flags), &[]); + assert_eq!(code, 0, "{stderr}"); + let expected = if refreshed { PATCHED_LIB } else { UPSTREAM_LIB }; + assert_eq!(installed_lib(&gem_dir), expected, "premise"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + std::fs::remove_dir_all(home.join("cache")).unwrap(); + (gem_dir, home) +} + +/// Every `detail` (a warning's) or `reason` (an event's) that `--json` +/// output carries under `code`, wherever the command puts it. +fn details_with_code(env: &serde_json::Value, code: &str) -> Vec { + fn walk(value: &serde_json::Value, code: &str, out: &mut Vec) { + match value { + serde_json::Value::Object(map) => { + if map + .get("code") + .or(map.get("errorCode")) + .and_then(|c| c.as_str()) + == Some(code) + { + let detail = map.get("detail").or(map.get("reason")); + out.push( + detail + .and_then(|d| d.as_str()) + .unwrap_or_default() + .to_string(), + ); + } + map.values().for_each(|v| walk(v, code, out)); + } + serde_json::Value::Array(items) => items.iter().for_each(|v| walk(v, code, out)), + _ => {} + } + } + let mut out = Vec::new(); + walk(env, code, &mut out); + out +} + +/// #2092: a gem home with no `cache/` dir has no archive to judge the +/// installed copy by. The hosted unwind judges it by the pin's patch record +/// instead, as the scan does in that home, and puts the upstream gem back: +/// otherwise the app keeps loading the patch under the restored lock, and +/// no later `bundle install` changes that. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_restores_an_install_whose_home_cache_was_pruned() { + for command in HOSTED_UNWINDS { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; + let views_before = view_requests(&server).await; + + let mut args = command.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("{command:?}: not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "{command:?}: {env}\n{stderr}"); + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + assert!(!lock.contains("/patch-registry/"), "{command:?}:\n{lock}"); + assert_eq!( + installed_lib(&gem_dir), + UPSTREAM_LIB, + "{command:?}: the upstream gem is back: {env}" + ); + assert_eq!( + details_with_code(&env, "upstream_gem_install_refreshed").len(), + 1, + "{command:?}: {env}" + ); + assert!( + details_with_code(&env, "upstream_gem_stale_install").is_empty(), + "{command:?}: nothing is left on the patched build: {env}" + ); + assert!( + !home.join("cache").exists(), + "{command:?}: a pruned cache dir is not created" + ); + assert_eq!( + view_requests(&server).await - views_before, + 1, + "{command:?}: one patch record, for that pin" + ); + } +} + +/// The same in a human run: the refresh is a progress line, and the gem is +/// not counted among the packages that keep their patched bytes. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_reports_the_pruned_home_refresh_in_a_human_run() { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = hosted_with_pruned_home_cache(&server, &proj, true).await; + + // A dry run says what it would do and changes nothing. + let would = format!( + "Would replace the installed copy of 1 gem with the upstream build: {DEP} {DEP_VERSION}." + ); + let (code, stdout, stderr) = + unwind_run(&proj, &server.uri(), &["rollback", "--yes", "--dry-run"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&would), "{stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "Replaced the installed copy of 1 gem with the upstream build: {DEP} {DEP_VERSION}." + )), + "{stdout}\n{stderr}" + ); + assert!( + !stdout.contains("patched bytes") && !stderr.contains("still"), + "nothing is left to reinstall:\n{stdout}\n{stderr}" + ); +} + +/// #2092: when no patch record can be had for such a copy (the API fails), +/// nothing tells it from the patched build. It is left as it is and named +/// as a copy that could not be checked, with the reason and the files to +/// remove: never passed over in silence. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_names_a_pruned_home_install_no_record_can_judge() { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + // The view answers 500. + mount_api_for(&server, Some(0), &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; + let before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); + + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes", "--json"]); + 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!(snapshot(&home), before, "left as it is"); + assert!( + details_with_code(&env, "upstream_gem_install_refreshed").is_empty(), + "{env}" + ); + assert!( + gem_downloads_since(&server, asked_before).await.is_empty(), + "no gem was downloaded for a copy nothing judged" + ); + let unchecked = details_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(unchecked.len(), 1, "the copy is reported: {env}"); + let spec = home + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}.gemspec")); + for needle in [ + PURL, + "could not be checked against the upstream gem", + "its gem home has no archive of it and its patch record could not be fetched", + "it still holds the patched build", + "run `bundle install`", + gem_dir.to_str().unwrap(), + spec.to_str().unwrap(), + ] { + assert!( + unchecked[0].contains(needle), + "missing {needle:?}: {}", + unchecked[0] + ); + } + + // A human run counts it apart, in one warning. + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + hosted_with_pruned_home_cache(&server, &proj, true).await; + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stderr.contains("1 gem on disk could not be checked") + && stderr.contains("its patch record could not be fetched"), + "{stdout}\n{stderr}" + ); +} + +/// #2092 where nothing proves the upstream gem's sha256 (a lock without +/// `CHECKSUMS`, with `--offline` or a registry that does not answer): the +/// copy cannot be replaced, but it is not passed over. Offline no record is +/// fetched and the copy is named as one that could not be checked; with the +/// API in reach the record proves it patched and it is named as stale. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_names_a_pruned_home_install_with_no_upstream_sha256() { + for (offline, needles) in [ + ( + true, + [ + "could not be checked against the upstream gem", + "`--offline` is set, so its patch record was not fetched", + ], + ), + ( + false, + [ + "its patched install at", + "nothing pins the sha256 of the upstream gem", + ], + ), + ] { + let server = MockServer::start().await; + let patched = real_gem(PATCHED_LIB); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + // No rubygems.org stand-in: the compact index is a 404. + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; + let before = snapshot(&home); + let views_before = view_requests(&server).await; + + let mut args = vec!["rollback", "--yes", "--json"]; + if offline { + args.push("--offline"); + } + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("offline={offline}: not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "offline={offline}: {env}\n{stderr}"); + assert_eq!(snapshot(&home), before, "offline={offline}: left as it is"); + let left = details_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(left.len(), 1, "offline={offline}: reported: {env}"); + for needle in + needles + .into_iter() + .chain([PURL, "run `bundle install`", gem_dir.to_str().unwrap()]) + { + assert!( + left[0].contains(needle), + "offline={offline}: missing {needle:?}: {}", + left[0] + ); + } + assert_eq!( + view_requests(&server).await - views_before, + usize::from(!offline), + "offline={offline}: an offline run fetches no record" + ); + } +} + +/// The record judges, it does not assume: an installed copy that is still +/// the upstream gem (the scan was told not to refresh it) is left alone in +/// a home with no `cache/` dir too, with no warning and no gem download. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_leaves_an_upstream_install_in_a_pruned_home_alone() { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (_, home) = hosted_with_pruned_home_cache(&server, &proj, false).await; + let before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); + + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes", "--json"]); + 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!(snapshot(&home), before, "nothing changed"); + assert!( + details_with_code(&env, "upstream_gem_install_refreshed").is_empty() + && details_with_code(&env, "upstream_gem_stale_install").is_empty(), + "{env}" + ); + assert!( + gem_downloads_since(&server, asked_before).await.is_empty(), + "no gem was downloaded" + ); +} + /// The vendored half of the patch API for the fixture's patch: the grant /// names the patched `.gem` and the stub gemspec a path source loads, each /// with its sha512, beside the hosted registry override. Priority 1, so it diff --git a/docs/ecosystems.md b/docs/ecosystems.md index c8f89d538..761b7823f 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2030,6 +2030,11 @@ with a native extension is installed into a staging directory by RubyGems, with owns the installed copy, and swapped in once it has compiled; with no such Ruby, or with `--no-gem-native-rebuild`, it is left alone. After the scan `bundle exec` runs the patched code, and every kind of reinstall keeps it. `rollback` and `remove` do the same with the upstream gem. +That holds in a gem home with no `cache/` directory too (Bundler 4.1's `prune` setting, an image +that deletes it, `gem cleanup`): with no archive to compare, the installed files are checked +against the patch itself, in both directions. If the patch can't be looked up during a `rollback` +or `remove`, the copy is left alone and the run warns (`upstream_gem_stale_install`), naming the +files to remove before `bundle install`. Vendoring a gem that was hosted (`vendor`, `scan --mode vendored`) leaves the installed copies as they are: Bundler loads the vendored copy from then on. When that vendored gem is later unwound (`rollback`, `remove`, `vendor --revert`), Bundler loads the installed copy again, so the unwind