affidavit 26.6.22

Provenance Layer — receipt assembly and certification (verify a witness against a format standard; never decide honesty).
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
//! Vulnerability and VEX correlation over a canonical SBOM.
//!
//! This module is the *vulnerability* axis of affidavit's supply-chain
//! provenance layer. Where [`crate::sbom`] normalizes the catalogue of
//! components and their dependency relationships, this module answers the next
//! question every Fortune-5 security program asks: *which of these components
//! are affected by a known vulnerability, how severe is it, is it actually
//! exploitable, and what else in the graph inherits that risk?*
//!
//! # Combinatorial maximalism
//!
//! Real-world correlation spans every advisory source × every identifier scheme
//! × every exploitability assertion. This module covers that surface:
//!
//! - **Advisory identity**: CVE (`CVE-2024-1234`), GHSA, OSV, or vendor IDs are
//!   all carried opaquely as [`Vulnerability::id`] strings.
//! - **Component matching**: PURL (exact), CPE 2.3 (exact), then name substring
//!   — the three coordinate systems the ecosystem actually ships.
//! - **Scoring**: CVSS v3.1 base score → [`Severity`] banding, carried by a
//!   lightweight [`CvssVector`] that keeps the vector string without re-parsing
//!   its metrics.
//! - **Exploitability (VEX)**: [`VexStatement`]s assert `NotAffected`,
//!   `Affected`, `Fixed`, or `UnderInvestigation` per (vuln, component) pair and
//!   suppress matches the supplier has cleared.
//! - **Risk propagation**: a vulnerability on component C is inherited by every
//!   component that (transitively) depends on C — the blast radius.
//!
//! # Doctrine
//!
//! Consistent with affidavit's *certify, don't decide* doctrine, this module
//! *correlates* declared advisories against a declared SBOM. It does not decide
//! whether an advisory is accurate or whether a VEX assertion is truthful; it
//! reports what the inputs imply, deterministically.
//!
//! # Determinism
//!
//! Every public function produces a deterministically ordered result. Matches
//! sort by `(component_bom_ref, vuln_id)`; propagation results sort by
//! `(dependent, vuln_id)`; aggregation uses a [`BTreeMap`]. No wall-clock, no
//! filesystem, no network: the same inputs always yield the same output.

use crate::sbom::Sbom;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};

/// CVSS v3.1 qualitative severity band.
///
/// Ordered from least to most severe so that [`Severity`] values can be compared
/// directly (`Critical > High > … > None`) when computing a maximum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Severity {
    /// No measurable impact (CVSS base score exactly 0.0).
    None,
    /// Low severity (0.1–3.9).
    Low,
    /// Medium severity (4.0–6.9).
    Medium,
    /// High severity (7.0–8.9).
    High,
    /// Critical severity (9.0–10.0).
    Critical,
}

impl Severity {
    /// Map a CVSS v3.1 base score to its qualitative band.
    ///
    /// Bands per the CVSS v3.1 specification: `0.0` None; `0.1–3.9` Low;
    /// `4.0–6.9` Medium; `7.0–8.9` High; `9.0–10.0` Critical. Scores are
    /// clamped to `0.0..=10.0` so out-of-range inputs still yield a band rather
    /// than panicking — validation of the raw score is [`CvssVector::validate`].
    pub fn from_cvss(score: f64) -> Severity {
        let s = if score.is_nan() {
            0.0
        } else {
            score.clamp(0.0, 10.0)
        };
        if s <= 0.0 {
            Severity::None
        } else if s < 4.0 {
            Severity::Low
        } else if s < 7.0 {
            Severity::Medium
        } else if s < 9.0 {
            Severity::High
        } else {
            Severity::Critical
        }
    }

    /// Canonical lowercase tag used in identifiers and reports.
    pub fn tag(&self) -> &'static str {
        match self {
            Severity::None => "none",
            Severity::Low => "low",
            Severity::Medium => "medium",
            Severity::High => "high",
            Severity::Critical => "critical",
        }
    }
}

/// The qualitative band label for a CVSS base score (free function form).
///
/// Equivalent to `Severity::from_cvss(score).tag()`; provided as a standalone
/// helper for callers that only want the label without the enum.
pub fn cvss_band(score: f64) -> &'static str {
    Severity::from_cvss(score).tag()
}

/// A lightweight CVSS carrier: the base score plus the optional vector string.
///
/// The CVSS vector string (e.g. `CVSS:3.1/AV:N/AC:L/...`) is carried opaquely;
/// this module deliberately does *not* re-derive the base score from the vector
/// metrics. The authoritative number is [`CvssVector::base_score`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CvssVector {
    /// CVSS v3.1 base score in the range `0.0..=10.0`.
    pub base_score: f64,
    /// The full CVSS vector string, if the advisory carried one.
    pub vector: Option<String>,
}

impl CvssVector {
    /// Construct a CVSS carrier from a base score with no vector string.
    pub fn from_score(base_score: f64) -> Self {
        CvssVector {
            base_score,
            vector: None,
        }
    }

    /// Construct a CVSS carrier with both a base score and a vector string.
    pub fn with_vector(base_score: f64, vector: impl Into<String>) -> Self {
        CvssVector {
            base_score,
            vector: Some(vector.into()),
        }
    }

    /// The qualitative [`Severity`] band for this vector's base score.
    pub fn severity(&self) -> Severity {
        Severity::from_cvss(self.base_score)
    }

    /// Validate that the base score is a finite number within `0.0..=10.0`.
    ///
    /// # Errors
    ///
    /// Returns [`VulnerabilityError::InvalidCvssScore`] if the score is NaN,
    /// infinite, negative, or greater than `10.0`.
    pub fn validate(&self) -> Result<(), VulnerabilityError> {
        if !self.base_score.is_finite() || !(0.0..=10.0).contains(&self.base_score) {
            return Err(VulnerabilityError::InvalidCvssScore(self.base_score));
        }
        Ok(())
    }
}

/// A known vulnerability / advisory affecting one or more component coordinates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Vulnerability {
    /// Advisory identifier (e.g. `CVE-2024-1234`, `GHSA-xxxx-xxxx-xxxx`).
    pub id: String,
    /// Free-text description of the vulnerability, if available.
    pub description: Option<String>,
    /// CVSS scoring carrier.
    pub cvss: CvssVector,
    /// PURLs this advisory declares as affected (exact-match coordinates).
    pub affected_purls: Vec<String>,
    /// CPE 2.3 identifiers this advisory declares as affected.
    pub affected_cpes: Vec<String>,
    /// Versions in which this vulnerability is fixed (informational).
    pub fixed_versions: Vec<String>,
}

impl Vulnerability {
    /// Construct a vulnerability from an id and a CVSS base score, with no
    /// affected coordinates yet declared.
    pub fn new(id: impl Into<String>, base_score: f64) -> Self {
        Vulnerability {
            id: id.into(),
            description: None,
            cvss: CvssVector::from_score(base_score),
            affected_purls: Vec::new(),
            affected_cpes: Vec::new(),
            fixed_versions: Vec::new(),
        }
    }

    /// The qualitative severity band of this vulnerability's CVSS score.
    pub fn severity(&self) -> Severity {
        self.cvss.severity()
    }
}

/// The exploitability status of a vulnerability against a specific component,
/// per the VEX (Vulnerability Exploitability eXchange) model.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum VexStatus {
    /// The component is not affected (suppresses the match).
    NotAffected,
    /// The component is affected and exploitable.
    Affected,
    /// The vulnerability is already fixed in this component (suppresses).
    Fixed,
    /// Exploitability is still being investigated (does not suppress).
    UnderInvestigation,
}

impl VexStatus {
    /// Canonical lowercase tag.
    pub fn tag(&self) -> &'static str {
        match self {
            VexStatus::NotAffected => "not_affected",
            VexStatus::Affected => "affected",
            VexStatus::Fixed => "fixed",
            VexStatus::UnderInvestigation => "under_investigation",
        }
    }

    /// Whether a match carrying this status should be suppressed (cleared).
    ///
    /// `NotAffected` and `Fixed` clear a match; `Affected` and
    /// `UnderInvestigation` keep it.
    pub fn suppresses(&self) -> bool {
        matches!(self, VexStatus::NotAffected | VexStatus::Fixed)
    }
}

/// A VEX assertion: the exploitability status of a vulnerability against a
/// specific component.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VexStatement {
    /// The advisory id this statement is about.
    pub vuln_id: String,
    /// The `bom_ref` of the component this statement is about.
    pub component_bom_ref: String,
    /// The asserted exploitability status.
    pub status: VexStatus,
    /// Optional justification text (e.g. "vulnerable_code_not_in_execute_path").
    pub justification: Option<String>,
}

impl VexStatement {
    /// Construct a VEX statement.
    pub fn new(
        vuln_id: impl Into<String>,
        component_bom_ref: impl Into<String>,
        status: VexStatus,
    ) -> Self {
        VexStatement {
            vuln_id: vuln_id.into(),
            component_bom_ref: component_bom_ref.into(),
            status,
            justification: None,
        }
    }
}

/// A correlated match of a vulnerability against a component.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct VulnerabilityMatch {
    /// The advisory id that matched.
    pub vuln_id: String,
    /// The `bom_ref` of the matched component.
    pub component_bom_ref: String,
    /// The severity band of the matched vulnerability.
    pub severity: Severity,
    /// How the match was made: `"purl"`, `"cpe"`, or `"name"`.
    pub matched_by: String,
}

/// Match every vulnerability against every component in the SBOM.
///
/// For each (component, vulnerability) pair the first applicable coordinate
/// system wins, in priority order:
///
/// 1. **purl** — exact equality against any of the component's PURL.
/// 2. **cpe** — exact equality against the component's CPE 2.3 string.
/// 3. **name** — the component name appears as a substring of an affected PURL
///    or CPE (the loose fallback for advisories that name a package without a
///    precise coordinate).
///
/// At most one match is produced per (component, vulnerability) pair. The result
/// is sorted by `(component_bom_ref, vuln_id)` for determinism.
pub fn match_vulnerabilities(sbom: &Sbom, vulns: &[Vulnerability]) -> Vec<VulnerabilityMatch> {
    let mut matches = Vec::new();

    for component in &sbom.components {
        for vuln in vulns {
            if let Some(matched_by) = match_kind(component, vuln) {
                matches.push(VulnerabilityMatch {
                    vuln_id: vuln.id.clone(),
                    component_bom_ref: component.bom_ref.clone(),
                    severity: vuln.severity(),
                    matched_by: matched_by.to_string(),
                });
            }
        }
    }

    matches.sort();
    matches
}

/// Decide whether and how a vulnerability matches a single component.
///
/// Returns the matching coordinate label (`"purl"`, `"cpe"`, or `"name"`) or
/// `None` if no coordinate matched.
fn match_kind(component: &crate::sbom::Component, vuln: &Vulnerability) -> Option<&'static str> {
    // 1. Exact PURL match.
    if let Some(purl) = component.purl.as_deref() {
        if vuln.affected_purls.iter().any(|p| p == purl) {
            return Some("purl");
        }
    }

    // 2. Exact CPE match.
    if let Some(cpe) = component.cpe.as_deref() {
        if vuln.affected_cpes.iter().any(|c| c == cpe) {
            return Some("cpe");
        }
    }

    // 3. Name substring fallback (only for non-empty names).
    let name = component.name.trim();
    if !name.is_empty() {
        let in_purls = vuln.affected_purls.iter().any(|p| p.contains(name));
        let in_cpes = vuln.affected_cpes.iter().any(|c| c.contains(name));
        if in_purls || in_cpes {
            return Some("name");
        }
    }

    None
}

/// Apply VEX statements to a set of matches, dropping any match the supplier has
/// cleared.
///
/// A match for `(vuln_id, component_bom_ref)` is dropped when a VEX statement for
/// the same pair carries a [`VexStatus::suppresses`] status (`NotAffected` or
/// `Fixed`). `Affected`, `UnderInvestigation`, and *unstated* pairs are kept.
///
/// The relative order of surviving matches is preserved (the input order, which
/// [`match_vulnerabilities`] already canonicalizes).
pub fn apply_vex(matches: &[VulnerabilityMatch], vex: &[VexStatement]) -> Vec<VulnerabilityMatch> {
    // Index suppressing statements by (vuln_id, component) for O(1) lookup.
    let suppressed: BTreeSet<(&str, &str)> = vex
        .iter()
        .filter(|s| s.status.suppresses())
        .map(|s| (s.vuln_id.as_str(), s.component_bom_ref.as_str()))
        .collect();

    matches
        .iter()
        .filter(|m| !suppressed.contains(&(m.vuln_id.as_str(), m.component_bom_ref.as_str())))
        .cloned()
        .collect()
}

/// Propagate vulnerability risk across the dependency graph.
///
/// For each direct match on component `C`, every component `X` that
/// (transitively) depends on `C` inherits the vulnerability at the *same*
/// severity. A component is considered impacted by a vuln on `C` iff
/// `C ∈ X.transitive_dependencies` **or** `X == C` (a component is impacted by
/// its own direct match).
///
/// The result is the set of `(impacted_bom_ref, vuln_id, severity)` triples,
/// deduplicated (a component impacted via several paths appears once per vuln)
/// and sorted by `(impacted_bom_ref, vuln_id)` for determinism.
pub fn propagate_risk(
    sbom: &Sbom,
    matches: &[VulnerabilityMatch],
) -> Vec<(String, String, Severity)> {
    // Precompute, for each component, the set of bom_refs it transitively
    // depends on. Keyed by bom_ref for deterministic iteration.
    let mut reachable: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
    for component in &sbom.components {
        let deps: BTreeSet<String> = sbom
            .transitive_dependencies(&component.bom_ref)
            .into_iter()
            .collect();
        reachable.insert(component.bom_ref.as_str(), deps);
    }

    // (impacted_bom_ref, vuln_id) -> severity. BTreeMap dedups and sorts.
    let mut impacted: BTreeMap<(String, String), Severity> = BTreeMap::new();

    for m in matches {
        let affected = m.component_bom_ref.as_str();
        for component in &sbom.components {
            let inherits = component.bom_ref == affected
                || reachable
                    .get(component.bom_ref.as_str())
                    .is_some_and(|deps| deps.contains(affected));
            if inherits {
                impacted
                    .entry((component.bom_ref.clone(), m.vuln_id.clone()))
                    .and_modify(|sev| {
                        if m.severity > *sev {
                            *sev = m.severity;
                        }
                    })
                    .or_insert(m.severity);
            }
        }
    }

    impacted
        .into_iter()
        .map(|((bom_ref, vuln_id), severity)| (bom_ref, vuln_id, severity))
        .collect()
}

/// An aggregated vulnerability posture report for an SBOM.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VulnerabilityReport {
    /// Total number of components in the SBOM.
    pub total_components: usize,
    /// Total number of (vuln, component) matches before VEX suppression.
    pub total_matches: usize,
    /// Histogram of matches by severity tag (post-match, pre-VEX).
    pub by_severity: BTreeMap<String, usize>,
    /// The most severe band present among the matches.
    pub max_severity: Severity,
    /// Number of matches still exploitable after applying VEX.
    pub exploitable_after_vex: usize,
}

/// Build a [`VulnerabilityReport`] by running match → apply_vex → aggregate.
///
/// The `by_severity` histogram and `max_severity` are computed over the *raw*
/// matches (before VEX), while `exploitable_after_vex` reflects the count that
/// survives VEX suppression — so a report shows both the discovered surface and
/// the residual exploitable surface.
pub fn build_report(
    sbom: &Sbom,
    vulns: &[Vulnerability],
    vex: &[VexStatement],
) -> VulnerabilityReport {
    let matches = match_vulnerabilities(sbom, vulns);
    let surviving = apply_vex(&matches, vex);

    let mut by_severity: BTreeMap<String, usize> = BTreeMap::new();
    let mut max_severity = Severity::None;
    for m in &matches {
        *by_severity.entry(m.severity.tag().to_string()).or_insert(0) += 1;
        if m.severity > max_severity {
            max_severity = m.severity;
        }
    }

    VulnerabilityReport {
        total_components: sbom.components.len(),
        total_matches: matches.len(),
        by_severity,
        max_severity,
        exploitable_after_vex: surviving.len(),
    }
}

/// An error raised during vulnerability correlation.
#[derive(Debug, thiserror::Error)]
pub enum VulnerabilityError {
    /// A CVSS base score was outside the valid `0.0..=10.0` range (or non-finite).
    #[error("invalid CVSS base score: {0} (must be within 0.0..=10.0)")]
    InvalidCvssScore(f64),
    /// A referenced component `bom_ref` is not present in the SBOM.
    #[error("unknown component: {0}")]
    UnknownComponent(String),
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sbom::{Component, Dependency, Sbom, SbomFormat};

    /// A component carrying an explicit PURL and CPE.
    fn comp_with_ids(
        bom_ref: &str,
        name: &str,
        version: &str,
        purl: Option<&str>,
        cpe: Option<&str>,
    ) -> Component {
        let mut c = Component::library(bom_ref, name, version);
        c.purl = purl.map(|s| s.to_string());
        c.cpe = cpe.map(|s| s.to_string());
        c
    }

    /// A 3-level chain SBOM: A -> B -> C.
    fn chain_sbom() -> Sbom {
        let mut sbom = Sbom::new(SbomFormat::CycloneDx16, "1.6");
        sbom.components.push(comp_with_ids(
            "A",
            "app-a",
            "1.0",
            Some("pkg:cargo/app-a@1.0"),
            None,
        ));
        sbom.components.push(comp_with_ids(
            "B",
            "lib-b",
            "2.0",
            Some("pkg:cargo/lib-b@2.0"),
            None,
        ));
        sbom.components.push(comp_with_ids(
            "C",
            "lib-c",
            "3.0",
            Some("pkg:cargo/lib-c@3.0"),
            Some("cpe:2.3:a:vendor:lib-c:3.0:*:*:*:*:*:*:*"),
        ));
        sbom.dependencies.push(Dependency {
            dependent: "A".to_string(),
            depends_on: vec!["B".to_string()],
        });
        sbom.dependencies.push(Dependency {
            dependent: "B".to_string(),
            depends_on: vec!["C".to_string()],
        });
        sbom.canonicalize();
        sbom
    }

    fn vuln_on_purl(id: &str, score: f64, purl: &str) -> Vulnerability {
        let mut v = Vulnerability::new(id, score);
        v.affected_purls.push(purl.to_string());
        v
    }

    // ----- CVSS → severity banding (boundaries) -----

    #[test]
    fn cvss_banding_at_boundaries() {
        assert_eq!(Severity::from_cvss(0.0), Severity::None);
        assert_eq!(Severity::from_cvss(0.1), Severity::Low);
        assert_eq!(Severity::from_cvss(3.9), Severity::Low);
        assert_eq!(Severity::from_cvss(4.0), Severity::Medium);
        assert_eq!(Severity::from_cvss(6.9), Severity::Medium);
        assert_eq!(Severity::from_cvss(7.0), Severity::High);
        assert_eq!(Severity::from_cvss(8.9), Severity::High);
        assert_eq!(Severity::from_cvss(9.0), Severity::Critical);
        assert_eq!(Severity::from_cvss(10.0), Severity::Critical);
    }

    #[test]
    fn cvss_band_free_function_matches_enum() {
        assert_eq!(cvss_band(0.0), "none");
        assert_eq!(cvss_band(2.0), "low");
        assert_eq!(cvss_band(5.5), "medium");
        assert_eq!(cvss_band(7.5), "high");
        assert_eq!(cvss_band(9.8), "critical");
    }

    #[test]
    fn cvss_vector_severity_and_clamping() {
        assert_eq!(CvssVector::from_score(9.1).severity(), Severity::Critical);
        // Out-of-range still bands (clamped) rather than panicking.
        assert_eq!(Severity::from_cvss(11.0), Severity::Critical);
        assert_eq!(Severity::from_cvss(-1.0), Severity::None);
        assert_eq!(Severity::from_cvss(f64::NAN), Severity::None);
    }

    #[test]
    fn severity_ordering_is_monotonic() {
        assert!(Severity::Critical > Severity::High);
        assert!(Severity::High > Severity::Medium);
        assert!(Severity::Medium > Severity::Low);
        assert!(Severity::Low > Severity::None);
    }

    // ----- matching: purl vs cpe vs name -----

    #[test]
    fn matches_by_exact_purl() {
        let sbom = chain_sbom();
        let vulns = vec![vuln_on_purl("CVE-2024-0001", 7.5, "pkg:cargo/lib-c@3.0")];
        let matches = match_vulnerabilities(&sbom, &vulns);
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].component_bom_ref, "C");
        assert_eq!(matches[0].matched_by, "purl");
        assert_eq!(matches[0].severity, Severity::High);
    }

    #[test]
    fn matches_by_exact_cpe_when_no_purl() {
        let sbom = chain_sbom();
        let mut v = Vulnerability::new("CVE-2024-0002", 5.0);
        v.affected_cpes
            .push("cpe:2.3:a:vendor:lib-c:3.0:*:*:*:*:*:*:*".to_string());
        let matches = match_vulnerabilities(&sbom, &[v]);
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].component_bom_ref, "C");
        assert_eq!(matches[0].matched_by, "cpe");
    }

    #[test]
    fn matches_by_name_substring_fallback() {
        let sbom = chain_sbom();
        // Affected purl mentions the name "lib-b" but is not the exact purl.
        let mut v = Vulnerability::new("CVE-2024-0003", 8.0);
        v.affected_purls.push("pkg:npm/lib-b@99.0".to_string());
        let matches = match_vulnerabilities(&sbom, &[v]);
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].component_bom_ref, "B");
        assert_eq!(matches[0].matched_by, "name");
    }

    #[test]
    fn purl_match_takes_priority_over_name() {
        let sbom = chain_sbom();
        // Exact purl for C AND a name substring; purl must win.
        let mut v = Vulnerability::new("CVE-2024-0004", 9.5);
        v.affected_purls.push("pkg:cargo/lib-c@3.0".to_string());
        let matches = match_vulnerabilities(&sbom, &[v]);
        let c_match = matches
            .iter()
            .find(|m| m.component_bom_ref == "C")
            .expect("C should match");
        assert_eq!(c_match.matched_by, "purl");
    }

    #[test]
    fn no_match_yields_empty() {
        let sbom = chain_sbom();
        let vulns = vec![vuln_on_purl(
            "CVE-2024-9999",
            5.0,
            "pkg:cargo/not-present@0.0",
        )];
        assert!(match_vulnerabilities(&sbom, &vulns).is_empty());
    }

    #[test]
    fn matches_are_sorted_deterministically() {
        let mut sbom = Sbom::new(SbomFormat::CycloneDx16, "1.6");
        sbom.components.push(comp_with_ids(
            "Z",
            "zeta",
            "1.0",
            Some("pkg:cargo/zeta@1.0"),
            None,
        ));
        sbom.components.push(comp_with_ids(
            "A",
            "alpha",
            "1.0",
            Some("pkg:cargo/alpha@1.0"),
            None,
        ));
        let vulns = vec![
            vuln_on_purl("CVE-2", 5.0, "pkg:cargo/zeta@1.0"),
            vuln_on_purl("CVE-1", 5.0, "pkg:cargo/alpha@1.0"),
        ];
        let matches = match_vulnerabilities(&sbom, &vulns);
        assert_eq!(matches.len(), 2);
        // Sorted by (component_bom_ref, vuln_id): A before Z.
        assert_eq!(matches[0].component_bom_ref, "A");
        assert_eq!(matches[1].component_bom_ref, "Z");
    }

    // ----- VEX suppression -----

    #[test]
    fn vex_not_affected_suppresses_match() {
        let sbom = chain_sbom();
        let vulns = vec![vuln_on_purl("CVE-2024-0010", 7.5, "pkg:cargo/lib-c@3.0")];
        let matches = match_vulnerabilities(&sbom, &vulns);
        let vex = vec![VexStatement::new(
            "CVE-2024-0010",
            "C",
            VexStatus::NotAffected,
        )];
        let surviving = apply_vex(&matches, &vex);
        assert!(surviving.is_empty());
    }

    #[test]
    fn vex_fixed_suppresses_match() {
        let sbom = chain_sbom();
        let vulns = vec![vuln_on_purl("CVE-2024-0011", 7.5, "pkg:cargo/lib-c@3.0")];
        let matches = match_vulnerabilities(&sbom, &vulns);
        let vex = vec![VexStatement::new("CVE-2024-0011", "C", VexStatus::Fixed)];
        assert!(apply_vex(&matches, &vex).is_empty());
    }

    #[test]
    fn vex_affected_and_under_investigation_kept() {
        let sbom = chain_sbom();
        let vulns = vec![vuln_on_purl("CVE-2024-0012", 7.5, "pkg:cargo/lib-c@3.0")];
        let matches = match_vulnerabilities(&sbom, &vulns);

        let affected = vec![VexStatement::new("CVE-2024-0012", "C", VexStatus::Affected)];
        assert_eq!(apply_vex(&matches, &affected).len(), 1);

        let investigating = vec![VexStatement::new(
            "CVE-2024-0012",
            "C",
            VexStatus::UnderInvestigation,
        )];
        assert_eq!(apply_vex(&matches, &investigating).len(), 1);

        // Unstated pair is also kept.
        assert_eq!(apply_vex(&matches, &[]).len(), 1);
    }

    #[test]
    fn vex_only_suppresses_matching_pair() {
        let sbom = chain_sbom();
        let vulns = vec![
            vuln_on_purl("CVE-A", 7.5, "pkg:cargo/lib-c@3.0"),
            vuln_on_purl("CVE-B", 5.0, "pkg:cargo/lib-b@2.0"),
        ];
        let matches = match_vulnerabilities(&sbom, &vulns);
        assert_eq!(matches.len(), 2);
        // Suppress only CVE-A on C; CVE-B on B survives.
        let vex = vec![VexStatement::new("CVE-A", "C", VexStatus::NotAffected)];
        let surviving = apply_vex(&matches, &vex);
        assert_eq!(surviving.len(), 1);
        assert_eq!(surviving[0].vuln_id, "CVE-B");
    }

    // ----- risk propagation -----

    #[test]
    fn risk_propagates_through_three_level_chain() {
        let sbom = chain_sbom();
        // Vuln on C: B and A both (transitively) depend on C, so all three are
        // impacted (C directly, B and A by inheritance).
        let vulns = vec![vuln_on_purl("CVE-PROP", 9.0, "pkg:cargo/lib-c@3.0")];
        let matches = match_vulnerabilities(&sbom, &vulns);
        let impacted = propagate_risk(&sbom, &matches);

        let refs: Vec<&str> = impacted.iter().map(|(r, _, _)| r.as_str()).collect();
        assert!(refs.contains(&"A"), "A inherits via A->B->C");
        assert!(refs.contains(&"B"), "B inherits via B->C");
        assert!(refs.contains(&"C"), "C is directly affected");
        assert_eq!(impacted.len(), 3);
        // All inherit Critical severity (9.0).
        assert!(impacted
            .iter()
            .all(|(_, _, sev)| *sev == Severity::Critical));
    }

    #[test]
    fn risk_does_not_propagate_to_unrelated_components() {
        let mut sbom = chain_sbom();
        // Add isolated component D with no edges.
        sbom.components.push(comp_with_ids(
            "D",
            "lib-d",
            "1.0",
            Some("pkg:cargo/lib-d@1.0"),
            None,
        ));
        sbom.canonicalize();
        let vulns = vec![vuln_on_purl("CVE-ISO", 5.0, "pkg:cargo/lib-c@3.0")];
        let matches = match_vulnerabilities(&sbom, &vulns);
        let impacted = propagate_risk(&sbom, &matches);
        let refs: Vec<&str> = impacted.iter().map(|(r, _, _)| r.as_str()).collect();
        assert!(!refs.contains(&"D"), "D is unrelated to C");
    }

    #[test]
    fn risk_propagation_is_sorted_and_deduplicated() {
        let sbom = chain_sbom();
        // Two matches for the same vuln on C should not duplicate impacted rows.
        let vulns = vec![vuln_on_purl("CVE-DUP", 7.0, "pkg:cargo/lib-c@3.0")];
        let mut matches = match_vulnerabilities(&sbom, &vulns);
        // Duplicate the C match.
        let dup = matches[0].clone();
        matches.push(dup);
        let impacted = propagate_risk(&sbom, &matches);
        assert_eq!(impacted.len(), 3, "A, B, C — no duplicates");
        // Sorted by (bom_ref, vuln_id).
        let refs: Vec<&str> = impacted.iter().map(|(r, _, _)| r.as_str()).collect();
        assert_eq!(refs, vec!["A", "B", "C"]);
    }

    #[test]
    fn risk_propagation_empty_when_no_matches() {
        let sbom = chain_sbom();
        assert!(propagate_risk(&sbom, &[]).is_empty());
    }

    // ----- report aggregation -----

    #[test]
    fn report_aggregates_counts_and_max_severity() {
        let sbom = chain_sbom();
        let vulns = vec![
            vuln_on_purl("CVE-HI", 7.5, "pkg:cargo/lib-c@3.0"), // High on C
            vuln_on_purl("CVE-CR", 9.5, "pkg:cargo/lib-b@2.0"), // Critical on B
        ];
        let report = build_report(&sbom, &vulns, &[]);
        assert_eq!(report.total_components, 3);
        assert_eq!(report.total_matches, 2);
        assert_eq!(report.max_severity, Severity::Critical);
        assert_eq!(report.by_severity.get("high"), Some(&1));
        assert_eq!(report.by_severity.get("critical"), Some(&1));
        assert_eq!(report.exploitable_after_vex, 2);
    }

    #[test]
    fn report_reflects_vex_suppression_in_exploitable_count() {
        let sbom = chain_sbom();
        let vulns = vec![
            vuln_on_purl("CVE-X", 7.5, "pkg:cargo/lib-c@3.0"),
            vuln_on_purl("CVE-Y", 5.0, "pkg:cargo/lib-b@2.0"),
        ];
        let vex = vec![VexStatement::new("CVE-X", "C", VexStatus::NotAffected)];
        let report = build_report(&sbom, &vulns, &vex);
        // Both matched, but one is suppressed by VEX.
        assert_eq!(report.total_matches, 2);
        assert_eq!(report.exploitable_after_vex, 1);
    }

    #[test]
    fn report_empty_sbom_and_vulns() {
        let sbom = Sbom::new(SbomFormat::CycloneDx16, "1.6");
        let report = build_report(&sbom, &[], &[]);
        assert_eq!(report.total_components, 0);
        assert_eq!(report.total_matches, 0);
        assert_eq!(report.max_severity, Severity::None);
        assert_eq!(report.exploitable_after_vex, 0);
        assert!(report.by_severity.is_empty());
    }

    // ----- CVSS validation errors -----

    #[test]
    fn cvss_validate_rejects_out_of_range() {
        assert!(matches!(
            CvssVector::from_score(11.0).validate(),
            Err(VulnerabilityError::InvalidCvssScore(_))
        ));
        assert!(matches!(
            CvssVector::from_score(-0.1).validate(),
            Err(VulnerabilityError::InvalidCvssScore(_))
        ));
        assert!(matches!(
            CvssVector::from_score(f64::INFINITY).validate(),
            Err(VulnerabilityError::InvalidCvssScore(_))
        ));
    }

    #[test]
    fn cvss_validate_accepts_in_range() {
        assert!(CvssVector::from_score(0.0).validate().is_ok());
        assert!(CvssVector::from_score(10.0).validate().is_ok());
        assert!(CvssVector::with_vector(5.5, "CVSS:3.1/AV:N")
            .validate()
            .is_ok());
    }

    #[test]
    fn vex_status_tags_and_suppression() {
        assert_eq!(VexStatus::NotAffected.tag(), "not_affected");
        assert_eq!(VexStatus::UnderInvestigation.tag(), "under_investigation");
        assert!(VexStatus::NotAffected.suppresses());
        assert!(VexStatus::Fixed.suppresses());
        assert!(!VexStatus::Affected.suppresses());
        assert!(!VexStatus::UnderInvestigation.suppresses());
    }

    #[test]
    fn unknown_component_error_displays() {
        let e = VulnerabilityError::UnknownComponent("missing".to_string());
        assert!(e.to_string().contains("missing"));
    }
}