Files
pruefwerk/compliance-core/src/scan_changes.rs
T
sharangandClaude Opus 5.5 f5697ff21d
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy MCP (push) Successful in 58s
CI / Deploy Docs (push) Successful in 1m29s
CI / Deploy Dashboard (push) Successful in 6m12s
CI / Deploy Agent (push) Successful in 8m13s
feat(scan): record which components each scan added, updated or removed (#974) (#975)
Before a stage replaces its part of a target's SBOM (the code SBOM, the
CODESYS libraries, the firmware components), the entries it replaces are
compared with the new ones and the changes are added to the scan run
(`component_changes`, at most 5000; `None` on runs from before). A
component is its package manager and name; one version before and one
after is an update, otherwise each new version an addition and each gone
one a removal.

The Verlauf API joins them with the scan's CVEs: a new CVE goes with the
component now at its version, a gone one with the component that was at
its version, and what no change explains is an advisory row. The scan's
drill-down shows the mockup's table (neu / aktualisiert / entfernt / neue
Advisory, version before → after, CVEs +n −m) above the CVE list; scans
from before say the components were not recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:18:01 +00:00

395 lines
14 KiB
Rust

//! What each scan of a target changed: the CVE alerts it found new and those
//! it found gone (#957, the "Verlauf" view).
//!
//! Computed from the stored alerts and runs alone, no snapshots. A completed
//! scan's window runs from the end of the completed scan before it to its own
//! end; an alert counts as new in the window its `created_at` falls in, and
//! as gone in the window its `resolved_at` falls in. A target's first
//! completed scan is its baseline: what it found is the whole SBOM, not a
//! change. A scan that did not complete (queued, running, failed,
//! interrupted) changes nothing: what came in meanwhile belongs to the next
//! completed scan.
//!
//! Only an alert's current state is stored, so an alert reported again after
//! it was resolved loses its `resolved_at` and is not seen as gone back then
//! (as in [`crate::cve_history`]). Alerts the daily CVE monitor adds between
//! two scans count for the next scan, which is when its report shows them.
use std::collections::BTreeMap;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::component_changes::{ComponentChange, ComponentChangeKind};
use crate::models::notification::{parse_severity, NotificationSeverity};
use crate::models::{CveAlert, ScanRun, ScanRunStatus};
/// The scans a history shows unless asked otherwise.
pub const DEFAULT_SCANS: usize = 20;
/// The most scans a history may show.
pub const MAX_SCANS: usize = 50;
/// One CVE alert a scan found new or gone.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CveChange {
/// The CVE id (or the advisory's, when it has no CVE alias).
pub cve: String,
pub package: String,
pub version: String,
pub severity: NotificationSeverity,
}
impl CveChange {
fn of(alert: &CveAlert) -> Self {
Self {
cve: alert.cve().to_string(),
package: alert.affected_package.clone(),
version: alert.affected_version.clone(),
severity: parse_severity(alert.severity.as_deref(), alert.cvss_score),
}
}
}
/// What one scan changed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScanChange {
/// The run's id (hex).
pub run_id: String,
pub status: ScanRunStatus,
pub started_at: DateTime<Utc>,
#[serde(default)]
pub completed_at: Option<DateTime<Utc>>,
/// New findings the scan stored.
#[serde(default)]
pub new_findings: u32,
/// The target's first completed scan: no changes, it set the start.
#[serde(default)]
pub baseline: bool,
/// The CVE alerts found new in the scan's window, most severe first.
pub new_cves: Vec<CveChange>,
/// The CVE alerts found gone in the scan's window, most severe first.
pub gone_cves: Vec<CveChange>,
/// The components the scan changed, each with the CVEs it brought and
/// took, and the advisories that changed for components it left alone
/// (#974); `None` when the run did not record its component changes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub components: Option<Vec<ComponentRow>>,
}
/// A line of what a scan changed in its components.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ComponentRowKind {
Added,
Updated,
Removed,
/// The component did not change; advisories about it did.
Advisory,
}
/// One component a scan changed, or whose advisories changed, with the
/// CVEs that came and went with it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ComponentRow {
pub kind: ComponentRowKind,
pub name: String,
/// The version before; `None` for an addition.
#[serde(default)]
pub from: Option<String>,
/// The version after; `None` for a removal.
#[serde(default)]
pub to: Option<String>,
pub cves_new: u32,
pub cves_gone: u32,
}
/// The rows of a scan that changed `changes` and saw `new` and `gone` CVEs:
/// a new CVE goes with the component now at its version, a gone one with
/// the component that was at its version; what no change explains is an
/// advisory row per component and version. Rows with CVEs first, then by
/// name.
fn component_rows(
changes: &[ComponentChange],
new: &[CveChange],
gone: &[CveChange],
) -> Vec<ComponentRow> {
let count = |cves: &[CveChange], name: &str, version: Option<&str>| {
version.map_or(0, |v| {
cves.iter()
.filter(|c| c.package == name && c.version == v)
.count() as u32
})
};
let mut rows: Vec<ComponentRow> = changes
.iter()
.map(|c| ComponentRow {
kind: match c.kind {
ComponentChangeKind::Added => ComponentRowKind::Added,
ComponentChangeKind::Updated => ComponentRowKind::Updated,
ComponentChangeKind::Removed => ComponentRowKind::Removed,
},
name: c.name.clone(),
from: c.from.clone(),
to: c.to.clone(),
cves_new: count(new, &c.name, c.to.as_deref()),
cves_gone: count(gone, &c.name, c.from.as_deref()),
})
.collect();
let explained = |cve: &CveChange, after: bool| {
changes.iter().any(|c| {
let version = if after { &c.to } else { &c.from };
c.name == cve.package && version.as_deref() == Some(cve.version.as_str())
})
};
let mut advisories: BTreeMap<(&str, &str), (u32, u32)> = BTreeMap::new();
for cve in new.iter().filter(|c| !explained(c, true)) {
advisories
.entry((cve.package.as_str(), cve.version.as_str()))
.or_default()
.0 += 1;
}
for cve in gone.iter().filter(|c| !explained(c, false)) {
advisories
.entry((cve.package.as_str(), cve.version.as_str()))
.or_default()
.1 += 1;
}
rows.extend(
advisories
.into_iter()
.map(|((name, version), (cves_new, cves_gone))| ComponentRow {
kind: ComponentRowKind::Advisory,
name: name.to_string(),
from: Some(version.to_string()),
to: Some(version.to_string()),
cves_new,
cves_gone,
}),
);
rows.sort_by(|a, b| {
let quiet = |r: &ComponentRow| r.cves_new + r.cves_gone == 0;
quiet(a).cmp(&quiet(b)).then_with(|| a.name.cmp(&b.name))
});
rows
}
/// The changes of `runs` (one target's, any order) from `alerts` (the same
/// target's), oldest scan first.
///
/// # Arguments
///
/// * `runs` - the scans to show
/// * `since` - when the completed scan before them ended; `None` when they
/// go back to the target's first scan
/// * `alerts` - the target's CVE alerts (at least those created or resolved
/// after `since`)
///
/// # Examples
///
/// ```
/// use compliance_core::scan_changes::changes;
///
/// assert!(changes(&[], None, &[]).is_empty());
/// ```
pub fn changes(
runs: &[ScanRun],
since: Option<DateTime<Utc>>,
alerts: &[CveAlert],
) -> Vec<ScanChange> {
let mut sorted: Vec<&ScanRun> = runs.iter().collect();
sorted.sort_by_key(|r| r.started_at);
let mut start = since;
let mut out = Vec::with_capacity(sorted.len());
for run in sorted {
let end = run
.completed_at
.filter(|_| run.status == ScanRunStatus::Completed);
let (new_cves, gone_cves) = match (start, end) {
(Some(from), Some(to)) => {
let within = |at: DateTime<Utc>| from < at && at <= to;
(
ranked(alerts.iter().filter(|a| within(a.created_at))),
ranked(alerts.iter().filter(|a| a.resolved_at.is_some_and(&within))),
)
}
_ => (Vec::new(), Vec::new()),
};
let baseline = end.is_some() && start.is_none();
if end.is_some() {
start = end;
}
// The baseline's changes are its whole SBOM, not a change.
let components = run
.component_changes
.as_deref()
.filter(|_| !baseline)
.map(|changes| component_rows(changes, &new_cves, &gone_cves));
out.push(ScanChange {
run_id: run.id.map(|id| id.to_hex()).unwrap_or_default(),
status: run.status.clone(),
started_at: run.started_at,
completed_at: run.completed_at,
new_findings: run.new_findings_count,
baseline,
new_cves,
gone_cves,
components,
});
}
out
}
/// `alerts` as changes, the most severe first, then by package and CVE.
fn ranked<'a>(alerts: impl Iterator<Item = &'a CveAlert>) -> Vec<CveChange> {
let mut list: Vec<CveChange> = alerts.map(CveChange::of).collect();
list.sort_by(|a, b| {
b.severity
.cmp(&a.severity)
.then_with(|| a.package.cmp(&b.package))
.then_with(|| a.cve.cmp(&b.cve))
});
list
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use crate::models::{CveSource, ScanTrigger};
fn at(hour: u32) -> DateTime<Utc> {
format!("2026-11-10T{hour:02}:00:00Z").parse().unwrap()
}
fn run(started: u32, status: ScanRunStatus, completed: Option<u32>) -> ScanRun {
let mut run = ScanRun::new("t1".into(), ScanTrigger::Scheduled);
run.id = Some(bson::oid::ObjectId::new());
run.status = status;
run.started_at = at(started);
run.completed_at = completed.map(at);
run
}
fn alert(cve: &str, severity: &str, created: u32, resolved: Option<u32>) -> CveAlert {
let mut a = CveAlert::new(
cve.into(),
"t1".into(),
"openssl".into(),
"3.0.9".into(),
CveSource::Osv,
);
a.severity = Some(severity.into());
a.created_at = at(created);
a.resolved_at = resolved.map(at);
a
}
#[test]
fn each_completed_scan_gets_what_came_and_went_since_the_one_before() {
let runs = [
run(1, ScanRunStatus::Completed, Some(2)),
run(3, ScanRunStatus::Failed, Some(4)),
run(5, ScanRunStatus::Completed, Some(6)),
run(7, ScanRunStatus::Running, None),
];
let alerts = [
// Found by the first scan: its baseline, not a change.
alert("CVE-2026-0001", "high", 2, Some(6)),
// Added by the monitor while the failed scan ran: the next
// completed scan reports it.
alert("CVE-2026-0002", "critical", 4, None),
alert("CVE-2026-0003", "low", 6, None),
];
let changes = changes(&runs, None, &alerts);
// The first scan is the baseline; the failed and the running scan
// change nothing.
let baselines: Vec<bool> = changes.iter().map(|c| c.baseline).collect();
assert_eq!(baselines, [true, false, false, false]);
assert!(changes[0].new_cves.is_empty());
assert!(changes[1].new_cves.is_empty() && changes[3].new_cves.is_empty());
let new: Vec<&str> = changes[2].new_cves.iter().map(|c| c.cve.as_str()).collect();
assert_eq!(new, ["CVE-2026-0002", "CVE-2026-0003"], "most severe first");
let gone: Vec<&str> = changes[2]
.gone_cves
.iter()
.map(|c| c.cve.as_str())
.collect();
assert_eq!(gone, ["CVE-2026-0001"]);
assert_eq!(
changes[2].new_cves[0].severity,
NotificationSeverity::Critical
);
}
#[test]
fn a_scans_cves_go_with_the_components_it_changed_the_rest_are_advisories() {
let change = |kind, name: &str, from: Option<&str>, to: Option<&str>| ComponentChange {
kind,
package_manager: "npm".into(),
name: name.into(),
from: from.map(String::from),
to: to.map(String::from),
};
let cve = |id: &str, package: &str, version: &str| CveChange {
cve: id.into(),
package: package.into(),
version: version.into(),
severity: NotificationSeverity::High,
};
let changes = [
change(
ComponentChangeKind::Updated,
"openssl",
Some("3.0.9"),
Some("3.0.11"),
),
change(ComponentChangeKind::Added, "libxml2", None, Some("2.11.4")),
change(ComponentChangeKind::Removed, "libpng", Some("1.6.39"), None),
change(ComponentChangeKind::Added, "quiet", None, Some("1.0.0")),
];
let new = [
cve("CVE-1", "openssl", "3.0.11"),
cve("CVE-2", "libxml2", "2.11.4"),
cve("CVE-3", "busybox", "1.36.0"),
];
let gone = [
cve("CVE-4", "openssl", "3.0.9"),
cve("CVE-5", "libpng", "1.6.39"),
];
let rows = component_rows(&changes, &new, &gone);
let read: Vec<(ComponentRowKind, &str, u32, u32)> = rows
.iter()
.map(|r| (r.kind.clone(), r.name.as_str(), r.cves_new, r.cves_gone))
.collect();
assert_eq!(
read,
[
(ComponentRowKind::Advisory, "busybox", 1, 0),
(ComponentRowKind::Removed, "libpng", 0, 1),
(ComponentRowKind::Added, "libxml2", 1, 0),
(ComponentRowKind::Updated, "openssl", 1, 1),
// Changes without CVEs last.
(ComponentRowKind::Added, "quiet", 0, 0),
]
);
}
#[test]
fn a_history_that_starts_later_takes_its_window_from_the_scan_before() {
let runs = [run(5, ScanRunStatus::Completed, Some(6))];
let alerts = [
alert("CVE-2026-0001", "high", 2, None),
alert("CVE-2026-0002", "high", 4, None),
];
let changes = changes(&runs, Some(at(3)), &alerts);
assert!(!changes[0].baseline);
let new: Vec<&str> = changes[0].new_cves.iter().map(|c| c.cve.as_str()).collect();
assert_eq!(new, ["CVE-2026-0002"]);
}
}