diff --git a/README.md b/README.md index 159b6fd..9e452d9 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,8 @@ The agent exposes a REST API on port 3001: |--------|----------|-------------| | `GET` | `/api/v1/health` | Health check | | `GET` | `/api/v1/stats/overview` | Summary statistics and trends | +| `GET` | `/api/v1/cve-history?days=30[&target=][&project=][&per_target=true]` | Open CVEs with a fixed version per day (UTC) by severity, for the tenant, a target or a project, with the open critical/high findings | +| `GET` | `/api/v1/targets/{id}/top-updates` | The package updates that close the most of a target's open CVEs with a fix | | `GET` | `/api/v1/targets` | List targets (Prüfobjekte), each with its newest scan run | | `POST` | `/api/v1/targets` | Create a target | | `GET` / `PATCH` / `DELETE` | `/api/v1/targets/{id}` | Read, update (name, type, artifacts, `scan_config` incl. `issue_tracker`) or delete a target | diff --git a/compliance-agent/src/api/handlers/cve_history.rs b/compliance-agent/src/api/handlers/cve_history.rs new file mode 100644 index 0000000..03bc7d6 --- /dev/null +++ b/compliance-agent/src/api/handlers/cve_history.rs @@ -0,0 +1,218 @@ +//! The CVE charts of the overview and a target's page (#952): open CVEs +//! with a fix per day, and the package updates that close the most of them. +//! +//! Both read the tenant's own database; the org-role middleware lets every +//! role that may read call them, like the other target and CVE reads. + +use axum::extract::{Extension, Path, Query}; +use axum::http::StatusCode; +use axum::Json; +use mongodb::bson::{doc, oid::ObjectId, Document}; +use serde::{Deserialize, Deserializer}; + +use compliance_core::cve_history::{ + top_updates, window, CveHistory, OpenFindings, TopUpdate, DEFAULT_DAYS, MAX_DAYS, +}; +use compliance_core::models::CveAlert; +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult}; +use super::health::open_findings_by_severity; +use crate::database::Database; + +/// The updates a target's "Wo handeln" table lists. +const TOP_UPDATES_SHOWN: usize = 10; + +/// The query of [`cve_history`]. +#[derive(Debug, Deserialize)] +pub struct HistoryQuery { + /// Days back from today, `1..=90` (clamped); 30 when not given. + #[serde(default = "default_days", deserialize_with = "de_days")] + pub days: u32, + /// Only this target. Takes precedence over `project`. + #[serde(default)] + pub target: Option, + /// Only the targets of this project (`targets.project_ids`). + #[serde(default)] + pub project: Option, + /// Also each target's own series, for the overview's repo cards. + #[serde(default)] + pub per_target: bool, +} + +fn default_days() -> u32 { + DEFAULT_DAYS +} + +/// Clamp a caller-supplied number of days to `1..=MAX_DAYS`. +fn de_days<'de, D: Deserializer<'de>>(d: D) -> Result { + Ok(u32::deserialize(d)?.clamp(1, MAX_DAYS)) +} + +/// A non-empty, trimmed query value. +fn given(value: Option<&str>) -> Option<&str> { + value.map(str::trim).filter(|v| !v.is_empty()) +} + +/// The target ids the query is about: one target, a project's targets, or +/// `None` for every target of the tenant. +async fn scope(db: &Database, query: &HistoryQuery) -> Result>, StatusCode> { + if let Some(target) = given(query.target.as_deref()) { + return Ok(Some(vec![target.to_string()])); + } + let Some(project) = given(query.project.as_deref()) else { + return Ok(None); + }; + let rows: Vec = collect_cursor_async( + db.onboarded_targets() + .clone_with_type::() + .find(doc! { "project_ids": project }) + .projection(doc! { "_id": 1 }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?, + ) + .await; + Ok(Some( + rows.iter() + .filter_map(|row| row.get_object_id("_id").ok().map(|id| id.to_hex())) + .collect(), + )) +} + +/// The alerts with a fixed version that may be open at some point after +/// `since`, of `targets` (every target with `None`). The long texts are +/// left out; the history does not need them. +async fn alerts_with_fix( + db: &Database, + targets: Option<&[String]>, + since: chrono::DateTime, +) -> Result, StatusCode> { + let mut filter = doc! { + "fixed_versions.0": { "$exists": true }, + "$or": [ + { "resolved_at": null }, + { "resolved_at": { "$gte": mongodb::bson::DateTime::from_chrono(since) } }, + ], + }; + if let Some(targets) = targets { + filter.insert("repo_id", doc! { "$in": targets }); + } + let cursor = db + .cve_alerts() + .find(filter) + .projection(doc! { + "summary": 0, "llm_impact_summary": 0, "advisories": 0, "exploitation": 0, + }) + .await + .map_err(|e| { + tracing::warn!("CVE history: loading alerts failed: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + Ok(collect_cursor_async(cursor).await) +} + +/// `GET /api/v1/cve-history?days=30[&target=][&project=][&per_target=true]` +/// — per day (UTC, oldest first, today last) the open CVEs with a fixed +/// version, by severity, for the tenant, one target or one project's +/// targets; plus the open critical and high findings of the same scope. +/// +/// A CVE counts on day `d` when, at the end of `d`: its alert was found +/// (`created_at`), not resolved (`resolved_at` unset or later), not settled +/// by a VEX `not_affected` / `fixed` stated by then (`vex.at`), and its +/// advisory names a fixed version. One CVE counts once per target (its +/// GHSA and CVE alias, or two packages, are one), at its highest severity; +/// a tenant's or project's count is the sum over its targets. See +/// [`compliance_core::cve_history`] for what the stored state cannot show. +#[tracing::instrument(skip_all)] +pub async fn cve_history( + Extension(agent): AgentExt, + tenant: TenantCtx, + Query(query): Query, +) -> ApiResult { + let db = tenant_db(&agent, &tenant).await?; + let now = chrono::Utc::now(); + let since = window(now, query.days).first().map_or(now, |(_, end)| *end); + let targets = scope(&db, &query).await?; + let findings_scope = match &targets { + Some(ids) => doc! { "repo_id": { "$in": ids } }, + None => doc! {}, + }; + let (alerts, by_severity) = tokio::join!( + alerts_with_fix(&db, targets.as_deref(), since), + open_findings_by_severity(&db, findings_scope), + ); + let mut history = CveHistory::of(&alerts?, now, query.days); + let count = |name: &str| by_severity.get(name).copied().unwrap_or(0); + history.open_findings = OpenFindings { + critical: count("critical"), + high: count("high"), + }; + if !query.per_target { + history.targets.clear(); + } + Ok(Json(ApiResponse { + data: history, + total: None, + page: None, + })) +} + +/// `GET /api/v1/targets/{id}/top-updates` — the package updates that close +/// the most of the target's open CVEs with a fix (at most ten): package, +/// current version, the highest fixed version its alerts name, and how +/// many CVEs (and critical ones) it closes. 404 for a target the tenant +/// does not have. +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn target_top_updates( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> ApiResult> { + let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?; + let db = tenant_db(&agent, &tenant).await?; + db.onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + let now = chrono::Utc::now(); + let ids = [id]; + let alerts = alerts_with_fix(&db, Some(&ids), now).await?; + let mut updates = top_updates(&alerts, now); + let total = updates.len() as u64; + updates.truncate(TOP_UPDATES_SHOWN); + Ok(Json(ApiResponse { + data: updates, + total: Some(total), + page: None, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn query(text: &str) -> HistoryQuery { + let uri: axum::http::Uri = format!("/api/v1/cve-history?{text}").parse().unwrap(); + Query::::try_from_uri(&uri).unwrap().0 + } + + #[test] + fn the_days_are_clamped_and_default_to_thirty() { + assert_eq!(query("").days, 30); + assert_eq!(query("days=0").days, 1); + assert_eq!(query("days=100000").days, MAX_DAYS); + let q = query("days=7&target=t1&per_target=true"); + assert_eq!( + (q.days, q.target.as_deref(), q.per_target), + (7, Some("t1"), true) + ); + } + + #[test] + fn a_blank_scope_means_every_target() { + assert_eq!(given(Some(" ")), None); + assert_eq!(given(Some(" p1 ")), Some("p1")); + assert_eq!(given(None), None); + } +} diff --git a/compliance-agent/src/api/handlers/health.rs b/compliance-agent/src/api/handlers/health.rs index e25c114..caa8e4f 100644 --- a/compliance-agent/src/api/handlers/health.rs +++ b/compliance-agent/src/api/handlers/health.rs @@ -57,14 +57,19 @@ fn health_answer(mongo_reachable: bool) -> (axum::http::StatusCode, Json std::collections::HashMap { use futures_util::TryStreamExt; + let mut matching = scope; + matching.insert("status", doc! { "$in": OPEN_STATUSES.to_vec() }); let pipeline = vec![ - doc! { "$match": { "status": { "$in": OPEN_STATUSES.to_vec() } } }, + doc! { "$match": matching }, doc! { "$group": { "_id": "$severity", "n": { "$sum": 1 } } }, ]; let rows: Vec = match db.findings().aggregate(pipeline).await { @@ -116,7 +121,7 @@ pub async fn stats_overview( .await .unwrap_or(0) }, - open_findings_by_severity(db), + open_findings_by_severity(db, doc! {}), ); let severity = |name: &str| by_severity.get(name).copied().unwrap_or(0); let total_findings = by_severity.values().sum(); diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index f5ef4f7..c49251a 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -1,5 +1,6 @@ pub mod admin; pub mod chat; +pub mod cve_history; pub mod cve_matrix; pub mod dast; pub mod demo_seed; diff --git a/compliance-agent/src/api/role_gate/router_tests.rs b/compliance-agent/src/api/role_gate/router_tests.rs index aa94ba5..2143856 100644 --- a/compliance-agent/src/api/role_gate/router_tests.rs +++ b/compliance-agent/src/api/role_gate/router_tests.rs @@ -150,6 +150,12 @@ fn routes() -> Vec<(Method, String, bool)> { false, ), (Method::GET, "/api/v1/sbom/export".into(), false), + (Method::GET, "/api/v1/cve-history?days=30".into(), false), + ( + Method::GET, + format!("/api/v1/targets/{ID}/top-updates"), + false, + ), (Method::GET, "/api/v1/licenses/conclusions".into(), false), (Method::PUT, "/api/v1/licenses/conclusions".into(), true), ( diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 784a326..e234f77 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -125,6 +125,15 @@ pub fn build_router() -> Router { "/api/v1/targets/{id}/cve-matrix", get(handlers::cve_matrix::target_cve_matrix), ) + // Open CVEs with a fix per day, and the updates closing most (#952). + .route( + "/api/v1/cve-history", + get(handlers::cve_history::cve_history), + ) + .route( + "/api/v1/targets/{id}/top-updates", + get(handlers::cve_history::target_top_updates), + ) .route("/api/v1/targets/{id}/vex", get(handlers::vex::export_vex)) .route("/api/v1/targets/{id}/csaf", get(handlers::vex::export_csaf)) .route("/api/v1/targets/{id}/enisa", get(handlers::vex::list_enisa)) diff --git a/compliance-core/src/cve_history.rs b/compliance-core/src/cve_history.rs new file mode 100644 index 0000000..b908c3d --- /dev/null +++ b/compliance-core/src/cve_history.rs @@ -0,0 +1,429 @@ +//! 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, + #[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>, +} + +/// 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, days: u32) -> Vec<(NaiveDate, DateTime)> { + 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) -> 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, days: u32) -> Self { + let window = window(now, days); + let empty: Vec = window + .iter() + .map(|(date, _)| CveDay { + date: *date, + ..CveDay::default() + }) + .collect(); + let mut targets: BTreeMap> = 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) -> Vec { + let Some((_, end)) = window(now, 1).pop() else { + return Vec::new(); + }; + type Key<'a> = (&'a str, &'a str); + let mut packages: HashMap, 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 = 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.with_ymd_and_hms(2026, 11, 10, 14, 0, 0).unwrap() + } + + fn at(day: u32, hour: u32) -> DateTime { + Utc.with_ymd_and_hms(2026, 11, day, hour, 0, 0).unwrap() + } + + fn alert(repo: &str, cve: &str, severity: &str, created: DateTime) -> 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) -> 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 { + days.iter().map(CveDay::urgent).collect() + } + + #[test] + fn the_window_ends_today_with_each_days_midnight() { + let w = window(now(), 3); + let dates: Vec = 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::>(), + [(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 = top_updates(&[high, critical], now()) + .into_iter() + .map(|u| u.package) + .collect(); + assert_eq!(names, ["zlib", "log4j-core"]); + } +} diff --git a/compliance-core/src/lib.rs b/compliance-core/src/lib.rs index 144c1cc..176f540 100644 --- a/compliance-core/src/lib.rs +++ b/compliance-core/src/lib.rs @@ -4,6 +4,7 @@ pub mod control_check; pub mod csaf_docs; pub mod csaf_ingest; pub mod cve_groups; +pub mod cve_history; pub mod cve_matrix; pub mod db; pub mod encoding; diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 2924f3c..7235427 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -4507,9 +4507,6 @@ tbody tr:last-child td { color: var(--text-tertiary); } -.sev-critical-text { color: var(--sev-critical); } -.sev-high-text { color: var(--sev-high); } - .ov-grid { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); @@ -4539,54 +4536,15 @@ tbody tr:last-child td { padding: 14px 18px; } -.ov-targets, .ov-next-list { list-style: none; } -.ov-target { - display: grid; - grid-template-columns: minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(90px, auto); - gap: 16px; - align-items: center; - padding: 12px 18px; - border-bottom: 1px solid var(--border); -} - -.ov-target:last-child { - border-bottom: none; -} - -.ov-target-name { - display: grid; - min-width: 0; -} - -.ov-target-name a { - color: var(--text-primary); - font-weight: 500; - text-decoration: none; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.ov-target-name a:hover { - color: var(--accent); -} - .ov-target-type { font-size: 11.5px; color: var(--text-tertiary); } -.ov-target-scan { - justify-self: end; - font-size: 12px; - color: var(--text-tertiary); - white-space: nowrap; -} - .ov-next-list li { display: grid; grid-template-columns: auto minmax(0, 1fr); @@ -4655,15 +4613,318 @@ tbody tr:last-child td { .ov-figure:nth-child(-n+2) { border-bottom: 1px solid var(--border); } +} - .ov-target { - grid-template-columns: 1fr; - gap: 6px; +/* ── CVE trend (#952): tiles, 30-day bars, sparklines, repo cards ── + Critical and high CVEs with a fix. The two reds are fixed for the light + theme; the dark theme lightens them to stay readable on its panels. */ +:root { + --cve-critical: #7E2318; + --cve-high: #B3452F; +} + +:root[data-theme="dark"] { + --cve-critical: #E06A58; + --cve-high: #F2A48C; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --cve-critical: #E06A58; + --cve-high: #F2A48C; + } +} + +.cve-kpi-critical { color: var(--cve-critical); } +.cve-kpi-high { color: var(--cve-high); } + +.cve-chart-card { + margin-bottom: 20px; +} + +.cve-chart-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 14px; +} + +.cve-chart-head h3 { + font-size: 14px; + font-weight: 600; +} + +.cve-chart-head p { + font-size: 12px; + color: var(--text-tertiary); + max-width: 70ch; +} + +.cve-legend { + display: flex; + gap: 14px; + list-style: none; + font-size: 12px; + color: var(--text-secondary); + white-space: nowrap; +} + +.cve-legend li { + display: inline-flex; + align-items: center; + gap: 6px; +} + +.cve-dot { + width: 10px; + height: 10px; + border-radius: 2px; +} + +.cve-dot.cve-critical { background: var(--cve-critical); } +.cve-dot.cve-high { background: var(--cve-high); } + +.cve-chart { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + grid-template-rows: 160px auto; + column-gap: 8px; +} + +.cve-chart-axis { + display: flex; + flex-direction: column; + justify-content: space-between; + font-family: var(--font-mono); + font-size: 10.5px; + line-height: 1; + text-align: right; + color: var(--text-faint); + font-variant-numeric: tabular-nums; +} + +/* Gridlines at the top and the middle; the baseline is the border. */ +.cve-chart-bars { + display: flex; + align-items: stretch; + gap: 2px; + border-bottom: 1px solid var(--border-strong); + background-image: linear-gradient(to bottom, var(--border) 1px, transparent 1px); + background-size: 100% 50%; +} + +.cve-bar { + display: flex; + flex: 1 1 0; + flex-direction: column; + justify-content: flex-end; + min-width: 0; + border-radius: 2px 2px 0 0; + overflow: hidden; + transition: opacity 0.15s var(--ease-out), background 0.15s var(--ease-out); +} + +.cve-bar-critical { display: block; background: var(--cve-critical); } +.cve-bar-high { display: block; background: var(--cve-high); } + +/* Hovering one day dims the others. */ +.cve-chart-bars:hover .cve-bar { opacity: 0.45; } + +.cve-chart-bars .cve-bar:hover { + opacity: 1; + background: var(--bg-card-hover); +} + +.cve-chart-dates { + grid-column: 2; + display: flex; + justify-content: space-between; + padding-top: 4px; + font-family: var(--font-mono); + font-size: 10.5px; + color: var(--text-faint); +} + +.cve-spark { + flex-shrink: 0; + width: 96px; + height: 24px; + overflow: visible; + color: var(--cve-high); +} + +/* The overview's targets by project. */ +.card.ov-projects { + padding: 0; +} + +.ov-project { + padding: 14px 18px; + border-bottom: 1px solid var(--border); +} + +.ov-project:last-child { + border-bottom: none; +} + +.ov-project-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 10px; +} + +.ov-project-title { + display: grid; + gap: 2px; + min-width: 0; +} + +.ov-project-title h4 { + font-size: 13.5px; + font-weight: 600; +} + +.ov-project-title span { + font-size: 12px; + color: var(--text-tertiary); +} + +.ov-project .ov-more { + padding: 10px 0 0; +} + +.repo-cards { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); + gap: 10px; +} + +.repo-card { + display: grid; + gap: 10px; + align-content: start; + min-width: 0; + padding: 12px; + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius); +} + +.repo-card-name { + display: grid; + min-width: 0; +} + +.repo-card-name a { + color: var(--text-primary); + font-weight: 500; + text-decoration: none; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.repo-card-name a:hover, +.repo-card-cves:hover .repo-card-n { + color: var(--accent); +} + +.repo-card-cves { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: center; + gap: 4px 8px; + color: inherit; + text-decoration: none; +} + +/* A card's sparkline runs the card's width under its count. */ +.repo-card-cves .cve-spark { + grid-column: 1 / -1; + width: 100%; +} + +.repo-card-n { + font-size: 22px; + font-weight: 600; + letter-spacing: -0.02em; + font-variant-numeric: tabular-nums; +} + +.repo-card-label { + display: grid; + font-size: 11.5px; + color: var(--text-tertiary); +} + +.repo-card-split { + font-size: 11px; + color: var(--text-faint); +} + +.repo-card-cra { + display: block; + color: inherit; + text-decoration: none; +} + +.repo-card-foot { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + gap: 6px 10px; + font-size: 12px; + color: var(--text-tertiary); +} + +.repo-card-links { + display: flex; + gap: 10px; +} + +.repo-card-links a { + color: var(--accent); + text-decoration: none; +} + +.repo-card-links a:hover { + text-decoration: underline; +} + +/* A target's "Wo handeln" table. */ +.cve-act { + margin-bottom: 20px; +} + +.cve-act-table code { + font-family: var(--font-mono); + font-size: 12px; +} + +.cve-act-table .num { + text-align: right; + font-variant-numeric: tabular-nums; +} + +.cve-act-critical { + display: block; + font-size: 11px; + color: var(--cve-critical); +} + +@media (max-width: 720px) { + .cve-chart { + grid-template-rows: 120px auto; } - .ov-target-scan { - justify-self: start; + .cve-chart-head { + flex-direction: column; + gap: 8px; } + } /* ── Targets list ── */ @@ -5237,7 +5498,6 @@ tbody tr:last-child td { } /* The overview's list cards pad their own rows. */ -.card.ov-cra, .card.ov-next { padding: 0; } diff --git a/compliance-dashboard/src/components/cve_trend.rs b/compliance-dashboard/src/components/cve_trend.rs new file mode 100644 index 0000000..d29d39e --- /dev/null +++ b/compliance-dashboard/src/components/cve_trend.rs @@ -0,0 +1,286 @@ +//! The CVE trend (#952): the KPI tiles and the stacked bar chart of the last +//! 30 days, the sparkline of a project or target, and a target's "Wo +//! handeln" table. Used by the overview and the target page. Plain HTML, +//! CSS and SVG; no chart library. + +use compliance_core::cve_history::{CveDay, CveHistory}; +use dioxus::prelude::*; +use dioxus_free_icons::icons::bs_icons::BsArrowRight; +use dioxus_free_icons::Icon; + +use crate::app::Route; +use crate::i18n::texts::{common, cve_trend as tx}; +use crate::i18n::use_lang; +use crate::infrastructure::cve_history::{fetch_cve_history, fetch_top_updates}; + +/// The y axis' top for a highest bar of `max`: the smallest of 2, 4, 6, 8 +/// and 10 times a power of ten that is not below it. Always even, so the +/// middle label is a whole number. +pub fn axis_top(max: u32) -> u32 { + let mut scale: u64 = 1; + loop { + for step in [2u64, 4, 6, 8, 10] { + let top = step * scale; + if top >= u64::from(max) { + return u32::try_from(top).unwrap_or(u32::MAX); + } + } + scale *= 10; + } +} + +/// The points of a sparkline of `values` in a `width` × `height` box: the +/// first value at the left edge, the last at the right, 0 one unit above +/// the bottom and the highest value one unit below the top. +pub fn sparkline_points(values: &[u32], width: f32, height: f32) -> String { + let max = values.iter().copied().max().unwrap_or(0).max(1) as f32; + let step = if values.len() > 1 { + width / (values.len() - 1) as f32 + } else { + 0.0 + }; + let usable = (height - 2.0).max(0.0); + values + .iter() + .enumerate() + .map(|(i, v)| { + let x = i as f32 * step; + let y = height - 1.0 - (*v as f32 / max) * usable; + format!("{x:.1},{y:.1}") + }) + .collect::>() + .join(" ") +} + +/// The change from the first to the last day of `days` of the count `of`. +pub fn change(days: &[CveDay], of: fn(&CveDay) -> u32) -> i64 { + match (days.first(), days.last()) { + (Some(first), Some(last)) => i64::from(of(last)) - i64::from(of(first)), + _ => 0, + } +} + +/// A bar's height in percent of the axis' `top`. +fn percent(n: u32, top: u32) -> f32 { + n as f32 * 100.0 / top.max(1) as f32 +} + +/// The four tiles and the bar chart of one scope (the tenant, or the target +/// `target`; empty for the tenant). Each tile opens the list behind it, +/// filtered to the target. +#[component] +pub fn CveDashboard(history: CveHistory, target: String) -> Element { + let lang = use_lang()(); + let days = &history.days; + let today = days.last().copied().unwrap_or_default(); + let span = days.len(); + let critical_change = tx::change(change(days, |d| d.critical), span, lang); + let high_change = tx::change(change(days, |d| d.high), span, lang); + let findings = history.open_findings; + rsx! { + div { class: "ov-figures", + Link { to: Route::SbomPage { target: target.clone() }, class: "ov-figure", + span { class: "ov-figure-label", {tx::CVE_CRITICAL.get(lang)} } + span { class: "ov-figure-value cve-kpi-critical", "{today.critical}" } + span { class: "ov-figure-sub", "{critical_change}" } + } + Link { to: Route::SbomPage { target: target.clone() }, class: "ov-figure", + span { class: "ov-figure-label", {tx::CVE_HIGH.get(lang)} } + span { class: "ov-figure-value cve-kpi-high", "{today.high}" } + span { class: "ov-figure-sub", "{high_change}" } + } + Link { to: Route::findings(target.clone()), class: "ov-figure", + span { class: "ov-figure-label", {tx::FINDINGS_CRITICAL.get(lang)} } + span { class: "ov-figure-value", "{findings.critical}" } + span { class: "ov-figure-sub", {tx::OPEN_NOW.get(lang)} } + } + Link { to: Route::findings(target), class: "ov-figure", + span { class: "ov-figure-label", {tx::FINDINGS_HIGH.get(lang)} } + span { class: "ov-figure-value", "{findings.high}" } + span { class: "ov-figure-sub", {tx::OPEN_NOW.get(lang)} } + } + } + section { class: "card cve-chart-card", + div { class: "cve-chart-head", + div { + h3 { {tx::CHART_TITLE.get(lang)} } + p { {tx::CHART_HINT.get(lang)} } + } + ul { class: "cve-legend", + li { span { class: "cve-dot cve-critical" } {common::CRITICAL.get(lang)} } + li { span { class: "cve-dot cve-high" } {common::HIGH.get(lang)} } + } + } + CveBars { days: history.days.clone() } + } + } +} + +/// The stacked bars of `days`: critical at the bottom, high on top, one bar +/// a day with its counts as the tooltip; the axis reads 0, middle and top. +#[component] +pub fn CveBars(days: Vec) -> Element { + let lang = use_lang()(); + let top = axis_top(days.iter().map(CveDay::urgent).max().unwrap_or(0)); + let mid = top / 2; + let first = days.first().map(|d| d.date.format("%d.%m.").to_string()); + let last = days.last().map(|d| d.date.format("%d.%m.").to_string()); + rsx! { + div { class: "cve-chart", + div { class: "cve-chart-axis", "aria-hidden": "true", + span { "{top}" } + span { "{mid}" } + span { "0" } + } + div { class: "cve-chart-bars", role: "img", "aria-label": tx::CHART_LABEL.get(lang), + for day in days { + div { + key: "{day.date}", + class: "cve-bar", + title: tx::bar_title(day.date, day.critical, day.high, lang), + span { class: "cve-bar-high", style: "height: {percent(day.high, top)}%;" } + span { class: "cve-bar-critical", style: "height: {percent(day.critical, top)}%;" } + } + } + } + div { class: "cve-chart-dates", "aria-hidden": "true", + span { {first.unwrap_or_default()} } + span { {last.unwrap_or_default()} } + } + } + } +} + +/// A small line of `values` (oldest first), in the text colour around it. +#[component] +pub fn Sparkline(values: Vec, label: String) -> Element { + let points = sparkline_points(&values, 100.0, 24.0); + rsx! { + svg { + class: "cve-spark", + view_box: "0 0 100 24", + preserve_aspect_ratio: "none", + role: "img", + "aria-label": "{label}", + polyline { + points: "{points}", + fill: "none", + stroke: "currentColor", + stroke_width: "1.5", + stroke_linejoin: "round", + vector_effect: "non-scaling-stroke", + } + } + } +} + +/// The top of a target's page: its tiles and chart, and the package updates +/// that close the most of its open CVEs with a fix. +#[component] +pub fn TargetCveDashboard(target_id: String) -> Element { + let lang = use_lang()(); + let id = use_signal(|| target_id.clone()); + let history = use_resource(move || async move { fetch_cve_history(id(), false).await.ok() }); + let updates = use_resource(move || async move { fetch_top_updates(id()).await.ok() }); + rsx! { + match history.read().clone() { + Some(Some(history)) => rsx! { CveDashboard { history, target: target_id.clone() } }, + Some(None) => rsx! { div { class: "card", p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } } }, + None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, + } + section { class: "card cve-act", + div { class: "target-card-head", + div { + h3 { {tx::WHERE_TO_ACT.get(lang)} } + p { class: "target-muted", {tx::WHERE_TO_ACT_HINT.get(lang)} } + } + Link { to: Route::SbomPage { target: target_id.clone() }, class: "target-card-link", + {tx::ALL_CVES.get(lang)} + Icon { icon: BsArrowRight, width: 14, height: 14 } + } + } + match &*updates.read() { + Some(Some(list)) if list.is_empty() => rsx! { p { class: "target-muted", {tx::NO_UPDATES.get(lang)} } }, + Some(Some(list)) => rsx! { + div { class: "table-wrapper", + table { class: "cve-act-table", + thead { + tr { + th { {tx::COL_PACKAGE.get(lang)} } + th { {tx::COL_CURRENT.get(lang)} } + th { {tx::COL_FIXED.get(lang)} } + th { class: "num", {tx::COL_CVES.get(lang)} } + } + } + tbody { + for update in list.iter() { + tr { key: "{update.package}@{update.current_version}", + td { code { "{update.package}" } } + td { code { "{update.current_version}" } } + td { code { "{update.fixed_version}" } } + td { class: "num", + strong { "{update.cves}" } + if update.critical > 0 { + span { class: "cve-act-critical", {tx::of_them_critical(update.critical, lang)} } + } + } + } + } + } + } + } + }, + Some(None) => rsx! { p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } }, + None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn day(critical: u32, high: u32) -> CveDay { + CveDay { + critical, + high, + ..CveDay::default() + } + } + + #[test] + fn the_axis_top_is_even_and_not_below_the_highest_bar() { + assert_eq!(axis_top(0), 2); + assert_eq!(axis_top(1), 2); + assert_eq!(axis_top(3), 4); + assert_eq!(axis_top(7), 8); + assert_eq!(axis_top(11), 20); + assert_eq!(axis_top(41), 60); + assert_eq!(axis_top(1000), 1000); + assert_eq!(axis_top(u32::MAX), u32::MAX); + } + + #[test] + fn the_sparkline_spans_the_box_from_bottom_to_top() { + assert_eq!( + sparkline_points(&[0, 5, 10], 100.0, 24.0), + "0.0,23.0 50.0,12.0 100.0,1.0" + ); + // All zero: a flat line at the bottom, no division by zero. + assert_eq!( + sparkline_points(&[0, 0], 100.0, 24.0), + "0.0,23.0 100.0,23.0" + ); + assert_eq!(sparkline_points(&[3], 100.0, 24.0), "0.0,1.0"); + assert_eq!(sparkline_points(&[], 100.0, 24.0), ""); + } + + #[test] + fn the_change_is_the_last_day_against_the_first() { + let days = [day(4, 1), day(9, 9), day(2, 6)]; + assert_eq!(change(&days, |d| d.critical), -2); + assert_eq!(change(&days, |d| d.high), 5); + assert_eq!(change(&[], |d| d.high), 0); + } +} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index ed14e01..234813c 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -8,6 +8,7 @@ pub mod component_overview; pub mod copy_button; pub mod cra_bar; pub mod cve_matrix; +pub mod cve_trend; pub mod demo_targets; pub mod evidence_button; pub mod file_tree; diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 354d43c..8c06ec9 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -220,42 +220,6 @@ pub mod overview { de: "Prüfobjekte", en: "Targets", }; - pub const OPEN_FINDINGS: Text = Text { - de: "Offene Befunde", - en: "Open findings", - }; - pub const CRITICAL_LC: Text = Text { - de: "kritisch", - en: "critical", - }; - pub const HIGH_LC: Text = Text { - de: "hoch", - en: "high", - }; - pub const COMPONENTS: Text = Text { - de: "Komponenten", - en: "Components", - }; - pub const IN_SBOM: Text = Text { - de: "in der Stückliste", - en: "in the SBOM", - }; - pub const KNOWN_VULNS: Text = Text { - de: "Bekannte Schwachstellen", - en: "Known vulnerabilities", - }; - pub const IN_COMPONENTS: Text = Text { - de: "CVE in Komponenten", - en: "CVEs in components", - }; - pub const CRA_BY_TARGET: Text = Text { - de: "CRA-Stand je Prüfobjekt", - en: "CRA status by target", - }; - pub const CRA_BY_TARGET_HINT: Text = Text { - de: "Die 40 Anforderungen aus Anhang I; ein Klick öffnet den Stand im Einzelnen.", - en: "The 40 Annex I requirements; select a target for the details.", - }; pub const CRA_UNAVAILABLE: Text = Text { de: "Nicht auswertbar", en: "Not available", @@ -272,10 +236,6 @@ pub mod overview { de: "Keine offenen Befunde.", en: "No open findings.", }; - pub const ALL_TARGETS: Text = Text { - de: "Alle Prüfobjekte", - en: "All targets", - }; pub const ALL_FINDINGS: Text = Text { de: "Alle Befunde", en: "All findings", @@ -333,6 +293,204 @@ pub mod overview { }; } +/// The CVE trend charts and tiles of the overview and a target's page, and +/// the overview's targets by project (#952). +pub mod cve_trend { + use super::super::Lang; + use super::Text; + + pub const CVE_CRITICAL: Text = Text { + de: "Kritische CVE mit Fix", + en: "Critical CVEs with a fix", + }; + pub const CVE_HIGH: Text = Text { + de: "Hohe CVE mit Fix", + en: "High CVEs with a fix", + }; + pub const FINDINGS_CRITICAL: Text = Text { + de: "Kritische Befunde", + en: "Critical findings", + }; + pub const FINDINGS_HIGH: Text = Text { + de: "Hohe Befunde", + en: "High findings", + }; + pub const OPEN_NOW: Text = Text { + de: "offen", + en: "open", + }; + pub const CHART_TITLE: Text = Text { + de: "Offene CVE mit Fix", + en: "Open CVEs with a fix", + }; + pub const CHART_HINT: Text = Text { + de: "Kritisch und hoch, je Tag der letzten 30 Tage (UTC); jede CVE einmal \ + je Prüfobjekt, ohne die per VEX erledigten.", + en: "Critical and high per day over the last 30 days (UTC); each CVE once \ + per target, without those settled by VEX.", + }; + pub const CHART_LABEL: Text = Text { + de: "Balkendiagramm der offenen kritischen und hohen CVE mit Fix je Tag", + en: "Bar chart of the open critical and high CVEs with a fix per day", + }; + pub const LOAD_FAILED: Text = Text { + de: "Der CVE-Verlauf konnte nicht geladen werden.", + en: "The CVE history could not be loaded.", + }; + pub const BY_PROJECT: Text = Text { + de: "Prüfobjekte nach Projekt", + en: "Targets by project", + }; + pub const BY_PROJECT_HINT: Text = Text { + de: "Die Projekte aus dem Portal; ein Prüfobjekt in mehreren Projekten steht \ + unter jedem.", + en: "The projects from the portal; a target in several projects is shown \ + under each.", + }; + pub const NO_PROJECT: Text = Text { + de: "Ohne Projekt", + en: "No project", + }; + pub const WITH_FIX: Text = Text { + de: "CVE mit Fix", + en: "CVEs with a fix", + }; + pub const WHERE_TO_ACT: Text = Text { + de: "Wo handeln", + en: "Where to act", + }; + pub const WHERE_TO_ACT_HINT: Text = Text { + de: "Die Paket-Updates, die die meisten offenen CVE mit Fix schließen.", + en: "The package updates that close the most open CVEs with a fix.", + }; + pub const COL_PACKAGE: Text = Text { + de: "Paket", + en: "Package", + }; + pub const COL_CURRENT: Text = Text { + de: "Aktuell", + en: "Current", + }; + pub const COL_FIXED: Text = Text { + de: "Behoben in", + en: "Fixed in", + }; + pub const COL_CVES: Text = Text { + de: "Schließt CVE", + en: "Closes CVEs", + }; + pub const NO_UPDATES: Text = Text { + de: "Keine offenen CVE mit Fix.", + en: "No open CVEs with a fix.", + }; + pub const ALL_CVES: Text = Text { + de: "Alle Komponenten und CVE", + en: "All components and CVEs", + }; + + /// The change over the chart's `days` days: "+3 in 30 Tagen", + /// "−2 in 30 days", "unverändert in 30 Tagen". + pub fn change(delta: i64, days: usize, lang: Lang) -> String { + match (delta, lang) { + (0, Lang::De) => format!("unverändert in {days} Tagen"), + (0, Lang::En) => format!("unchanged in {days} days"), + (d, Lang::De) if d > 0 => format!("+{d} in {days} Tagen"), + (d, Lang::En) if d > 0 => format!("+{d} in {days} days"), + (d, Lang::De) => format!("\u{2212}{} in {days} Tagen", d.unsigned_abs()), + (d, Lang::En) => format!("\u{2212}{} in {days} days", d.unsigned_abs()), + } + } + + /// One bar's tooltip: "10.11.2026: 2 kritisch, 5 hoch", + /// "2026-11-10: 2 critical, 5 high". + pub fn bar_title(date: chrono::NaiveDate, critical: u32, high: u32, lang: Lang) -> String { + match lang { + Lang::De => format!( + "{}: {critical} kritisch, {high} hoch", + date.format("%d.%m.%Y") + ), + Lang::En => format!("{date}: {critical} critical, {high} high"), + } + } + + /// A project's summary: "3 Prüfobjekte · 12 offene CVE mit Fix". + pub fn project_summary(targets: usize, cves: u32, lang: Lang) -> String { + let targets = super::targets::count(targets as u64, lang); + match (lang, cves) { + (Lang::De, 1) => format!("{targets} · 1 offene CVE mit Fix"), + (Lang::De, n) => format!("{targets} · {n} offene CVE mit Fix"), + (Lang::En, 1) => format!("{targets} · 1 open CVE with a fix"), + (Lang::En, n) => format!("{targets} · {n} open CVEs with a fix"), + } + } + + /// The critical and high ones of a count: "2 kritisch · 5 hoch". + pub fn split(critical: u32, high: u32, lang: Lang) -> String { + match lang { + Lang::De => format!("{critical} kritisch · {high} hoch"), + Lang::En => format!("{critical} critical · {high} high"), + } + } + + /// The link under a project's first cards: "4 weitere Prüfobjekte". + pub fn more_targets(n: usize, lang: Lang) -> String { + match (lang, n) { + (Lang::De, 1) => "1 weiteres Prüfobjekt".to_string(), + (Lang::De, n) => format!("{n} weitere Prüfobjekte"), + (Lang::En, 1) => "1 more target".to_string(), + (Lang::En, n) => format!("{n} more targets"), + } + } + + /// The critical ones of an update's CVEs: "davon 2 kritisch". + pub fn of_them_critical(n: u32, lang: Lang) -> String { + match lang { + Lang::De => format!("davon {n} kritisch"), + Lang::En => format!("{n} critical"), + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn the_change_reads_like_the_language_with_a_real_minus() { + assert_eq!(change(3, 30, Lang::De), "+3 in 30 Tagen"); + assert_eq!(change(-2, 30, Lang::En), "\u{2212}2 in 30 days"); + assert_eq!(change(0, 30, Lang::De), "unverändert in 30 Tagen"); + } + + #[test] + fn a_bar_names_its_day_and_counts() { + let day = chrono::NaiveDate::from_ymd_opt(2026, 11, 10).unwrap(); + assert_eq!( + bar_title(day, 2, 5, Lang::De), + "10.11.2026: 2 kritisch, 5 hoch" + ); + assert_eq!( + bar_title(day, 2, 5, Lang::En), + "2026-11-10: 2 critical, 5 high" + ); + } + + #[test] + fn a_project_summary_counts_targets_and_cves() { + assert_eq!( + project_summary(3, 12, Lang::De), + "3 Prüfobjekte · 12 offene CVE mit Fix" + ); + assert_eq!( + project_summary(1, 1, Lang::En), + "1 target · 1 open CVE with a fix" + ); + assert_eq!(split(2, 5, Lang::En), "2 critical · 5 high"); + assert_eq!(more_targets(1, Lang::De), "1 weiteres Prüfobjekt"); + assert_eq!(more_targets(4, Lang::En), "4 more targets"); + } + } +} + /// Scan runs: status, phases and the stages a run did not execute. pub mod scans { use super::Text; diff --git a/compliance-dashboard/src/infrastructure/cve_history.rs b/compliance-dashboard/src/infrastructure/cve_history.rs new file mode 100644 index 0000000..c8ee647 --- /dev/null +++ b/compliance-dashboard/src/infrastructure/cve_history.rs @@ -0,0 +1,41 @@ +//! The open CVEs with a fix per day, and the updates that close the most of +//! a target's (#952). + +use compliance_core::cve_history::{CveHistory, TopUpdate}; +use dioxus::prelude::*; + +/// The last 30 days (`GET /api/v1/cve-history`): of one target when +/// `target` is not empty, else of the whole tenant; with every target's own +/// series when `per_target`. +#[server] +pub async fn fetch_cve_history( + target: String, + per_target: bool, +) -> Result { + let mut req = super::agent_client::agent_get("/api/v1/cve-history").await?; + if !target.is_empty() { + req = req.query(&[("target", target)]); + } + if per_target { + req = req.query(&[("per_target", "true")]); + } + let resp = req + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let body: serde_json::Value = super::agent_client::json_or_error(resp).await?; + serde_json::from_value(body["data"].clone()).map_err(|e| ServerFnError::new(e.to_string())) +} + +/// The updates that close the most of target `id`'s open CVEs with a fix +/// (`GET /api/v1/targets/{id}/top-updates`). +#[server] +pub async fn fetch_top_updates(id: String) -> Result, ServerFnError> { + let resp = super::agent_client::agent_get(&format!("/api/v1/targets/{id}/top-updates")) + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let body: serde_json::Value = super::agent_client::json_or_error(resp).await?; + serde_json::from_value(body["data"].clone()).map_err(|e| ServerFnError::new(e.to_string())) +} diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index 1bd5314..bfd8348 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -2,6 +2,7 @@ // the #[server] macro generates client stubs for the web target) pub mod auth_check; pub mod chat; +pub mod cve_history; pub mod cve_matrix; pub mod dast; pub mod download; diff --git a/compliance-dashboard/src/pages/overview.rs b/compliance-dashboard/src/pages/overview.rs index e220b34..d3a8e22 100644 --- a/compliance-dashboard/src/pages/overview.rs +++ b/compliance-dashboard/src/pages/overview.rs @@ -4,46 +4,77 @@ use dioxus_free_icons::Icon; use crate::app::Route; use crate::components::cra_bar::CraBar; +use crate::components::cve_trend::{CveDashboard, Sparkline}; use crate::components::page_header::PageHeader; use crate::components::severity_badge::SeverityBadge; -use crate::i18n::texts::{common, overview, scans as scan_texts}; +use crate::i18n::texts::{common, cve_trend, nav, overview, scans as scan_texts}; use crate::i18n::{format_ago, use_lang, Lang}; -use crate::infrastructure::evidence::{fetch_compliance_summary, ComplianceSummaryRow}; +use crate::infrastructure::cve_history::fetch_cve_history; +use crate::infrastructure::evidence::{fetch_compliance_summary, ComplianceSummaryRow, CraCounts}; use crate::infrastructure::findings::{fetch_findings, location, FindingsQuery}; use crate::infrastructure::mcp::fetch_mcp_servers; use crate::infrastructure::onboarding::fetch_targets; use crate::infrastructure::platform::use_source_only; +use crate::infrastructure::projects::{fetch_projects, project_ids_of}; use crate::infrastructure::stats::fetch_overview_stats; -use compliance_core::models::{ScanRun, ScanRunStatus}; +use compliance_core::cve_history::{CveDay, CveHistory}; +use compliance_core::models::{Project, ScanRun, ScanRunStatus}; /// Open findings the "Next up" list shows. const NEXT_UP: usize = 6; -/// Targets "CRA status by target" lists; the rest are on the targets page. -const TARGETS_SHOWN: usize = 8; +/// Target cards a project shows; the rest are on the targets page. +const CARDS_PER_PROJECT: usize = 6; -/// One target's line in "CRA status by target". +/// One target's card under its projects. #[derive(Debug, Clone, PartialEq)] struct TargetLine { id: String, name: String, target_type: String, - summary: Option, + /// Its CRA Annex I counts, `None` when the agent could not evaluate it. + counts: Option, /// The last scan's status, and when it finished (or started, if running). last_scan: Option<(ScanRunStatus, chrono::DateTime)>, + project_ids: Vec, + /// Today's open critical and high CVEs with a fix. + critical: u32, + high: u32, + /// Critical plus high per day, oldest first; empty without a history. + trend: Vec, } -/// The targets joined with their CRA counts, those with the most violated -/// requirements first, then by name. +impl TargetLine { + /// Today's open critical and high CVEs with a fix together. + fn urgent(&self) -> u32 { + self.critical + self.high + } +} + +/// The targets joined with their CRA counts and CVE trend: the most open +/// critical and high CVEs with a fix first, then the most violated +/// requirements, then by name. fn target_lines( targets: &[serde_json::Value], summary: &[ComplianceSummaryRow], + history: Option<&CveHistory>, ) -> Vec { let mut lines: Vec = targets .iter() .filter_map(|t| { let id = t.get("_id")?.get("$oid")?.as_str()?.to_string(); + let own = history.and_then(|h| h.targets.get(&id)); + let today = own.and_then(|s| s.last()).copied().unwrap_or_default(); + // A target without alerts in the window is flat at zero. + let trend = match (own, history) { + (Some(series), _) => series.iter().map(CveDay::urgent).collect(), + (None, Some(h)) => vec![0; h.days.len()], + (None, None) => Vec::new(), + }; Some(TargetLine { - summary: summary.iter().find(|s| s.target_id == id).cloned(), + counts: summary + .iter() + .find(|s| s.target_id == id) + .and_then(|s| s.counts), name: t.get("name")?.as_str()?.to_string(), target_type: t .get("target_type") @@ -55,24 +86,82 @@ fn target_lines( .filter(|r| !r.is_null()) .and_then(|r| serde_json::from_value::(r.clone()).ok()) .map(|run| (run.status, run.completed_at.unwrap_or(run.started_at))), + project_ids: project_ids_of(t), + critical: today.critical, + high: today.high, + trend, id, }) }) .collect(); - let violated = |l: &TargetLine| { - l.summary - .as_ref() - .and_then(|s| s.counts) - .map_or(0, |c| c.not_satisfied) - }; + let violated = |l: &TargetLine| l.counts.map_or(0, |c| c.not_satisfied); lines.sort_by(|a, b| { - violated(b) - .cmp(&violated(a)) + b.urgent() + .cmp(&a.urgent()) + .then_with(|| violated(b).cmp(&violated(a))) .then_with(|| a.name.cmp(&b.name)) }); lines } +/// The targets of one project, or (`project` `None`) those in none. +#[derive(Debug, Clone, PartialEq)] +struct ProjectGroup { + project: Option, + lines: Vec, +} + +impl ProjectGroup { + /// The project's critical plus high CVEs with a fix per day: the sum of + /// its targets' trends. + fn trend(&self) -> Vec { + let len = self.lines.iter().map(|l| l.trend.len()).max().unwrap_or(0); + let mut sum = vec![0; len]; + for line in &self.lines { + for (total, n) in sum.iter_mut().zip(&line.trend) { + *total += n; + } + } + sum + } + + /// Today's open critical and high CVEs with a fix of its targets. + fn urgent(&self) -> u32 { + self.lines.iter().map(TargetLine::urgent).sum() + } +} + +/// `lines` by project, in the registry's order, each in the order of +/// `lines`: a target in several projects under each, those in none (or +/// only in deleted ones) last. Projects without targets are left out. +fn group_by_project(lines: &[TargetLine], projects: &[Project]) -> Vec { + let in_project = |line: &TargetLine, id: &str| line.project_ids.iter().any(|p| p == id); + let mut groups: Vec = projects + .iter() + .map(|p| ProjectGroup { + project: Some(p.clone()), + lines: lines + .iter() + .filter(|l| in_project(l, &p.id)) + .cloned() + .collect(), + }) + .filter(|g| !g.lines.is_empty()) + .collect(); + let rest: Vec = lines + .iter() + .filter(|l| !projects.iter().any(|p| in_project(l, &p.id))) + .cloned() + .collect(); + if !rest.is_empty() { + groups.push(ProjectGroup { + project: None, + lines: rest, + }); + } + groups +} + #[component] pub fn OverviewPage() -> Element { let lang = use_lang()(); @@ -83,6 +172,8 @@ pub fn OverviewPage() -> Element { let stats = use_resource(|| async { fetch_overview_stats().await.ok() }); let targets = use_resource(|| async { fetch_targets().await.ok() }); let summary = use_resource(|| async { fetch_compliance_summary().await.ok() }); + let projects = use_resource(|| async { fetch_projects().await.ok() }); + let history = use_resource(|| async { fetch_cve_history(String::new(), true).await.ok() }); let next_up = use_resource(|| async { fetch_findings(FindingsQuery { page: 1, @@ -113,59 +204,35 @@ pub fn OverviewPage() -> Element { } } }, - Some(Some(s)) => rsx! { - div { class: "ov-figures", - Link { to: Route::TargetsPage {}, class: "ov-figure", - span { class: "ov-figure-label", {overview::TARGETS.get(lang)} } - span { class: "ov-figure-value", "{s.total_repositories}" } - } - Link { to: Route::findings(String::new()), class: "ov-figure", - span { class: "ov-figure-label", {overview::OPEN_FINDINGS.get(lang)} } - span { class: "ov-figure-value", "{s.total_findings}" } - span { class: "ov-figure-sub", - span { class: "sev-critical-text", "{s.critical_findings} {overview::CRITICAL_LC.get(lang)}" } - " · " - span { class: "sev-high-text", "{s.high_findings} {overview::HIGH_LC.get(lang)}" } - } - } - Link { to: Route::SbomPage { target: String::new() }, class: "ov-figure", - span { class: "ov-figure-label", {overview::COMPONENTS.get(lang)} } - span { class: "ov-figure-value", "{s.total_sbom_entries}" } - span { class: "ov-figure-sub", {overview::IN_SBOM.get(lang)} } - } - Link { to: Route::SbomPage { target: String::new() }, class: "ov-figure", - span { class: "ov-figure-label", {overview::KNOWN_VULNS.get(lang)} } - span { class: "ov-figure-value", "{s.total_cve_alerts}" } - span { class: "ov-figure-sub", {overview::IN_COMPONENTS.get(lang)} } - } + Some(Some(_)) => rsx! { + match history.read().clone() { + Some(Some(history)) => rsx! { CveDashboard { history, target: String::new() } }, + Some(None) => rsx! { div { class: "card", p { class: "ov-muted", {cve_trend::LOAD_FAILED.get(lang)} } } }, + None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, } div { class: "ov-grid", - section { class: "card ov-cra", + section { class: "card ov-projects", div { class: "ov-section-head", - h3 { {overview::CRA_BY_TARGET.get(lang)} } - p { {overview::CRA_BY_TARGET_HINT.get(lang)} } + h3 { {cve_trend::BY_PROJECT.get(lang)} } + p { {cve_trend::BY_PROJECT_HINT.get(lang)} } } - match (&*targets.read(), &*summary.read()) { - (Some(Some(t)), Some(rows)) => { - let lines = target_lines(&t.data, rows.as_deref().unwrap_or_default()); - let more = lines.len() > TARGETS_SHOWN; + match &*targets.read() { + Some(Some(t)) => { + let summary = summary.read().clone().flatten().unwrap_or_default(); + let projects = projects.read().clone().flatten().unwrap_or_default(); + let lines = target_lines(&t.data, &summary, history.read().as_ref().and_then(|h| h.as_ref())); + let groups = group_by_project(&lines, &projects); + // Without any project, the one group is every target. + let only = groups.len() == 1; rsx! { - ul { class: "ov-targets", - for line in lines.into_iter().take(TARGETS_SHOWN) { - TargetRow { line, lang } - } - } - if more { - Link { to: Route::TargetsPage {}, class: "ov-more", - {overview::ALL_TARGETS.get(lang)} - Icon { icon: BsArrowRight, width: 14, height: 14 } - } + for group in groups { + ProjectSection { key: "{group.project.as_ref().map(|p| p.id.as_str()).unwrap_or_default()}", group, only, lang } } } } - (Some(None), _) => rsx! { p { class: "ov-muted", {overview::LIST_LOAD_FAILED.get(lang)} } }, - _ => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, + Some(None) => rsx! { p { class: "ov-muted", {overview::LIST_LOAD_FAILED.get(lang)} } }, + None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, } } @@ -250,10 +317,49 @@ pub fn OverviewPage() -> Element { } } -/// One target in "CRA status by target": its name, its CRA bar and its last -/// scan; the name opens its CRA status. +/// One project's head (its name, how many targets and open CVEs with a fix, +/// its trend) and its first target cards; `only` when it is the one group, +/// then named after the targets rather than "Ohne Projekt". #[component] -fn TargetRow(line: TargetLine, lang: Lang) -> Element { +fn ProjectSection(group: ProjectGroup, only: bool, lang: Lang) -> Element { + let name = match (&group.project, only) { + (Some(project), _) => project.name.clone(), + (None, true) => overview::TARGETS.get(lang).to_string(), + (None, false) => cve_trend::NO_PROJECT.get(lang).to_string(), + }; + let summary = cve_trend::project_summary(group.lines.len(), group.urgent(), lang); + let trend = group.trend(); + let more = group.lines.len().saturating_sub(CARDS_PER_PROJECT); + rsx! { + div { class: "ov-project", + div { class: "ov-project-head", + div { class: "ov-project-title", + h4 { "{name}" } + span { "{summary}" } + } + if !trend.is_empty() { + Sparkline { values: trend, label: "{cve_trend::CHART_TITLE.get(lang)}: {name}" } + } + } + div { class: "repo-cards", + for line in group.lines.into_iter().take(CARDS_PER_PROJECT) { + RepoCard { key: "{line.id}", line, lang } + } + } + if more > 0 { + Link { to: Route::TargetsPage {}, class: "ov-more", + {cve_trend::more_targets(more, lang)} + Icon { icon: BsArrowRight, width: 14, height: 14 } + } + } + } + } +} + +/// One target's card: its open critical and high CVEs with a fix and their +/// trend, its CRA bar, its last scan, and the lists behind them. +#[component] +fn RepoCard(line: TargetLine, lang: Lang) -> Element { let now = chrono::Utc::now(); let scanned = line.last_scan.as_ref().map(|(status, when)| { let (badge, label) = crate::components::scan_runs::status_badge(status); @@ -264,26 +370,43 @@ fn TargetRow(line: TargetLine, lang: Lang) -> Element { *status == ScanRunStatus::Completed, ) }); + let split = cve_trend::split(line.critical, line.high, lang); rsx! { - li { class: "ov-target", - div { class: "ov-target-name", - Link { to: Route::CompliancePage { id: line.id.clone() }, "{line.name}" } + article { class: "repo-card", + div { class: "repo-card-name", + Link { to: Route::target(line.id.clone()), "{line.name}" } span { class: "ov-target-type", {crate::i18n::texts::kinds::target_type(&line.target_type, lang)} } } - div { class: "ov-target-bar", - match line.summary.as_ref().and_then(|s| s.counts) { - Some(counts) => rsx! { CraBar { counts, compact: true } }, - None => rsx! { span { class: "ov-muted", {overview::CRA_UNAVAILABLE.get(lang)} } }, + Link { to: Route::SbomPage { target: line.id.clone() }, class: "repo-card-cves", title: "{split}", + span { class: "repo-card-n", "{line.urgent()}" } + span { class: "repo-card-label", + {cve_trend::WITH_FIX.get(lang)} + span { class: "repo-card-split", "{split}" } + } + if !line.trend.is_empty() { + Sparkline { values: line.trend.clone(), label: "{cve_trend::CHART_TITLE.get(lang)}: {line.name}" } } } - div { class: "ov-target-scan", - match scanned { - Some((_, _, ago, true)) => rsx! { span { "{ago}" } }, - Some((badge, status, ago, false)) => rsx! { - span { class: "{badge}", "{status}" } - span { " {ago}" } - }, - None => rsx! { span { class: "ov-muted", {scan_texts::NEVER_SCANNED.get(lang)} } }, + Link { to: Route::CompliancePage { id: line.id.clone() }, class: "repo-card-cra", + match line.counts { + Some(counts) => rsx! { CraBar { counts, compact: true } }, + None => rsx! { span { class: "ov-target-type", {overview::CRA_UNAVAILABLE.get(lang)} } }, + } + } + div { class: "repo-card-foot", + span { class: "repo-card-scan", + match scanned { + Some((_, _, ago, true)) => rsx! { "{ago}" }, + Some((badge, status, ago, false)) => rsx! { + span { class: "{badge}", "{status}" } + " {ago}" + }, + None => rsx! { {scan_texts::NEVER_SCANNED.get(lang)} }, + } + } + span { class: "repo-card-links", + Link { to: Route::findings(line.id.clone()), {nav::FINDINGS.get(lang)} } + Link { to: Route::SbomPage { target: line.id.clone() }, {nav::SBOM.get(lang)} } } } } @@ -429,3 +552,104 @@ fn RuntimeSections() -> Element { } } } + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::models::ProjectKind; + + fn project(id: &str, name: &str) -> Project { + Project { + id: id.to_string(), + name: name.to_string(), + kind: ProjectKind::Product, + description: String::new(), + } + } + + fn target(id: &str, name: &str, projects: &[&str]) -> serde_json::Value { + serde_json::json!({ "_id": { "$oid": id }, "name": name, "project_ids": projects }) + } + + fn day(date: &str, critical: u32, high: u32) -> CveDay { + CveDay { + date: date.parse().unwrap(), + critical, + high, + ..CveDay::default() + } + } + + fn names(group: &ProjectGroup) -> Vec<&str> { + group.lines.iter().map(|l| l.name.as_str()).collect() + } + + #[test] + fn targets_with_open_cves_come_first_with_their_trend() { + let history = CveHistory { + days: vec![day("2026-11-09", 1, 0), day("2026-11-10", 1, 2)], + targets: [( + "b".to_string(), + vec![day("2026-11-09", 1, 0), day("2026-11-10", 1, 2)], + )] + .into(), + ..CveHistory::default() + }; + let targets = [target("a", "alpha", &[]), target("b", "beta", &[])]; + let lines = target_lines(&targets, &[], Some(&history)); + assert_eq!(lines[0].name, "beta"); + assert_eq!((lines[0].critical, lines[0].high), (1, 2)); + assert_eq!(lines[0].trend, [1, 3]); + // No alerts in the window: flat at zero over the same days. + assert_eq!(lines[1].trend, [0, 0]); + // Without a history: no trend at all. + assert!(target_lines(&targets, &[], None)[0].trend.is_empty()); + } + + #[test] + fn targets_are_grouped_by_project_with_those_in_none_last() { + let targets = [ + target("a", "alpha", &["p1", "p2"]), + target("b", "beta", &["p2"]), + target("c", "gamma", &["deleted"]), + target("d", "delta", &[]), + ]; + let lines = target_lines(&targets, &[], None); + let projects = [ + project("p1", "Lok"), + project("p2", "Steuerung"), + project("p3", "Leer"), + ]; + let groups = group_by_project(&lines, &projects); + let heads: Vec> = groups + .iter() + .map(|g| g.project.as_ref().map(|p| p.name.as_str())) + .collect(); + // The empty project is left out; a target in two projects is in both. + assert_eq!(heads, [Some("Lok"), Some("Steuerung"), None]); + assert_eq!(names(&groups[0]), ["alpha"]); + assert_eq!(names(&groups[1]), ["alpha", "beta"]); + assert_eq!(names(&groups[2]), ["delta", "gamma"]); + } + + #[test] + fn a_projects_trend_and_count_are_its_targets_summed() { + let line = |name: &str, critical, high, trend: Vec| TargetLine { + id: name.to_string(), + name: name.to_string(), + target_type: String::new(), + counts: None, + last_scan: None, + project_ids: Vec::new(), + critical, + high, + trend, + }; + let group = ProjectGroup { + project: Some(project("p1", "Lok")), + lines: vec![line("a", 1, 2, vec![1, 3]), line("b", 0, 4, vec![2, 4])], + }; + assert_eq!(group.trend(), [3, 7]); + assert_eq!(group.urgent(), 7); + } +} diff --git a/compliance-dashboard/src/pages/target.rs b/compliance-dashboard/src/pages/target.rs index 7d5f52d..1117a7d 100644 --- a/compliance-dashboard/src/pages/target.rs +++ b/compliance-dashboard/src/pages/target.rs @@ -11,6 +11,7 @@ use crate::components::artifact_upload::ArtifactUpload; use crate::components::billing_swap::BillingSwap; use crate::components::cra_bar::CraBar; use crate::components::cve_matrix::CveView; +use crate::components::cve_trend::TargetCveDashboard; use crate::components::evidence_button::EvidencePackButton; use crate::components::layer_pins::LayerPinsCard; use crate::components::manual_findings::ManualFindingsPanel; @@ -241,6 +242,9 @@ pub fn TargetPage(id: String, cve_severity: Option, cve_vex: Option