Repository navigation
Expand file tree
/
Copy pathecosystem_dispatch.rs
More file actions
2310 lines (2161 loc) · 94.8 KB
/
Copy pathecosystem_dispatch.rs
File metadata and controls
2310 lines (2161 loc) · 94.8 KB
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use socket_patch_core::crawlers::{
CrawledPackage, CrawlerOptions, Ecosystem, NpmCrawler, PythonCrawler, RubyCrawler,
};
use socket_patch_core::utils::purl::strip_purl_qualifiers;
use socket_patch_core::utils::purl_key::PurlKey;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use crate::args::GlobalArgs;
use socket_patch_core::crawlers::npm_crawler::with_store_peer_variant_copies;
use socket_patch_core::crawlers::walk_pool;
use socket_patch_core::crawlers::CargoCrawler;
use socket_patch_core::crawlers::ComposerCrawler;
use socket_patch_core::crawlers::DenoCrawler;
use socket_patch_core::crawlers::GoCrawler;
use socket_patch_core::crawlers::MavenCrawler;
use socket_patch_core::crawlers::NuGetCrawler;
/// Whether [`crawl_all_ecosystems`] actually visits this PURL's ecosystem
/// in THIS process. An unrecognized `pkg:<type>/` (a newer CLI's ecosystem
/// in a committed manifest) has no crawler at all — for those, absence
/// from the crawl carries no information about whether the package is
/// installed. Callers that read "not in the crawl" as "no longer
/// installed" (scan's prune GC) must not judge them.
pub fn crawl_covers_purl(purl: &str) -> bool {
Ecosystem::from_purl(purl).is_some()
}
/// Partition PURLs by ecosystem, filtering by the `--ecosystems` flag if set.
pub fn partition_purls(
purls: &[String],
allowed_ecosystems: Option<&[String]>,
) -> HashMap<Ecosystem, Vec<String>> {
let mut map: HashMap<Ecosystem, Vec<String>> = HashMap::new();
for purl in purls {
if let Some(eco) = Ecosystem::from_purl(purl) {
if let Some(allowed) = allowed_ecosystems {
if !allowed.iter().any(|a| a == eco.cli_name()) {
continue;
}
}
map.entry(eco).or_default().push(purl.clone());
}
}
map
}
/// Standard scan-one-ecosystem pattern: discover source paths, run
/// `find_by_purls` on each, and merge results into `$out` keyed by PURL
/// (first wins). Used by every ecosystem except pypi (which dedups
/// PURLs and, on rollback, remaps base PURLs back to qualified ones).
///
/// `$using_label` is the noun in "Using <X> at: <path>" for global
/// scans; pass `""` to suppress that line. The banner is progress chrome
/// and goes to STDERR like the macro's two warnings: stdout belongs to
/// `--json` envelopes and the VEX document, so a caller that forgets to
/// fold `json` into `$silent` cannot corrupt them.
macro_rules! scan_ecosystem {
(
out = $out:ident,
partitioned = $partitioned:expr,
eco = $eco:expr,
options = $options:expr,
silent = $silent:expr,
crawler = $crawler:expr,
get_paths = $get_paths:ident,
using_label = $using_label:expr,
err_label = $err_label:expr,
purls_override = $purls_override:expr,
on_match = $on_match:expr $(,)?
) => {{
if let Some(purls) = $partitioned.get(&$eco) {
if !purls.is_empty() {
let crawler = $crawler;
let purls_to_use: Vec<String> = $purls_override(purls);
match crawler.$get_paths($options).await {
Ok(paths) => {
let using: &str = $using_label;
if !using.is_empty()
&& ($options.global || $options.global_prefix.is_some())
&& !$silent
{
// Status chrome: stderr, so it can never reach a
// machine stream (`--json` envelope, vex document).
if let Some(first) = paths.first() {
eprintln!("Using {} at: {}", using, first.display());
}
}
for path in &paths {
match crawler.find_by_purls(path, &purls_to_use).await {
Ok(packages) => {
$on_match(&mut $out, purls, packages);
}
Err(e) => {
if !$silent {
eprintln!(
"Warning: Failed to scan {}: {}",
path.display(),
e
);
}
}
}
}
}
Err(e) => {
if !$silent {
eprintln!("Warning: Failed to find {}: {}", $err_label, e);
}
}
}
}
}
}};
}
/// Signature shared by `merge_first_wins` and `merge_qualified`.
/// `dispatch_find` swaps between them so the rollback path can fan one
/// crawler result back out to every caller-supplied qualified PURL. The
/// output map holds a `Vec` of paths per PURL: most ecosystems install one
/// physical copy of a `name@version`, but npm genuinely nests duplicates
/// (see `merge_npm_copies`), so the type itself must be able to carry more
/// than one.
type MergeFn = fn(&mut HashMap<String, Vec<PathBuf>>, &[String], HashMap<String, CrawledPackage>);
/// Push `path` under `purl` unless that exact path is already recorded —
/// keeps discovery order (root/first-found first) while deduping a path
/// reached twice across the macro's per-source-path calls.
fn push_path(out: &mut HashMap<String, Vec<PathBuf>>, purl: String, path: PathBuf) {
let paths = out.entry(purl).or_default();
if !paths.contains(&path) {
paths.push(path);
}
}
/// Default merge for the single-copy ecosystems (cargo / go / composer /
/// nuget / deno): keep the FIRST path discovered per PURL, matching the
/// historical `HashMap<String, PathBuf>` first-wins contract exactly. These
/// ecosystems resolve one logical install per `name@version`, but the same
/// install is legitimately reachable from several source roots (e.g. NuGet's
/// global cache *and* a project-local packages folder). Patching each root
/// would re-apply to what is effectively the same package — a scope-expanding
/// behavior change that is out of scope for the npm multi-copy fix and would,
/// for a shared global cache, mutate state other projects rely on. Fanning out
/// to genuinely-distinct installs is npm-only (`merge_npm_copies`); if a
/// per-root fan-out is ever wanted for these ecosystems it must be an explicit,
/// separately-tested decision.
fn merge_first_wins(
out: &mut HashMap<String, Vec<PathBuf>>,
_purls: &[String],
packages: HashMap<String, CrawledPackage>,
) {
for (purl, pkg) in packages {
// First source root to resolve this PURL wins; later roots that
// resolve the same PURL are ignored (true first-wins).
let paths = out.entry(purl).or_default();
if paths.is_empty() {
paths.push(pkg.path);
}
}
}
/// Release-variant merge for the APPLY path: keyed by the crawler-returned
/// base PURL (apply's variant loop groups by base), accumulating EVERY
/// distinct path discovered across the ecosystem's source roots in
/// discovery (precedence) order. The gem crawler legitimately discovers
/// several coexisting stores holding REAL physical copies of one
/// `gem@version` (bundler's scoped `<engine>/<abi>/gems` beside the flat
/// `gems/` layout, or an env `BUNDLE_PATH` store) — first-wins would drop
/// the second copy, so apply would patch one store while the other bundler
/// loads pristine bytes. Collapsing consumers still take the first
/// (highest-precedence) path; apply fans out per-copy for gem and Maven
/// (`~/.m2` and each Gradle cache are distinct installs some build reads;
/// PyPI keeps its one-install-dir contract — see the apply variant loop).
fn merge_variant_copies(
out: &mut HashMap<String, Vec<PathBuf>>,
_purls: &[String],
packages: HashMap<String, CrawledPackage>,
) {
for (purl, pkg) in packages {
push_path(out, purl, pkg.path);
}
}
/// npm merge: the npm crawler returns EVERY physical copy of each PURL
/// (nested duplicates, diamonds, `file:` dups), so fold every path in.
/// A one-path `HashMap<String, PathBuf>` would silently drop every copy
/// after the first.
fn merge_npm_copies(
out: &mut HashMap<String, Vec<PathBuf>>,
_purls: &[String],
packages: HashMap<String, Vec<CrawledPackage>>,
) {
for (purl, pkgs) in packages {
for pkg in pkgs {
push_path(out, purl.clone(), pkg.path);
}
}
}
/// `paths` in order with every path that resolves to an already-listed
/// directory dropped: two discovered site-packages paths can name ONE
/// directory (a `lib64 -> lib` symlink, a symlinked venv), as can two npm
/// copies (see [`distinct_npm_copies`]), and patching it twice would report
/// the second pass `already_patched`. A path that can't be canonicalized is
/// kept as-is.
pub(crate) async fn distinct_install_dirs(paths: &[PathBuf]) -> Vec<PathBuf> {
let mut seen: HashSet<PathBuf> = HashSet::new();
let mut out = Vec::with_capacity(paths.len());
for path in paths {
let key = tokio::fs::canonicalize(path)
.await
.unwrap_or_else(|_| path.clone());
if seen.insert(key) {
out.push(path.clone());
}
}
out
}
/// Collapse each npm PURL's copies to distinct physical directories, in
/// discovery order (the first spelling of each directory wins). The
/// resolver walks every `node_modules` root, so a pnpm / Bun isolated
/// workspace yields one copy twice: as the root's `.pnpm` store entry and
/// as a member's `packages/a/node_modules/<dep>` link to it. Visiting both
/// patched (or restored) it once and reported the second visit as a
/// phantom `already_patched` / already-original event (#633). The map
/// itself keeps every spelling, because path targets (`scan` / `rollback
/// packages/a`) select a copy by the member's link; only the commands that
/// act per copy collapse it. Genuinely distinct copies (nested duplicates,
/// store peer variants) have distinct real paths and are all kept.
pub(crate) async fn distinct_npm_copies(map: &mut HashMap<String, Vec<PathBuf>>) {
for (purl, paths) in map.iter_mut() {
if paths.len() > 1 && Ecosystem::from_purl(purl) == Some(Ecosystem::Npm) {
*paths = distinct_install_dirs(paths).await;
}
}
}
/// Release-variant merge: the crawler is queried with base PURLs (no
/// `?qualifiers`); fan the resulting paths back out to every qualified
/// caller-supplied PURL that strips to the same base. Used for the
/// release-variant ecosystems (PyPI / RubyGems / Maven) so a single
/// installed package directory is mapped to every manifest variant for
/// later hash-based selection.
fn merge_qualified(
out: &mut HashMap<String, Vec<PathBuf>>,
purls: &[String],
packages: HashMap<String, CrawledPackage>,
) {
for (base_purl, pkg) in packages {
for qualified in purls {
if strip_purl_qualifiers(qualified) == base_purl {
push_path(out, qualified.clone(), pkg.path.clone());
}
}
}
}
/// Strip qualifiers and dedupe — the crawler only needs the base PURL of
/// a release-variant ecosystem; the variant is resolved later by hashing
/// the installed files.
fn dedup_qualified_purls(purls: &[String]) -> Vec<String> {
purls
.iter()
.map(|p| strip_purl_qualifiers(p).to_string())
.collect::<HashSet<_>>()
.into_iter()
.collect()
}
fn passthrough_purls(purls: &[String]) -> Vec<String> {
purls.to_vec()
}
/// Drive every enabled ecosystem's find-by-purls path, accumulating
/// into one `purl -> path` map.
///
/// `variant_merge` lets the rollback variant fan a single crawler result
/// out to every caller-supplied qualified PURL; everything else just
/// inserts the crawler-returned PURL with first-wins semantics. It is
/// applied to the release-variant ecosystems (PyPI / RubyGems / Maven),
/// which are also queried with deduped base PURLs.
///
/// `npm_roots`, when given, are the `node_modules` roots an earlier crawl of
/// the same options and (untouched) tree walked — used instead of walking
/// the tree for them again ([`NpmRootsCrawler`]).
async fn dispatch_find(
partitioned: &HashMap<Ecosystem, Vec<String>>,
options: &CrawlerOptions,
silent: bool,
variant_merge: MergeFn,
npm_roots: Option<&[PathBuf]>,
) -> HashMap<String, Vec<PathBuf>> {
let mut out: HashMap<String, Vec<PathBuf>> = HashMap::new();
scan_ecosystem!(
out = out,
partitioned = partitioned,
eco = Ecosystem::Npm,
options = options,
silent = silent,
crawler = NpmRootsCrawler { roots: npm_roots },
get_paths = get_node_modules_paths,
using_label = "global npm packages",
err_label = "npm packages",
purls_override = passthrough_purls,
// npm's crawler returns EVERY physical copy per PURL; fold them all
// in (multi-copy silent-partial fix) rather than first-wins.
on_match = merge_npm_copies,
);
scan_ecosystem!(
out = out,
partitioned = partitioned,
eco = Ecosystem::Pypi,
options = options,
silent = silent,
crawler = PythonCrawler,
get_paths = get_site_packages_paths,
using_label = "",
err_label = "Python packages",
purls_override = dedup_qualified_purls,
on_match = variant_merge,
);
scan_ecosystem!(
out = out,
partitioned = partitioned,
eco = Ecosystem::Cargo,
options = options,
silent = silent,
crawler = CargoCrawler,
get_paths = get_crate_source_paths,
using_label = "cargo crate sources",
err_label = "Cargo crates",
purls_override = passthrough_purls,
on_match = merge_first_wins,
);
scan_ecosystem!(
out = out,
partitioned = partitioned,
eco = Ecosystem::Gem,
options = options,
silent = silent,
crawler = RubyCrawler,
get_paths = get_gem_paths,
using_label = "ruby gem paths",
err_label = "Ruby gems",
// RubyGems has per-platform release variants (`?platform=`); the
// crawler emits the base PURL and the platform is resolved by
// hashing the installed files, same as PyPI.
purls_override = dedup_qualified_purls,
on_match = variant_merge,
);
scan_ecosystem!(
out = out,
partitioned = partitioned,
eco = Ecosystem::Golang,
options = options,
silent = silent,
crawler = GoCrawler,
get_paths = get_module_cache_paths,
using_label = "Go module cache",
err_label = "Go modules",
purls_override = passthrough_purls,
on_match = merge_first_wins,
);
scan_ecosystem!(
out = out,
partitioned = partitioned,
eco = Ecosystem::Maven,
options = options,
silent = silent,
crawler = MavenCrawler,
// Every cache holding a copy: `~/.m2` first, then each Gradle
// `files-2.1` (the user home's and the read-only one), whose
// version dirs every join site expands through
// `gradle_cache::installed_copies`. `variant_merge` keeps every
// distinct copy (`push_path`), and the Maven join sites
// ([`JvmScope`]) split them into the copies a build consumes.
get_paths = get_maven_copy_paths,
using_label = "Maven repository",
err_label = "Maven packages",
// Maven has per-classifier release variants
// (`?classifier=&ext=`) that coexist as distinct jars in
// one version dir; the crawler emits the base PURL and
// each variant is resolved by hashing its jar file.
purls_override = dedup_qualified_purls,
on_match = variant_merge,
);
scan_ecosystem!(
out = out,
partitioned = partitioned,
eco = Ecosystem::Composer,
options = options,
silent = silent,
crawler = ComposerCrawler,
get_paths = get_vendor_paths,
using_label = "PHP vendor packages",
err_label = "PHP packages",
purls_override = passthrough_purls,
on_match = merge_first_wins,
);
scan_ecosystem!(
out = out,
partitioned = partitioned,
eco = Ecosystem::Nuget,
options = options,
silent = silent,
crawler = NuGetCrawler,
get_paths = get_nuget_package_paths,
using_label = "NuGet packages",
err_label = "NuGet packages",
purls_override = passthrough_purls,
on_match = merge_first_wins,
);
scan_ecosystem!(
out = out,
partitioned = partitioned,
eco = Ecosystem::Deno,
options = options,
silent = silent,
crawler = DenoCrawler,
get_paths = get_jsr_cache_paths,
using_label = "Deno JSR cache",
err_label = "Deno JSR packages",
purls_override = passthrough_purls,
on_match = merge_first_wins,
);
out
}
/// Collapse a multi-copy map to one representative path per PURL (the
/// first-discovered — root-copy-first for npm). Consumers that only need
/// "is it installed / where is a representative copy" (`vendor`, `vex`,
/// `get`, `repair vendor`) use the collapsing wrappers below
/// (`HashMap<String, PathBuf>`). `apply` and
/// `rollback` — which must touch EVERY copy — use the `_all` variants.
pub(crate) fn collapse_to_first(multi: HashMap<String, Vec<PathBuf>>) -> HashMap<String, PathBuf> {
multi
.into_iter()
.filter_map(|(purl, paths)| paths.into_iter().next().map(|p| (purl, p)))
.collect()
}
/// For each ecosystem in the partitioned map, create the crawler, discover
/// source paths, and look up the given PURLs. Returns a unified `purl ->
/// [paths]` map carrying EVERY physical copy (npm nests duplicates). Used
/// by `apply`, which patches all copies.
pub async fn find_all_packages_for_purls(
partitioned: &HashMap<Ecosystem, Vec<String>>,
options: &CrawlerOptions,
silent: bool,
) -> HashMap<String, Vec<PathBuf>> {
// Release-variant ecosystems accumulate every distinct discovered copy
// (base-PURL keyed) instead of first-wins: the gem crawler surfaces
// coexisting bundler stores whose copies apply must ALL patch. The
// rollback variant below gets the same multi-copy carry from
// `merge_qualified`'s `push_path`. Single-copy ecosystems keep true
// first-wins via their own `merge_first_wins` wiring in
// `dispatch_find`.
dispatch_find(partitioned, options, silent, merge_variant_copies, None).await
}
/// Multi-copy variant of `find_packages_for_rollback` (qualified-aware
/// merge). Used by `rollback`, which restores every physical copy.
pub async fn find_all_packages_for_rollback(
partitioned: &HashMap<Ecosystem, Vec<String>>,
options: &CrawlerOptions,
silent: bool,
) -> HashMap<String, Vec<PathBuf>> {
find_all_packages_for_rollback_reusing(partitioned, options, silent, None).await
}
/// [`find_all_packages_for_rollback`], taking the npm `node_modules` roots
/// from `prior` as [`find_packages_for_rollback_reusing`] does. Used by
/// `scan`'s path scoping, which must see the same copies `rollback`'s path
/// targets do.
pub async fn find_all_packages_for_rollback_reusing(
partitioned: &HashMap<Ecosystem, Vec<String>>,
options: &CrawlerOptions,
silent: bool,
prior: Option<&NpmCrawlSnapshot>,
) -> HashMap<String, Vec<PathBuf>> {
let npm_roots = prior
.filter(|p| p.taken_with(options))
.map(|p| p.roots.as_slice());
dispatch_find(partitioned, options, silent, merge_qualified, npm_roots).await
}
/// Qualified-aware PURL resolution for rollback, vendor, repair and
/// narrow-release lookups: remaps qualified PURLs (PyPI `?artifact_id=`,
/// RubyGems `?platform=`, Maven `?classifier=&ext=`) to the base PURL the
/// crawler found, keyed back by the caller's qualified spelling. Returns one
/// representative copy per PURL. (Its base-keyed twin,
/// `collapse_to_first(find_all_packages_for_purls(..))`, has no production
/// caller: manifest and ledger keys are qualified for the release-variant
/// ecosystems, and a base-keyed map never matched them — the in-file tests
/// pin that contrast.)
pub async fn find_packages_for_rollback(
partitioned: &HashMap<Ecosystem, Vec<String>>,
options: &CrawlerOptions,
silent: bool,
) -> HashMap<String, PathBuf> {
find_packages_for_rollback_reusing(partitioned, options, silent, None).await
}
/// [`find_packages_for_rollback`], taking the npm `node_modules` roots from
/// `prior` (a crawl of the same options earlier in this process, over a
/// tree nothing has touched since) instead of walking the tree for them
/// again. Only the root discovery is reused: each root is still searched
/// by `find_by_purls`, so copy choice and order are unchanged. A snapshot
/// taken with other options is ignored.
pub async fn find_packages_for_rollback_reusing(
partitioned: &HashMap<Ecosystem, Vec<String>>,
options: &CrawlerOptions,
silent: bool,
prior: Option<&NpmCrawlSnapshot>,
) -> HashMap<String, PathBuf> {
let npm_roots = prior
.filter(|p| p.taken_with(options))
.map(|p| p.roots.as_slice());
collapse_to_first(dispatch_find(partitioned, options, silent, merge_qualified, npm_roots).await)
}
/// The npm half of one [`crawl_ecosystems_with_npm`] run: the packages
/// the npm crawler found (its whole output, in crawl order) and the
/// `node_modules` roots it walked, with the options they were taken with.
/// Handed from `scan`'s crawl to its vendor step so the vendor engine does
/// not walk the same untouched tree again ([`npm_paths_by_identity_in`],
/// [`find_packages_for_rollback_reusing`]).
#[derive(Debug, Clone)]
pub struct NpmCrawlSnapshot {
cwd: PathBuf,
global: bool,
global_prefix: Option<PathBuf>,
roots: Vec<PathBuf>,
packages: Vec<CrawledPackage>,
}
impl NpmCrawlSnapshot {
/// Whether this snapshot was crawled with exactly `options`.
fn taken_with(&self, options: &CrawlerOptions) -> bool {
// Destructured, not field-by-field: a new crawler option that
// changes what the crawler walks has to be answered here, and the
// compiler is what asks. Everything this snapshot stands in for
// was crawled with these options and nothing else.
let CrawlerOptions {
cwd,
global,
global_prefix,
} = options;
self.cwd == *cwd && self.global == *global && self.global_prefix == *global_prefix
}
/// The crawled npm packages, when crawled with exactly `options`.
pub(crate) fn packages_for(&self, options: &CrawlerOptions) -> Option<&[CrawledPackage]> {
self.taken_with(options).then_some(self.packages.as_slice())
}
/// The `node_modules` roots the crawl walked — exactly what
/// `NpmCrawler::get_node_modules_paths` returns for the same options and
/// tree — when crawled with exactly `options`.
pub(crate) fn roots_for(&self, options: &CrawlerOptions) -> Option<&[PathBuf]> {
self.taken_with(options).then_some(self.roots.as_slice())
}
}
/// [`NpmCrawler`] for [`dispatch_find`], answering its root discovery from
/// an earlier crawl's roots when it has them.
struct NpmRootsCrawler<'a> {
roots: Option<&'a [PathBuf]>,
}
impl NpmRootsCrawler<'_> {
async fn get_node_modules_paths(
&self,
options: &CrawlerOptions,
) -> Result<Vec<PathBuf>, std::io::Error> {
match self.roots {
Some(roots) => Ok(roots.to_vec()),
None => NpmCrawler.get_node_modules_paths(options).await,
}
}
async fn find_by_purls(
&self,
node_modules_path: &std::path::Path,
purls: &[String],
) -> Result<HashMap<String, Vec<CrawledPackage>>, std::io::Error> {
NpmCrawler.find_by_purls(node_modules_path, purls).await
}
}
/// The installed copy of each npm purl in `purls`, found by its
/// `package.json` identity (a full npm crawl) instead of its install path.
/// An npm ALIAS dependency (`"lp": "npm:left-pad@1.3.0"`) reached through a
/// symlinked importer entry is one the name-keyed resolvers above never
/// take as a copy; callers use this as the last lookup before calling a
/// package missing (`vendor`, and `vex` for a purl nothing else found).
/// The crawl dedups by name@version, so this yields ONE copy per purl — the
/// first the crawl reaches — never every alias beside a normal install
/// (the core resolver's alias pass returns those). Keyed by the caller's spelling; a purl with no copy has no
/// entry. No crawl runs when `purls` is empty.
pub(crate) async fn npm_paths_by_identity(
options: &CrawlerOptions,
purls: &[&String],
) -> HashMap<String, Vec<PathBuf>> {
if purls.is_empty() {
return HashMap::new();
}
let installed = NpmCrawler::new().crawl_all(options).await;
npm_paths_by_identity_in(&installed, purls)
}
/// [`npm_paths_by_identity`] over an npm crawl already in hand (the whole
/// output of `NpmCrawler::crawl_all` for the same options, over a tree
/// nothing has touched since) instead of crawling again.
pub(crate) fn npm_paths_by_identity_in(
installed: &[CrawledPackage],
purls: &[&String],
) -> HashMap<String, Vec<PathBuf>> {
let mut out = HashMap::new();
for purl in purls {
let want = PurlKey::new(purl);
let paths: Vec<PathBuf> = installed
.iter()
.filter(|pkg| PurlKey::new(&pkg.purl) == want)
.map(|pkg| pkg.path.clone())
.collect();
if !paths.is_empty() {
out.insert((*purl).clone(), paths);
}
}
out
}
/// Resolve manifest PURLs to every installed on-disk copy (crawl order;
/// partition, build crawler options from the global args, dispatch). Uses
/// the rollback (qualified-aware) resolver, never a base-keyed collapse of
/// [`find_all_packages_for_purls`]: release-variant ecosystems (PyPI /
/// RubyGems / Maven) key the manifest by *qualified* PURLs
/// (`?artifact_id=`, `?platform=`, `?classifier=&ext=`), but the crawler
/// only knows the *base* PURL. A base-keyed result map would make every
/// qualified manifest lookup miss, so every PyPI/Gem/Maven
/// patch would silently resolve as `package_not_found`. The rollback
/// variant fans each base path back out to every qualified manifest PURL
/// — the same mapping the manifest was written with (`get` uses the same
/// resolver). `vex` hashes every copy of a manifest purl and of a hosted
/// one from this one lookup; npm copies include their store variants.
///
/// With `prior`, the npm `node_modules` roots come
/// from it (a crawl of the same options earlier in this process, over
/// a tree whose directories nothing has touched since) instead of walking
/// the tree for them again — the every-copy twin of
/// [`find_packages_for_rollback_reusing`]. Only the root discovery is
/// reused: each root is still searched by `find_by_purls`, so copy choice
/// and order are unchanged. A snapshot taken with other options is ignored.
///
/// Read-only by contract (its one caller is `vex`), so it also searches the
/// gem stores under a refused out-of-tree `.bundle/config` path
/// (`RubyCrawler::verification_only_gem_paths`), which the write paths never
/// see.
pub async fn find_manifest_package_copies_reusing(
purls: &[String],
common: &GlobalArgs,
quiet: bool,
prior: Option<&NpmCrawlSnapshot>,
) -> HashMap<String, Vec<PathBuf>> {
let partitioned = partition_purls(purls, common.ecosystems.as_deref());
let crawler_options = common.crawler_options();
let npm_roots = prior.and_then(|p| p.roots_for(&crawler_options));
let mut copies = dispatch_find(
&partitioned,
&crawler_options,
quiet,
merge_qualified,
npm_roots,
)
.await;
// `apply` also writes every store variant of each npm copy (a pnpm peer
// suffix, a Deno `_N` copy index, a vlt peer extra), so "every copy"
// includes them (#603).
for (purl, paths) in copies.iter_mut() {
if purl.starts_with("pkg:npm/") {
*paths = with_store_peer_variant_copies(std::mem::take(paths)).await;
}
}
// Verification also READS a `.bundle/config` bundle path the crawler
// refused as a write root (it resolves outside the project): bundler
// installs into and loads from it, so a copy there must verify too —
// skipping it would leave an unpatched gem looking "not installed",
// which the hosted lockfile basis then attests (#709).
if let Some(gem_purls) = partitioned.get(&Ecosystem::Gem) {
let stores = RubyCrawler
.verification_only_gem_paths(&crawler_options)
.await;
let bases = dedup_qualified_purls(gem_purls);
for store in &stores {
if let Ok(found) = RubyCrawler.find_by_purls(store, &bases).await {
merge_qualified(&mut copies, gem_purls, found);
}
}
}
copies
}
// ── JVM copies ──────────────────────────────────────────────────────────
/// What the Maven join sites (apply, rollback, vex) need to know about the
/// run's JVM caches, resolved once per run: which copies a build consumes,
/// which are read-only, and whether the build verifies its dependencies.
#[derive(Debug, Clone)]
pub(crate) struct JvmScope {
pub env: socket_patch_core::crawlers::maven_crawler::JvmEnv,
/// The local Gradle build's `m2_gate` (local mode only; `None` in a
/// global run, where every cache counts).
pub gate: Option<socket_patch_core::crawlers::maven_crawler::M2Gate>,
/// `gradle/verification-metadata.xml` of the cwd's build (or the
/// ancestor build it belongs to), local mode only.
pub verification_metadata: Option<PathBuf>,
}
/// The installed copies of one Maven purl, split by how a build reads them.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct MavenCopies {
/// Writable copies some build consumes: `~/.m2` version dirs (unless
/// ignored) and Gradle user-home version dirs, in lookup order.
pub consumed: Vec<PathBuf>,
/// Copies in the read-only Gradle cache (`GRADLE_RO_DEP_CACHE`): read
/// by Gradle, never written.
pub read_only: Vec<PathBuf>,
/// `~/.m2` copies a Gradle-only build never reads (no `mavenLocal()`).
/// A Coursier or Ivy copy (sbt, Mill, scala-cli) is never one: the
/// `mavenLocal()` gate is about `~/.m2` alone.
pub m2_ignored: Vec<PathBuf>,
}
impl JvmScope {
/// The scope of a run with `common`'s flags, over the process
/// environment.
pub(crate) async fn of(common: &GlobalArgs) -> Self {
use socket_patch_core::crawlers::gradle_cache;
use socket_patch_core::crawlers::maven_crawler::{m2_gate, JvmEnv};
let env = JvmEnv::from_process();
if common.is_global() {
return Self {
env,
gate: None,
verification_metadata: None,
};
}
let cwd = common.cwd.clone();
let probe_env = env.clone();
let probe = move || {
let gate = m2_gate(&cwd, &probe_env);
let metadata = gradle_cache::build_roots(&cwd)
.into_iter()
.map(|root| root.join("gradle").join("verification-metadata.xml"))
.find(|p| p.is_file());
(gate, metadata)
};
// Script reads and stats: off the async workers.
let (gate, verification_metadata) = tokio::task::spawn_blocking(probe)
.await
.expect("JVM scope probe panicked");
Self {
env,
gate: Some(gate),
verification_metadata,
}
}
/// Whether a build of this run reads `~/.m2` (always, except a local
/// Gradle-only build that never declares `mavenLocal()`).
pub(crate) fn m2_consumed(&self) -> bool {
use socket_patch_core::crawlers::maven_crawler::M2Gate;
self.gate.as_ref() != Some(&M2Gate::Ignored)
}
/// Whether `path` lies in the read-only Gradle cache.
pub(crate) fn is_read_only(&self, path: &std::path::Path) -> bool {
self.env
.gradle
.as_ref()
.and_then(|h| h.ro_files21.as_deref())
.is_some_and(|ro| path.starts_with(ro))
}
/// Split the copies the resolver found for one purl.
pub(crate) fn split(&self, paths: &[PathBuf]) -> MavenCopies {
let mut out = MavenCopies::default();
for path in paths {
if self.is_read_only(path) {
out.read_only.push(path.clone());
} else if self
.env
.m2_repo
.as_ref()
.is_some_and(|m2| path.starts_with(m2))
&& !self.m2_consumed()
{
out.m2_ignored.push(path.clone());
} else {
out.consumed.push(path.clone());
}
}
out
}
}
/// Box the future `make` returns, constructing it inside this (non-async)
/// frame so the caller's poll frame only ever holds the pointer.
fn boxed<'a, T, F, Fut>(make: F) -> std::pin::Pin<Box<dyn std::future::Future<Output = T> + 'a>>
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = T> + 'a,
{
Box::pin(make())
}
/// Crawl all ecosystems and return all packages, per-ecosystem counts and
/// the gem crawl's refused config-sourced `BUNDLE_PATH`
/// (`BundleStoreDiscovery::skipped_config_path`, local mode only) —
/// recovered from the crawl that hit it, so callers surfacing the advisory
/// never probe the Bundler roots a second time.
pub async fn crawl_all_ecosystems(
options: &CrawlerOptions,
) -> (
Vec<CrawledPackage>,
HashMap<Ecosystem, usize>,
Option<String>,
) {
crawl_ecosystems(options, None).await
}
/// [`crawl_all_ecosystems`] over only the ecosystems `only` names
/// (`--ecosystems` spellings; `None` crawls every one). A crawler that is
/// not selected never runs: it contributes no packages and no `counts`
/// entry. Each crawler reports only its own ecosystem's purls, so the
/// selected ecosystems' packages, their order and their counts are exactly
/// the full crawl's.
pub async fn crawl_ecosystems(
options: &CrawlerOptions,
only: Option<&[String]>,
) -> (
Vec<CrawledPackage>,
HashMap<Ecosystem, usize>,
Option<String>,
) {
let (packages, counts, skipped_config_path, _) = crawl_every_ecosystem(options, only).await;
(packages, counts, skipped_config_path)
}
/// [`crawl_all_ecosystems`], also handing back the npm half of the crawl as
/// an [`NpmCrawlSnapshot`] (its packages are the leading `counts[Npm]`
/// entries of the package list).
#[cfg(test)]
pub async fn crawl_all_ecosystems_with_npm(
options: &CrawlerOptions,
) -> (
Vec<CrawledPackage>,
HashMap<Ecosystem, usize>,
Option<String>,
NpmCrawlSnapshot,
) {
let (packages, counts, skipped_config_path, snapshot) =
crawl_ecosystems_with_npm(options, None).await;
let snapshot = snapshot.expect("a crawl of every ecosystem crawls npm");
(packages, counts, skipped_config_path, snapshot)
}
/// [`crawl_ecosystems`], also handing back the npm half of the crawl as an
/// [`NpmCrawlSnapshot`] — `None` when `only` leaves npm out, so nothing
/// mistakes the skipped crawl for an empty `node_modules`.
pub async fn crawl_ecosystems_with_npm(
options: &CrawlerOptions,
only: Option<&[String]>,
) -> (
Vec<CrawledPackage>,
HashMap<Ecosystem, usize>,
Option<String>,
Option<NpmCrawlSnapshot>,
) {
let (packages, counts, skipped_config_path, npm_roots) =
crawl_every_ecosystem(options, only).await;
let snapshot = counts
.get(&Ecosystem::Npm)
.map(|&npm_count| NpmCrawlSnapshot {
cwd: options.cwd.clone(),
global: options.global,
global_prefix: options.global_prefix.clone(),
roots: npm_roots,
packages: packages[..npm_count].to_vec(),
});
(packages, counts, skipped_config_path, snapshot)
}
/// Whether a crawl limited to `only` visits `eco` (`None`: every one).
fn crawl_selects(only: Option<&[String]>, eco: Ecosystem) -> bool {
only.is_none_or(|list| list.iter().any(|name| name == eco.cli_name()))
}
/// The crawl behind the entry points above; the fourth element is the npm
/// crawler's `node_modules` roots (empty when npm was not selected).
async fn crawl_every_ecosystem(
options: &CrawlerOptions,
only: Option<&[String]>,
) -> (
Vec<CrawledPackage>,
HashMap<Ecosystem, usize>,
Option<String>,
Vec<PathBuf>,
) {
// The nine crawlers are independent (none prints, none mutates shared
// state), so they run concurrently; their blocking walks and
// subprocesses sit on the blocking pool. Results are consumed in the
// fixed order below, so packages and counts are exactly the serial
// run's. Each future is heap-allocated through `boxed` (constructed
// in that helper's frame) so joining nine does not grow the caller's
// poll frame by their combined size. Under a tight descriptor limit
// they run one at a time instead, keeping the serial run's descriptor
// profile (see `walk_pool`): a crawler treats a failed open as an
// absent dir, so extra concurrent descriptors could silently drop
// packages there. A crawler `only` leaves out resolves to its empty
// result without running.
macro_rules! crawl {
($eco:expr, $crawl:expr) => {
boxed(move || async move {
if crawl_selects(only, $eco) {
Some($crawl.await)
} else {
None
}
})
};
}
let (npm, pypi, cargo, gems, golang, maven, composer, nuget, deno) =
if walk_pool::fd_limit_is_tight() {
(
crawl!(Ecosystem::Npm, NpmCrawler.crawl_all_with_roots(options)).await,
crawl!(Ecosystem::Pypi, PythonCrawler.crawl_all(options)).await,
crawl!(Ecosystem::Cargo, CargoCrawler.crawl_all(options)).await,
crawl!(
Ecosystem::Gem,
RubyCrawler.crawl_all_with_discovery(options)
)
.await,
crawl!(Ecosystem::Golang, GoCrawler.crawl_all(options)).await,
crawl!(Ecosystem::Maven, MavenCrawler.crawl_all(options)).await,
crawl!(Ecosystem::Composer, ComposerCrawler.crawl_all(options)).await,
crawl!(Ecosystem::Nuget, NuGetCrawler.crawl_all(options)).await,
crawl!(Ecosystem::Deno, DenoCrawler.crawl_all(options)).await,
)
} else {
tokio::join!(
crawl!(Ecosystem::Npm, NpmCrawler.crawl_all_with_roots(options)),
crawl!(Ecosystem::Pypi, PythonCrawler.crawl_all(options)),
crawl!(Ecosystem::Cargo, CargoCrawler.crawl_all(options)),
crawl!(
Ecosystem::Gem,
RubyCrawler.crawl_all_with_discovery(options)
),
crawl!(Ecosystem::Golang, GoCrawler.crawl_all(options)),
crawl!(Ecosystem::Maven, MavenCrawler.crawl_all(options)),
crawl!(Ecosystem::Composer, ComposerCrawler.crawl_all(options)),
crawl!(Ecosystem::Nuget, NuGetCrawler.crawl_all(options)),
crawl!(Ecosystem::Deno, DenoCrawler.crawl_all(options)),
)
};
let (npm, npm_roots) = match npm {
Some((packages, roots)) => (Some(packages), roots),
None => (None, Vec::new()),
};
let (gems, gem_discovery) = match gems {
Some((packages, discovery)) => (Some(packages), discovery),
None => (None, None),
};
let mut all_packages = Vec::new();
let mut counts: HashMap<Ecosystem, usize> = HashMap::new();
for (eco, pkgs) in [
(Ecosystem::Npm, npm),
(Ecosystem::Pypi, pypi),
(Ecosystem::Cargo, cargo),
(Ecosystem::Gem, gems),
(Ecosystem::Golang, golang),
(Ecosystem::Maven, maven),
(Ecosystem::Composer, composer),
(Ecosystem::Nuget, nuget),
(Ecosystem::Deno, deno),