Repository navigation
Expand file tree
/
Copy pathecosystem_dispatch.rs
More file actions
2829 lines (2663 loc) · 116 KB
/
Copy pathecosystem_dispatch.rs
File metadata and controls
2829 lines (2663 loc) · 116 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::{Path, PathBuf};
use crate::args::GlobalArgs;
use socket_patch_core::crawlers::npm_crawler::{
build_npm_purl, parse_package_name, retain_live_store_copies, 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_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()
}
/// Of `purls` (manifest keys), the Cargo ones whose agent-mode in-place
/// patch may still be on disk: a copy [`find_cargo_copies`] locates
/// (`shadowed_registry`: see there) with at least one file at its record's afterHash, or one that cannot be read to
/// tell (an I/O error, an unsafe key: kept fail-closed). Sorted.
///
/// Cargo is the one ecosystem whose patched copy outlives the project's
/// use of it: the registry cache is shared machine-wide and nothing
/// deletes a crate from it when a project vendors the crate (#336) or
/// stops locking it (#1278). Its manifest record holds the only
/// before-blobs that can restore that copy, so callers about to drop the
/// record must first restore the copy (`rollback`) or keep the record
/// (`scan --prune`). A vendored crate's committed copy under
/// `.socket/vendor/` is never one of these locations.
pub async fn cargo_copies_still_patched<'a>(
manifest: &socket_patch_core::manifest::schema::PatchManifest,
purls: impl IntoIterator<Item = &'a String>,
options: &CrawlerOptions,
blobs_path: &std::path::Path,
shadowed_registry: bool,
) -> Vec<String> {
use socket_patch_core::patch::rollback::{verify_file_rollback, VerifyRollbackStatus};
let cargo: Vec<String> = purls
.into_iter()
.filter(|p| Ecosystem::from_purl(p) == Some(Ecosystem::Cargo))
.filter(|p| manifest.patches.contains_key(p.as_str()))
.cloned()
.collect();
if cargo.is_empty() {
return Vec::new();
}
let found = find_cargo_copies(cargo, options, shadowed_registry).await;
let mut patched = Vec::new();
for (purl, paths) in &found {
let Some(record) = manifest.patches.get(purl) else {
continue;
};
'copies: for path in paths {
for (file, info) in &record.files {
let v = verify_file_rollback(path, file, info, blobs_path).await;
let still = match v.status {
VerifyRollbackStatus::Ready | VerifyRollbackStatus::MissingBlob => true,
VerifyRollbackStatus::NotFound => !v.is_absent(),
VerifyRollbackStatus::AlreadyOriginal | VerifyRollbackStatus::HashMismatch => {
false
}
};
if still {
patched.push(purl.clone());
break 'copies;
}
}
}
}
patched.sort();
patched
}
/// The copies of the Cargo `purls` [`find_all_packages_for_rollback`]
/// locates (the roots rollback restores), plus, with `shadowed_registry`,
/// the shared `$CARGO_HOME/registry/src` copies of a local Cargo project
/// whose cargo config replaces crates.io with a `cargo vendor` directory,
/// whose crawl searches only that dir — where
/// an apply from before `cargo vendor` may have left the patch. The prune
/// only reads them (its keep decision); rollback restores them only for a
/// vendored crate whose record it is about to drop (#336).
pub async fn find_cargo_copies(
purls: Vec<String>,
options: &CrawlerOptions,
shadowed_registry: bool,
) -> HashMap<String, Vec<PathBuf>> {
let partitioned = HashMap::from([(Ecosystem::Cargo, purls)]);
let mut found = find_all_packages_for_rollback(&partitioned, options, true).await;
let local = !options.global && options.global_prefix.is_none();
let cargo_project =
options.cwd.join("Cargo.toml").is_file() || options.cwd.join("Cargo.lock").is_file();
if shadowed_registry
&& local
&& cargo_project
&& CargoCrawler::new()
.directory_source(&options.cwd)
.await
.is_some()
{
let registry = CrawlerOptions {
cwd: options.cwd.clone(),
global: true,
global_prefix: None,
};
for (purl, paths) in find_all_packages_for_rollback(&partitioned, ®istry, true).await {
let copies = found.entry(purl).or_default();
for path in paths {
if !copies.contains(&path) {
copies.push(path);
}
}
}
}
found
}
/// 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
/// with the ecosystem's `$on_match` merge (first-wins, or every copy for
/// npm, cargo and the release-variant ecosystems).
///
/// `$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 the `dispatch_find` merges (`merge_first_wins`,
/// `merge_cargo_copies`, `merge_variant_copies`, `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 (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 an explicit, separately-tested decision
/// per ecosystem: npm (`merge_npm_copies`) and cargo's registry index dirs
/// (`merge_cargo_copies`).
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);
}
}
/// Cargo merge: keep EVERY crates.io copy, one per registry index dir.
/// The shared registry cache extracts a crate once per index dir
/// (`index.crates.io-6f17d22bba15001f` for cargo 1.70–1.84,
/// `index.crates.io-1949cf8c6b5b557f` for cargo ≥ 1.85, the pre-1.70 git
/// index), and each cargo builds from its own. First-wins patched, checked
/// and restored only the copy in the first dir in listing order, so a
/// project on the other cargo kept building the unpatched crate while
/// `apply` reported success and `vex` attested it (#339).
///
/// A `pkg:cargo` PURL names a crates.io crate, so a same-`name@version`
/// copy in another registry's dir (a private registry, a hosted Socket
/// patch registry) is a different crate: it is kept only when no crates.io
/// copy exists, as the single first-found copy it always was. A
/// `cargo vendor` tree or `--global-prefix` is one root, so one copy.
fn merge_cargo_copies(
out: &mut HashMap<String, Vec<PathBuf>>,
_purls: &[String],
packages: HashMap<String, CrawledPackage>,
) {
for (purl, pkg) in packages {
let paths = out.entry(purl).or_default();
if paths.is_empty() {
paths.push(pkg.path);
} else if is_crates_io_copy(&pkg.path) && !paths.contains(&pkg.path) {
if paths.iter().all(|p| is_crates_io_copy(p)) {
paths.push(pkg.path);
} else {
// The first-found copy belongs to another registry.
*paths = vec![pkg.path];
}
}
}
}
/// Whether `crate_dir` sits in a crates.io index dir of the registry
/// cache: `index.crates.io-<hash>` (sparse, cargo ≥ 1.70) or the git
/// index's `github.com-1ecc6299db9ec823` (cargo < 1.70).
fn is_crates_io_copy(crate_dir: &std::path::Path) -> bool {
crate_dir
.parent()
.and_then(|p| p.file_name())
.and_then(|n| n.to_str())
.is_some_and(|n| n.starts_with("index.crates.io-") || n == "github.com-1ecc6299db9ec823")
}
/// 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>>,
) {
merge_each_copy(merge_variant_copies, out, purls, packages);
}
/// `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; every other ecosystem
/// inserts the crawler-returned PURL with its own fixed merge. 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::new(),
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,
// One copy per registry index dir, each built by another cargo.
on_match = merge_cargo_copies,
);
scan_ecosystem!(
out = out,
partitioned = partitioned,
eco = Ecosystem::Gem,
options = options,
silent = silent,
crawler = GemCopiesCrawler,
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,
// One gem home can hold a version's ruby-platform AND platform
// builds; fold every copy in (#1092).
on_match = |out: &mut HashMap<String, Vec<PathBuf>>,
purls: &[String],
packages: HashMap<String, Vec<CrawledPackage>>| {
merge_each_copy(variant_merge, out, purls, packages)
},
);
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`. Cargo keeps every registry index
// copy (`merge_cargo_copies`); the single-copy ecosystems keep true
// first-wins via their own `merge_first_wins` wiring in
// `dispatch_find`. An npm purl with no copy can still be reached
// through a workspace member's alias link (#1494).
dispatch_find_with_npm_links(
partitioned,
options,
silent,
merge_variant_copies,
None,
NpmLinks::ForUnresolved,
)
.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. An npm purl
/// with no copy can still be reached through a workspace member's alias
/// link (#1494), as for apply.
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>> {
dispatch_find_with_npm_links(
partitioned,
options,
silent,
merge_qualified,
prior,
NpmLinks::ForUnresolved,
)
.await
}
/// The install paths that reach each purl, for `scan`'s and `rollback`'s
/// path targets: [`find_all_packages_for_rollback_reusing`]'s copies plus
/// every matching npm root link, not only those of purls with no copy
/// (#1266). The result is for path matching only: it can name one
/// physical copy more than once.
pub async fn find_package_paths_for_path_scope(
partitioned: &HashMap<Ecosystem, Vec<String>>,
options: &CrawlerOptions,
silent: bool,
prior: Option<&NpmCrawlSnapshot>,
) -> HashMap<String, Vec<PathBuf>> {
dispatch_find_with_npm_links(
partitioned,
options,
silent,
merge_qualified,
prior,
NpmLinks::All,
)
.await
}
/// Which npm root links [`dispatch_find_with_npm_links`] adds.
#[derive(Clone, Copy, PartialEq, Eq)]
enum NpmLinks {
/// Every link to a purl asked for: path scoping matches by install
/// path, so each spelling counts.
All,
/// Only links to purls the resolver found no copy of. The commands
/// that act per copy already reach every store peer variant of a
/// found copy through the apply engine's fan-out, so a link to one
/// would be a second visit (#633); and a link into first-party source
/// beside a found registry copy must not turn into a refusal.
ForUnresolved,
}
/// [`dispatch_find`]'s copies, plus each npm package link directly in a
/// `node_modules` root (scoped ones one level down) whose target's
/// `package.json` names one of the npm purls asked for (see [`NpmLinks`]
/// for which), after the copies.
///
/// The crawler records a plain-name link at its own path
/// (`packages/a/node_modules/ms`), but never an alias link
/// (`packages/a/node_modules/lp -> …/.pnpm/left-pad@1.3.0/node_modules/left-pad`):
/// links are not physical copies, and the resolver must see each copy
/// once (#856). Yet pnpm's isolated linker, vlt and npm's
/// `install-strategy=linked` reach a workspace member's ALIAS dependency
/// only through such a link. Path scoping needs it to select the member
/// (#1266), and a run from inside the member, whose `node_modules` is the
/// only root, has no other route to the copy at all (#1494). A link is
/// matched by its target's own identity, not against the crawled copies,
/// so a link to a store peer variant the crawl skipped still counts, and
/// the cost is one pass over the root links however many purls are asked
/// for (none when every purl already has a copy and only the unresolved
/// ones' links are wanted).
async fn dispatch_find_with_npm_links(
partitioned: &HashMap<Ecosystem, Vec<String>>,
options: &CrawlerOptions,
silent: bool,
variant_merge: MergeFn,
prior: Option<&NpmCrawlSnapshot>,
links: NpmLinks,
) -> HashMap<String, Vec<PathBuf>> {
let mut wanted: HashMap<PurlKey, Vec<String>> = HashMap::new();
for purl in partitioned.get(&Ecosystem::Npm).into_iter().flatten() {
wanted
.entry(PurlKey::new(purl))
.or_default()
.push(purl.clone());
}
let npm_roots = match prior.and_then(|p| p.roots_for(options)) {
_ if wanted.is_empty() => None,
Some(roots) => Some(roots.to_vec()),
None => NpmCrawler.get_node_modules_paths(options).await.ok(),
};
let mut found = dispatch_find(
partitioned,
options,
silent,
variant_merge,
npm_roots.as_deref(),
)
.await;
let Some(roots) = npm_roots else {
return found;
};
if links == NpmLinks::ForUnresolved {
let resolved = |purl: &String| found.get(purl).is_some_and(|paths| !paths.is_empty());
wanted.retain(|_, purls| {
purls.retain(|purl| !resolved(purl));
!purls.is_empty()
});
if wanted.is_empty() {
return found;
}
}
// A failed enumeration only loses the extra links; the copies stand.
let links = tokio::task::spawn_blocking(move || npm_links_to(&wanted, &roots))
.await
.unwrap_or_default();
for (purl, link) in links {
let paths = found.entry(purl).or_default();
if !paths.contains(&link) {
paths.push(link);
}
}
found
}
/// Every package link directly in one of `roots` (scoped ones one level
/// down) whose target directory's `package.json` `name@version` is a key
/// of `wanted`, paired with each purl spelling that key stands for.
fn npm_links_to(
wanted: &HashMap<PurlKey, Vec<String>>,
roots: &[PathBuf],
) -> Vec<(String, PathBuf)> {
let entries = |dir: &Path| -> Vec<(String, PathBuf, std::fs::FileType)> {
let Ok(read) = std::fs::read_dir(dir) else {
return Vec::new();
};
read.filter_map(Result::ok)
.filter_map(|e| {
let name = e.file_name().to_string_lossy().into_owned();
let file_type = e.file_type().ok()?;
(!name.starts_with('.')).then(|| (name, e.path(), file_type))
})
.collect()
};
let identity = |link: &Path| -> Option<PurlKey> {
let target = std::fs::canonicalize(link).ok()?;
let text =
socket_patch_core::utils::fs::read_regular_to_string_sync(&target.join("package.json"))
.ok()?;
let pkg: serde_json::Value =
serde_json::from_str(socket_patch_core::formats::text::strip_bom(&text)).ok()?;
let name = pkg.get("name")?.as_str()?;
let version = pkg.get("version")?.as_str()?;
if name.is_empty() || version.is_empty() {
return None;
}
let (namespace, leaf) = parse_package_name(name);
Some(PurlKey::new(&build_npm_purl(
namespace.as_deref(),
&leaf,
version,
)))
};
let mut out = Vec::new();
for root in roots {
let mut links = Vec::new();
for (name, path, file_type) in entries(root) {
if name.starts_with('@') && file_type.is_dir() {
links.extend(
entries(&path)
.into_iter()
.filter(|(_, _, ft)| ft.is_symlink())
.map(|(_, p, _)| p),
);
} else if file_type.is_symlink() {
links.push(path);
}
}
for link in links {
let Some(key) = identity(&link) else {
continue;
};
for purl in wanted.get(&key).into_iter().flatten() {
out.push((purl.clone(), link.clone()));
}
}
}
out
}
/// 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. An npm purl with no copy can still
/// be reached through a workspace member's alias link (#1494).
pub async fn find_packages_for_rollback_reusing(
partitioned: &HashMap<Ecosystem, Vec<String>>,
options: &CrawlerOptions,
silent: bool,
prior: Option<&NpmCrawlSnapshot>,
) -> HashMap<String, PathBuf> {
collapse_to_first(
dispatch_find_with_npm_links(
partitioned,
options,
silent,
merge_qualified,
prior,
NpmLinks::ForUnresolved,
)
.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())
}
}
/// [`RubyCrawler`] for [`dispatch_find`], returning every installed copy of
/// each gem in a gem home (the ruby-platform dir and each platform dir).
struct GemCopiesCrawler;
impl GemCopiesCrawler {
async fn get_gem_paths(
&self,
options: &CrawlerOptions,
) -> Result<Vec<PathBuf>, std::io::Error> {
RubyCrawler.get_gem_paths(options).await
}
async fn find_by_purls(
&self,
gem_path: &std::path::Path,
purls: &[String],
) -> Result<HashMap<String, Vec<CrawledPackage>>, std::io::Error> {
RubyCrawler.find_all_by_purls(gem_path, purls).await
}
}
/// Feed every copy in `packages` through `merge`, one copy at a time and in
/// order, so a crawler that returns several copies per PURL reaches the
/// one-copy [`MergeFn`]s unchanged.
fn merge_each_copy(
merge: MergeFn,
out: &mut HashMap<String, Vec<PathBuf>>,
purls: &[String],
packages: HashMap<String, Vec<CrawledPackage>>,
) {
for (purl, copies) in packages {
for pkg in copies {
merge(out, purls, HashMap::from([(purl.clone(), pkg)]));
}
}
}
/// [`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,