diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 74e5e02d1..4f7754aa6 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -460,7 +460,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm *What never refreshes.* A hosted → vendored takeover (`vendor`, `scan` / `get --mode vendored` over a hosted pin) puts the gem on its upstream entry only on its way to the vendored `path:` source, which is what Bundler loads from then on. The copies Bundler already holds are unused leftovers there, so the takeover changes none of them and downloads no gem for them: resetting the installed copy to the upstream build would cost a registry download in the mode that needs none, and would turn a patched leftover into an unpatched one that `vex` reports against the vendored artifact (`vendored_tree_out_of_sync`, whose gem wording names the copy and how to remove it). Its `upstream_gem_stale_cache` advisory about a patched cache-dir archive is as before. A vendored unwind (`remove`, `rollback`, `vendor --revert`, `scan --prune`, `vendor`'s reconcile of a vendored gem) likewise only names that archive, and never replaces it. -*A vendored unwind after a hosted scan.* Once a vendored gem is unwound, Bundler loads its installed copy again, so the leftover is in use: if a hosted scan made that copy the patched build before the gem was vendored, the patched code would keep running under the upstream lock, and on bundler ≥ 2.6 `bundle pristine` would fail on the upstream checksum. A wet `rollback`, `remove`, `vendor --revert` or `vendor` reconcile that put a vendored gem back on its upstream entry therefore applies the unwind direction's refresh to the gem's INSTALLED copies when the lock now resolves the gem from rubygems.org (a gem from another remote is not judged: nothing proves its entry is the upstream one), under the same rules (staleness judged by `/cache/.gem` against the upstream sha256; a project-local gem home only, unless `--gem-refresh-shared`; `--no-gem-install-refresh`; an archive on disk, else rubygems.org unless `--offline`), with the same `upstream_gem_install_refreshed` note and `upstream_gem_stale_install` warning. `--json` carries them where the command carries a vendored revert's advisories (rollback `warnings[]`; `remove` / `vendor` advisory events); a human run prints the progress line after the gem's own line and one warning for the gems left on the patched build. The upstream sha256 is looked up only for a gem that has an installed copy with its archive, so the unwind of a gem that is not installed needs no network. A gem that was only ever vendored has the upstream archive there: nothing is downloaded or changed. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry is refused (a plain-`http` `SOCKET_RUBYGEMS_URL`, see the unwind direction), such an installed copy is reported as one that could not be checked, whichever of the two it is: nothing tells them apart. A `--dry-run` does not preview this (the lock on disk is still the vendored one), and `scan --prune` does not refresh. +*A vendored unwind after a hosted or an agent scan.* Once a vendored gem is unwound, Bundler loads its installed copy again, so the leftover is in use: if a hosted scan made that copy the patched build before the gem was vendored, the patched code would keep running under the upstream lock, and on bundler ≥ 2.6 `bundle pristine` would fail on the upstream checksum. If agent mode patched that copy in place before the gem was vendored (#2093), the takeover moved its manifest record into the vendor ledger and kept the patched files, so the patched code would keep running with no record left that `rollback` or `apply --check` could act on. A gem `.socket/manifest.json` still has a record for is different: its in-place patch is agent mode's and on record (standalone `vendor` works from the manifest and keeps the record), so the vendored unwind does not judge its installed copy by a record. A wet `rollback`, `remove`, `vendor --revert` or `vendor` reconcile that put a vendored gem back on its upstream entry therefore applies the unwind direction's refresh to the gem's INSTALLED copies when the lock now resolves the gem from rubygems.org (a gem from another remote is not judged: nothing proves its entry is the upstream one), under the same rules (staleness judged by `/cache/.gem` against the upstream sha256, and by the patch record of a detached ledger entry (`scan` / `get --mode vendored`) whose gem the manifest has no record for: a copy whose files all hash to the record's `afterHash` values is stale whatever archive its gem home holds, or when it holds none; a project-local gem home only, unless `--gem-refresh-shared`; `--no-gem-install-refresh`; an archive on disk, else rubygems.org unless `--offline`), with the same `upstream_gem_install_refreshed` note and `upstream_gem_stale_install` warning. `--json` carries them where the command carries a vendored revert's advisories (rollback `warnings[]`; `remove` / `vendor` advisory events); a human run prints the progress line after the gem's own line and one warning for the gems left on the patched build. The upstream sha256 is looked up only for a gem that has an installed copy with its archive, or one holding the record's patched files, so the unwind of a gem that is not installed needs no network. A gem that was only ever vendored has the upstream archive there: nothing is downloaded or changed. A copy agent mode patched is reinstalled from the upstream archive RubyGems kept beside it, so nothing is downloaded for it either unless that archive is gone (a pruned `cache/`); the reinstall also removes what agent mode kept in the gem dir. When nothing proves the upstream sha256 for such a copy (`--offline` under a lock without `CHECKSUMS`), it is left as it is and named by `upstream_gem_stale_install`. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry is refused (a plain-`http` `SOCKET_RUBYGEMS_URL`, see the unwind direction), such an installed copy is reported as one that could not be checked, whichever of the two it is: nothing tells them apart. A `--dry-run` does not preview this (the lock on disk is still the vendored one), and `scan --prune` does not refresh. **Pipenv hosted redirect (`Pipfile.lock`, pipfile-spec 6)**: every category other than `_meta` (`default`, `develop`, and Pipenv 2022+ named categories) that pins the package at the patched version is rewritten to the hosted reference — `{"file" | "path": "#sha256=", "hashes": ["sha256:"]}` with `markers`/`extras`/`index` kept exactly as Pipenv wrote them (present or absent: whether Pipenv records `index` depends on its release, the Pipfile spelling and the locking environment, so only the entry itself knows) and `version` dropped; `_meta` (the Pipfile content hash) and the Pipfile itself are never touched, so `pipenv install --deploy`/`sync`/`verify` keep passing. The reference KEY depends on the installing Pipenv: releases 7–11 only install `path` references, 2018 and later `file` ones (0–6 write pipfile-spec < 6 and are refused). The release is probed once per command with `pipenv --version`, resolved on ABSOLUTE `PATH` entries only (a relative entry would run a `pipenv` planted in the scanned repository; `.bat`/`.cmd` shims are found through `PATHEXT` on Windows), only when a pypi patch actually targets an entry of the lock, and `SOCKET_PIPENV_MAJOR=` pins the answer without spawning anything. An unknown installer selects `file` and warns `redirect_pipenv_installer_unknown` only when the lock was rewritten. **Refusal scope**: a pin/source CONFLICT (another version pinned, a foreign `file`/`path` source, a VCS/editable dependency) refuses the whole dependency atomically across categories as `redirect_pipenv_refused` AND vetoes the sibling Python rewriters (requirements.txt / uv.lock / pyproject) for that patch — the project's Pipenv install could not pick the patch up, so a half-redirected checkout is refused; anything else (no entry for the package, an old pipfile-spec, an unparseable lock, a digest-less patch) is `redirect_pipenv_skipped` and leaves the siblings alone (a stale Pipfile.lock in a uv/Poetry/requirements project must not block them). The veto applies to a LIVE lock only: a `Pipfile.lock` with no `Pipfile` beside it is abandoned, so its conflict refuses that file but never the siblings. Hash enforcement at install time is split by era — the `#sha256=` URL fragment is what Pipenv 2023+ verifies, the `hashes` list what 2018–2022 verify, Pipenv 11 either — so both are load-bearing. **Pipenv stale-install guard**: Pipenv never reinstalls a release that is already present (`pipenv install`, `install --deploy` and `sync` all exit 0 and keep the installed bytes — measured on 11.10.4, 2018.11.26 and 2026.8.0, hosted and vendored), so after the rewrite the run probes the Python crawler's site-packages (VIRTUAL_ENV, `./.venv`, `./venv`, Pipenv's out-of-tree `WORKON_HOME` venv; `--global`/`--global-prefix` honoured) for each confirmed Pipfile.lock redirect with the Python stale-install guard's evidence (the pinned patched wheel, else the patch record; STALE needs positive evidence, read-only, skipped on `--dry-run`, stale purls excluded from the same-run `--vex` `assume_applied` set) and the Python stale-install guard (`redirect_pypi_stale_install`, see above) names the site-packages dir and the Pipenv-specific verified remedy: `pipenv run pip uninstall -y && pipenv sync` (or `pipenv --rm && pipenv sync`), with the `sync` arguments following the lock, since plain `pipenv sync` installs only `default`: the targeted form re-syncs the categories that pin the package (`--dev` for `develop`, `--categories ""` for a named category) and the `--rm` form re-syncs every non-empty category — NOT `pipenv uninstall`, which rewrites the Pipfile and re-locks the patch away. The vendored backend emits the twin `pypi_pipenv_stale_install` (`skipped` warning event). **Rollback** (v5.0, upstream restore): each hosted entry gets its registry shape back — `"version": "=="`, the entry's own `index` carried back unchanged (refused unless it — and the Pipfile's explicit `index`, if any — names a PyPI source in `_meta.sources`), and every release file's sha256 from PyPI's JSON API (`SOCKET_PYPI_JSON_API`), sorted by filename as Pipenv records them; an entry that pins another version beside the hosted reference is refused with the `git checkout` remedy (see "Hosted unwind coverage"). A Pipfile names no project, so a same-run `--vex` on a Pipenv project needs `--vex-product` (or a git remote) to detect a product purl. **Discovery**: `Pipfile.lock` is part of the lockfile inventory (every category's `==` pins, with the lock's digest set as `Sha256AnyOf` integrity so a lock-only checkout can be vendored by fetching the pure wheel through PyPI's JSON API — only when `_meta.sources` name the public index; a private-index lock stays discovery-only and never reaches pypi.org), and Socket's own hosted / vendored references stay discoverable as the package they replace, so a re-scan of an already-redirected or already-vendored lock-only checkout re-confirms it (`--vex` attests, vendored reports `already_vendored`) instead of finding nothing. @@ -2251,8 +2251,8 @@ 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): 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_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): an installed copy only. A human run prints a progress line instead. | +| `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_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. | | `redirect_gem_no_checksums_section` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock has no `CHECKSUMS` section (Bundler < 2.6 does not write one), so it cannot record the sha256 of the patched gems. They are redirected all the same (manifest and lock converged, frozen installs accept the pair) and pinned by source alone. Reported once per run, naming the gems; relock with Bundler ≥ 2.6 (`bundle lock --add-checksums`) and re-run to pin the checksums too. | diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 3a46fe529..9f0a78ff5 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -11,6 +11,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use socket_patch_core::crawlers::Ecosystem; +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}; @@ -831,31 +832,42 @@ enum Scope { /// 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. +/// +/// `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 +/// that record's patched ones is stale whatever its archive says, and +/// whether or not `upstream` has its purl: agent mode patched it in place +/// beside the upstream archive (#2093). async fn stale_after_restore( common: &GlobalArgs, upstream: &BTreeMap>, + records: &BTreeMap, scope: Scope, ) -> Vec { use socket_patch_core::vendor::file_sha256_hex; - let purls: Vec = upstream.keys().cloned().collect(); + let purls: Vec = upstream + .keys() + .chain(records.keys()) + .collect::>() + .into_iter() + .cloned() + .collect(); let mut out = Vec::new(); for copy in installed_with_archives(common, &purls).await { - let Some(sha) = upstream.get(©.purl) else { - continue; - }; // With no upstream sha256 (the registry that would give it was // refused) nothing can be judged, so the copy is listed whether // 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 sha { - None => true, - Some(sha) => { + let listed = match upstream.get(©.purl) { + None => false, + Some(None) => true, + Some(Some(sha)) => { matches!(file_sha256_hex(©.archive).await, Some(got) if &got != sha) } }; - if listed { + if listed || holds_patch(©, records).await { out.push(StaleGem { purl: copy.purl, leaf: copy.leaf, @@ -895,6 +907,20 @@ async fn stale_after_restore( out } +/// 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. +async fn holds_patch(copy: &InstalledCopy, records: &BTreeMap) -> bool { + match records.get(©.purl) { + Some(record) => { + socket_patch_core::vex::verify::judge_installed_record(©.dir, record) + .await + .patched + } + None => false, + } +} + /// What an unwind's refresh did, for [`crate::commands::hosted_unwind`] /// and the vendored unwind ([`crate::commands::vendored_backend`]). #[derive(Debug, Default)] @@ -919,13 +945,19 @@ pub(crate) async fn after_restore( restored: &[String], staged: &BTreeMap>, ) -> RestoreRefresh { - refresh_restored(common, restored, staged, Scope::All).await + refresh_restored(common, restored, staged, &BTreeMap::new(), Scope::All).await } /// After a wet vendored unwind put the gems `unwound` back on their /// upstream entries (the lock on disk says so): Bundler loads their /// installed copies again, and a copy that a hosted scan replaced with the /// patched build before the gem was vendored is still that build (#2083). +/// So is a copy agent mode patched in place before the gem was vendored: +/// the takeover moved its manifest record into the vendor ledger and kept +/// the patched files, so once the ledger entry is gone nothing else could +/// undo them (#2093). `records` is each unwound gem's ledger record, by +/// purl; a copy whose files are the record's patched ones is such a copy, +/// whatever archive its gem home holds. /// Those copies are brought back to the upstream gem exactly as /// [`after_restore`] does it. An archive in Bundler's cache dir is not /// touched: the vendored unwind names it (`upstream_gem_stale_cache`). @@ -936,27 +968,38 @@ pub(crate) async fn after_restore( pub(crate) async fn after_vendored_unwind( common: &GlobalArgs, unwound: &[String], + records: &BTreeMap, ) -> RestoreRefresh { - let installed: BTreeSet = installed_with_archives(common, unwound) - .await - .into_iter() - .filter(|copy| copy.archive.is_file()) - .map(|copy| copy.purl) - .collect(); + let mut installed: BTreeSet = BTreeSet::new(); + for copy in installed_with_archives(common, unwound).await { + if copy.archive.is_file() || holds_patch(©, records).await { + installed.insert(copy.purl); + } + } if installed.is_empty() { return RestoreRefresh::default(); } let installed: Vec = installed.into_iter().collect(); - refresh_restored(common, &installed, &BTreeMap::new(), Scope::Installed).await + refresh_restored( + common, + &installed, + &BTreeMap::new(), + records, + Scope::Installed, + ) + .await } async fn refresh_restored( common: &GlobalArgs, restored: &[String], staged: &BTreeMap>, + records: &BTreeMap, scope: Scope, ) -> RestoreRefresh { - use socket_patch_core::patch::redirect::upstream::{gem_upstream_archive, UpstreamArchive}; + use socket_patch_core::patch::redirect::upstream::{ + gem_resolves_from_rubygems, gem_upstream_archive, UpstreamArchive, + }; use socket_patch_core::vendor::registry_fetch::SecureRegistryClient; let policy = Policy::of(common); @@ -966,6 +1009,13 @@ async fn refresh_restored( // The gems 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(); + // 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 + // when nothing proves the upstream sha256 (`--offline` or a registry + // error, under a lock without `CHECKSUMS`): it is then reported, not + // refreshed. + let mut judged: BTreeMap = BTreeMap::new(); for purl in restored .iter() .filter(|p| Ecosystem::from_purl(p) == Some(Ecosystem::Gem)) @@ -984,21 +1034,31 @@ async fn refresh_restored( } shas.insert(purl.clone(), Some(sha256)); urls.insert(purl.clone(), url); + if let Some(record) = records.get(purl) { + judged.insert(purl.clone(), record.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 => {} + None => { + if let Some(record) = records.get(purl) { + if gem_resolves_from_rubygems(&common.cwd, purl).await { + judged.insert(purl.clone(), record.clone()); + } + } + } } } - if shas.is_empty() && unverified.is_empty() { + if shas.is_empty() && unverified.is_empty() && judged.is_empty() { return RestoreRefresh::default(); } - let stale = stale_after_restore(common, &shas, scope).await; + let stale = stale_after_restore(common, &shas, &judged, scope).await; let unjudged = unverified.keys().map(|purl| (purl.clone(), None)).collect(); - let unchecked = stale_after_restore(common, &unjudged, Scope::Installed).await; + let unchecked = + stale_after_restore(common, &unjudged, &BTreeMap::new(), Scope::Installed).await; if stale.is_empty() && unchecked.is_empty() { return RestoreRefresh::default(); } @@ -1020,7 +1080,7 @@ 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, scope).await + stale_after_restore(common, &shas, &judged, scope).await } else { stale }; diff --git a/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs b/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs index fa9b006f8..c69952b5c 100644 --- a/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs +++ b/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs @@ -159,8 +159,11 @@ impl<'a> VendoredBackend<'a> { ) -> Vec { let mut out = Vec::with_capacity(keys.len()); // The gems a wet revert put back on their upstream entries: the - // index of each one's element in `out`, and its purl. + // index of each one's element in `out`, and its purl. With the + // patch record of each one the ledger alone owned (a detached + // entry), which the entry takes with it. let mut unwound_gems: Vec<(usize, String)> = Vec::new(); + let mut gem_records = std::collections::BTreeMap::new(); for key in keys { let Some(entry) = state.entries.get(key).cloned() else { out.push(RevertedEntry { @@ -228,6 +231,9 @@ impl<'a> VendoredBackend<'a> { .await; if is_gem(&entry.ecosystem) { unwound_gems.push((out.len(), entry.base_purl.clone())); + if let (true, Some(record)) = (entry.detached, &entry.record) { + gem_records.insert(entry.base_purl.clone(), record.clone()); + } } } } @@ -243,7 +249,8 @@ impl<'a> VendoredBackend<'a> { break; } } - self.refresh_unwound_gems(&unwound_gems, &mut out).await; + self.refresh_unwound_gems(&unwound_gems, &gem_records, &mut out) + .await; out } @@ -251,7 +258,10 @@ impl<'a> VendoredBackend<'a> { /// that a hosted scan replaced with the patched build before the gem /// was vendored still is that build, so the app would keep running the /// patch under an upstream lock, and `bundle pristine` would fail on - /// the upstream checksum (#2083). Bring those copies back to the + /// the upstream checksum (#2083). One that agent mode patched in place + /// before the gem was vendored still holds the patched files, and + /// `records` (the record of each unwound gem that the ledger alone + /// owned) is the last thing that can tell (#2093). Bring those copies back to the /// upstream gem as the hosted unwind does, and name what is left (the /// "Gem stale-install guard" section of CLI_CONTRACT.md). /// @@ -259,14 +269,22 @@ impl<'a> VendoredBackend<'a> { /// one, on the entry of its gem. A human run gets the progress lines on /// the last unwound gem's entry, so they print once every revert is /// reported, and ONE warning for the gems still on their patched build. - async fn refresh_unwound_gems(&self, unwound: &[(usize, String)], out: &mut [RevertedEntry]) { + async fn refresh_unwound_gems( + &self, + unwound: &[(usize, String)], + records: &std::collections::BTreeMap, + out: &mut [RevertedEntry], + ) { let Some((first, _)) = unwound.first() else { return; }; let (first, last) = (*first, unwound[unwound.len() - 1].0); let purls: Vec = unwound.iter().map(|(_, purl)| purl.clone()).collect(); + let records = self.ended_records(records).await; + let records = &records; let refresh = - crate::commands::gem_refresh::after_vendored_unwind(&self.common, &purls).await; + crate::commands::gem_refresh::after_vendored_unwind(&self.common, &purls, records) + .await; for (index, purl) in unwound { if refresh.refreshed_installs.contains(purl) { out[*index].gem_install_refreshed = true; @@ -297,6 +315,36 @@ impl<'a> VendoredBackend<'a> { } } + /// The patch record each unwound gem's installed copies are judged by: + /// `ledger` (the records of detached entries, which the ledger alone + /// owned) without the gems `.socket/manifest.json` has a record for. + /// The in-place patch of such a gem is agent mode's and on record + /// there, so this unwind does not end it. A manifest that cannot be + /// read proves nothing, so no gem is judged then. + async fn ended_records( + &self, + ledger: &std::collections::BTreeMap, + ) -> std::collections::BTreeMap { + use socket_patch_core::utils::purl_key::PurlKey; + if ledger.is_empty() { + return Default::default(); + } + let manifest = socket_patch_core::manifest::operations::read_manifest( + &self.common.resolved_manifest_path(), + ) + .await; + let in_manifest: std::collections::HashSet = match manifest { + Ok(Some(manifest)) => manifest.patches.keys().map(|k| PurlKey::new(k)).collect(), + Ok(None) => Default::default(), + Err(_) => return Default::default(), + }; + ledger + .iter() + .filter(|(purl, _)| !in_manifest.contains(&PurlKey::new(purl))) + .map(|(purl, record)| (purl.clone(), record.clone())) + .collect() + } + /// Dropping a vendored Go `replace` leaves a committed /// vendor/modules.txt still recording it, which breaks every default /// build until `go mod vendor` runs. The undo commands 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 bfa6545c0..f4d1b93f5 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -5786,6 +5786,139 @@ async fn gem_vendored_unwind_restores_an_install_the_hosted_scan_patched() { } } +/// #2093 through one vendored unwind `command`: agent mode patched the +/// installed gem in place, and a vendored takeover then moved its manifest +/// record into the vendor ledger and left the patched files (the vendored +/// copy is loaded instead). The later unwind puts the pair back on the +/// upstream `GEM` entry, where bundler loads the installed copy again, +/// and nothing is left that records the patch. The unwind must put the +/// upstream gem back: the app then loads the upstream code, and every +/// kind of reinstall succeeds and keeps it. +fn vendored_unwind_restores_an_agent_patched_gem(fx: &RedirectFixture, command: &str) { + let dir = stage_warm_install(fx, &format!("agent-vendored-{command}")); + let installed = fresh_installed_lib(&dir, &format!("{DEP}-{DEP_VERSION}"), "vuln_gem.rb"); + assert!( + std::fs::read(&installed).unwrap() == orig_lib().into_bytes(), + "{command}: premise: the upstream gem is installed" + ); + // What `scan --mode agent` leaves: the lib patched in place, the + // record of it, and both blobs. + std::fs::write(&installed, patched_lib()).unwrap(); + common::write_in_place_patch_record( + &dir.join(".socket"), + PURL, + UUID, + "lib/vuln_gem.rb", + orig_lib().as_bytes(), + patched_lib().as_bytes(), + ); + + let api = fx._server.uri(); + let upstream = format!("{api}/upstream"); + let cwd = dir.to_str().expect("utf8 tmp path"); + let common = [ + "--json", + "--cwd", + cwd, + "--api-url", + &api, + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + &api, + ]; + let envs = [("SOCKET_RUBYGEMS_URL", upstream.as_str())]; + let mut takeover = vec!["get", UUID, "--mode", "vendored", "--yes"]; + takeover.extend(common); + let (code, stdout, stderr) = run_socket_env(&dir, &takeover, &envs); + assert_eq!( + code, 0, + "{command}: takeover:\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!( + stdout.contains("vendor_manifest_record_migrated"), + "{command}: premise: the takeover owns the record now:\n{stdout}" + ); + let vendored = bundle(&dir, &["install"]); + assert!( + vendored.status.success(), + "{command}: vendored install:\n{}", + String::from_utf8_lossy(&vendored.stderr) + ); + assert!( + std::fs::read(&installed).unwrap() == patched_lib().into_bytes(), + "{command}: premise: the takeover and its install leave the installed copy" + ); + + let mut argv: Vec<&str> = match command { + "vendor --revert" => vec!["vendor", "--revert", "--yes"], + "remove" => vec!["remove", PURL, "--yes"], + _ => vec![command, PURL], + }; + argv.extend(common); + let (code, stdout, stderr) = run_socket_env(&dir, &argv, &envs); + 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}"); + assert!( + env.to_string().contains("upstream_gem_install_refreshed") + && !env.to_string().contains("upstream_gem_stale_install"), + "{command}: {env}" + ); + assert!( + std::fs::read(&installed).unwrap() == orig_lib().into_bytes(), + "{command}: the installed copy is the upstream gem again: {env}" + ); + + let redownload = if fx.bundler.at_least(2, 0) { + "--redownload" + } else { + "--force" + }; + let probe = "require \"vuln_gem\"; print VulnGem.status"; + for args in [&["install"][..], &["install", redownload], &["pristine"]] { + let out = bundle(&dir, args); + assert!( + out.status.success(), + "{command}: bundle {args:?} after the unwind:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + let run = bundle(&dir, &["exec", "ruby", "-e", probe]); + assert_eq!( + String::from_utf8_lossy(&run.stdout), + "VULNERABLE", + "{command}: bundle {args:?} leaves the upstream code loaded:\n{}", + String::from_utf8_lossy(&run.stderr) + ); + } +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 1.17); the unpinned `test` \ + job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_vendored_unwind_restores_an_install_agent_mode_patched() { + let Some(fx) = redirect_scanned_project( + "agent-vendored-unwind", + Spelling::Gemfile, + false, + true, + None, + Driver::ScanVex, + ) + .await + else { + return; + }; + mount_vendored_grant(&fx).await; + for command in ["remove", "rollback", "vendor --revert"] { + vendored_unwind_restores_an_agent_patched_gem(&fx, command); + } +} + /// #1831: a hosted redirect over a CRLF Gemfile (a Windows checkout, or /// `core.autocrlf=true`) keeps it CRLF throughout: the edit is the option /// alone, the real bundler installs the pair frozen and has nothing to 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 f15166818..e1045f6ec 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 @@ -3249,6 +3249,382 @@ async fn vendored_unwind_leaves_an_upstream_install_alone() { } } +/// A project whose gem agent mode patched in place and a vendored scan +/// then took over: the takeover moved the manifest record into the vendor +/// ledger and left the installed copy (patched files, upstream archive in +/// the gem home's `cache/`) alone. Returns the installed gem dir and that +/// archive. +async fn agent_then_vendored(server: &MockServer, proj: &Path) -> (PathBuf, PathBuf) { + agent_then_vendored_from(server, proj, "https://rubygems.org").await +} + +/// [`agent_then_vendored`], with `remote` as the pair's gem source. +async fn agent_then_vendored_from( + server: &MockServer, + proj: &Path, + remote: &str, +) -> (PathBuf, PathBuf) { + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(server, None, &sha256_of(&patched)).await; + serve_upstream_gem(server, &upstream).await; + mount_vendored_grant(server, &patched).await; + std::fs::create_dir_all(proj).unwrap(); + write_manifest_pair(proj); + for file in ["Gemfile", "Gemfile.lock"] { + let text = std::fs::read_to_string(proj.join(file)).unwrap(); + assert!(text.contains("https://rubygems.org"), "premise: {text}"); + std::fs::write( + proj.join(file), + text.replace("https://rubygems.org", remote), + ) + .unwrap(); + } + let home = project_home(proj); + let gem_dir = agent_patched_install(proj, &home); + let archive = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); + + let uri = server.uri(); + let (code, stdout, stderr) = unwind_run( + proj, + &uri, + &["scan", "--mode", "vendored", "--yes", "--json"], + ); + assert_eq!(code, 0, "takeover:\n{stdout}\n{stderr}"); + let gemfile = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); + assert!( + gemfile.contains(".socket/vendor/gem/"), + "premise:\n{gemfile}" + ); + let manifest = std::fs::read_to_string(proj.join(".socket").join("manifest.json")).unwrap(); + assert!( + stdout.contains("vendor_manifest_record_migrated") && !manifest.contains(PURL), + "premise: the takeover owns the record now:\n{stdout}\n{manifest}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise"); + assert_eq!(std::fs::read(&archive).unwrap(), upstream, "premise"); + (gem_dir, archive) +} + +/// The gem downloads (`/gems/.gem`, from any registry) among the +/// requests `server` received after the first `skip`. +async fn gem_downloads_since(server: &MockServer, skip: usize) -> Vec { + server + .received_requests() + .await + .unwrap_or_default() + .iter() + .skip(skip) + .map(|request| request.url.path().to_string()) + .filter(|path| path.contains("/gems/")) + .collect() +} + +/// #2093: a vendored takeover of a gem agent mode patched in place drops +/// the manifest record and keeps the patched files in the installed copy. +/// Once the vendored gem is unwound Bundler loads that copy again, and no +/// record is left that could undo the patch. The unwind therefore puts +/// the upstream gem back, from the upstream archive RubyGems kept in the +/// gem home (nothing is downloaded), and leaves nothing of agent mode's +/// in the gem dir. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_restores_an_install_agent_mode_patched() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, archive) = agent_then_vendored(&server, &proj).await; + let asked_before = server.received_requests().await.unwrap().len(); + + let mut args = unwind.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); + let pair = format!( + "{}{}", + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap() + ); + assert!( + !pair.contains(".socket/vendor/"), + "{unwind:?}: the gem is back on its upstream entry:\n{pair}" + ); + assert_eq!( + installed_lib(&gem_dir), + UPSTREAM_LIB, + "{unwind:?}: the installed copy is the upstream build again: {env}" + ); + assert!( + !gem_dir.join(".socket-patch-kept").exists(), + "{unwind:?}: the copy is a fresh install of the upstream gem: {env}" + ); + assert_eq!( + std::fs::read(&archive).unwrap(), + real_gem(UPSTREAM_LIB), + "{unwind:?}: the upstream archive is untouched: {env}" + ); + let fetched = gem_downloads_since(&server, asked_before).await; + assert!(fetched.is_empty(), "{unwind:?}: downloaded {fetched:?}"); + let text = env.to_string(); + assert!( + text.contains("upstream_gem_install_refreshed") + && !text.contains("upstream_gem_stale_install"), + "{unwind:?}: {env}" + ); + } +} + +/// The same with the gem home's `cache/` pruned (Bundler 4.1 `prune`, a +/// Docker image's `rm -rf ruby/*/cache`): the ledger's record still proves +/// the installed files are the patched ones, so the upstream gem is +/// downloaded and installed over them. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_restores_an_agent_patched_install_without_its_archive() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, archive) = agent_then_vendored(&server, &proj).await; + std::fs::remove_dir_all(archive.parent().unwrap()).unwrap(); + let asked_before = server.received_requests().await.unwrap().len(); + + let mut args = unwind.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); + assert_eq!( + installed_lib(&gem_dir), + UPSTREAM_LIB, + "{unwind:?}: the installed copy is the upstream build again: {env}" + ); + assert_eq!( + gem_downloads_since(&server, asked_before).await, + [format!("/upstream/gems/{DEP}-{DEP_VERSION}.gem")], + "{unwind:?}: one download, of the upstream gem" + ); + let text = env.to_string(); + assert!( + text.contains("upstream_gem_install_refreshed") + && !text.contains("upstream_gem_stale_install"), + "{unwind:?}: {env}" + ); + } +} + +/// An agent-patched copy the unwind may not replace +/// (`--no-gem-install-refresh`) or cannot (`--offline` with the archive +/// pruned) is left exactly as it was and named with the files to remove, +/// not passed over as if it were the upstream build. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_names_an_agent_patched_install_it_leaves() { + for (unwind, opt_out) in VENDORED_UNWINDS + .into_iter() + .flat_map(|unwind| [(unwind, true), (unwind, false)]) + { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, archive) = agent_then_vendored(&server, &proj).await; + let home = project_home(&proj); + if !opt_out { + std::fs::remove_dir_all(archive.parent().unwrap()).unwrap(); + } + let held_before = snapshot(&home); + + let mut args = unwind.to_vec(); + args.push("--json"); + args.push(if opt_out { + "--no-gem-install-refresh" + } else { + "--offline" + }); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env = common::parse_json_envelope(&stdout); + let case = format!("{unwind:?} opt_out={opt_out}"); + assert_eq!(code, 0, "{case}: {env}\nstderr:\n{stderr}"); + assert!( + snapshot(&home) == held_before, + "{case}: the gem home changed: {env}" + ); + let text = env.to_string(); + let spec = home + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}.gemspec")); + for needle in [ + "upstream_gem_stale_install", + gem_dir.to_str().unwrap(), + spec.to_str().unwrap(), + "bundle install", + ] { + // The envelope JSON-escapes a Windows path's backslashes. + let needle = needle.replace('\\', "\\\\"); + assert!(text.contains(&needle), "{case}: no {needle:?} in {env}"); + } + assert!( + !text.contains("upstream_gem_install_refreshed"), + "{case}: {env}" + ); + } +} + +/// A manifest record for the gem means its in-place patch is agent mode's +/// and still on record, so a vendored unwind does not end it: +/// `vendor --revert` undoes the vendoring only and leaves the installed +/// copy as it is. Two ways there: standalone `vendor`, which works from +/// the manifest and keeps the record in it, and an agent-mode record +/// written again after a vendored takeover. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_leaves_an_install_the_manifest_still_records() { + for standalone in [true, false] { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let home = project_home(&proj); + let uri = server.uri(); + let gem_dir = if standalone { + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_upstream_gem(&server, &upstream).await; + mount_vendored_grant(&server, &patched).await; + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let gem_dir = agent_patched_install(&proj, &home); + let (code, stdout, stderr) = unwind_run(&proj, &uri, &["vendor", "--yes", "--json"]); + assert_eq!(code, 0, "vendor:\n{stdout}\n{stderr}"); + gem_dir + } else { + let (gem_dir, _) = agent_then_vendored(&server, &proj).await; + common::write_in_place_patch_record( + &proj.join(".socket"), + PURL, + UUID, + "lib/stale_probe_gem.rb", + UPSTREAM_LIB.as_bytes(), + PATCHED_LIB.as_bytes(), + ); + gem_dir + }; + let case = format!("standalone={standalone}"); + let manifest_path = proj.join(".socket").join("manifest.json"); + assert!( + std::fs::read_to_string(proj.join("Gemfile")) + .unwrap() + .contains(".socket/vendor/gem/") + && std::fs::read_to_string(&manifest_path) + .unwrap() + .contains(PURL), + "{case}: premise: vendored, with the record in the manifest" + ); + let held_before = snapshot(&home); + + let (code, stdout, stderr) = + unwind_run(&proj, &uri, &["vendor", "--revert", "--yes", "--json"]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{case}: {env}\nstderr:\n{stderr}"); + assert!( + !std::fs::read_to_string(proj.join("Gemfile")) + .unwrap() + .contains(".socket/vendor/"), + "{case}: the vendoring is undone: {env}" + ); + assert!( + snapshot(&home) == held_before, + "{case}: the gem home changed: {env}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{case}"); + assert!( + std::fs::read_to_string(&manifest_path) + .unwrap() + .contains(PURL), + "{case}: the manifest keeps the record: {env}" + ); + let text = env.to_string(); + for code in [ + "upstream_gem_install_refreshed", + "upstream_gem_stale_install", + ] { + assert!(!text.contains(code), "{case}: {code} in {env}"); + } + } +} + +/// A gem the lock resolves from another remote is not judged, as in every +/// unwind refresh: nothing proves its restored entry is the upstream one, +/// and rubygems.org is not asked about a gem that is not its own. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_does_not_judge_an_agent_patched_gem_from_another_remote() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = + agent_then_vendored_from(&server, &proj, "https://gems.example.test").await; + let home = project_home(&proj); + let held_before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); + + let mut args = unwind.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); + assert!( + std::fs::read_to_string(proj.join("Gemfile.lock")) + .unwrap() + .contains("remote: https://gems.example.test/"), + "{unwind:?}: premise: back on the other remote" + ); + assert!( + snapshot(&home) == held_before, + "{unwind:?}: the gem home changed: {env}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{unwind:?}"); + let upstream_asked = server + .received_requests() + .await + .unwrap() + .iter() + .skip(asked_before) + .any(|request| request.url.path().starts_with("/upstream/")); + assert!(!upstream_asked, "{unwind:?}: the unwind asked rubygems.org"); + let text = env.to_string(); + for code in [ + "upstream_gem_install_refreshed", + "upstream_gem_stale_install", + ] { + assert!(!text.contains(code), "{unwind:?}: {code} in {env}"); + } + } +} + +/// The human run says what it replaced, and rollback's "keeps its patched +/// bytes" note no longer counts the gem. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_reports_the_agent_patched_refresh_in_a_human_run() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = agent_then_vendored(&server, &proj).await; + + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), unwind); + assert_eq!(code, 0, "{unwind:?}: {stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "{unwind:?}"); + assert!( + stdout.contains(&format!( + "Replaced the installed copy of 1 gem with the upstream build: {DEP} \ + {DEP_VERSION}." + )), + "{unwind:?}: {stdout}\n{stderr}" + ); + assert!( + !stdout.contains("keeps its patched bytes") && !stderr.contains("still holds"), + "{unwind:?}: {stdout}\n{stderr}" + ); + } +} + /// What `scan --mode agent` leaves of the fixture gem under `home`: the /// upstream install with its lib patched in place, the upstream archive /// still in the home's `cache/`, and the manifest record (with both blobs) 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 8bd6e4bc9..3324cf632 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs @@ -1122,6 +1122,20 @@ pub(super) async fn upstream_archive( }) } +/// 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 { + let Some((_, name, version)) = crate::utils::purl::purl_parts(purl) else { + return false; + }; + for file in BUNDLER_LOCKS { + if let Ok(text) = crate::utils::fs::read_regular_to_string(&root.join(file)).await { + return rubygems_locked(&to_lf(&text), &name, &version); + } + } + 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 { 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 83b247c81..fb0054d4a 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs @@ -970,6 +970,14 @@ pub async fn gem_upstream_archive( gem::upstream_archive(root, restored, purl, offline).await } +/// Whether the lock on disk at `root` resolves the ruby-platform gem `purl` +/// from rubygems.org: the gem is then on its upstream registry entry, also +/// where [`gem_upstream_archive`] is `None` because nothing proves the +/// archive's sha256 (an offline run, a registry error). +pub async fn gem_resolves_from_rubygems(root: &Path, purl: &str) -> bool { + gem::resolves_from_rubygems(root, purl).await +} + /// Restore every pin in `pins` to its default upstream registry entry. /// See the module docs for the contract. pub async fn restore_upstream( diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 317516802..2bdc413b3 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1967,8 +1967,11 @@ and every kind of reinstall keeps it. `rollback` and `remove` do the same with t 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 -puts the upstream gem back there too. A gem that was only ever vendored still has the upstream -build installed, and its unwind changes nothing in the gem home. +puts the upstream gem back there too. The same holds for a gem that agent mode patched in place +before `scan --mode vendored` (or `get --mode vendored`) took it over: the unwind reinstalls the +upstream gem over the patched files in the project's own gem home, and warns about a copy it +leaves (a shared gem home, `--no-gem-install-refresh`). A gem that was only ever vendored still +has the upstream build installed, and its unwind changes nothing in the gem home. Nothing is changed when the patched gem cannot be downloaded or verified: the run still exits 0 and warns (`redirect_gem_stale_install`), naming the files to remove by hand. `--dry-run` only