Repository navigation
Expand file tree
/
Copy pathledgers.rs
More file actions
732 lines (695 loc) · 26.9 KB
/
Copy pathledgers.rs
File metadata and controls
732 lines (695 loc) · 26.9 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
//! The project's patch stores read as one view: the agent manifest
//! (`.socket/manifest.json`), the vendored ledger
//! (`.socket/vendor/state.json`) and the hosted records. v5 hosted mode
//! keeps no ledger, so the hosted records are the lockfiles' hosted pins
//! (shaped as uuid-only records) or a run's fetched records, plus a pre-v5
//! redirect ledger (`.socket/vendor/redirect-state.json`) read, never
//! written, for migration.
//!
//! One owner-precedence rule decides which store owns a purl every reader
//! merges ([`Ledgers::owned`], [`Ledgers::listed`], [`Ledgers::matching`]):
//!
//! 1. A manifest key is owned by the manifest. It claims every vendored
//! entry filed under that key or whose `base_purl` it names; a claimed
//! entry's embedded record is a fallback copy. The group's vendored
//! entry is the one filed under the key, else the lowest-keyed entry
//! naming it as `base_purl` (so `HashMap` order never decides).
//! 2. Every unclaimed vendored entry owns its ledger key.
//! 3. A hosted record owns its key when neither of the above does.
//!
//! So: manifest > vendored > hosted, by ledger key. The losing copies stay
//! reachable as alternates ([`Owned::alts`]) for readers that decide by
//! lockfile evidence (`vex`). The hosted records only ever join as the
//! last store.
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use crate::manifest::schema::{PatchManifest, PatchRecord};
use crate::patch::redirect::upstream::HostedPin;
use crate::patch::redirect::{CorruptRedirectState, RedirectState};
use crate::utils::purl::canonical_purl;
use crate::utils::purl_key::PurlKey;
use crate::utils::target::Target;
use crate::vendor::{VendorEntry, VendorState};
/// A patch store, in owner-precedence order (a lower store wins a key).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Store {
/// `.socket/manifest.json` (agent mode).
Manifest,
/// `.socket/vendor/state.json` (vendored mode).
Vendored,
/// The hosted records (lockfile pins, a run's fetched records, or a
/// pre-v5 redirect ledger read for migration).
Hosted,
}
/// The three stores as loaded, each with its own outcome so every caller
/// keeps its error posture (strict, lenient, per-leg).
pub struct LoadedLedgers {
/// `Ok(None)`: absent; `Err(InvalidData)`: unparseable; other `Err`: I/O.
pub manifest: std::io::Result<Option<PatchManifest>>,
/// Absent is `Ok(empty)`; `Err` is unreadable or malformed.
pub vendor: std::io::Result<VendorState>,
/// The pre-v5 redirect ledger, read only (absent is `Ok(None)`).
pub redirect: Result<Option<RedirectState>, CorruptRedirectState>,
}
impl LoadedLedgers {
/// Load the manifest at `manifest_path`, the vendored ledger and any
/// pre-v5 redirect ledger of `project_root`, concurrently.
pub async fn load(project_root: &Path, manifest_path: &Path) -> Self {
let (manifest, vendor, redirect) = tokio::join!(
crate::manifest::operations::read_manifest(manifest_path),
crate::vendor::load_state(project_root),
crate::patch::redirect::load_redirect_state(project_root),
);
Self {
manifest,
vendor,
redirect,
}
}
/// The readable stores (a failed store reads as absent).
pub fn view(&self) -> Ledgers<'_> {
Ledgers {
manifest: self.manifest.as_ref().ok().and_then(Option::as_ref),
vendor: self.vendor.as_ref().ok(),
redirect: self.redirect.as_ref().ok().and_then(Option::as_ref),
}
}
}
/// A borrowed view over whichever stores a caller has.
#[derive(Clone, Copy, Default)]
pub struct Ledgers<'a> {
pub manifest: Option<&'a PatchManifest>,
pub vendor: Option<&'a VendorState>,
pub redirect: Option<&'a RedirectState>,
}
/// One owner key with the store that owns it and every copy under it.
#[derive(Debug, Clone)]
pub struct Owned<'a> {
pub key: &'a str,
pub store: Store,
pub uuid: &'a str,
/// The owner's record; `None` for a legacy vendored entry that embeds
/// none.
pub record: Option<&'a PatchRecord>,
/// The vendored entry in this group (the owner itself, or the one the
/// manifest key claimed), with its ledger key.
pub vendor: Option<(&'a str, &'a VendorEntry)>,
/// Whether the hosted records hold one under this key.
pub hosted: bool,
/// The losing copies' records, in precedence order.
pub alts: Vec<&'a PatchRecord>,
}
/// One copy [`Ledgers::listed`] shows.
#[derive(Debug, Clone, Copy)]
pub struct Listed<'a> {
pub key: &'a str,
pub record: &'a PatchRecord,
pub store: Store,
}
/// Every store's entries a remove/rollback identifier matches, each sorted
/// by key.
#[derive(Debug, Clone, Default)]
pub struct Matches {
pub manifest: Vec<String>,
pub vendor: Vec<(String, VendorEntry)>,
pub hosted: Vec<String>,
}
impl Matches {
pub fn is_empty(&self) -> bool {
self.manifest.is_empty() && self.vendor.is_empty() && self.hosted.is_empty()
}
}
/// The lockfiles' hosted pins a remove/rollback `target` selects, sorted
/// by purl: every pin the target names ([`Target::matches_patch`]), plus
/// every pin wiring the same release as one of `manifest_keys` (the
/// manifest entries the target matched). The second half is the hosted
/// twin of [`Ledgers::matching`]'s claim groups: `remove <uuid>` of a
/// manifest record whose package a later hosted scan re-pinned to another
/// patch generation unwinds that pin too, instead of leaving it live with
/// no record.
pub fn hosted_pins_matching(
pins: &[HostedPin],
target: &Target,
manifest_keys: &[String],
) -> Vec<HostedPin> {
let mut matches: Vec<HostedPin> = pins
.iter()
.filter(|pin| {
target.matches_patch(&pin.purl, &pin.uuid)
|| manifest_keys
.iter()
.any(|key| PurlKey::same(key, &pin.purl))
})
.cloned()
.collect();
matches.sort_by(|a, b| a.purl.cmp(&b.purl).then(a.uuid.cmp(&b.uuid)));
matches
}
fn sorted_keys<V>(map: &HashMap<String, V>) -> Vec<&String> {
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
keys
}
impl<'a> Ledgers<'a> {
/// Every vendored entry grouped under the manifest key that claims it
/// (rule 1 of the module docs), each group sorted by ledger key. Built
/// in one pass over the sorted ledger, so the views stay O(V log V + M).
fn claims(&self) -> HashMap<&'a str, Vec<(&'a String, &'a VendorEntry)>> {
let mut claims: HashMap<&'a str, Vec<(&'a String, &'a VendorEntry)>> = HashMap::new();
if let Some(vendor) = self.vendor {
for key in sorted_keys(&vendor.entries) {
let entry = &vendor.entries[key];
if let Some(owner) = self.claimant(key, entry) {
claims.entry(owner).or_default().push((key, entry));
}
}
}
claims
}
/// A claim group's representative entry: the one filed under the
/// manifest key itself, else the lowest-keyed.
fn primary<'c>(
key: &str,
group: &'c [(&'a String, &'a VendorEntry)],
) -> Option<&'c (&'a String, &'a VendorEntry)> {
group
.iter()
.find(|(k, _)| k.as_str() == key)
.or_else(|| group.first())
}
/// The manifest key that claims the vendored entry filed under `key`
/// (rule 1 of the module docs): `key` itself, else its `base_purl`.
fn claimant(&self, key: &str, entry: &VendorEntry) -> Option<&'a str> {
let manifest = self.manifest?;
manifest
.patches
.get_key_value(key)
.or_else(|| manifest.patches.get_key_value(&entry.base_purl))
.map(|(k, _)| k.as_str())
}
/// Whether the vendored entry filed under `key` has a manifest owner.
pub fn vendor_claimed(&self, key: &str) -> bool {
self.vendor
.and_then(|v| v.entries.get(key))
.is_some_and(|entry| self.claimant(key, entry).is_some())
}
/// One group per owner key: the manifest's keys (sorted), then the
/// unclaimed vendored keys (sorted), then the hosted keys neither owns
/// (sorted).
pub fn owned(&self) -> Vec<Owned<'a>> {
let hosted_records = self.redirect.map(|r| &r.records);
let hosted_record = |key: &str| hosted_records.and_then(|r| r.get(key));
let mut out: Vec<Owned<'a>> = Vec::new();
let claims = self.claims();
if let Some(manifest) = self.manifest {
for key in sorted_keys(&manifest.patches) {
let record = &manifest.patches[key];
let group = claims
.get(key.as_str())
.map(Vec::as_slice)
.unwrap_or_default();
let vendor = Self::primary(key, group).copied();
let mut alts: Vec<&'a PatchRecord> = Vec::new();
alts.extend(vendor.and_then(|(_, e)| e.record.as_ref()));
// Any further entry this key claims (another variant of
// the same base purl) is a fallback copy too.
alts.extend(
group
.iter()
.filter(|(k, _)| vendor.is_none_or(|(vk, _)| vk != *k))
.filter_map(|(_, e)| e.record.as_ref()),
);
alts.extend(hosted_record(key));
out.push(Owned {
key,
store: Store::Manifest,
uuid: &record.uuid,
record: Some(record),
vendor: vendor.map(|(k, e)| (k.as_str(), e)),
hosted: hosted_record(key).is_some(),
alts,
});
}
}
if let Some(vendor) = self.vendor {
for key in sorted_keys(&vendor.entries) {
let entry = &vendor.entries[key];
if self.claimant(key, entry).is_some() {
continue;
}
out.push(Owned {
key,
store: Store::Vendored,
uuid: &entry.uuid,
record: entry.record.as_ref(),
vendor: Some((key.as_str(), entry)),
hosted: hosted_record(key).is_some(),
alts: hosted_record(key).into_iter().collect(),
});
}
}
if let Some(records) = hosted_records {
let taken: HashSet<&str> = out.iter().map(|o| o.key).collect();
for (key, record) in records {
if taken.contains(key.as_str()) {
continue;
}
out.push(Owned {
key,
store: Store::Hosted,
uuid: &record.uuid,
record: Some(record),
vendor: None,
hosted: true,
alts: Vec::new(),
});
}
}
out
}
/// Every record copy worth showing, sorted by key then store: all
/// manifest and hosted records, and every vendored record except a
/// claimed non-`detached` entry's (a standalone `vendor` entry's
/// fallback copy of the manifest record it is claimed by). A `detached`
/// entry is the only copy of its record, so it shows even beside a
/// manifest entry — coexistence is real state, labeled apart.
pub fn listed(&self) -> Vec<Listed<'a>> {
let mut out: Vec<Listed<'a>> = Vec::new();
if let Some(manifest) = self.manifest {
out.extend(manifest.patches.iter().map(|(key, record)| Listed {
key,
record,
store: Store::Manifest,
}));
}
if let Some(vendor) = self.vendor {
out.extend(vendor.entries.iter().filter_map(|(key, entry)| {
let record = entry.record.as_ref()?;
(entry.detached || self.claimant(key, entry).is_none()).then_some(Listed {
key,
record,
store: Store::Vendored,
})
}));
}
if let Some(redirect) = self.redirect {
out.extend(redirect.records.iter().map(|(key, record)| Listed {
key,
record,
store: Store::Hosted,
}));
}
out.sort_by(|a, b| a.key.cmp(b.key).then(a.store.cmp(&b.store)));
out
}
/// Every entry a remove/rollback `target` matches: manifest and hosted
/// records by [`Target::matches_patch`] on their key, vendored entries
/// by [`VendorEntry::matches_target`] (key or base purl) or by belonging
/// to a matched manifest key's claim group (rule 1 of the module docs).
///
/// The claim group is what makes a uuid target generation-blind: a
/// manifest key and the vendored entry it claims are ONE owned pin,
/// whichever patch generation each store recorded. When `get`/`scan`
/// recorded a superseding patch B in the manifest while the ledger still
/// holds the vendored generation A, `remove <B>` must revert A's
/// vendoring too (#999), or the lockfile keeps consuming A's artifact
/// with no record left.
pub fn matching(&self, target: &Target) -> Matches {
let mut manifest: Vec<String> = self
.manifest
.into_iter()
.flat_map(|m| m.patches.iter())
.filter(|(key, rec)| target.matches_patch(key, &rec.uuid))
.map(|(key, _)| key.clone())
.collect();
manifest.sort();
let claimed_by_match = |key: &str, entry: &VendorEntry| {
self.claimant(key, entry)
.is_some_and(|owner| manifest.binary_search_by(|m| m.as_str().cmp(owner)).is_ok())
};
let mut vendor: Vec<(String, VendorEntry)> = self
.vendor
.into_iter()
.flat_map(|s| s.entries.iter())
.filter(|(key, entry)| {
entry.matches_target(key, target) || claimed_by_match(key, entry)
})
.map(|(k, e)| (k.clone(), e.clone()))
.collect();
vendor.sort_by(|a, b| a.0.cmp(&b.0));
let hosted: Vec<String> = self
.redirect
.into_iter()
.flat_map(|r| r.records.iter())
.filter(|(key, rec)| target.matches_patch(key, &rec.uuid))
.map(|(key, _)| key.clone())
.collect();
Matches {
manifest,
vendor,
hosted,
}
}
/// The purls both the hosted records and the vendored ledger claim, in
/// the records' display spelling ([`canonical_purl`]: qualifiers
/// dropped, percent-decoded), sorted and deduplicated: each is stale in
/// exactly one store, which only the live lockfile can tell.
pub fn hosted_vendored_overlap(&self) -> Vec<String> {
let (Some(redirect), Some(vendor)) = (self.redirect, self.vendor) else {
return Vec::new();
};
if vendor.entries.is_empty() {
return Vec::new();
}
// Match by `PurlKey`, so the API purl form the redirect records carry
// matches the vendor entry's key or base purl in any spelling.
// Two spellings of one release (composer `@3.0.2` and
// `@3.0.2.0`, NuGet case twins) are ONE overlap: deduplicate by
// `PurlKey`, reporting the smallest display spelling.
let vendor_purls = vendor.purl_keys();
let mut overlap: std::collections::BTreeMap<PurlKey, String> =
std::collections::BTreeMap::new();
for purl in redirect
.records
.keys()
.filter(|p| crate::vendor::purl_keys_cover(&vendor_purls, p))
{
let display = canonical_purl(purl);
overlap
.entry(PurlKey::new(purl))
.and_modify(|kept| {
if display < *kept {
*kept = display.clone();
}
})
.or_insert(display);
}
let mut out: Vec<String> = overlap.into_values().collect();
out.sort();
out
}
}
/// A uuid-only stand-in record (a legacy vendored entry that embeds no
/// record, or a lockfile pin with no store record).
pub fn uuid_only_record(uuid: &str) -> PatchRecord {
PatchRecord {
uuid: uuid.to_string(),
exported_at: String::new(),
files: HashMap::new(),
vulnerabilities: HashMap::new(),
description: String::new(),
license: String::new(),
tier: String::new(),
}
}
/// Fold the hosted pins and the vendor ledger's patch records into the
/// manifest view update detection consults. Hosted mode records purl→uuid
/// ONLY in the lockfiles (`hosted_pins`, uuid only; v5 keeps no hosted
/// ledger) and vendored mode ONLY in `.socket/vendor/state.json`, so without
/// this fold a pure hosted or vendored project's `updates[]` would always
/// be empty. Precedence on a collision: manifest > hosted pins > vendor
/// ledger (the live lock over a possibly superseded vendored entry); the
/// vendor entries fold under the shared owner rule
/// ([`Ledgers::owned`]), so one the manifest
/// claims (its key or base purl) stays behind the manifest's record.
/// Vendor entries are keyed by their ledger key (`detect_updates` bridges
/// the spellings); a legacy entry without an embedded record contributes
/// its uuid alone. Borrows the manifest untouched when nothing else
/// contributes.
pub fn merge_ledger_records_for_updates<'a>(
manifest: Option<&'a PatchManifest>,
vendor: Option<&VendorState>,
hosted_pins: &[(String, String)],
) -> Option<Cow<'a, PatchManifest>> {
let vendor = vendor.filter(|s| !s.entries.is_empty());
if vendor.is_none() && hosted_pins.is_empty() {
return manifest.map(Cow::Borrowed);
}
let mut merged = manifest.cloned().unwrap_or_default();
for (purl, uuid) in hosted_pins {
merged
.patches
.entry(purl.clone())
.or_insert_with(|| uuid_only_record(uuid));
}
let ledgers = Ledgers {
manifest,
vendor,
redirect: None,
};
for owned in ledgers.owned() {
if owned.store == Store::Manifest {
continue;
}
merged
.patches
.entry(owned.key.to_string())
.or_insert_with(|| {
owned
.record
.cloned()
.unwrap_or_else(|| uuid_only_record(owned.uuid))
});
}
Some(Cow::Owned(merged))
}
#[cfg(test)]
mod tests {
use super::*;
fn record(uuid: &str) -> PatchRecord {
uuid_only_record(uuid)
}
fn entry(uuid: &str, base: &str, detached: bool, rec: Option<&str>) -> VendorEntry {
let mut value = serde_json::json!({
"uuid": uuid,
"basePurl": base,
"ecosystem": "npm",
"artifact": { "path": "", "sha256": "" },
"wiring": [],
"detached": detached,
});
if let Some(r) = rec {
value["record"] = serde_json::to_value(record(r)).unwrap();
}
serde_json::from_value(value).expect("vendor entry fixture")
}
fn manifest(pairs: &[(&str, &str)]) -> PatchManifest {
let mut m = PatchManifest::new();
for (k, u) in pairs {
m.patches.insert(k.to_string(), record(u));
}
m
}
fn vendor(pairs: Vec<(&str, VendorEntry)>) -> VendorState {
let mut s = VendorState::new();
for (k, e) in pairs {
s.entries.insert(k.to_string(), e);
}
s
}
fn redirect(pairs: &[(&str, &str)]) -> RedirectState {
let mut r = RedirectState::new();
for (k, u) in pairs {
r.records.insert(k.to_string(), record(u));
}
r
}
#[test]
fn manifest_beats_vendored_beats_hosted() {
let m = manifest(&[("pkg:npm/a@1", "m")]);
let v = vendor(vec![
("pkg:npm/a@1", entry("v", "pkg:npm/a@1", true, Some("v"))),
("pkg:npm/b@1", entry("vb", "pkg:npm/b@1", true, Some("vb"))),
]);
let r = redirect(&[
("pkg:npm/a@1", "h"),
("pkg:npm/b@1", "hb"),
("pkg:npm/c@1", "hc"),
]);
let l = Ledgers {
manifest: Some(&m),
vendor: Some(&v),
redirect: Some(&r),
};
let owned = l.owned();
let got: Vec<(&str, Store, &str, Vec<&str>)> = owned
.iter()
.map(|o| {
(
o.key,
o.store,
o.uuid,
o.alts.iter().map(|a| a.uuid.as_str()).collect(),
)
})
.collect();
assert_eq!(
got,
vec![
("pkg:npm/a@1", Store::Manifest, "m", vec!["v", "h"]),
("pkg:npm/b@1", Store::Vendored, "vb", vec!["hb"]),
("pkg:npm/c@1", Store::Hosted, "hc", vec![]),
]
);
}
#[test]
fn a_manifest_key_claims_the_entry_naming_it_as_base_purl() {
let m = manifest(&[("pkg:npm/a@1", "m")]);
let v = vendor(vec![
(
"pkg:npm/a@1?x=2",
entry("v2", "pkg:npm/a@1", false, Some("v2")),
),
(
"pkg:npm/a@1?x=1",
entry("v1", "pkg:npm/a@1", false, Some("v1")),
),
]);
let l = Ledgers {
manifest: Some(&m),
vendor: Some(&v),
redirect: None,
};
let owned = l.owned();
assert_eq!(owned.len(), 1);
assert_eq!(owned[0].vendor.map(|(k, _)| k), Some("pkg:npm/a@1?x=1"));
let alts: Vec<&str> = owned[0].alts.iter().map(|a| a.uuid.as_str()).collect();
assert_eq!(alts, vec!["v1", "v2"]);
assert!(l.vendor_claimed("pkg:npm/a@1?x=1"));
assert!(l.vendor_claimed("pkg:npm/a@1?x=2"));
// Claimed fallback copies are not listed.
let listed: Vec<(&str, Store)> = l.listed().iter().map(|e| (e.key, e.store)).collect();
assert_eq!(listed, vec![("pkg:npm/a@1", Store::Manifest)]);
}
#[test]
fn a_detached_claimed_entry_still_lists() {
let m = manifest(&[("pkg:npm/a@1", "m")]);
let v = vendor(vec![(
"pkg:npm/a@1",
entry("v", "pkg:npm/a@1", true, Some("v")),
)]);
let l = Ledgers {
manifest: Some(&m),
vendor: Some(&v),
redirect: None,
};
assert_eq!(l.listed().len(), 2);
assert_eq!(l.owned().len(), 1);
}
#[test]
fn matching_spans_every_store() {
let m = manifest(&[("pkg:npm/a@1", "m")]);
let v = vendor(vec![(
"pkg:npm/a@1?q=1",
entry("v", "pkg:npm/a@1", true, None),
)]);
let r = redirect(&[("pkg:npm/a@1", "h"), ("pkg:npm/b@1", "hb")]);
let l = Ledgers {
manifest: Some(&m),
vendor: Some(&v),
redirect: Some(&r),
};
let found = l.matching(&Target::parse("pkg:npm/a@1"));
assert_eq!(found.manifest, vec!["pkg:npm/a@1"]);
assert_eq!(found.vendor.len(), 1);
assert_eq!(found.hosted, vec!["pkg:npm/a@1"]);
assert!(l.matching(&Target::parse("nope")).is_empty());
assert_eq!(l.matching(&Target::parse("hb")).hosted, vec!["pkg:npm/b@1"]);
}
#[test]
fn overlap_reports_one_entry_per_release_across_spellings() {
let v = vendor(vec![
(
"pkg:nuget/newtonsoft.json@13.0.1",
entry("v", "pkg:nuget/newtonsoft.json@13.0.1", true, None),
),
(
"pkg:composer/acme/lib@3.0.2",
entry("c", "pkg:composer/acme/lib@3.0.2", true, None),
),
]);
let r = redirect(&[
("pkg:nuget/Newtonsoft.Json@13.0.1", "h1"),
("pkg:nuget/newtonsoft.json@13.0.1", "h2"),
("pkg:composer/acme/lib@3.0.2", "h3"),
("pkg:composer/acme/lib@3.0.2.0", "h4"),
]);
let l = Ledgers {
manifest: None,
vendor: Some(&v),
redirect: Some(&r),
};
assert_eq!(
l.hosted_vendored_overlap(),
vec![
"pkg:composer/acme/lib@3.0.2".to_string(),
"pkg:nuget/Newtonsoft.Json@13.0.1".to_string(),
]
);
}
/// #999: a uuid identifier that matches the manifest's generation also
/// selects the vendored entry the matched key claims, even when the
/// ledger recorded an older generation; an unclaimed entry for another
/// package does not ride along.
#[test]
fn matching_by_uuid_spans_the_claimed_vendored_generation() {
let m = manifest(&[("pkg:npm/a@1", "new")]);
let v = vendor(vec![
("pkg:npm/a@1", entry("old", "pkg:npm/a@1", false, None)),
("pkg:npm/b@1", entry("other", "pkg:npm/b@1", false, None)),
]);
let l = Ledgers {
manifest: Some(&m),
vendor: Some(&v),
redirect: None,
};
let found = l.matching(&Target::parse("new"));
assert_eq!(found.manifest, vec!["pkg:npm/a@1"]);
let keys: Vec<&str> = found.vendor.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(keys, vec!["pkg:npm/a@1"]);
// Without the manifest, the old generation only matches its own uuid.
let ledger_only = Ledgers {
vendor: Some(&v),
..Default::default()
};
assert!(ledger_only
.matching(&Target::parse("new"))
.vendor
.is_empty());
assert_eq!(ledger_only.matching(&Target::parse("old")).vendor.len(), 1);
}
fn pin(purl: &str, uuid: &str) -> HostedPin {
HostedPin {
purl: purl.into(),
uuid: uuid.into(),
files: vec![],
}
}
#[test]
fn hosted_pins_matching_spans_generations_of_matched_keys() {
let pins = vec![
pin("pkg:npm/a@1", "hosted-b"),
pin("pkg:npm/c@1", "hosted-c"),
pin("pkg:pypi/six@1.16.0", "hosted-six"),
];
// By identifier alone.
let by_uuid = hosted_pins_matching(&pins, &Target::parse("hosted-c"), &[]);
assert_eq!(by_uuid, vec![pin("pkg:npm/c@1", "hosted-c")]);
// A matched manifest key (another generation, qualifiers and all)
// selects the pin wiring its release.
let keys = vec![
"pkg:npm/a@1".to_string(),
"pkg:pypi/six@1.16.0?artifact_id=x".to_string(),
];
let got = hosted_pins_matching(&pins, &Target::parse("agent-a"), &keys);
assert_eq!(
got,
vec![
pin("pkg:npm/a@1", "hosted-b"),
pin("pkg:pypi/six@1.16.0", "hosted-six")
]
);
assert!(hosted_pins_matching(&pins, &Target::parse("nope"), &[]).is_empty());
}
}