socket-patch-core 3.2.0

Core library for socket-patch: manifest, hash, crawlers, patch engine, API client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Integration coverage for `crawlers::ruby_crawler`. Drives
//! branches the apply-CLI suite skips: vendor/bundle local mode,
//! global gem discovery via `~/.gem/ruby/*/gems`,
//! `~/.rbenv/versions/*/lib/ruby/gems/*/gems`, system paths,
//! Gemfile vs Gemfile.lock vs neither.

use std::path::Path;

use serial_test::serial;
use socket_patch_core::crawlers::ruby_crawler::parse_gem_env_output;
use socket_patch_core::crawlers::types::CrawlerOptions;
use socket_patch_core::crawlers::RubyCrawler;

#[test]
fn parse_gem_env_output_well_formed() {
    assert_eq!(
        parse_gem_env_output("/Users/foo/.gem/ruby/3.2.0\n").as_deref(),
        Some("/Users/foo/.gem/ruby/3.2.0")
    );
}

#[test]
fn parse_gem_env_output_empty_returns_none() {
    assert_eq!(parse_gem_env_output(""), None);
    assert_eq!(parse_gem_env_output("   \n  "), None);
}

const ORG_PURL: &str = "pkg:gem/rails@7.1.0";

fn options_at(root: &Path) -> CrawlerOptions {
    CrawlerOptions {
        cwd: root.to_path_buf(),
        global: false,
        global_prefix: None,
        batch_size: 100,
    }
}

/// Stage a gem under <gem_path>/<name>-<version>/lib so verify_gem_at_path
/// accepts it.
async fn stage_gem(gem_path: &Path, name: &str, version: &str) -> std::path::PathBuf {
    let pkg_dir = gem_path.join(format!("{name}-{version}"));
    tokio::fs::create_dir_all(pkg_dir.join("lib"))
        .await
        .unwrap();
    pkg_dir
}

// ── find_by_purls ──────────────────────────────────────────────

#[tokio::test]
async fn find_by_purls_finds_gem_in_gem_path() {
    let tmp = tempfile::tempdir().unwrap();
    let pkg_dir = stage_gem(tmp.path(), "rails", "7.1.0").await;

    let crawler = RubyCrawler;
    let result = crawler
        .find_by_purls(tmp.path(), &[ORG_PURL.to_string()])
        .await
        .unwrap();
    assert_eq!(result.len(), 1);
    assert_eq!(result.get(ORG_PURL).unwrap().path, pkg_dir);
}

#[tokio::test]
async fn find_by_purls_accepts_gem_with_gemspec_only() {
    let tmp = tempfile::tempdir().unwrap();
    // Stage with .gemspec but NO lib/ directory (alternate marker).
    let pkg_dir = tmp.path().join("rails-7.1.0");
    tokio::fs::create_dir(&pkg_dir).await.unwrap();
    tokio::fs::write(pkg_dir.join("rails.gemspec"), b"# gemspec")
        .await
        .unwrap();

    let crawler = RubyCrawler;
    let result = crawler
        .find_by_purls(tmp.path(), &[ORG_PURL.to_string()])
        .await
        .unwrap();
    assert_eq!(result.len(), 1);
}

#[tokio::test]
async fn find_by_purls_rejects_dir_without_lib_or_gemspec() {
    let tmp = tempfile::tempdir().unwrap();
    let pkg_dir = tmp.path().join("rails-7.1.0");
    tokio::fs::create_dir(&pkg_dir).await.unwrap();
    // Neither lib/ nor .gemspec → verify_gem_at_path returns false.

    let crawler = RubyCrawler;
    let result = crawler
        .find_by_purls(tmp.path(), &[ORG_PURL.to_string()])
        .await
        .unwrap();
    assert!(result.is_empty());
}

#[tokio::test]
async fn find_by_purls_no_match_returns_empty() {
    let tmp = tempfile::tempdir().unwrap();
    let crawler = RubyCrawler;
    let result = crawler
        .find_by_purls(tmp.path(), &[ORG_PURL.to_string()])
        .await
        .unwrap();
    assert!(result.is_empty());
}

#[tokio::test]
async fn find_by_purls_invalid_purl_skipped() {
    let tmp = tempfile::tempdir().unwrap();
    let crawler = RubyCrawler;
    let result = crawler
        .find_by_purls(tmp.path(), &["pkg:not-gem/rails@7.1.0".to_string()])
        .await
        .unwrap();
    assert!(result.is_empty());
}

// ── crawl_all ─────────────────────────────────────────────────

#[tokio::test]
async fn crawl_all_discovers_gems_in_path() {
    let tmp = tempfile::tempdir().unwrap();
    stage_gem(tmp.path(), "rails", "7.1.0").await;
    stage_gem(tmp.path(), "nokogiri", "1.16.5").await;

    let crawler = RubyCrawler;
    let opts = CrawlerOptions {
        cwd: tmp.path().to_path_buf(),
        global: true,
        global_prefix: Some(tmp.path().to_path_buf()),
        batch_size: 100,
    };
    let result = crawler.crawl_all(&opts).await;
    assert_eq!(result.len(), 2);
}

// ── get_gem_paths ──────────────────────────────────────────────

#[tokio::test]
async fn get_gem_paths_with_global_prefix_returns_only_prefix() {
    let tmp = tempfile::tempdir().unwrap();
    let crawler = RubyCrawler;
    let opts = CrawlerOptions {
        cwd: tmp.path().to_path_buf(),
        global: true,
        global_prefix: Some(tmp.path().to_path_buf()),
        batch_size: 100,
    };
    let paths = crawler.get_gem_paths(&opts).await.unwrap();
    assert_eq!(paths, vec![tmp.path().to_path_buf()]);
}

#[tokio::test]
async fn get_gem_paths_vendor_bundle_takes_precedence_over_global() {
    let tmp = tempfile::tempdir().unwrap();
    // Build a vendor/bundle/ruby/<ver>/gems layout. Bundler's scan
    // pattern is `vendor/bundle/ruby/<ver>/gems`.
    let vendor = tmp.path().join("vendor").join("bundle").join("ruby");
    let gems = vendor.join("3.2.0").join("gems");
    tokio::fs::create_dir_all(&gems).await.unwrap();

    let crawler = RubyCrawler;
    let paths = crawler
        .get_gem_paths(&options_at(tmp.path()))
        .await
        .unwrap();
    assert!(
        paths.iter().any(|p| p == &gems),
        "vendor/bundle gems dir must be discovered; got {paths:?}"
    );
}

#[tokio::test]
async fn get_gem_paths_no_gemfile_returns_empty() {
    let tmp = tempfile::tempdir().unwrap();
    // No Gemfile, no Gemfile.lock, no vendor/bundle.
    let crawler = RubyCrawler;
    let paths = crawler
        .get_gem_paths(&options_at(tmp.path()))
        .await
        .unwrap();
    assert!(paths.is_empty(), "non-Ruby dir must return empty paths");
}

#[tokio::test]
#[serial]
async fn get_gem_paths_with_gemfile_no_vendor_returns_paths() {
    let tmp = tempfile::tempdir().unwrap();
    // Gemfile present, no vendor/bundle. Falls back to `gem env gemdir`.
    // This either returns paths (if `gem` is on PATH and produces output)
    // or empty (if `gem` is missing). Both are valid — the contract is
    // "doesn't crash".
    tokio::fs::write(tmp.path().join("Gemfile"), b"source 'https://rubygems.org'")
        .await
        .unwrap();

    let crawler = RubyCrawler;
    let _ = crawler
        .get_gem_paths(&options_at(tmp.path()))
        .await
        .unwrap();
    // No assertion on contents — just contract that no panic occurs.
}

#[tokio::test]
#[serial]
async fn get_gem_paths_with_gemfile_lock_only_works_too() {
    let tmp = tempfile::tempdir().unwrap();
    tokio::fs::write(tmp.path().join("Gemfile.lock"), b"GEM\n")
        .await
        .unwrap();
    let crawler = RubyCrawler;
    let _ = crawler
        .get_gem_paths(&options_at(tmp.path()))
        .await
        .unwrap();
}

// ── global gem discovery ───────────────────────────────────────

#[tokio::test]
#[serial]
async fn global_gem_discovery_via_home_dotgem_layout() {
    let tmp = tempfile::tempdir().unwrap();
    // Build a ~/.gem/ruby/3.2.0/gems layout.
    let gems = tmp
        .path()
        .join(".gem")
        .join("ruby")
        .join("3.2.0")
        .join("gems");
    tokio::fs::create_dir_all(&gems).await.unwrap();

    let prev = std::env::var("HOME").ok();
    std::env::set_var("HOME", tmp.path());
    let crawler = RubyCrawler;
    let opts = CrawlerOptions {
        cwd: tmp.path().to_path_buf(),
        global: true,
        global_prefix: None,
        batch_size: 100,
    };
    let paths = crawler.get_gem_paths(&opts).await.unwrap();
    if let Some(v) = prev {
        std::env::set_var("HOME", v);
    }

    assert!(
        paths.iter().any(|p| p == &gems),
        "~/.gem/ruby/*/gems must be discovered; got {paths:?}"
    );
}

#[path = "common/mod.rs"]
mod common;

/// `scan_gem_dir` short-circuits when the gem path is unreadable —
/// drives ruby_crawler.rs:270 read_dir Err arm.
#[cfg(unix)]
#[tokio::test]
async fn crawl_all_handles_unreadable_gem_dir() {
    if common::uid_is_root() {
        eprintln!("SKIP: chmod 000 is a no-op under root");
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let gem_dir = tmp.path().join("blocked-gems");
    tokio::fs::create_dir(&gem_dir).await.unwrap();
    let _ = stage_gem(&gem_dir, "rails", "7.1.0").await;
    common::chmod_unreadable(&gem_dir);

    let crawler = RubyCrawler;
    let opts = CrawlerOptions {
        cwd: tmp.path().to_path_buf(),
        global: true,
        global_prefix: Some(gem_dir.clone()),
        batch_size: 100,
    };
    let result = crawler.crawl_all(&opts).await;
    common::chmod_readable(&gem_dir);

    assert!(result.is_empty(), "unreadable gem dir must yield empty");
}

/// `RubyCrawler::default()` should forward to `new()`.
#[test]
fn ruby_crawler_default_and_new_construct_cleanly() {
    let _a = RubyCrawler::default();
    let _b = RubyCrawler::new();
}

/// With a Gemfile present and `gem` not on PATH, the local-mode
/// `gem env gemdir` fallback at L56-64 must short-circuit cleanly
/// (run_gem_env returns None via the `.output().ok()?` arm). The
/// crawler then exits the if-block and returns an empty Vec.
#[tokio::test]
#[serial]
async fn get_gem_paths_local_gemfile_no_gem_binary_returns_empty() {
    let tmp = tempfile::tempdir().unwrap();
    tokio::fs::write(
        tmp.path().join("Gemfile"),
        b"source 'https://rubygems.org'\n",
    )
    .await
    .unwrap();

    let empty_path = tempfile::tempdir().unwrap();
    let prev = std::env::var("PATH").ok();
    std::env::set_var("PATH", empty_path.path());

    let crawler = RubyCrawler;
    let paths = crawler
        .get_gem_paths(&options_at(tmp.path()))
        .await
        .unwrap();

    if let Some(v) = prev {
        std::env::set_var("PATH", v);
    } else {
        std::env::remove_var("PATH");
    }

    assert!(
        paths.is_empty(),
        "no gem binary + no vendor must yield empty"
    );
}

/// Global mode with `gem` not on PATH and HOME pointing at a tempdir
/// containing no gem layouts at all must yield an empty result. This
/// drives the `run_gem_env` Err arms for both `gemdir` and `gempath`,
/// and the fallback_globs loop's read_dir-Err arm for each candidate.
#[tokio::test]
#[serial]
async fn global_gem_discovery_no_binary_no_home_layout_returns_empty() {
    let tmp = tempfile::tempdir().unwrap();
    let empty_path = tempfile::tempdir().unwrap();

    let prev_path = std::env::var("PATH").ok();
    let prev_home = std::env::var("HOME").ok();
    std::env::set_var("PATH", empty_path.path());
    std::env::set_var("HOME", tmp.path());

    let crawler = RubyCrawler;
    let opts = CrawlerOptions {
        cwd: tmp.path().to_path_buf(),
        global: true,
        global_prefix: None,
        batch_size: 100,
    };
    let paths = crawler.get_gem_paths(&opts).await.unwrap();

    if let Some(v) = prev_path {
        std::env::set_var("PATH", v);
    } else {
        std::env::remove_var("PATH");
    }
    if let Some(v) = prev_home {
        std::env::set_var("HOME", v);
    } else {
        std::env::remove_var("HOME");
    }

    // The crawler also probes system paths like /usr/local/lib/ruby/gems;
    // those may or may not exist on the test host. The contract here is
    // that the crawler does not panic and returns *no* paths sourced from
    // HOME (which had nothing staged).
    assert!(
        paths.iter().all(|p| !p.starts_with(tmp.path())),
        "no HOME-derived path should be returned; got {paths:?}"
    );
}

/// `~/.rvm/gems/<set>/gems` layout — exercises the third fallback in
/// the rbenv/rvm/gem fallback_globs loop.
#[tokio::test]
#[serial]
async fn global_gem_discovery_via_rvm_layout() {
    let tmp = tempfile::tempdir().unwrap();
    let gems = tmp
        .path()
        .join(".rvm")
        .join("gems")
        .join("ruby-3.2.0")
        .join("gems");
    tokio::fs::create_dir_all(&gems).await.unwrap();

    let prev = std::env::var("HOME").ok();
    std::env::set_var("HOME", tmp.path());
    let crawler = RubyCrawler;
    let opts = CrawlerOptions {
        cwd: tmp.path().to_path_buf(),
        global: true,
        global_prefix: None,
        batch_size: 100,
    };
    let paths = crawler.get_gem_paths(&opts).await.unwrap();
    if let Some(v) = prev {
        std::env::set_var("HOME", v);
    }

    assert!(
        paths.iter().any(|p| p == &gems),
        "~/.rvm/gems/*/gems must be discovered; got {paths:?}"
    );
}

#[tokio::test]
#[serial]
async fn global_gem_discovery_via_rbenv_layout() {
    let tmp = tempfile::tempdir().unwrap();
    // Build a ~/.rbenv/versions/3.2.0/lib/ruby/gems/3.2.0/gems layout.
    let gems = tmp
        .path()
        .join(".rbenv")
        .join("versions")
        .join("3.2.0")
        .join("lib")
        .join("ruby")
        .join("gems")
        .join("3.2.0")
        .join("gems");
    tokio::fs::create_dir_all(&gems).await.unwrap();

    let prev = std::env::var("HOME").ok();
    std::env::set_var("HOME", tmp.path());
    let crawler = RubyCrawler;
    let opts = CrawlerOptions {
        cwd: tmp.path().to_path_buf(),
        global: true,
        global_prefix: None,
        batch_size: 100,
    };
    let paths = crawler.get_gem_paths(&opts).await.unwrap();
    if let Some(v) = prev {
        std::env::set_var("HOME", v);
    }

    assert!(
        paths.iter().any(|p| p == &gems),
        "~/.rbenv/versions/*/lib/ruby/gems/*/gems must be discovered; got {paths:?}"
    );
}