diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 11ff110b6..e0dfd0759 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -431,7 +431,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm - An installed dir is judged by the archive RubyGems installed it from, `/cache/.gem`: an archive whose sha256 is a patched artifact's (the grant's `gemChecksumSha256`, else its tarball sha256) is already patched and never warns, any other readable archive is stale, and a missing or unreadable one is never evidence by itself. - When there is no readable archive (a pruned `cache/`, `gem cleanup`) or no patched sha to compare it with, and no agent-mode record (below), the scan fetches that patch's record (`…/patches/view/`, for that purl only) and judges the dir by its `afterHash` map; if that fetch fails too, the dir is unjudged: no warning, but the same run's `--vex` withholds the purl (`stale_install_unverified`) instead of assuming it patched. Otherwise hosted mode fetches no patch record. -- An agent-mode manifest record of the same patch judges the dir by its `afterHash` file map instead (an in-place patch keeps the upstream archive), so an agent→hosted migration stays quiet. +- An agent-mode manifest record of the same patch judges the dir's files by its `afterHash` file map instead. An in-place patch keeps the upstream archive in `/cache/`, and that archive is what `bundle pristine` and `bundle install --redownload` reinstall from (#2089): with a `CHECKSUMS` section in the lock Bundler removes the gem and fails on the pinned checksum (exit 37, and every later `bundle install` fails too), without one it reinstalls the unpatched gem. So files the record proves patched beside a readable archive that is not a patched artifact's are stale as well, by that archive alone: the refresh replaces the archive with the verified patched one under the same rules as an installed copy (project-local by default, a shared gem home only with `--gem-refresh-shared`) and never touches the gem dir, where agent mode keeps a native gem's original build; left alone, the warning says that the files are patched in place and names the archive as the one file to remove. With the patched archive beside them, with no readable archive, or with no patched sha256 to compare it with, the record's verdict stands and an agent→hosted migration stays quiet. - When several confirmed variant purls resolve to one installed dir, ANY of them judging it patched keeps it quiet. - Staleness needs **positive evidence** — bytes actually read that are not the patched state — so missing or unreadable files never mark a copy stale. - A committed cache-dir archive whose sha256 is readable and differs from the patched artifact's is stale by itself, even with no installed dir at all (a fresh checkout with a committed stale cache). @@ -452,8 +452,8 @@ The rewriter reads a fixed set of candidate files from the project root: the npm *What is reported.* - Each refreshed materialization is a `redirect_gem_install_refreshed` note in the JSON `warnings[]`; a human run prints one progress line per kind instead (`Replaced the installed copy of 2 gems with the patched build: …`). A replaced cache-dir archive is listed with the files to commit. -- Each materialization that is still stale is a `redirect_gem_stale_install` warning in the JSON `warnings[]`, in three flavors: an installed copy in a SHARED gem home (left alone; the remedy is the project-local bundle path, `bundle config set --local path vendor/bundle && bundle install`, which installs every gem of the project from the lock's sources and leaves the shared home untouched, or `--gem-refresh-shared`; never a delete list); a PROJECT-LOCAL installed copy the refresh did not fix (the reason — the archive could not be downloaded or verified, a native build failed, the path is outside the project, the refresh is turned off — and the files to remove by hand, including the project's stale cache-dir archive when there is one); and a cache-dir archive alone. The warning re-fires on every re-scan until the stale materialization is gone. -- 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. +- Each materialization that is still stale is a `redirect_gem_stale_install` warning in the JSON `warnings[]`, in three flavors: an installed copy in a SHARED gem home (left alone; the remedy is the project-local bundle path, `bundle config set --local path vendor/bundle && bundle install`, which installs every gem of the project from the lock's sources and leaves the shared home untouched, or `--gem-refresh-shared`; never a delete list); a PROJECT-LOCAL installed copy the refresh did not fix (the reason — the archive could not be downloaded or verified, a native build failed, the path is outside the project, the refresh is turned off — and the files to remove by hand, including the project's stale cache-dir archive when there is one); and a cache-dir archive alone. An installed copy that agent mode patched in place (stale by its upstream archive only, see above) gets the first two flavors in its own words: the detail names the archive and what a reinstall from it does, the delete list is that archive alone (never the `specifications` entry), and it never calls the install unpatched. Its refresh note reads `replaced the upstream archive of the install patched in place at …`, and the human progress line `Replaced the upstream archive beside 1 gem patched in place with the patched gem: …`; that archive is not a file to commit. The warning re-fires on every re-scan until the stale materialization is gone. +- 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. A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 03fc059f5..db047df5c 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -95,6 +95,12 @@ pub(crate) struct StaleGem { pub(crate) installed: Option<(PathBuf, bool)>, /// The stale archive in Bundler's cache dir. pub(crate) cache_archive: Option, + /// The installed files already hold the patch (agent mode patched them + /// in place); what is stale is the upstream archive RubyGems kept + /// beside them, `/cache/.gem`. Only that archive is + /// replaced: the gem dir, with what agent mode keeps in it, stays as + /// it is. + pub(crate) in_place: bool, } /// What the run may refresh. @@ -179,6 +185,9 @@ pub(crate) struct Attempt { pub(crate) refreshed: Vec<(String, Target)>, /// Why a target the pass did not refresh is as it was, by its path. left: BTreeMap, + /// The gem-home archives among the targets: the upstream archive + /// beside an install patched in place ([`StaleGem::in_place`]). + in_place: BTreeSet, } impl Attempt { @@ -192,10 +201,19 @@ impl Attempt { self.refreshed .iter() .filter_map(|(_, target)| match target { - Target::CacheArchive(path) => Some(path.as_path()), - Target::Installed(_) => None, + Target::CacheArchive(path) if !self.in_place.contains(path) => Some(path.as_path()), + _ => None, }) } + + /// Whether the pass brought an installed copy in line with the lock: + /// it replaced the copy, or the archive beside one patched in place. + pub(crate) fn refreshed_an_install(&self) -> bool { + self.refreshed.iter().any(|(_, target)| match target { + Target::Installed(_) => true, + Target::CacheArchive(path) => self.in_place.contains(path), + }) + } } /// One leaf's part of a pass: the archive, and each target with the purl @@ -221,9 +239,15 @@ pub(crate) async fn attempt( for gem in gems { let mut targets = Vec::new(); let candidates = [ - gem.installed - .as_ref() - .map(|(dir, local)| (Target::Installed(dir.clone()), *local)), + match (&gem.installed, gem.in_place) { + // Patched in place: the archive beside it, never the dir. + (Some((dir, local)), true) => home_cache_archive(dir).map(|archive| { + out.in_place.insert(archive.clone()); + (Target::CacheArchive(archive), *local) + }), + (Some((dir, local)), false) => Some((Target::Installed(dir.clone()), *local)), + (None, _) => None, + }, gem.cache_archive .as_ref() .map(|path| (Target::CacheArchive(path.clone()), true)), @@ -321,16 +345,28 @@ const LOCAL_PATH_REMEDY: &str = "bundle config set --local path vendor/bundle && /// installed copy's `specifications` entry and cached archive (Bundler /// then counts the gem as missing and has no archive to reinstall from), /// and the stale archive in Bundler's own cache dir. +/// +/// For a copy patched in place it is the cached archive alone: the files +/// are patched, and with no archive a reinstall fetches the gem from the +/// lock's source. fn files_to_remove(gem: &StaleGem) -> Vec { let mut files = Vec::new(); if let Some((dir, _)) = &gem.installed { - files.extend(home_spec(dir)); + if !gem.in_place { + files.extend(home_spec(dir)); + } files.extend(home_cache_archive(dir)); } files.extend(gem.cache_archive.clone()); files } +/// What the upstream archive beside an in-place patch does once the lock +/// pins the patched gem. +const IN_PLACE_REINSTALL: &str = "`bundle pristine` and `bundle install --redownload` reinstall \ + from that archive: with a `CHECKSUMS` section in the lock Bundler removes the gem and fails \ + on the checksum, without one it brings the unpatched gem back"; + fn display_list(paths: &[PathBuf]) -> String { paths .iter() @@ -373,6 +409,35 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh let (stale, wanted) = (direction.stale(), direction.wanted()); let reuse = format!("`bundle install` reuses an installed gem instead of fetching the {wanted} one"); + if let (true, Some((dir, project_local))) = (gem.in_place, &gem.installed) { + let archive = home_cache_archive(dir).unwrap_or_default(); + let held = format!( + "{purl} {switched}, but the copy patched in place at {} still has its upstream \ + archive at {}", + dir.display(), + archive.display() + ); + return if !project_local && !matches!(why, Some(Why::Disabled | Why::Failed(_))) { + format!( + "{held}. {IN_PLACE_REINSTALL}. Other projects may load that shared gem home, so \ + it was left alone. Install the {wanted} gem for this project only with \ + `{LOCAL_PATH_REMEDY}`, or re-run with `--gem-refresh-shared` to replace the \ + shared archive" + ) + } else { + format!( + "{held}, which was not replaced{}. {IN_PLACE_REINSTALL}. {}", + reason(why), + after_hint( + retry_hint(direction, why), + &format!( + "remove {} and run `bundle install`", + display_list(&files_to_remove(gem)) + ) + ), + ) + }; + } match &gem.installed { Some((dir, false)) if !matches!(why, Some(Why::Disabled | Why::Failed(_))) => format!( "{purl} {switched}, but the shared gem home still holds its {stale} install at \ @@ -462,11 +527,12 @@ pub(crate) struct Report { /// stale after `attempt`. fn why_stale(gem: &StaleGem, attempt: &Attempt) -> Why { let path = match (&gem.installed, &gem.cache_archive) { - (Some((dir, _)), _) => dir.as_path(), - (None, Some(archive)) => archive.as_path(), - (None, None) => Path::new(""), + (Some((dir, _)), _) if gem.in_place => home_cache_archive(dir).unwrap_or_default(), + (Some((dir, _)), _) => dir.clone(), + (None, Some(archive)) => archive.clone(), + (None, None) => PathBuf::new(), }; - attempt.left.get(path).cloned().unwrap_or_else(|| { + attempt.left.get(&path).cloned().unwrap_or_else(|| { // The pass replaced it and the probe after it still calls it stale. Why::Failed("it did not verify after the refresh".to_string()) }) @@ -492,22 +558,26 @@ pub(crate) fn report( } else { (direction.refreshed_code(), "replaced", "Replaced") }; - let (mut installed, mut archives) = (Vec::new(), Vec::new()); + let (mut installed, mut archives, mut in_place) = (Vec::new(), Vec::new(), Vec::new()); for (purl, target) in &attempt.refreshed { let what = match target { Target::Installed(_) => { installed.push(purl.as_str()); - "install" + format!("{stale_word} install") + } + Target::CacheArchive(path) if attempt.in_place.contains(path) => { + in_place.push(purl.as_str()); + "upstream archive of the install patched in place".to_string() } Target::CacheArchive(_) => { archives.push(purl.as_str()); - "archive" + format!("{stale_word} archive") } }; out.warnings.push(( code, format!( - "{purl}: {would} the {stale_word} {what} at {} with the {wanted} gem", + "{purl}: {would} the {what} at {} with the {wanted} gem", target.path().display() ), )); @@ -519,6 +589,14 @@ pub(crate) fn report( labels(installed.iter().copied()) )); } + if !in_place.is_empty() { + out.progress.push(format!( + "{replaced} the upstream archive beside {} patched in place with the {wanted} gem: \ + {}.", + plural(in_place.len(), "gem", "gems"), + labels(in_place.iter().copied()) + )); + } if !archives.is_empty() { out.progress.push(format!( "{replaced} {} in Bundler's cache dir with the {wanted} gem: {}.", @@ -534,8 +612,13 @@ pub(crate) fn report( let mut shared: BTreeMap> = BTreeMap::new(); // reason → the gems not refreshed for it. let mut local: BTreeMap> = BTreeMap::new(); + // The gems left alone in a shared home that are patched in place. + let mut shared_in_place = 0; for gem in stale { let why = why_stale(gem, attempt); + if why == Why::Shared && gem.installed.is_some() && gem.in_place { + shared_in_place += 1; + } out.warnings.push(( direction.stale_code(), stale_detail(direction, gem, Some(&why)), @@ -557,6 +640,18 @@ pub(crate) fn report( .collect::>() .len(); let headline = match direction { + Direction::Patched if stale.iter().all(|gem| gem.in_place) => format!( + "{} on disk after the switch to hosted patches", + plural( + count, + "gem patched in place still has its upstream archive", + "gems patched in place still have their upstream archives" + ) + ), + Direction::Patched if stale.iter().any(|gem| gem.in_place) => format!( + "{} unpatched files or archives on disk after the switch to hosted patches", + plural(count, "gem still has", "gems still have") + ), Direction::Patched => format!( "{} still unpatched on disk after the switch to hosted patches", plural(count, "gem is", "gems are") @@ -580,10 +675,23 @@ pub(crate) fn report( } else { ("them", "copies") }; + // Why a copy left alone matters: an unpatched one keeps being + // used, one patched in place is undone by a reinstall. + let mut why = String::new(); + if shared_in_place < shared_gems { + why.push_str(&format!( + "`bundle install` reuses an installed gem instead of fetching the {wanted} one. " + )); + } + if shared_in_place > 0 { + why.push_str( + "`bundle pristine` and `bundle install --redownload` reinstall a gem patched in \ + place from the upstream archive beside it. ", + ); + } bullets.push(format!( - "`bundle install` reuses an installed gem instead of fetching the {wanted} one. To \ - install {them} for this project only, run `{LOCAL_PATH_REMEDY}`, or re-run with \ - `--gem-refresh-shared` to replace the shared {copies}." + "{why}To install {them} for this project only, run `{LOCAL_PATH_REMEDY}`, or re-run \ + with `--gem-refresh-shared` to replace the shared {copies}." )); } for (why, gems) in &local { @@ -652,6 +760,7 @@ async fn stale_after_restore( leaf, installed: Some((pkg.path.clone(), home.project_local)), cache_archive: None, + in_place: false, }), _ => {} } @@ -669,6 +778,7 @@ async fn stale_after_restore( leaf, installed: None, cache_archive: Some(archive), + in_place: false, }), _ => {} } @@ -793,6 +903,7 @@ mod tests { leaf: format!("{name}-1.0.0"), installed: Some((dir, project_local)), cache_archive: None, + in_place: false, } } @@ -933,7 +1044,7 @@ mod tests { Target::CacheArchive(PathBuf::from("vendor/cache/rack-2.2.3.gem")), ), ], - left: BTreeMap::new(), + ..Attempt::default() }; let root = Path::new("."); let out = report( @@ -977,6 +1088,112 @@ mod tests { && detail.contains("would replace the patched"))); } + /// A copy agent mode patched in place is stale by its upstream archive + /// only (#2089), and every message says so: the dry-run note, the + /// warning of a copy left alone, and the headline when no gem under it + /// is actually unpatched. + #[tokio::test] + async fn in_place_patched_gems_are_never_called_unpatched() { + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + // With the archive RubyGems kept beside it. + let in_place = |name: &str, home: &Path, project_local: bool| { + std::fs::create_dir_all(home.join("cache")).unwrap(); + std::fs::write(home.join("cache").join(format!("{name}-1.0.0.gem")), b"up").unwrap(); + StaleGem { + in_place: true, + ..installed(name, home, project_local) + } + }; + let local = in_place("rack", &proj.join("vendor/bundle/ruby/3.4.0"), true); + let shared_home = tmp.path().join("gemhome"); + let shared = in_place("rexml", &shared_home, false); + let gems = vec![local.clone(), shared.clone()]; + + // A dry run plans the project's own copy. + let dry = policy(&proj, true, false, true); + let out = report(Direction::Patched, &[], &pass(&gems, &dry).await, &dry); + assert_eq!(out.warnings.len(), 1, "{:?}", out.warnings); + assert!( + out.warnings[0] + .1 + .contains("would replace the upstream archive of the install patched in place at"), + "{}", + out.warnings[0].1 + ); + assert_eq!( + out.progress, + [ + "Would replace the upstream archive beside 1 gem patched in place with the \ + patched gem: rack 1.0.0." + ] + ); + + // Refresh off: both are left, each with its own remedy. + let off = policy(&proj, false, false, false); + let out = report(Direction::Patched, &gems, &pass(&gems, &off).await, &off); + let summary = out.summary.expect("a summary"); + assert_eq!( + summary.headline, + "2 gems patched in place still have their upstream archives on disk after the \ + switch to hosted patches" + ); + assert_eq!(out.warnings.len(), 2); + for (_, detail) in &out.warnings { + assert!( + detail.contains("patched in place") + && detail.contains("upstream archive at") + && detail.contains("`bundle pristine`") + && !detail.contains("unpatched install"), + "{detail}" + ); + } + let of = |gem: &StaleGem| { + let needle = gem.purl.as_str(); + out.warnings + .iter() + .find(|(_, detail)| detail.starts_with(needle)) + .map(|(_, detail)| detail.clone()) + .unwrap() + }; + let cache = home_cache_archive(&local.installed.as_ref().unwrap().0).unwrap(); + assert!( + of(&local).contains("`--no-gem-install-refresh` is set") + && of(&local).contains(&format!("emove {} and run", cache.display())) + && !of(&local).contains("specifications") + && of(&local).ends_with("and run `bundle install`"), + "{}", + of(&local) + ); + assert!( + of(&shared).contains("`--gem-refresh-shared`") + && of(&shared).contains(LOCAL_PATH_REMEDY) + && !of(&shared).to_lowercase().contains("remove "), + "a shared home never gets a delete list: {}", + of(&shared) + ); + + let shared_why = summary + .bullets + .iter() + .find(|b| b.contains("--gem-refresh-shared")) + .expect("the shared-home remedy"); + assert!( + shared_why.starts_with("`bundle pristine` and `bundle install --redownload` reinstall") + && !shared_why.contains("reuses an installed gem"), + "{shared_why}" + ); + + // Beside a gem that is unpatched, the headline covers both. + let mixed = vec![local, installed("puma", &shared_home, false)]; + let out = report(Direction::Patched, &mixed, &pass(&mixed, &off).await, &off); + assert_eq!( + out.summary.expect("a summary").headline, + "2 gems still have unpatched files or archives on disk after the switch to hosted \ + patches" + ); + } + /// What a pass may replace: the project's own copies; a shared home, or /// a project path that resolves outside the project, only with /// `--gem-refresh-shared`; nothing with `--no-gem-install-refresh`. diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 8934e26f5..2cd93365c 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -264,19 +264,22 @@ impl<'a> ViewFallback<'a> { /// the tree) or one other projects share, and, for a project-local copy, /// the project's committed cache-dir archive when it is stale too (bundler /// installs from it in preference to fetching, so the same refresh and the -/// same remedy cover it). +/// same remedy cover it). `in_place`: the files hold an agent-mode patch +/// and only the archive RubyGems kept beside them is stale. fn stale_installed_gem( purl: &str, gem_dir: &Path, leaf: &str, project_local: bool, project_cache_gem: Option<&Path>, + in_place: bool, ) -> StaleGem { StaleGem { purl: purl.to_string(), leaf: leaf.to_string(), installed: Some((gem_dir.to_path_buf(), project_local)), cache_archive: project_cache_gem.map(Path::to_path_buf), + in_place, } } @@ -307,6 +310,7 @@ fn stale_cache_gem(purl: &str, cache_path: &Path) -> StaleGem { leaf, installed: None, cache_archive: Some(cache_path.to_path_buf()), + in_place: false, } } @@ -319,8 +323,12 @@ fn stale_cache_gem(purl: &str, cache_path: &Path) -> StaleGem { /// * An installed dir is judged by the archive RubyGems installed it from, /// `/cache/.gem`: one whose sha256 is a patched artifact's is /// patched, any other readable one is stale. An agent-mode manifest -/// record of the same patch judges the dir by its `afterHash` map instead -/// (an in-place patch keeps the upstream archive). +/// record of the same patch judges the dir's files by its `afterHash` +/// map instead. An in-place patch keeps the upstream archive, though, and +/// that archive is what `bundle pristine` and `--redownload` reinstall +/// from: files the record proves patched beside a readable archive that +/// is not a patched artifact's are stale as well (`StaleGem::in_place`): +/// the refresh replaces that archive and leaves the dir as it is. /// * With neither (no readable archive, or no patched sha to compare it /// with), the patch's view record judges the dir ([`ViewFallback`]). A /// dir that record cannot judge either (the fetch failed, or `--offline`) @@ -377,6 +385,9 @@ async fn gem_stale_install_warnings( leaf: String, patched: bool, positive: bool, + /// An agent-mode record proved the files patched, and the archive + /// RubyGems installed the dir from is not a patched artifact's. + upstream_archive: bool, /// Some variant had no evidence at all (see `unjudged_purls`). unjudged: bool, /// Every candidate purl installed in this dir. @@ -438,31 +449,47 @@ async fn gem_stale_install_warnings( leaf: leaf.to_string(), patched: false, positive: false, + upstream_archive: false, unjudged: false, purls: std::collections::BTreeSet::new(), project_local: *project_local, }); entry.purls.insert((*purl).to_string()); - let judged = match local { - Some(record) => Some(judge_installed_record(&pkg.path, record).await), - None => match gem_artifact_shas.get(&gem_sha_key(purl)) { - Some(patched_shas) => { - let archive = pkg - .path - .parent() - .and_then(Path::parent) - .map(|home| home.join("cache").join(format!("{leaf}.gem"))); - let sha = match archive { - Some(archive) => file_sha256_hex(&archive).await, - None => None, - }; - sha.map(|sha| InstalledRecordJudgment { - patched: patched_shas.contains(&sha), - stale_evidence: !patched_shas.contains(&sha), + // Whether the archive RubyGems installed the dir from is a + // patched artifact's; `None` without a readable archive or a + // patched sha to compare it with. + let archive_patched = || async { + match ( + gem_artifact_shas.get(&gem_sha_key(purl)), + gem_refresh::home_cache_archive(&pkg.path), + ) { + (Some(patched_shas), Some(archive)) => { + file_sha256_hex(&archive).await.map(|sha| { + patched_shas + .iter() + .any(|patched| patched.eq_ignore_ascii_case(&sha)) }) } - None => None, - }, + _ => None, + } + }; + let judged = match local { + Some(record) => { + let judged = judge_installed_record(&pkg.path, record).await; + if judged.patched + && !entry.upstream_archive + && archive_patched().await == Some(false) + { + entry.upstream_archive = true; + } + Some(judged) + } + None => archive_patched() + .await + .map(|patched| InstalledRecordJudgment { + patched, + stale_evidence: !patched, + }), }; match judged { Some(judged) => entry.record(purl, judged), @@ -492,10 +519,12 @@ async fn gem_stale_install_warnings( // a remedy that leaves it behind silently reinstates the stale bytes. let mut cache_covered: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new(); for (dir, j) in &dir_state { - if j.patched { + // Files patched in place beside the upstream archive (#2089). + let in_place = j.patched && j.upstream_archive; + if j.patched && !in_place { continue; } - if !j.positive { + if !in_place && !j.positive { if j.unjudged { out.unjudged_purls.extend(j.purls.iter().cloned()); } @@ -525,6 +554,7 @@ async fn gem_stale_install_warnings( &j.leaf, j.project_local, folded_cache.as_deref(), + in_place, ); out.warnings.push(gem_stale_warning(&gem, None)); out.gems.push(gem); @@ -580,7 +610,8 @@ struct GemRefreshed { summary: Option, /// The cache-dir archives replaced: files the project commits. replaced_archives: Vec, - /// An installed copy was replaced with the patched gem. + /// An installed copy was replaced with the patched gem, or the upstream + /// archive beside one patched in place was. replaced_installs: bool, } @@ -588,11 +619,12 @@ struct GemRefreshed { /// held, as the run's next steps need it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum GemCopies { - /// None was found unpatched and none was replaced. + /// None was found stale (unpatched, or patched in place beside its + /// upstream archive) and none was replaced. Untouched, - /// Every unpatched one was replaced with the patched gem. + /// Every stale one was brought in line with the patched gem. Refreshed, - /// Some are still unpatched; the run's warning names the command. + /// Some are still stale; the run's warning names the command. Stale, } @@ -730,13 +762,7 @@ async fn refresh_stale_gems( } else { pass.replaced_archives().map(Path::to_path_buf).collect() }, - replaced_installs: !common.dry_run - && pass.refreshed.iter().any(|(_, target)| { - matches!( - target, - socket_patch_core::patch::gem_refresh::Target::Installed(_) - ) - }), + replaced_installs: !common.dry_run && pass.refreshed_an_install(), } } @@ -1938,9 +1964,11 @@ async fn run_redirect_selected_untracked( params.hosted_gem_mirror_check = true; // Stale-flagged purls are EXCLUDED from assume_applied: the same-run // envelope carries a redirect_gem_stale_install warning proving the - // installed materialization unpatched, so attesting that purl from - // this run's records would contradict the run's own warning. Excluded purls - // fall back to `vex`'s normal installed-tree verification. + // installed materialization unpatched (or, for a copy patched in + // place, undone by a reinstall from its upstream archive), so + // attesting that purl from this run's records would contradict the + // run's own warning. Excluded purls fall back to `vex`'s normal + // installed-tree verification, which still attests patched files. // A confirmed uuid whose bundled instance (#469) or `npm:` alias // entry (#1081) the rewriter had to skip leaves that copy // unpatched, so it too is verified, never assumed. @@ -3642,7 +3670,7 @@ mod tests { project_cache_gem: Option<&std::path::Path>, ) -> serde_json::Value { gem_stale_warning( - &stale_installed_gem(purl, gem_dir, leaf, project_local, project_cache_gem), + &stale_installed_gem(purl, gem_dir, leaf, project_local, project_cache_gem, false), None, ) } @@ -4316,6 +4344,95 @@ mod tests { assert!(out.stale_purls.is_empty()); } + /// #2089: an agent-mode record proves the installed files patched, but + /// an in-place patch keeps the upstream archive in the home's `cache/`. + /// Once the lock pins the patched gem's sha256 that archive is what + /// `bundle pristine` and `--redownload` reinstall from, so the copy is + /// stale by its archive. The patched archive, or none at all, is quiet. + #[tokio::test] + async fn gem_stale_probe_flags_an_upstream_archive_beside_an_in_place_patch() { + use sha2::{Digest as _, Sha256}; + let tmp = tempfile::tempdir().unwrap(); + let gem_dir = materialize_gem(tmp.path(), GEM_PATCHED); + let home = gem_home(tmp.path()); + let cache = home.join("cache").join(format!("{GEM_LEAF}.gem")); + let shas = std::collections::BTreeMap::from([( + ("stale-unit".to_string(), "1.0.0".to_string()), + std::collections::BTreeSet::from([hex::encode(Sha256::digest(b"patched .gem"))]), + )]); + let (confirmed, records) = (one_confirmed(), one_record()); + let run = || async { + gem_stale_install_warnings( + tmp.path(), + false, + None, + &confirmed, + &records, + &shas, + &mut super::ViewFallback::offline(), + ) + .await + }; + + let out = run().await; + assert_eq!(out.warnings.len(), 1, "{:?}", out.warnings); + let detail = detail_of(&out.warnings[0]); + assert!(detail.contains("patched in place"), "{detail}"); + assert!( + !detail.contains("unpatched install"), + "the installed files are patched: {detail}" + ); + for path in [&gem_dir, &cache] { + assert!(detail.contains(&path.display().to_string()), "{detail}"); + } + assert!( + !detail.contains("specifications"), + "only the archive is to be removed: {detail}" + ); + assert_eq!( + out.stale_purls, + std::collections::BTreeSet::from([GEM_PURL.to_string()]) + ); + assert_eq!(out.gems.len(), 1, "handed to the refresh"); + assert!( + out.gems[0].in_place && out.gems[0].installed == Some((gem_dir.clone(), true)), + "{:?}", + out.gems[0] + ); + + // The grant may spell the sha256 in upper case. + let upper = std::collections::BTreeMap::from([( + ("stale-unit".to_string(), "1.0.0".to_string()), + std::collections::BTreeSet::from([ + hex::encode(Sha256::digest(b"upstream .gem")).to_uppercase() + ]), + )]); + let out = gem_stale_install_warnings( + tmp.path(), + false, + None, + &confirmed, + &records, + &upper, + &mut super::ViewFallback::offline(), + ) + .await; + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + + // The patched archive beside the patched files: nothing is stale. + std::fs::write(&cache, b"patched .gem").unwrap(); + let out = run().await; + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert!(out.stale_purls.is_empty()); + + // No archive: nothing a reinstall could bring back, so the record's + // verdict stands. + std::fs::remove_file(&cache).unwrap(); + let out = run().await; + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert!(out.stale_purls.is_empty() && out.unjudged_purls.is_empty()); + } + /// Committed `vendor/cache` handling, folded flavor: a stale install /// whose project also commits `vendor/cache/.gem` gets that /// archive in the SAME delete list — bundler installs from it first, diff --git a/crates/socket-patch-cli/tests/common/mod.rs b/crates/socket-patch-cli/tests/common/mod.rs index 466fdba6b..d6b49d4c6 100644 --- a/crates/socket-patch-cli/tests/common/mod.rs +++ b/crates/socket-patch-cli/tests/common/mod.rs @@ -367,6 +367,33 @@ pub fn write_minimal_manifest( path } +/// What agent mode records for one file it patched in place: the manifest +/// record of `purl` (`uuid`) for `file_name`, with both blobs. The caller +/// writes `after` over the installed file. +pub fn write_in_place_patch_record( + socket_dir: &Path, + purl: &str, + uuid: &str, + file_name: &str, + before: &[u8], + after: &[u8], +) { + let before_hash = git_sha256(before); + let after_hash = git_sha256(after); + write_minimal_manifest( + socket_dir, + purl, + uuid, + &[PatchEntry { + file_name, + before_hash: &before_hash, + after_hash: &after_hash, + }], + ); + write_blob(socket_dir, &before_hash, before); + write_blob(socket_dir, &after_hash, after); +} + /// Write a hosted redirect ledger (`.socket/vendor/redirect-state.json`) /// under `root` with the given PURL → record entries — the records-only /// shape `scan --mode hosted` persists (tests that need recorded `edits` 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 dd31ec3fc..f48cf9139 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -5296,7 +5296,15 @@ fn stage_warm_install(fx: &RedirectFixture, name: &str) -> PathBuf { /// (`install`, `--redownload`, `pristine`, a frozen install) must succeed /// and keep it: before the refresh they kept the upstream bytes, failed on /// the pinned checksum (exit 37), or left the gem dir deleted. -async fn scan_refreshes_a_warm_install(tag: &str, checksums_lock: bool) { +/// +/// `agent_patched` (#2089): agent mode patched the installed gem in place +/// before the hosted scan, and its manifest record proves it. The files +/// are the patched ones already, but the archive RubyGems reinstalls from +/// is still the upstream one, so `pristine` and `--redownload` removed the +/// gem and failed on the lock's checksum, or brought the unpatched gem +/// back. The scan must replace that archive, and leave the gem dir (where +/// agent mode keeps a native gem's original build) as it is. +async fn scan_refreshes_a_warm_install(tag: &str, checksums_lock: bool, agent_patched: bool) { let Some(fx) = redirect_scanned_project( tag, Spelling::Gemfile, @@ -5316,6 +5324,27 @@ async fn scan_refreshes_a_warm_install(tag: &str, checksums_lock: bool) { orig_lib().into_bytes(), "premise: the upstream gem is installed before the scan" ); + // A file of agent mode's own inside the gem dir. + let kept_in_gem_dir = agent_patched.then(|| { + lib.parent() + .and_then(Path::parent) + .expect("/lib/") + .join(".socket-patch-kept") + }); + if agent_patched { + // What `scan --mode agent` leaves: the lib patched in place, the + // record of it, and both blobs. + std::fs::write(&lib, 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(), + ); + std::fs::write(kept_in_gem_dir.as_ref().unwrap(), "kept").unwrap(); + } let api = fx._server.uri(); let (code, stdout, stderr) = run_hosted_scan(&dir, &api); @@ -5338,6 +5367,12 @@ async fn scan_refreshes_a_warm_install(tag: &str, checksums_lock: bool) { patched_lib().into_bytes(), "the installed gem is the patched one right after the scan" ); + if let Some(kept) = &kept_in_gem_dir { + assert!( + kept.is_file(), + "only the archive beside a gem patched in place is replaced" + ); + } // With no CHECKSUMS section the scan leaves the lock for one unfrozen // `bundle install` to converge (`redirect_gem_frozen_install`); with @@ -5384,14 +5419,28 @@ async fn scan_refreshes_a_warm_install(tag: &str, checksums_lock: bool) { #[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_hosted_scan_refreshes_a_warm_install() { - scan_refreshes_a_warm_install("warm-refresh", false).await; + scan_refreshes_a_warm_install("warm-refresh", false, false).await; } #[tokio::test(flavor = "multi_thread")] #[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] async fn gem_hosted_scan_refreshes_a_warm_install_with_a_checksums_lock() { - scan_refreshes_a_warm_install("warm-refresh-checksums", true).await; + scan_refreshes_a_warm_install("warm-refresh-checksums", true, false).await; +} + +#[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_hosted_scan_refreshes_an_agent_patched_warm_install() { + scan_refreshes_a_warm_install("warm-refresh-agent", false, true).await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_scan_refreshes_an_agent_patched_warm_install_with_a_checksums_lock() { + scan_refreshes_a_warm_install("warm-refresh-agent-checksums", true, true).await; } /// The vendored half of the patch API for the fixture's patch: the 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 6e68f5af5..44e4c012b 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 @@ -2783,3 +2783,230 @@ async fn refresh_is_not_run_by_a_hosted_to_vendored_takeover() { } } } + +/// 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) +/// that proves the patch. Returns the gem dir. +fn agent_patched_install(proj: &Path, home: &Path) -> PathBuf { + let gem_dir = install_real_gem(home, UPSTREAM_LIB); + std::fs::write(gem_dir.join("lib").join("stale_probe_gem.rb"), PATCHED_LIB).unwrap(); + common::write_in_place_patch_record( + &proj.join(".socket"), + PURL, + UUID, + "lib/stale_probe_gem.rb", + UPSTREAM_LIB.as_bytes(), + PATCHED_LIB.as_bytes(), + ); + // A file of agent mode's own inside the gem dir (a native gem keeps its + // original build there). + std::fs::write(gem_dir.join(".socket-patch-kept"), "kept").unwrap(); + gem_dir +} + +/// #2089: a gem agent mode patched in place keeps the upstream archive in +/// the gem home's `cache/`. Once the hosted scan pins the patched gem's +/// checksum in the lock, `bundle pristine` and `bundle install +/// --redownload` reinstall from that archive: Bundler 2.6 and later remove +/// the gem and fail on the checksum, older ones bring the unpatched gem +/// back. So the scan replaces that archive with the patched gem and leaves +/// the gem dir, whose files are patched already, exactly as it is; +/// `rollback` still gives the upstream gem back. +#[tokio::test(flavor = "multi_thread")] +async fn refresh_replaces_the_upstream_archive_beside_an_agent_patched_install() { + 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"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = project_home(&proj); + let gem_dir = agent_patched_install(&proj, &home); + let cache = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); + assert_eq!(std::fs::read(&cache).unwrap(), upstream, "fixture"); + + // A dry run says the copy would be replaced and changes nothing. + let uri = server.uri(); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &scan_args(&proj, &uri, &["--json", "--dry-run"]), + &[], + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!( + warnings_with_code(&env, "redirect_gem_install_would_refresh").len(), + 1, + "{env}" + ); + assert_eq!(std::fs::read(&cache).unwrap(), upstream); + + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!(hosted_pinned(&env), 1, "{env}"); + assert!( + stale_warnings(&env).is_empty(), + "nothing is left stale: {env}" + ); + let notes = warnings_with_code(&env, "redirect_gem_install_refreshed"); + assert!( + notes.len() == 1 + && notes[0].contains(&cache.display().to_string()) + && notes[0].contains("patched in place"), + "the archive, and only it: {env}" + ); + assert!( + gem_dir.join(".socket-patch-kept").is_file(), + "the gem dir is not replaced" + ); + assert_eq!( + std::fs::read(&cache).unwrap(), + patched, + "the archive RubyGems reinstalls from is the one the lock pins" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + assert!( + !home.join(".socket-patch-refresh").exists(), + "no stage left" + ); + + // A re-scan has nothing to refresh and nothing to warn about. + let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &[]); + assert_eq!(code, 0, "{stderr}"); + assert!( + !stderr.contains("Replaced") + && !stderr.contains("upstream archive") + && !stderr.contains("still unpatched"), + "{stderr}" + ); + + // `rollback` undoes both the hosted pin and the agent record: the + // upstream files and the upstream archive are back. + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + let rubygems = format!("{uri}/upstream"); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &[ + "rollback", + "--yes", + "--json", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + uri.as_str(), + ], + &[("SOCKET_RUBYGEMS_URL", rubygems.as_str())], + ); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB); + assert_eq!(std::fs::read(&cache).unwrap(), upstream); +} + +/// The same copy where the run may not replace it: it is left byte for +/// byte as it was, and the warning says what is wrong with it (the archive, +/// not the files, which are patched) and how to fix it. A shared gem home +/// gets the project-local path or `--gem-refresh-shared`; +/// `--no-gem-install-refresh` gets the files to remove. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn an_agent_patched_install_the_run_may_not_replace_is_warned_about() { + 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; + let uri = server.uri(); + let leaf = format!("{DEP}-{DEP_VERSION}"); + + // Project-local, refresh turned off. + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = project_home(&proj); + let gem_dir = agent_patched_install(&proj, &home); + let cache = home.join("cache").join(format!("{leaf}.gem")); + let spec = home.join("specifications").join(format!("{leaf}.gemspec")); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &scan_args(&proj, &uri, &["--json", "--no-gem-install-refresh"]), + &[], + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\n{stderr}"); + let details = stale_warnings(&env); + assert_eq!(details.len(), 1, "{env}"); + for needle in [ + "patched in place", + "`--no-gem-install-refresh` is set", + &format!("emove {} and run `bundle install`", cache.display()), + ] { + assert!( + details[0].contains(needle), + "missing {needle:?}: {details:?}" + ); + } + assert!( + !details[0].contains("unpatched install") + && !details[0].contains(&spec.display().to_string()), + "the installed files are patched, and stay installed: {details:?}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + assert_eq!(std::fs::read(&cache).unwrap(), upstream); + + // A shared gem home. + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = tmp.path().join("system-home"); + let bin_dir = tmp.path().join("fake-bin"); + stage_system_home_copy(&home, &bin_dir); + let gem_dir = agent_patched_install(&proj, &home); + let cache = home.join("cache").join(format!("{leaf}.gem")); + let path_env = [("PATH", bin_dir.to_str().unwrap())]; + let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &path_env); + assert_eq!(code, 0, "{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + assert_eq!( + std::fs::read(&cache).unwrap(), + upstream, + "the shared home is not touched" + ); + for needle in [ + "Warning: 1 gem patched in place still has its upstream archive on disk after the \ + switch to hosted patches.", + &format!( + " - Shared gem home {} (left alone, other projects may load it): {DEP} {DEP_VERSION}.", + home.display() + ), + "run `bundle config set --local path vendor/bundle && bundle install`", + "`--gem-refresh-shared`", + ] { + assert!(stderr.contains(needle), "missing {needle:?}:\n{stderr}"); + } + assert!(!stderr.contains("still unpatched on disk"), "{stderr}"); + + let (code, stdout, stderr) = common::run_with_env( + &proj, + &scan_args(&proj, &uri, &["--json", "--gem-refresh-shared"]), + &path_env, + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert!(stale_warnings(&env).is_empty(), "{env}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + assert_eq!(std::fs::read(&cache).unwrap(), patched); + assert!(gem_dir.join(".socket-patch-kept").is_file()); +} diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 6de6d91b6..4f531acdd 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1952,6 +1952,13 @@ rewrites the lock: - an archive in Bundler's cache dir (`vendor/cache`, or the configured `cache_path`). It is a committed file: the run lists it with the files to commit. +A gem that agent mode patched in place (`scan --mode agent`, `apply`) counts too. Its files are +already the patched ones, but the archive RubyGems kept beside it is still the upstream one, and +`bundle pristine` and `bundle install --redownload` reinstall from that archive: with a +`CHECKSUMS` section in the lock Bundler removes the gem and fails on the checksum, without one it +brings the unpatched gem back. So that archive is replaced with the patched one. The installed +files are left as they are. + They are replaced with the patched `.gem` the lock pins, checked against that sha256 first. A gem with a native extension is installed into a staging directory by RubyGems, with the Ruby that owns the installed copy, and swapped in once it has compiled; with no such Ruby, or with