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
8 changes: 7 additions & 1 deletion crates/socket-patch-cli/CLI_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -1709,7 +1709,13 @@ the model is **not uniform** today:
touch it (#709). Explicit env/config/standalone roots only count when `--cwd` holds a Bundler
manifest/lockfile. When the default `vendor/bundle` root holds no store, the gem homes `gem env`
reports are appended (default gems like json/uri only ever live there); which of the copies
found there are written is the "Copy classes" rule below. When the Bundler tier that
found there are written is the "Copy classes" rule below. The question is asked as
`gem env gemdir --norc` and `gem env gempath --norc`, which is Ruby's own `Gem.dir` and
`Gem.path` (`GEM_HOME` and `GEM_PATH` included): the gemrc keys `gemhome` and `gempath` move
only the `gem` command's directories, Ruby and Bundler never read them, so a directory only a
gemrc names is not one the project's (or, under `--global`, the machine's) gems are loaded
from, and it is not read (#2317). A `gem` that gives no answer with `--norc` is asked the same
question without it. When the Bundler tier that
decides the install path (the first of the app config, the environment and the global config that
sets `path`, `path.system` or `disable_shared_gems`) sets a truthy `path.system` (Bundler's own
coercion: anything but `false`/`f`/`no`/`n`/`0`/empty), bundler installs into and loads from the
Expand Down
105 changes: 105 additions & 0 deletions crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1143,3 +1143,108 @@ fn mismatched_home_copy_warns_on_human_stderr() {
);
assert_eq!(std::fs::read(&fx.home_file).unwrap(), foreign);
}

// ── A gemrc that moves the `gem` command's directories (#2317) ──────────

/// A `gem` that answers as the real command does under a gemrc that sets
/// `gemhome`: `env gemdir` and `env gempath` name `gemrc_home`, and only
/// with `--norc` the home Ruby itself loads from, `ruby_home`.
fn install_fake_gem_with_gemrc(bin_dir: &Path, gemrc_home: &Path, ruby_home: &Path) {
use std::os::unix::fs::PermissionsExt;
let script = format!(
"#!/bin/sh\n\
[ \"$1\" = env ] || exit 1\n\
case \"$2\" in gemdir|gempath) ;; *) exit 1 ;; esac\n\
for arg in \"$@\"; do\n\
if [ \"$arg\" = --norc ]; then printf '%s\\n' \"{ruby}\"; exit 0; fi\n\
done\n\
printf '%s\\n' \"{gemrc}\"\n",
ruby = ruby_home.display(),
gemrc = gemrc_home.display(),
);
let bin = bin_dir.join("gem");
std::fs::write(&bin, script).unwrap();
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
}

/// The system-gems fixture under such a gemrc: `gem-home` is the home
/// Ruby loads the project's gem from. Returns the copy in the gemrc's
/// directory, staged when `gemrc_copy` is given.
fn under_a_gemrc(fx: &Fixture, gemrc_copy: Option<&[u8]>) -> PathBuf {
let gemrc_home = fx.project.path().join("gemrc-home");
std::fs::create_dir_all(gemrc_home.join("gems")).unwrap();
install_fake_gem_with_gemrc(&fx.bin_dir, &gemrc_home, &home_dir(fx));
match gemrc_copy {
Some(bytes) => stage_copy(&gemrc_home, bytes),
None => gemrc_home.join("gems/rack-3.1.0/lib/rack.rb"),
}
}

/// `gemhome` in a gemrc, and the gem installed where Bundler put it
/// (Ruby's own gem home): the gem is installed, so `apply` patches it and
/// the check judges it. On `main` both exited 0 with the patch "not
/// installed, skipped", and the copy Ruby loads stayed unpatched.
#[test]
fn a_gemrc_gemhome_does_not_hide_the_copy_ruby_loads() {
let fx = build_fixture(Store::SystemGems, Home::Installed, ORIGINAL, BASE_PURL);
write_lock(&fx);
let gemrc_file = under_a_gemrc(&fx, None);

let (code, stdout, stderr) = run_command(&fx, &["apply", "--check"], &["--json"]);
let env = parse_env(&stdout);
assert_eq!(
code, 1,
"the unpatched copy Ruby loads is drift.\nenvelope: {env}\nstderr:\n{stderr}"
);

let (code, stdout, stderr) = run_apply(&fx, &["--json"]);
let env = parse_env(&stdout);
assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}");
assert_eq!(env["summary"]["applied"], 1, "envelope: {env}");
assert_eq!(
std::fs::read(&fx.home_file).unwrap(),
patched_bytes(),
"the copy Ruby loads must be patched"
);
assert!(!gemrc_file.exists(), "nothing is written for the gemrc");

let (code, stdout, stderr) = run_command(&fx, &["apply", "--check"], &["--json"]);
assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");
}

/// The gemrc's directory holds the same gem version (it is where
/// `gem install` puts gems on that machine). The project loads nothing
/// from it: the copy Ruby loads is the one patched and checked, and the
/// gemrc's copy is not written. On `main` the gemrc's copy was patched
/// and attested while the application kept loading unpatched code.
#[test]
fn a_copy_in_the_gemrc_gemhome_is_not_patched_in_place_of_rubys() {
let fx = build_fixture(Store::SystemGems, Home::Installed, ORIGINAL, BASE_PURL);
write_lock(&fx);
let gemrc_file = under_a_gemrc(&fx, Some(ORIGINAL));

let (code, stdout, stderr) = run_apply(&fx, &["--json"]);
let env = parse_env(&stdout);
assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}");
assert_eq!(env["summary"]["applied"], 1, "envelope: {env}");
assert_eq!(
std::fs::read(&fx.home_file).unwrap(),
patched_bytes(),
"the copy Ruby loads must be patched"
);
assert_eq!(
std::fs::read(&gemrc_file).unwrap(),
ORIGINAL,
"the gemrc's copy is not one the project loads"
);

// The check reads the copy Ruby loads: put the upstream bytes back
// there, leave patched bytes in the gemrc's copy, and it is drift.
std::fs::write(&fx.home_file, ORIGINAL).unwrap();
std::fs::write(&gemrc_file, patched_bytes()).unwrap();
let (code, stdout, stderr) = run_command(&fx, &["apply", "--check"], &["--json"]);
assert_eq!(
code, 1,
"a patched copy in the gemrc's directory proves nothing.\n{stdout}\n{stderr}"
);
}
130 changes: 130 additions & 0 deletions crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5463,3 +5463,133 @@ fn a_home_of_two_rubies_is_attested_from_the_first_graft() {
assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}");
assert_tree(&proj.join("vendor"), &tree_before, "after rollback");
}

// ── A gemrc that moves the `gem` command's directories (#2317) ──────────

/// One line of `cmd args` under `env`.
fn tool_says(cmd: &str, args: &[&str], env: &[(&str, &str)]) -> String {
let out = Command::new(cmd)
.args(args)
.envs(env.iter().copied())
.env_remove("RUBYOPT")
.output()
.unwrap();
assert!(
out.status.success(),
"{cmd} {args:?} failed:\n{}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}

/// The `gem` command applies the gemrc keys `gemhome` and `gempath` to
/// its own directories; Ruby and Bundler never read them. With the real
/// `gem` and `ruby`: a gemrc sends the `gem` command to one directory
/// while Ruby loads from another, both hold the gem, and agent mode must
/// patch and check the copy Ruby loads and leave the other alone. On
/// `main` the gemrc's copy was patched and `apply --check` passed over
/// the unpatched copy Ruby loads.
#[test]
#[ignore = "host capstone: asks the real gem and ruby for their directories; \
the unpinned `test` job skips it, the pinned-Ruby e2e leg runs it via --ignored"]
fn a_gemrc_gemhome_is_not_read_in_place_of_rubys_gem_dirs() {
if !(tool_works("ruby", &["-v"]) && tool_works("gem", &["--version"])) {
assert!(
!required(),
"SOCKET_PATCH_BUNDLER_E2E_REQUIRED=1 but ruby or gem is missing"
);
eprintln!("SKIP: ruby or gem is not available");
return;
}
const GEM_PURL: &str = "pkg:gem/sp_gemrc@1.0.0";
const BEFORE: &[u8] = b"module SpGemrc\n VALUE = 1\nend\n";
const AFTER: &[u8] = b"module SpGemrc\n VALUE = 2\nend\n";

let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let stage = |home: &Path| {
let file = home.join("gems/sp_gemrc-1.0.0/lib/sp_gemrc.rb");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, BEFORE).unwrap();
std::fs::create_dir_all(home.join("specifications")).unwrap();
file
};
// The home Ruby loads from (`GEM_HOME`), and the one the gemrc names.
let ruby_home = root.join("ruby-home");
let gemrc_home = root.join("gemrc-home");
let ruby_copy = stage(&ruby_home);
let gemrc_copy = stage(&gemrc_home);
let gemrc = root.join("gemrc");
std::fs::write(&gemrc, format!("gemhome: {}\n", gemrc_home.display())).unwrap();

let proj = root.join("proj");
std::fs::create_dir_all(&proj).unwrap();
std::fs::write(proj.join("Gemfile"), "source \"https://rubygems.org\"\n").unwrap();
std::fs::write(
proj.join("Gemfile.lock"),
"GEM\n remote: https://rubygems.org/\n specs:\n sp_gemrc (1.0.0)\n\n\
PLATFORMS\n ruby\n\nDEPENDENCIES\n sp_gemrc\n\nBUNDLED WITH\n 2.5.22\n",
)
.unwrap();
let socket = proj.join(".socket");
let (bh, ah) = (git_sha256(BEFORE), git_sha256(AFTER));
write_minimal_manifest(
&socket,
GEM_PURL,
"23172317-2317-4317-8317-231723172317",
&[PatchEntry {
file_name: "lib/sp_gemrc.rb",
before_hash: &bh,
after_hash: &ah,
}],
);
write_blob(&socket, &ah, AFTER);
write_blob(&socket, &bh, BEFORE);

let env = [
("GEMRC", gemrc.to_str().unwrap()),
("GEM_HOME", ruby_home.to_str().unwrap()),
("SOCKET_RUBYGEMS_URL", NO_REGISTRY),
];
// The premise, from the real tools: the two disagree under the gemrc.
assert_eq!(
tool_says("gem", &["env", "gemdir"], &env),
gemrc_home.to_str().unwrap(),
"the gem command follows the gemrc"
);
let gem_path = tool_says("ruby", &["-e", "puts Gem.path"], &env);
let gem_path: Vec<&str> = gem_path.lines().collect();
assert!(
gem_path.contains(&ruby_home.to_str().unwrap()),
"{gem_path:?}"
);
assert!(
!gem_path.contains(&gemrc_home.to_str().unwrap()),
"Ruby does not read the gemrc's gemhome: {gem_path:?}"
);

let run = |args: &[&str]| common::run_with_env(&proj, args, &env);
let (code, stdout, stderr) = run(&["apply", "--check", "--ecosystems", "gem"]);
assert_eq!(
code, 1,
"the copy Ruby loads is unpatched:\n{stdout}\n{stderr}"
);

let (code, stdout, stderr) = run(&["apply", "--json", "--offline", "--ecosystems", "gem"]);
assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}");
let event = common::envelope::event_for(&parse_json_envelope(&stdout), GEM_PURL).clone();
assert_eq!(event["action"], "applied", "{stdout}");
assert_eq!(
std::fs::read(&ruby_copy).unwrap(),
AFTER,
"the copy Ruby loads must be patched"
);
assert_eq!(
std::fs::read(&gemrc_copy).unwrap(),
BEFORE,
"the gemrc's copy is not one Ruby loads"
);

let (code, stdout, stderr) = run(&["apply", "--check", "--ecosystems", "gem"]);
assert_eq!(code, 0, "{stdout}\n{stderr}");
}
31 changes: 25 additions & 6 deletions crates/socket-patch-core/src/crawlers/ruby_crawler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,9 +311,10 @@ impl RubyCrawler {
false
}

/// The gem homes `gem env` itself reports, each mapped to its `gems/`
/// subdirectory: `gemdir` (the active `GEM_HOME`) first, then every
/// `gempath` (`GEM_PATH`) entry. Non-existent homes and duplicates are
/// The gem homes `gem env` reports with no gemrc applied
/// ([`Self::run_gem_env`]), each mapped to its `gems/` subdirectory:
/// `gemdir` (Ruby's `Gem.dir`, the active `GEM_HOME`) first, then
/// every `gempath` (`Gem.path`, `GEM_PATH`) entry. Non-existent homes and duplicates are
/// dropped, so the result is the deduped set of installed-gem roots in
/// RubyGems' own precedence order.
///
Expand Down Expand Up @@ -1059,12 +1060,30 @@ impl RubyCrawler {
.await
}

/// Run `gem env <key>` (on the blocking pool — it waits on a
/// Run `gem env <key> --norc` (on the blocking pool — it waits on a
/// subprocess) and return the trimmed stdout.
///
/// `--norc` makes the answer Ruby's own `Gem.dir` / `Gem.path`. The
/// `gem` command applies the gemrc keys `gemhome` and `gempath`
/// (`~/.gemrc`, the system gemrc, a `GEMRC` file) to its own
/// directories, and nothing else reads them: `require`, `bundle
/// install` and `bundle exec` load from the directories the
/// environment gives. Without the flag a gemrc that sets either key
/// names a directory the project loads nothing from and hides the
/// ones it does (#2317). `GEM_HOME` and `GEM_PATH` are the
/// environment's and count either way.
///
/// A `gem` that gives no answer with the flag (one too old to know
/// it, or a wrapper that refuses it) is asked again without it, the
/// question every release before this one asked: its answer is right
/// wherever no gemrc sets those keys, and no answer at all would
/// report every gem of a system-gems project as not installed.
async fn run_gem_env(key: &'static str, runner: ProbeRunner) -> Option<String> {
run_blocking(move || {
let stdout = runner.run("gem", &["env", key]);
parse_gem_env_output(stdout.as_deref().unwrap_or(""))
let ask = |args: &[&str]| {
parse_gem_env_output(runner.run("gem", args).as_deref().unwrap_or(""))
};
ask(&["env", key, "--norc"]).or_else(|| ask(&["env", key]))
})
.await
}
Expand Down
Loading
Loading