Skip to content
Merged
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
102 changes: 102 additions & 0 deletions crates/socket-patch-cli/tests/apply/gem_without_lib_dir.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
//! A gem that ships neither `lib/` nor a `.gemspec` in its own dir.
//!
//! `cassandra-web` packs `app.rb`, `app/` and `bin/` at its root; RubyGems
//! writes its spec only to `<home>/specifications/<leaf>.gemspec`. The
//! crawler judged an installed gem dir by `lib/` or an in-dir `.gemspec`, so
//! such a gem was never found and `apply` exited 1 with "The targeted
//! manifest patch matched no installed package", in agent mode and under
//! `--global --global-prefix <home>/gems` alike.

use std::path::{Path, PathBuf};

use serde_json::json;

use crate::apply_fixture::{
one_file, patch_record, run_gem, run_gem_apply, stage_blob, write_manifest,
};
use crate::common::git_sha256;

const PURL: &str = "pkg:gem/cassandra-web@0.5.0";
const LEAF: &str = "cassandra-web-0.5.0";
const ORIGINAL: &[u8] = b"class App < Sinatra::Base\n disable :protection\nend\n";
const PATCHED: &[u8] =
b"class App < Sinatra::Base\n set :protection, :except => [:json_csrf]\nend\n";

/// The gem home `<root>/vendor/bundle/ruby/3.4.0` holding `gems/<LEAF>/app.rb`
/// (and nothing else in the gem dir), with `specifications/<LEAF>.gemspec`
/// when `with_spec`, plus a manifest patching `app.rb`. Returns the home
/// and the installed file.
fn lib_less_gem(root: &Path, with_spec: bool) -> (PathBuf, PathBuf) {
let home = root.join("vendor/bundle/ruby/3.4.0");
let gem_dir = home.join("gems").join(LEAF);
std::fs::create_dir_all(gem_dir.join("bin")).unwrap();
std::fs::write(gem_dir.join("bin/cassandra-web"), b"#!/usr/bin/env ruby\n").unwrap();
let file = gem_dir.join("app.rb");
std::fs::write(&file, ORIGINAL).unwrap();
let specs = home.join("specifications");
std::fs::create_dir_all(&specs).unwrap();
if with_spec {
std::fs::write(specs.join(format!("{LEAF}.gemspec")), b"# installed spec\n").unwrap();
}
write_manifest(
root,
json!({ PURL: patch_record(
"63617373-616e-4472-a177-656200000000",
one_file("app.rb", ORIGINAL, PATCHED),
)}),
);
stage_blob(root, &git_sha256(PATCHED), PATCHED);
(home, file)
}

#[test]
fn a_gem_with_no_lib_dir_is_patched_by_its_installed_spec() {
let tmp = tempfile::tempdir().unwrap();
let (_home, file) = lib_less_gem(tmp.path(), true);

let (code, stdout, stderr) = run_gem_apply(tmp.path(), &[]);
assert_eq!(code, 0, "stdout={stdout} stderr={stderr}");
assert_eq!(std::fs::read(&file).unwrap(), PATCHED);
}

#[test]
fn a_gem_with_no_lib_dir_is_patched_under_a_global_prefix() {
let tmp = tempfile::tempdir().unwrap();
let (home, file) = lib_less_gem(tmp.path(), true);
let cwd = tmp.path().to_str().unwrap();
let prefix = home.join("gems");

let (code, stdout, stderr) = run_gem(
Path::new("."),
&[
"apply",
"--offline",
"--ecosystems",
"gem",
"--cwd",
cwd,
"--global",
"--global-prefix",
prefix.to_str().unwrap(),
],
&[],
);
assert_eq!(code, 0, "stdout={stdout} stderr={stderr}");
assert_eq!(std::fs::read(&file).unwrap(), PATCHED);
}

/// Without its spec, a lib-less dir is still no installed gem: RubyGems
/// cannot load it, so `apply` finds nothing and writes nothing.
#[test]
fn a_lib_less_dir_with_no_installed_spec_is_not_a_gem() {
let tmp = tempfile::tempdir().unwrap();
let (_home, file) = lib_less_gem(tmp.path(), false);

let (code, stdout, stderr) = run_gem_apply(tmp.path(), &[]);
assert_eq!(code, 1, "stdout={stdout} stderr={stderr}");
assert!(
stderr.contains("The targeted manifest patch matched no installed package"),
"stderr={stderr}"
);
assert_eq!(std::fs::read(&file).unwrap(), ORIGINAL);
}
1 change: 1 addition & 0 deletions crates/socket-patch-cli/tests/apply/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ mod check_verifies_installed_tree;
mod cli_gem_variant_mismatch_policy;
mod e2e_safety_advisories;
mod gem_stale_bundler_plugin;
mod gem_without_lib_dir;
mod in_process_gem_config_warning;
mod in_process_gem_fallback_home;
mod in_process_gem_multicopy;
Expand Down
134 changes: 105 additions & 29 deletions crates/socket-patch-core/src/crawlers/ruby_crawler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,8 @@ impl RubyCrawler {
// coordinate is a single path segment, so reject any that
// could traverse out of the gem root (`..`/`.`, a separator,
// an absolute path, NUL). `verify_gem_at_path` only checks
// for `lib/`/`.gemspec` and gems patch in place, so fail
// for `lib/`/`.gemspec` (in the dir, or the home's
// `specifications/`) and gems patch in place, so fail
// closed here — same as the deno/go/maven/npm/nuget guards.
if !path_safety::is_safe_name_version(name, version) {
continue;
Expand Down Expand Up @@ -1090,7 +1091,7 @@ impl RubyCrawler {

// Parse name-version from directory name
if let Some((name, version)) = Self::parse_dir_name_version(&dir_name_str) {
// Verify it looks like a gem (has .gemspec or lib/)
// Verify it looks like an installed gem
if !self.verify_gem_at_path(&gem_dir).await {
continue;
}
Expand All @@ -1114,28 +1115,11 @@ impl RubyCrawler {
results
}

/// Verify that a directory looks like an installed gem.
/// Checks for a `.gemspec` file or a `lib/` directory.
/// Verify that a directory looks like an installed gem
/// ([`verify_gem_at_path_sync`] on the blocking pool).
async fn verify_gem_at_path(&self, path: &Path) -> bool {
if !is_dir(path).await {
return false;
}

// Check for lib/ directory
if is_dir(&path.join("lib")).await {
return true;
}

// Check for any .gemspec file
for entry in list_dir_entries(path).await {
if let Some(name) = entry.file_name().to_str() {
if name.ends_with(".gemspec") {
return true;
}
}
}

false
let path = path.to_path_buf();
run_blocking(move || verify_gem_at_path_sync(&path)).await
}

/// Parse a gem directory name into its base `(name, version)`.
Expand Down Expand Up @@ -1307,14 +1291,21 @@ fn locate_gem_dirs_sync(
dirs
}

/// Blocking twin of `RubyCrawler::verify_gem_at_path`: a directory holding
/// `lib/` or a `.gemspec`.
/// Whether `path` looks like an installed gem dir: it holds `lib/` or a
/// `.gemspec`, or its gem home has `specifications/<leaf>.gemspec`.
///
/// A gem need not ship either: `cassandra-web` packs `app.rb`, `app/` and
/// `bin/` at its root, and RubyGems writes its spec only to
/// `<home>/specifications/<leaf>.gemspec`, the file RubyGems and Bundler
/// load the gem by. A spec under `specifications/default/` does not count:
/// a default gem's `gems/<leaf>/` dir holds only its executables, while its
/// code lives in Ruby's own lib dir.
fn verify_gem_at_path_sync(path: &Path) -> bool {
use crate::utils::fs::is_dir_sync;
if !is_dir_sync(path) {
return false;
}
if is_dir_sync(&path.join("lib")) {
if is_dir_sync(&path.join("lib")) || home_installed_spec(path) {
return true;
}
super::listing::list_dir_sync(path).iter().any(|entry| {
Expand Down Expand Up @@ -1597,6 +1588,23 @@ fn home_lists_copy(copy: &Path) -> Option<bool> {
listed
}

/// Whether the gem home of the gem dir `<home>/gems/<leaf>` has the
/// installed (non-default) gemspec `specifications/<leaf>.gemspec`.
fn home_installed_spec(copy: &Path) -> bool {
let (Some(leaf), Some(gems)) = (copy.file_name(), copy.parent()) else {
return false;
};
if gems.file_name() != Some(OsStr::new("gems")) {
return false;
}
let Some(home) = gems.parent() else {
return false;
};
let mut spec = leaf.to_os_string();
spec.push(".gemspec");
home.join("specifications").join(spec).is_file()
}

/// Whether a standalone bundle's `bundler/setup.rb` names the gem dir
/// `<home>/gems/<leaf>`, or cannot be read to tell. The file sits in the
/// bundle path: `<home>/bundler/` for a flat home, two levels up for the
Expand Down Expand Up @@ -6593,9 +6601,10 @@ mod tests {
/// A tampered manifest PURL whose name carries `..` must not resolve
/// to a directory outside the gem root. `locate_gem_dirs_sync` joins
/// `<name>-<version>` straight onto `gem_path`, and
/// `verify_gem_at_path` only checks for `lib/`/`.gemspec`, so without
/// a coordinate gate `pkg:gem/../outside@1.0.0` escapes the gem store
/// and the patch applies in place out of tree.
/// `verify_gem_at_path` only checks for `lib/`/`.gemspec` (in the dir,
/// or the home's `specifications/`), so without a coordinate gate
/// `pkg:gem/../outside@1.0.0` escapes the gem store and the patch
/// applies in place out of tree.
#[tokio::test]
async fn find_by_purls_rejects_traversal_coordinates() {
let dir = tempfile::tempdir().unwrap();
Expand Down Expand Up @@ -6810,6 +6819,73 @@ mod tests {
assert!(!crawler.verify_gem_at_path(&gem_dir).await);
}

/// A gem that ships neither `lib/` nor a `.gemspec` (`cassandra-web`:
/// `app.rb`, `app/`, `bin/` at its root) is installed when its gem home
/// has `specifications/<leaf>.gemspec`, for the PURL lookup and the
/// scan alike; without that spec, or with only a
/// `specifications/default/` one, the dir is still no gem.
#[tokio::test]
async fn verify_gem_lib_less_dir_listed_by_its_home_spec() {
let home = tempfile::tempdir().unwrap();
let gems = home.path().join("gems");
let gem_dir = gems.join("cassandra-web-0.5.0");
tokio::fs::create_dir_all(gem_dir.join("app"))
.await
.unwrap();
tokio::fs::write(gem_dir.join("app.rb"), b"# app")
.await
.unwrap();
let specs = home.path().join("specifications");
tokio::fs::create_dir_all(&specs).await.unwrap();

let crawler = RubyCrawler::new();
let purls = vec!["pkg:gem/cassandra-web@0.5.0".to_string()];
let options = CrawlerOptions {
cwd: home.path().to_path_buf(),
global: false,
global_prefix: Some(gems.clone()),
};
assert!(!crawler.verify_gem_at_path(&gem_dir).await);
assert!(crawler
.find_by_purls(&gems, &purls)
.await
.unwrap()
.is_empty());
assert!(crawler.crawl_all(&options).await.is_empty());

// A default gem's spec does not make its executables-only dir a copy.
tokio::fs::create_dir_all(specs.join("default"))
.await
.unwrap();
tokio::fs::write(
specs.join("default").join("cassandra-web-0.5.0.gemspec"),
b"# default spec",
)
.await
.unwrap();
assert!(!crawler.verify_gem_at_path(&gem_dir).await);
assert!(crawler
.find_by_purls(&gems, &purls)
.await
.unwrap()
.is_empty());
assert!(crawler.crawl_all(&options).await.is_empty());

tokio::fs::write(specs.join("cassandra-web-0.5.0.gemspec"), b"# spec")
.await
.unwrap();
assert!(crawler.verify_gem_at_path(&gem_dir).await);
let found = crawler.find_by_purls(&gems, &purls).await.unwrap();
assert_eq!(found["pkg:gem/cassandra-web@0.5.0"].path, gem_dir);
let scanned: Vec<_> = crawler
.crawl_all(&options)
.await
.into_iter()
.map(|p| p.purl)
.collect();
assert_eq!(scanned, ["pkg:gem/cassandra-web@0.5.0"]);
}

/// `locate_gem_dirs_sync`' platform-dir scan must skip a `<name>-<version>-*` dir
/// that matches the prefix but fails gem verification (a hollow
/// platform dir — no `lib/`, no `.gemspec`): alone it resolves
Expand Down
Loading