Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/socket-patch-cli/CLI_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ 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`; no delete list for a copy that was only left alone); 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; where `bundle install` would not replace the copy, the list starts with the gem directory itself, holds only the files that are still there, and the human warning's command is `rm -rf … && bundle install`: after a refresh that was tried and failed, a copy whose native extension a Ruby the run asked builds into another gem home (one in the tree of an earlier Ruby, `vendor/bundle/ruby/3.2.0`), for which the re-run named is one "with the Ruby that installed the gem first on `PATH`", and a gem directory whose gemspec is gone, for which no re-run is named); 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.
- 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`; no delete list for a copy that was only left alone); 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; where `bundle install` would not replace the copy, the list starts with the gem directory itself, holds only the files that are still there, and the human warning's command is `rm -rf … && bundle install`: after a refresh that was tried and failed, a copy whose native extension a Ruby the run asked builds into another gem home (one in the tree of an earlier Ruby, `vendor/bundle/ruby/3.2.0`), for which the re-run named is one "with the Ruby that installed the gem first on `PATH`", and a gem directory whose gemspec is gone, for which no re-run is named; and, after a refresh that was turned off or failed for any other reason, a copy (not a default gem's) whose gem home has another Ruby's beside it (`vendor/bundle/ruby/3.2.0` next to `ruby/3.3.0`), with the re-run that reason has otherwise); 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.

Expand Down
212 changes: 198 additions & 14 deletions crates/socket-patch-cli/src/commands/gem_refresh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use socket_patch_core::crawlers::ruby_crawler::is_default_gem_copy;
use socket_patch_core::crawlers::Ecosystem;
use socket_patch_core::formats::gem::GemBuild;
use socket_patch_core::manifest::schema::PatchRecord;
Expand Down Expand Up @@ -415,23 +416,83 @@ enum Outlives {
/// The gemspec is gone already: the gem dir is what is left of an
/// install, and nothing puts a gem back over it.
NoGemspec,
/// Nothing says the copy is another Ruby's, but its gem home is
/// beside another Ruby's (`vendor/bundle/ruby/3.2.0` next to
/// `ruby/3.3.0`): the Ruby that runs `bundle install` may install into
/// the other one.
BesideAnotherRuby,
}

/// Whether the gem home of the gem dir `<home>/gems/<leaf>` has another
/// Ruby's gem home beside it. Bundler and RubyGems keep one gem home per
/// Ruby ABI under one directory, each named by the ABI version
/// (`vendor/bundle/ruby/3.2.0`, `ruby/3.3.0`), and which of them
/// `bundle install` fills is up to the Ruby that runs it. Two gem homes
/// side by side under other names (`GEM_HOME`s someone picked) are not
/// that.
fn beside_another_gem_home(gem_dir: &Path) -> bool {
// `3.2.0`, `3.4.0+1` (a development Ruby), `9.4`.
let abi_named = |path: &Path| {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| {
name.starts_with(|c: char| c.is_ascii_digit())
&& name.contains('.')
&& name
.chars()
.all(|c| c.is_ascii_digit() || c == '.' || c == '+')
})
};
let Some(home) = gem_dir.parent().and_then(Path::parent) else {
return false;
};
if !abi_named(home) {
return false;
}
let Some(entries) = home
.parent()
.and_then(|homes| std::fs::read_dir(homes).ok())
else {
return false;
};
entries.flatten().any(|entry| {
let other = entry.path();
other.file_name() != home.file_name()
&& abi_named(&other)
&& other.join("gems").is_dir()
&& other.join("specifications").is_dir()
})
}

/// Whether the remedy for `gem`'s installed copy has to remove the gem
/// dir itself, and why. Only a copy a refresh failed on, never one left
/// alone (a shared home, a path outside the project,
/// `--no-gem-install-refresh`) or patched in place.
/// dir itself, and why. Only a copy a refresh failed on or was turned off
/// for (`--no-gem-install-refresh`), never one left alone for where it is
/// (a shared home, a path outside the project) or patched in place.
///
/// A refresh that found the copy in a tree no Ruby it asked installs into
/// says so. Any other (it is turned off, the gem could not be had, the
/// native rebuild is turned off or failed) does not say which Ruby will
/// run `bundle install`, and then a gem home beside another Ruby's is
/// reason enough: removing the gem dir is right whichever Ruby that is.
/// Not for a default gem, though: its gemspec stays under
/// `specifications/default/`, so nothing would put the gem dir back.
fn outlives_reinstall(gem: &StaleGem, why: Option<&Why>) -> Option<Outlives> {
let (Some((dir, _)), false, Some(Why::Failed(reason))) = (&gem.installed, gem.in_place, why)
else {
let (Some((dir, _)), false) = (&gem.installed, gem.in_place) else {
return None;
};
if gemspec_is_gone(dir) {
Some(Outlives::NoGemspec)
} else if reason.contains(socket_patch_core::patch::gem_ext::OWNED_BY_ANOTHER_RUBY) {
Some(Outlives::ForeignRuby)
} else {
None
match why {
Some(Why::Failed(_)) if gemspec_is_gone(dir) => Some(Outlives::NoGemspec),
Some(Why::Failed(reason))
if reason.contains(socket_patch_core::patch::gem_ext::OWNED_BY_ANOTHER_RUBY) =>
{
Some(Outlives::ForeignRuby)
}
Some(Why::Failed(_) | Why::Disabled)
if beside_another_gem_home(dir) && !is_default_gem_copy(dir) =>
{
Some(Outlives::BesideAnotherRuby)
}
_ => None,
}
}

Expand Down Expand Up @@ -528,6 +589,25 @@ fn reinstall_command(files: &[PathBuf], with_dirs: bool) -> String {
const GEM_DIR_REMOVED: &str = "The gem directory is removed too: `bundle install` does not \
replace a copy that has no gemspec or is in the gem home of another Ruby";

/// Why a remedy removes the gem dir of a copy whose gem home is beside
/// another Ruby's ([`Outlives::BesideAnotherRuby`]), after the remedy.
const BESIDE_ANOTHER_RUBY: &str = "The gem directory is removed too: `bundle install` replaces \
a copy only in the gem home of the Ruby that runs it, and more than one Ruby has a gem home \
here";

/// Why a remedy removes a gem dir, after the remedy: `outlives` is why
/// each of its copies that outlives a reinstall does.
fn gem_dir_removed(outlives: impl IntoIterator<Item = Outlives>) -> &'static str {
if outlives
.into_iter()
.all(|one| one == Outlives::BesideAnotherRuby)
{
BESIDE_ANOTHER_RUBY
} else {
GEM_DIR_REMOVED
}
}

/// `action` after `hint` (which ends mid-sentence), or as a sentence of
/// its own when there is none.
fn after_hint(hint: &str, action: &str) -> String {
Expand Down Expand Up @@ -628,17 +708,18 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh
}
Some((dir, _)) => {
let (paths, with_dir) = remedy_paths(gem, why);
let outlives = outlives_reinstall(gem, why);
format!(
"{purl} {switched}, but its {stale} install at {} was not refreshed{}, and \
{reuse}. {}{}",
dir.display(),
reason(why),
after_hint(
retry_hint(direction, why, outlives_reinstall(gem, why)),
retry_hint(direction, why, outlives),
&format!("remove {} and run `bundle install`", display_list(&paths))
),
if with_dir {
format!(". {GEM_DIR_REMOVED}")
format!(". {}", gem_dir_removed(outlives))
} else {
String::new()
},
Expand Down Expand Up @@ -938,7 +1019,10 @@ pub(crate) fn report(
.flatten();
let mut reinstall = format!("run `{}`", reinstall_command(&files, with_dirs));
if with_dirs {
reinstall.push_str(&format!(". {GEM_DIR_REMOVED}"));
let kinds = gems
.iter()
.filter_map(|gem| outlives_reinstall(gem, Some(why)));
reinstall.push_str(&format!(". {}", gem_dir_removed(kinds)));
}
let names = labels(gems.iter().map(|gem| gem.purl.as_str()));
bullets.push(match why {
Expand Down Expand Up @@ -2506,6 +2590,106 @@ mod tests {
);
}

/// #2242: a stale copy in a gem home beside another Ruby's
/// (`vendor/bundle/ruby/3.2.0` next to `ruby/3.3.0`), left before any
/// Ruby was asked which tree it installs into: the refresh is turned
/// off, the patched gem could not be had, or the native rebuild is
/// turned off. `bundle install` replaces the copy only when the Ruby
/// that runs it owns that tree, so the remedy removes the gem dir too,
/// which works with either Ruby. The re-run it names is unchanged.
#[tokio::test]
async fn a_copy_beside_another_rubys_tree_is_removed_with_its_gem_dir() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("vendor/bundle/ruby/3.2.0");
let gem = installed("json", &home, true);
let (dir, _) = gem.installed.clone().unwrap();
let spec = home.join("specifications/json-1.0.0.gemspec");
let rm_rf = format!(
"run `rm -rf {} {} && bundle install`",
dir.display(),
spec.display()
);
let rm_f = format!("run `rm -f {} ", spec.display());
let off = policy(tmp.path(), false, false, false);
let on = policy(tmp.path(), true, false, false);
let disabled = pass(std::slice::from_ref(&gem), &off).await;
let offline = pass(std::slice::from_ref(&gem), &on).await;
let no_rebuild = failed_for(
&gem,
"it builds a native extension, and --no-gem-native-rebuild is set",
);
let cases = [
(
&disabled,
&off,
"Re-run without `--no-gem-install-refresh`, or ",
),
(&offline, &on, "Re-run `socket-patch scan` to retry, or "),
(&no_rebuild, &on, "Re-run `socket-patch scan` to retry, or "),
];
let bullet_of = |pass: &Attempt, policy: &Policy, direction: Direction| {
let out = report(direction, std::slice::from_ref(&gem), pass, policy);
let detail = out.warnings[0].1.clone();
(out.summary.unwrap().bullets[0].clone(), detail)
};

// The only Ruby tree of its bundle path: the remedy it was.
for (pass, policy, retry) in cases {
let (bullet, _) = bullet_of(pass, policy, Direction::Patched);
assert!(bullet.contains(&format!("{retry}{rm_f}")), "{bullet}");
assert!(!bullet.contains("rm -rf"), "{bullet}");
}

// Nor does a directory beside it that is no Ruby's gem home: an
// empty ABI dir, a gem home under a name that is no ABI's.
std::fs::create_dir_all(home.with_file_name("3.1.0")).unwrap();
for part in ["gems", "specifications"] {
std::fs::create_dir_all(home.with_file_name("shared").join(part)).unwrap();
}
let (bullet, _) = bullet_of(&disabled, &off, Direction::Patched);
assert!(bullet.contains(&rm_f), "{bullet}");

// The tree of another Ruby beside it.
let other = home.with_file_name("3.3.0");
std::fs::create_dir_all(other.join("gems")).unwrap();
std::fs::create_dir_all(other.join("specifications")).unwrap();
for (pass, policy, retry) in cases {
let (bullet, detail) = bullet_of(pass, policy, Direction::Patched);
assert!(bullet.contains(&format!("{retry}{rm_rf}")), "{bullet}");
assert!(bullet.contains(BESIDE_ANOTHER_RUBY), "{bullet}");
let removed = format!(
"{retry}remove {}, {} and run `bundle install`. {BESIDE_ANOTHER_RUBY}",
dir.display(),
spec.display()
);
assert!(detail.contains(&removed), "{detail}");

// An unwind names no re-run, and the same paths.
let (bullet, _) = bullet_of(pass, policy, Direction::Upstream);
assert!(bullet.contains(&format!("R{}", &rm_rf[1..])), "{bullet}");
assert!(!bullet.contains("Re-run"), "{bullet}");
}

// A default gem keeps its gem dir: its entry under
// `specifications/default/` stays, so nothing would reinstall it.
std::fs::create_dir_all(home.join("specifications/default")).unwrap();
let default_spec = home.join("specifications/default/json-1.0.0.gemspec");
std::fs::write(&default_spec, "").unwrap();
let (bullet, _) = bullet_of(&disabled, &off, Direction::Patched);
assert!(bullet.contains(&rm_f), "{bullet}");
std::fs::remove_file(&default_spec).unwrap();

// A copy patched in place keeps its gem dir: only the archive
// beside it is stale.
let mut in_place = gem.clone();
in_place.in_place = true;
let detail = stale_detail(Direction::Patched, &in_place, Some(&Why::Disabled));
assert!(
!detail.contains(&format!("remove {}", dir.display())),
"{detail}"
);
}

#[test]
fn refreshed_gems_are_notes_and_one_progress_line_each_kind() {
let pass = Attempt {
Expand Down
Loading
Loading