Files
pruefwerk/compliance-core/src/cve_groups.rs
T
sharangandClaude Opus 5.5 87b1e281ed
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m19s
CI / Deploy MCP (push) Successful in 2m42s
CI / Deploy Dashboard (push) Successful in 6m14s
CI / Deploy Agent (push) Successful in 8m42s
fix(vex): a CVE a scan no longer finds is not stated fixed (#994) (#1015)
A scan never states VEX `fixed`. When a scan stops finding a CVE, its tracker issue stays open and gets one comment; a person closes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-27 22:23:03 +00:00

445 lines
15 KiB
Rust

//! A target's open CVE alerts grouped by the component they are in (#949):
//! what one update of the component fixes, so that whoever triages decides
//! once per package instead of once per CVE.
//!
//! Open means not settled: no `not_affected` or `fixed` statement, and not
//! found gone by a complete scan (see [`crate::vex_docs::status_of`]).
use std::cmp::Ordering;
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::models::CveAlert;
use crate::version::cmp_dotted;
use crate::vex_docs::status_of;
/// How severe a CVE is, as the groups count it. `Info` is a CVE the
/// advisory rates neither by name nor by CVSS score.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CveSeverity {
Info,
Low,
Medium,
High,
Critical,
}
impl CveSeverity {
/// The severity of `alert`: the advisory's rating (GitHub's `MODERATE`
/// is medium), else its CVSS score, else `Info`.
pub fn of(alert: &CveAlert) -> Self {
let named = alert.severity.as_deref().map(str::to_ascii_lowercase);
match named.as_deref() {
Some("critical") => Self::Critical,
Some("high") => Self::High,
Some("moderate" | "medium") => Self::Medium,
Some("low") => Self::Low,
_ => match alert.cvss_score {
Some(score) if score >= 9.0 => Self::Critical,
Some(score) if score >= 7.0 => Self::High,
Some(score) if score >= 4.0 => Self::Medium,
Some(score) if score > 0.0 => Self::Low,
_ => Self::Info,
},
}
}
/// The severity as the dashboard's badge names it (`high`).
pub fn as_str(self) -> &'static str {
match self {
Self::Info => "info",
Self::Low => "low",
Self::Medium => "medium",
Self::High => "high",
Self::Critical => "critical",
}
}
}
/// How many CVEs of a group have each severity.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SeverityCounts {
pub critical: usize,
pub high: usize,
pub medium: usize,
pub low: usize,
pub info: usize,
}
impl SeverityCounts {
fn add(&mut self, severity: CveSeverity) {
let count = match severity {
CveSeverity::Critical => &mut self.critical,
CveSeverity::High => &mut self.high,
CveSeverity::Medium => &mut self.medium,
CveSeverity::Low => &mut self.low,
CveSeverity::Info => &mut self.info,
};
*count += 1;
}
/// Each severity with its count, most severe first.
pub fn by_severity(&self) -> [(CveSeverity, usize); 5] {
[
(CveSeverity::Critical, self.critical),
(CveSeverity::High, self.high),
(CveSeverity::Medium, self.medium),
(CveSeverity::Low, self.low),
(CveSeverity::Info, self.info),
]
}
/// The counts of `self` and `other` together.
pub fn plus(self, other: Self) -> Self {
Self {
critical: self.critical + other.critical,
high: self.high + other.high,
medium: self.medium + other.medium,
low: self.low + other.low,
info: self.info + other.info,
}
}
/// The most severe severity counted, `Info` when none is.
pub fn max(&self) -> CveSeverity {
self.by_severity()
.into_iter()
.find(|(_, count)| *count > 0)
.map_or(CveSeverity::Info, |(severity, _)| severity)
}
}
/// The component a group is about, as its alerts name it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PackageKey {
pub package: String,
pub version: String,
/// The component's purl (`pkg:npm/vite@5.4.21`), when the alerts carry
/// one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub purl: Option<String>,
}
impl PackageKey {
/// The key of the component `alert` is about.
pub fn of(alert: &CveAlert) -> Self {
Self {
package: alert.affected_package.clone(),
version: alert.affected_version.clone(),
purl: alert.purl.clone(),
}
}
/// Whether `alert` is about this component.
pub fn matches(&self, alert: &CveAlert) -> bool {
self.package == alert.affected_package
&& self.version == alert.affected_version
&& self.purl == alert.purl
}
}
/// Whether `alert` still asks for a decision: neither stated `not_affected`
/// or `fixed`, nor found gone by a complete scan. Gone is not `fixed`
/// (#994); it only takes the alert off the list.
pub fn is_open(alert: &CveAlert) -> bool {
alert.resolved_at.is_none() && !status_of(alert).resolves()
}
/// The open CVE alerts of one component.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CveGroup {
#[serde(flatten)]
pub key: PackageKey,
/// The highest version above the component's own that the advisories
/// name as fixed: the update that fixes every CVE naming a fix.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fix_version: Option<String>,
/// How many of the CVEs name a fixed version, and so are fixed by
/// updating to `fix_version`.
pub fixable: usize,
/// The CVEs per severity; a CVE in several alerts (a GitHub advisory
/// and the NVD entry it aliases) counts once, at its highest severity.
pub counts: SeverityCounts,
/// Whether any of them is in CISA's KEV catalog.
pub kev: bool,
/// The highest EPSS score among them, 0 to 1.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub epss_max: Option<f64>,
/// The CVE ids, each once, sorted.
pub cve_ids: Vec<String>,
/// The alerts (hex object ids) a group decision states VEX on.
pub alert_ids: Vec<String>,
}
/// What [`group_open_alerts`] gathers per CVE: its highest severity and
/// whether an advisory names a fix above the component's version.
#[derive(Default)]
struct CveTally {
severity: Option<CveSeverity>,
fixable: bool,
}
/// The open alerts of `alerts` grouped by component, the most severe group
/// first (then the one with more CVEs, then by name and version).
pub fn group_open_alerts(alerts: &[CveAlert]) -> Vec<CveGroup> {
let mut by_component: BTreeMap<PackageKey, Vec<&CveAlert>> = BTreeMap::new();
for alert in alerts.iter().filter(|a| is_open(a)) {
by_component
.entry(PackageKey::of(alert))
.or_default()
.push(alert);
}
let mut groups: Vec<CveGroup> = by_component
.into_iter()
.map(|(key, members)| group(key, &members))
.collect();
groups.sort_by(|a, b| {
b.counts
.max()
.cmp(&a.counts.max())
.then_with(|| b.cve_ids.len().cmp(&a.cve_ids.len()))
.then_with(|| a.key.cmp(&b.key))
});
groups
}
/// The group of component `key` from its open alerts `members`.
fn group(key: PackageKey, members: &[&CveAlert]) -> CveGroup {
let above_current = |v: &&String| cmp_dotted(v, &key.version) == Ordering::Greater;
let mut tallies: BTreeMap<&str, CveTally> = BTreeMap::new();
let mut fix_version: Option<&String> = None;
let mut kev = false;
let mut epss_max: Option<f64> = None;
for alert in members {
let tally = tallies.entry(alert.cve()).or_default();
tally.severity = tally.severity.max(Some(CveSeverity::of(alert)));
for fixed in alert.fixed_versions.iter().filter(above_current) {
tally.fixable = true;
if fix_version.is_none_or(|best| cmp_dotted(fixed, best) == Ordering::Greater) {
fix_version = Some(fixed);
}
}
if let Some(exploitation) = &alert.exploitation {
kev |= exploitation.kev.is_some();
if let Some(epss) = &exploitation.epss {
epss_max = Some(epss_max.map_or(epss.score, |m| m.max(epss.score)));
}
}
}
let mut counts = SeverityCounts::default();
for tally in tallies.values() {
counts.add(tally.severity.unwrap_or(CveSeverity::Info));
}
CveGroup {
fix_version: fix_version.cloned(),
fixable: tallies.values().filter(|t| t.fixable).count(),
counts,
kev,
epss_max,
cve_ids: tallies.keys().map(|id| (*id).to_string()).collect(),
alert_ids: members
.iter()
.filter_map(|a| a.id.map(|o| o.to_hex()))
.collect(),
key,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::vex::{VexAssessment, VexStatus};
use crate::models::{CveSource, EpssScore, Exploitation, KevEntry};
fn alert(id: &str, package: &str, version: &str, severity: Option<&str>) -> CveAlert {
let mut a = CveAlert::new(
id.into(),
"t1".into(),
package.into(),
version.into(),
CveSource::Osv,
);
a.id = Some(bson::oid::ObjectId::new());
a.purl = Some(format!("pkg:npm/{package}@{version}"));
a.severity = severity.map(String::from);
a
}
fn fixed_in(mut a: CveAlert, versions: &[&str]) -> CveAlert {
a.fixed_versions = versions.iter().map(|v| v.to_string()).collect();
a
}
fn stated(mut a: CveAlert, status: VexStatus) -> CveAlert {
a.vex = Some(VexAssessment {
status,
justification: None,
impact_statement: Some("Build tool only.".into()),
action_statement: None,
by: "u1".into(),
by_name: None,
at: chrono::Utc::now(),
by_scan: false,
});
a
}
#[test]
fn severities_come_from_the_rating_then_the_cvss_score() {
let mut a = alert("CVE-2024-0001", "vite", "5.4.21", Some("MODERATE"));
assert_eq!(CveSeverity::of(&a), CveSeverity::Medium);
a.severity = None;
assert_eq!(CveSeverity::of(&a), CveSeverity::Info);
a.cvss_score = Some(9.8);
assert_eq!(CveSeverity::of(&a), CveSeverity::Critical);
a.cvss_score = Some(0.0);
assert_eq!(CveSeverity::of(&a), CveSeverity::Info);
a.severity = Some("High".into());
assert_eq!(CveSeverity::of(&a), CveSeverity::High);
assert_eq!(
serde_json::to_value(CveSeverity::Critical).ok(),
Some(serde_json::json!("critical"))
);
}
#[test]
fn open_alerts_group_by_component_with_the_highest_fix() {
let alerts = vec![
fixed_in(
alert("CVE-2025-0001", "vite", "5.4.21", Some("HIGH")),
&["5.4.22", "6.3.6"],
),
fixed_in(
alert("CVE-2025-0002", "vite", "5.4.21", Some("LOW")),
&["8.3.3"],
),
fixed_in(alert("CVE-2025-0003", "vite", "5.4.21", None), &["8.10.0"]),
// A fix below the component's version fixes nothing here.
fixed_in(alert("CVE-2025-0004", "vite", "5.4.21", None), &["4.0.0"]),
alert("CVE-2025-0005", "vite", "6.0.0", Some("CRITICAL")),
alert("CVE-2025-0006", "lodash", "4.17.20", Some("HIGH")),
];
let groups = group_open_alerts(&alerts);
let keys: Vec<(&str, &str)> = groups
.iter()
.map(|g| (g.key.package.as_str(), g.key.version.as_str()))
.collect();
// Most severe first; among the two `high` groups, more CVEs first.
assert_eq!(
keys,
[("vite", "6.0.0"), ("vite", "5.4.21"), ("lodash", "4.17.20")]
);
let vite = &groups[1];
assert_eq!(vite.fix_version.as_deref(), Some("8.10.0"));
assert_eq!(vite.fixable, 3);
assert_eq!(
vite.counts,
SeverityCounts {
high: 1,
low: 1,
info: 2,
..SeverityCounts::default()
}
);
assert_eq!(
vite.cve_ids,
[
"CVE-2025-0001",
"CVE-2025-0002",
"CVE-2025-0003",
"CVE-2025-0004"
]
);
assert_eq!(vite.alert_ids.len(), 4);
assert_eq!(groups[2].fix_version, None);
assert_eq!(groups[2].fixable, 0);
}
#[test]
fn settled_alerts_are_left_out_and_a_cve_counts_once() {
let mut gone = alert("CVE-2025-0003", "vite", "5.4.21", Some("HIGH"));
gone.resolved_at = Some(chrono::Utc::now());
let mut ghsa = alert("GHSA-aaaa-bbbb-cccc", "vite", "5.4.21", Some("LOW"));
ghsa.aliases = vec!["CVE-2025-0001".into()];
let alerts = vec![
alert("CVE-2025-0001", "vite", "5.4.21", Some("MEDIUM")),
ghsa,
stated(
alert("CVE-2025-0002", "vite", "5.4.21", Some("CRITICAL")),
VexStatus::NotAffected,
),
gone,
// Affected and under investigation still ask for a decision.
stated(
alert("CVE-2025-0004", "vite", "5.4.21", None),
VexStatus::Affected,
),
];
let groups = group_open_alerts(&alerts);
assert_eq!(groups.len(), 1);
let vite = &groups[0];
assert_eq!(vite.cve_ids, ["CVE-2025-0001", "CVE-2025-0004"]);
assert_eq!(vite.alert_ids.len(), 3);
assert_eq!(
vite.counts,
SeverityCounts {
medium: 1,
info: 1,
..SeverityCounts::default()
}
);
assert!(group_open_alerts(&alerts[2..4]).is_empty());
}
#[test]
fn a_group_has_the_worst_exploitation_of_its_cves() {
let mut kev = alert("CVE-2025-0001", "vite", "5.4.21", Some("LOW"));
kev.exploitation = Some(Exploitation {
kev: Some(KevEntry::default()),
epss: Some(EpssScore {
score: 0.2,
percentile: 0.9,
date: String::new(),
}),
ssvc_exploitation: None,
});
let mut likely = alert("CVE-2025-0002", "vite", "5.4.21", Some("LOW"));
likely.exploitation = Some(Exploitation {
epss: Some(EpssScore {
score: 0.7,
percentile: 0.99,
date: String::new(),
}),
..Exploitation::default()
});
let groups = group_open_alerts(&[kev, likely]);
assert!(groups[0].kev);
assert_eq!(groups[0].epss_max, Some(0.7));
let quiet = group_open_alerts(&[alert("CVE-2025-0003", "vite", "5.4.21", None)]);
assert!(!quiet[0].kev);
assert_eq!(quiet[0].epss_max, None);
}
#[test]
fn a_key_matches_the_alerts_of_its_component_only() {
let a = alert("CVE-2025-0001", "vite", "5.4.21", None);
let key = PackageKey::of(&a);
assert!(key.matches(&a));
let mut other_version = a.clone();
other_version.affected_version = "5.4.22".into();
assert!(!key.matches(&other_version));
let mut without_purl = a.clone();
without_purl.purl = None;
assert!(!key.matches(&without_purl));
// The group's JSON names the component at the top level, as the
// group decision's body does.
let groups = group_open_alerts(&[a]);
let json = serde_json::to_value(&groups[0]).unwrap_or_default();
assert_eq!(json["package"], "vite");
assert_eq!(json["purl"], "pkg:npm/vite@5.4.21");
assert_eq!(json["counts"]["info"], 1);
}
}