- GET /api/v1/cve-history: open CVEs with a fixed version per day (UTC)
by severity, for the tenant, one target or one project's targets, with
the open critical/high findings of the same scope; per-target series
on request. Computed from created_at, resolved_at and the VEX
statement's time, no snapshots.
- GET /api/v1/targets/{id}/top-updates: the package updates that close
the most of a target's open CVEs with a fix.
- Overview: KPI tiles with the 30-day change, a stacked bar chart of the
last 30 days, and the targets as cards grouped by portal project with
sparklines (instead of the CRA-by-target list).
- Target page: the same tiles and chart for the target, and a
"Wo handeln" table.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
430 lines
15 KiB
Rust
430 lines
15 KiB
Rust
//! Open CVE alerts over time, and the package updates that close the most
|
|
//! of them (#952): what the overview's and a target's CVE charts show.
|
|
//!
|
|
//! Computed from the stored alerts alone, no snapshots: an alert counts on
|
|
//! day `d` (UTC) when, at the end of `d`,
|
|
//!
|
|
//! * it had been found (`created_at`),
|
|
//! * it was not resolved yet (`resolved_at` unset or later),
|
|
//! * no VEX statement had settled it (`not_affected` or `fixed` stated at
|
|
//! `vex.at` or earlier), and
|
|
//! * its advisory names a fixed version (`fixed_versions` not empty).
|
|
//!
|
|
//! The unit is one CVE in one target: the same CVE in two packages of a
|
|
//! target (a GHSA and its CVE alias, two copies of a library) counts once,
|
|
//! at its highest severity; in two targets it counts twice. A tenant's or a
|
|
//! project's series is the sum of its targets' series.
|
|
//!
|
|
//! Only the current state of an alert is stored, so two things are not
|
|
//! seen in the past: an alert reported again after it was resolved loses
|
|
//! its `resolved_at` (it shows as open through the gap), and a withdrawn
|
|
//! VEX statement is overwritten (the alert shows as open throughout).
|
|
|
|
use std::cmp::Ordering;
|
|
use std::collections::{BTreeMap, HashMap, HashSet};
|
|
|
|
use chrono::{DateTime, Days, NaiveDate, Utc};
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use crate::models::notification::{parse_severity, NotificationSeverity};
|
|
use crate::models::CveAlert;
|
|
use crate::version::cmp_dotted;
|
|
|
|
/// The days a history covers unless asked otherwise.
|
|
pub const DEFAULT_DAYS: u32 = 30;
|
|
/// The most days a history may cover.
|
|
pub const MAX_DAYS: u32 = 90;
|
|
|
|
/// One day of a history: the open CVEs with a fixed version, by severity.
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct CveDay {
|
|
/// The day (UTC).
|
|
pub date: NaiveDate,
|
|
pub critical: u32,
|
|
pub high: u32,
|
|
pub medium: u32,
|
|
pub low: u32,
|
|
}
|
|
|
|
impl CveDay {
|
|
/// The critical and high ones: what the charts show.
|
|
pub fn urgent(&self) -> u32 {
|
|
self.critical + self.high
|
|
}
|
|
|
|
/// Count one CVE of `severity`.
|
|
fn count(&mut self, severity: &NotificationSeverity) {
|
|
match severity {
|
|
NotificationSeverity::Critical => self.critical += 1,
|
|
NotificationSeverity::High => self.high += 1,
|
|
NotificationSeverity::Medium => self.medium += 1,
|
|
NotificationSeverity::Low => self.low += 1,
|
|
}
|
|
}
|
|
|
|
/// Add another series' counts of the same day.
|
|
fn add(&mut self, other: &Self) {
|
|
self.critical += other.critical;
|
|
self.high += other.high;
|
|
self.medium += other.medium;
|
|
self.low += other.low;
|
|
}
|
|
}
|
|
|
|
/// Open findings of the same scope, the dashboards' other two tiles.
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct OpenFindings {
|
|
pub critical: u64,
|
|
pub high: u64,
|
|
}
|
|
|
|
/// The answer of `GET /api/v1/cve-history`.
|
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct CveHistory {
|
|
/// Oldest day first, today last.
|
|
pub days: Vec<CveDay>,
|
|
#[serde(default)]
|
|
pub open_findings: OpenFindings,
|
|
/// Each target's own series (same days), when asked for; a target
|
|
/// without alerts in the window is left out.
|
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
|
pub targets: BTreeMap<String, Vec<CveDay>>,
|
|
}
|
|
|
|
/// The days of a window of `days` days ending today (at least one), each
|
|
/// with the instant it ends: the next day's midnight, UTC.
|
|
pub fn window(now: DateTime<Utc>, days: u32) -> Vec<(NaiveDate, DateTime<Utc>)> {
|
|
let today = now.date_naive();
|
|
(0..days.max(1))
|
|
.rev()
|
|
.filter_map(|back| {
|
|
let date = today.checked_sub_days(Days::new(u64::from(back)))?;
|
|
let end = date.checked_add_days(Days::new(1))?.and_hms_opt(0, 0, 0)?;
|
|
Some((date, end.and_utc()))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Whether `alert` was open just before `end`: found before it, not
|
|
/// resolved and not settled by VEX by then. The fixed version is not
|
|
/// checked here.
|
|
pub fn open_before(alert: &CveAlert, end: DateTime<Utc>) -> bool {
|
|
alert.created_at < end
|
|
&& alert.resolved_at.is_none_or(|resolved| resolved >= end)
|
|
&& !alert
|
|
.vex
|
|
.as_ref()
|
|
.is_some_and(|vex| vex.status.resolves() && vex.at < end)
|
|
}
|
|
|
|
/// The alerts with a fixed version, by target and CVE id, each with its
|
|
/// severity class.
|
|
fn by_target_and_cve(
|
|
alerts: &[CveAlert],
|
|
) -> HashMap<(&str, &str), Vec<(&CveAlert, NotificationSeverity)>> {
|
|
let mut groups: HashMap<(&str, &str), Vec<_>> = HashMap::new();
|
|
for alert in alerts.iter().filter(|a| !a.fixed_versions.is_empty()) {
|
|
let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score);
|
|
groups
|
|
.entry((alert.repo_id.as_str(), alert.cve()))
|
|
.or_default()
|
|
.push((alert, severity));
|
|
}
|
|
groups
|
|
}
|
|
|
|
impl CveHistory {
|
|
/// The history of `alerts` over `days` days ending today, with every
|
|
/// target's series in [`Self::targets`].
|
|
pub fn of(alerts: &[CveAlert], now: DateTime<Utc>, days: u32) -> Self {
|
|
let window = window(now, days);
|
|
let empty: Vec<CveDay> = window
|
|
.iter()
|
|
.map(|(date, _)| CveDay {
|
|
date: *date,
|
|
..CveDay::default()
|
|
})
|
|
.collect();
|
|
let mut targets: BTreeMap<String, Vec<CveDay>> = BTreeMap::new();
|
|
for ((repo_id, _), members) in by_target_and_cve(alerts) {
|
|
let series = targets
|
|
.entry(repo_id.to_string())
|
|
.or_insert_with(|| empty.clone());
|
|
for (day, (_, end)) in series.iter_mut().zip(&window) {
|
|
let highest = members
|
|
.iter()
|
|
.filter(|(alert, _)| open_before(alert, *end))
|
|
.map(|(_, severity)| severity)
|
|
.max();
|
|
if let Some(severity) = highest {
|
|
day.count(severity);
|
|
}
|
|
}
|
|
}
|
|
let mut total = empty;
|
|
for series in targets.values() {
|
|
for (sum, day) in total.iter_mut().zip(series) {
|
|
sum.add(day);
|
|
}
|
|
}
|
|
Self {
|
|
days: total,
|
|
open_findings: OpenFindings::default(),
|
|
targets,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A package update and the open CVEs with a fix it closes, for a target's
|
|
/// "Wo handeln" table.
|
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct TopUpdate {
|
|
pub package: String,
|
|
pub current_version: String,
|
|
/// The highest version the alerts name as fixed.
|
|
pub fixed_version: String,
|
|
/// Open CVEs with a fix in this package and version.
|
|
pub cves: u32,
|
|
/// The critical ones among them.
|
|
pub critical: u32,
|
|
}
|
|
|
|
/// The updates of the packages with open CVEs (open at `now`, with a
|
|
/// fixed version), the most CVEs closed first, then the most critical,
|
|
/// then by name.
|
|
pub fn top_updates(alerts: &[CveAlert], now: DateTime<Utc>) -> Vec<TopUpdate> {
|
|
let Some((_, end)) = window(now, 1).pop() else {
|
|
return Vec::new();
|
|
};
|
|
type Key<'a> = (&'a str, &'a str);
|
|
let mut packages: HashMap<Key, (HashSet<&str>, HashSet<&str>, &str)> = HashMap::new();
|
|
for alert in alerts
|
|
.iter()
|
|
.filter(|a| !a.fixed_versions.is_empty() && open_before(a, end))
|
|
{
|
|
let key = (
|
|
alert.affected_package.as_str(),
|
|
alert.affected_version.as_str(),
|
|
);
|
|
let (cves, critical, fixed) = packages.entry(key).or_default();
|
|
cves.insert(alert.cve());
|
|
if parse_severity(alert.severity.as_deref(), alert.cvss_score)
|
|
== NotificationSeverity::Critical
|
|
{
|
|
critical.insert(alert.cve());
|
|
}
|
|
for version in &alert.fixed_versions {
|
|
if fixed.is_empty() || cmp_dotted(version, fixed) == Ordering::Greater {
|
|
*fixed = version;
|
|
}
|
|
}
|
|
}
|
|
let mut updates: Vec<TopUpdate> = packages
|
|
.into_iter()
|
|
.map(|((package, current), (cves, critical, fixed))| TopUpdate {
|
|
package: package.to_string(),
|
|
current_version: current.to_string(),
|
|
fixed_version: fixed.to_string(),
|
|
cves: u32::try_from(cves.len()).unwrap_or(u32::MAX),
|
|
critical: u32::try_from(critical.len()).unwrap_or(u32::MAX),
|
|
})
|
|
.collect();
|
|
updates.sort_by(|a, b| {
|
|
b.cves
|
|
.cmp(&a.cves)
|
|
.then_with(|| b.critical.cmp(&a.critical))
|
|
.then_with(|| a.package.cmp(&b.package))
|
|
.then_with(|| a.current_version.cmp(&b.current_version))
|
|
});
|
|
updates
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::models::vex::{VexAssessment, VexStatus};
|
|
use crate::models::CveSource;
|
|
use chrono::TimeZone;
|
|
|
|
/// 2026-11-10 14:00 UTC.
|
|
fn now() -> DateTime<Utc> {
|
|
Utc.with_ymd_and_hms(2026, 11, 10, 14, 0, 0).unwrap()
|
|
}
|
|
|
|
fn at(day: u32, hour: u32) -> DateTime<Utc> {
|
|
Utc.with_ymd_and_hms(2026, 11, day, hour, 0, 0).unwrap()
|
|
}
|
|
|
|
fn alert(repo: &str, cve: &str, severity: &str, created: DateTime<Utc>) -> CveAlert {
|
|
let mut a = CveAlert::new(
|
|
cve.into(),
|
|
repo.into(),
|
|
"log4j-core".into(),
|
|
"2.14.1".into(),
|
|
CveSource::Osv,
|
|
);
|
|
a.severity = Some(severity.into());
|
|
a.fixed_versions = vec!["2.17.1".into()];
|
|
a.created_at = created;
|
|
a
|
|
}
|
|
|
|
fn settled(status: VexStatus, when: DateTime<Utc>) -> VexAssessment {
|
|
VexAssessment {
|
|
status,
|
|
justification: None,
|
|
impact_statement: None,
|
|
action_statement: None,
|
|
by: "u1".into(),
|
|
by_name: None,
|
|
at: when,
|
|
by_scan: false,
|
|
}
|
|
}
|
|
|
|
/// The urgent (critical + high) count of each day, oldest first.
|
|
fn urgent(days: &[CveDay]) -> Vec<u32> {
|
|
days.iter().map(CveDay::urgent).collect()
|
|
}
|
|
|
|
#[test]
|
|
fn the_window_ends_today_with_each_days_midnight() {
|
|
let w = window(now(), 3);
|
|
let dates: Vec<String> = w.iter().map(|(d, _)| d.to_string()).collect();
|
|
assert_eq!(dates, ["2026-11-08", "2026-11-09", "2026-11-10"]);
|
|
assert_eq!(w[2].1, at(11, 0));
|
|
assert_eq!(window(now(), 0).len(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn an_alert_never_resolved_is_open_from_the_day_it_was_found() {
|
|
let h = CveHistory::of(
|
|
&[alert("t1", "CVE-2021-44228", "CRITICAL", at(8, 23))],
|
|
now(),
|
|
4,
|
|
);
|
|
assert_eq!(urgent(&h.days), [0, 1, 1, 1]);
|
|
assert_eq!(h.days[3].critical, 1);
|
|
}
|
|
|
|
#[test]
|
|
fn an_alert_resolved_on_a_day_no_longer_counts_on_that_day() {
|
|
let mut found_and_gone = alert("t1", "CVE-2021-44228", "HIGH", at(9, 8));
|
|
found_and_gone.resolved_at = Some(at(9, 17));
|
|
let mut gone_later = alert("t1", "CVE-2021-45046", "HIGH", at(8, 8));
|
|
gone_later.resolved_at = Some(at(10, 9));
|
|
let h = CveHistory::of(&[found_and_gone, gone_later], now(), 3);
|
|
assert_eq!(urgent(&h.days), [1, 1, 0]);
|
|
}
|
|
|
|
#[test]
|
|
fn an_alert_without_a_fixed_version_is_left_out() {
|
|
let mut a = alert("t1", "CVE-2021-44228", "CRITICAL", at(8, 8));
|
|
a.fixed_versions.clear();
|
|
let h = CveHistory::of(&[a.clone()], now(), 3);
|
|
assert_eq!(urgent(&h.days), [0, 0, 0]);
|
|
assert!(h.targets.is_empty());
|
|
assert!(top_updates(&[a], now()).is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn one_cve_counts_once_per_target_at_its_highest_severity() {
|
|
// The GHSA and its CVE alias, in two packages of one target.
|
|
let mut ghsa = alert("t1", "GHSA-jfh8-c2jp-5v3q", "HIGH", at(8, 8));
|
|
ghsa.aliases = vec!["CVE-2021-44228".into()];
|
|
ghsa.affected_package = "log4j-api".into();
|
|
let cve = alert("t1", "CVE-2021-44228", "CRITICAL", at(9, 8));
|
|
// The same CVE in another target counts there too.
|
|
let other = alert("t2", "CVE-2021-44228", "HIGH", at(8, 8));
|
|
let h = CveHistory::of(&[ghsa, cve, other], now(), 3);
|
|
assert_eq!(
|
|
h.targets["t1"]
|
|
.iter()
|
|
.map(|d| (d.critical, d.high))
|
|
.collect::<Vec<_>>(),
|
|
[(0, 1), (1, 0), (1, 0)]
|
|
);
|
|
assert_eq!(urgent(&h.targets["t2"]), [1, 1, 1]);
|
|
assert_eq!(urgent(&h.days), [2, 2, 2]);
|
|
}
|
|
|
|
#[test]
|
|
fn a_vex_statement_settles_an_alert_from_when_it_was_made() {
|
|
let mut not_affected = alert("t1", "CVE-2021-44228", "CRITICAL", at(8, 8));
|
|
not_affected.vex = Some(settled(VexStatus::NotAffected, at(9, 12)));
|
|
// Affected does not settle it.
|
|
let mut affected = alert("t1", "CVE-2021-45046", "HIGH", at(8, 8));
|
|
affected.vex = Some(settled(VexStatus::Affected, at(8, 9)));
|
|
let h = CveHistory::of(&[not_affected, affected], now(), 3);
|
|
assert_eq!(urgent(&h.days), [2, 1, 1]);
|
|
}
|
|
|
|
#[test]
|
|
fn medium_and_low_are_counted_apart_from_the_urgent_ones() {
|
|
let h = CveHistory::of(
|
|
&[
|
|
alert("t1", "GHSA-4jrv-ppp4-jm57", "MODERATE", at(10, 8)),
|
|
alert("t1", "CVE-2020-0001", "LOW", at(10, 8)),
|
|
],
|
|
now(),
|
|
1,
|
|
);
|
|
assert_eq!(
|
|
(h.days[0].medium, h.days[0].low, h.days[0].urgent()),
|
|
(1, 1, 0)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn the_update_closing_the_most_cves_comes_first_with_the_highest_fix() {
|
|
let mut first = alert("t1", "CVE-2021-44228", "CRITICAL", at(8, 8));
|
|
first.fixed_versions = vec!["2.15.0".into(), "2.12.2".into()];
|
|
let mut second = alert("t1", "CVE-2021-45046", "CRITICAL", at(8, 8));
|
|
second.fixed_versions = vec!["2.16.0".into()];
|
|
// The GHSA of the first CVE: no extra CVE closed.
|
|
let mut alias = alert("t1", "GHSA-jfh8-c2jp-5v3q", "CRITICAL", at(8, 8));
|
|
alias.aliases = vec!["CVE-2021-44228".into()];
|
|
alias.fixed_versions = vec!["2.17.1".into()];
|
|
let mut gson = alert("t1", "CVE-2022-25647", "HIGH", at(8, 8));
|
|
gson.affected_package = "gson".into();
|
|
gson.affected_version = "2.8.8".into();
|
|
gson.fixed_versions = vec!["2.8.9".into()];
|
|
// Resolved: closes nothing any more.
|
|
let mut gone = alert("t1", "CVE-2020-0002", "HIGH", at(8, 8));
|
|
gone.affected_package = "jackson".into();
|
|
gone.resolved_at = Some(at(9, 8));
|
|
let updates = top_updates(&[gson, first, second, alias, gone], now());
|
|
assert_eq!(
|
|
updates,
|
|
[
|
|
TopUpdate {
|
|
package: "log4j-core".into(),
|
|
current_version: "2.14.1".into(),
|
|
fixed_version: "2.17.1".into(),
|
|
cves: 2,
|
|
critical: 2,
|
|
},
|
|
TopUpdate {
|
|
package: "gson".into(),
|
|
current_version: "2.8.8".into(),
|
|
fixed_version: "2.8.9".into(),
|
|
cves: 1,
|
|
critical: 0,
|
|
},
|
|
]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn equal_counts_rank_the_more_critical_update_first() {
|
|
let high = alert("t1", "CVE-2020-0003", "HIGH", at(8, 8));
|
|
let mut critical = alert("t1", "CVE-2020-0004", "CRITICAL", at(8, 8));
|
|
critical.affected_package = "zlib".into();
|
|
let names: Vec<String> = top_updates(&[high, critical], now())
|
|
.into_iter()
|
|
.map(|u| u.package)
|
|
.collect();
|
|
assert_eq!(names, ["zlib", "log4j-core"]);
|
|
}
|
|
}
|