diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index 344bdc5..41a7d5d 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -23,6 +23,7 @@ pub mod platform; pub mod projects; pub use pentest_handlers as pentest; pub mod sbom; +pub mod sbom_ecosystems; pub mod scans; pub mod support; pub mod target_input; diff --git a/compliance-agent/src/api/handlers/sbom.rs b/compliance-agent/src/api/handlers/sbom.rs index 0aa9c57..569c35d 100644 --- a/compliance-agent/src/api/handlers/sbom.rs +++ b/compliance-agent/src/api/handlers/sbom.rs @@ -31,7 +31,7 @@ pub async fn sbom_filters( .unwrap_or_default() .into_iter() .filter_map(|v| v.as_str().map(|s| s.to_string())) - .filter(|s| !s.is_empty() && s != "unknown" && s != "file") + .filter(|s| compliance_core::sbom_ecosystems::is_filterable_manager(s)) .collect(); let licenses: Vec = db diff --git a/compliance-agent/src/api/handlers/sbom_ecosystems.rs b/compliance-agent/src/api/handlers/sbom_ecosystems.rs new file mode 100644 index 0000000..674217c --- /dev/null +++ b/compliance-agent/src/api/handlers/sbom_ecosystems.rs @@ -0,0 +1,131 @@ +//! GET /api/v1/targets/{id}/sbom-ecosystems: a target's SBOM components per +//! ecosystem, and how many of them have a known vulnerability (#957). + +use axum::extract::{Extension, Path}; +use axum::http::StatusCode; +use axum::Json; +use futures_util::TryStreamExt; +use mongodb::bson::{doc, Document}; +use serde::Deserialize; + +use super::dto::{tenant_db, AgentExt, ApiResponse, ApiResult}; +use compliance_core::sbom_ecosystems::{rank, EcosystemCount}; +use compliance_core::tenant_ctx::TenantCtx; + +/// One row of [`pipeline`]: a package manager with its counts. `_id` is +/// `None` for components stored without one. +#[derive(Debug, Deserialize)] +struct EcosystemRow { + #[serde(rename = "_id")] + package_manager: Option, + components: u64, + with_cve: u64, +} + +impl From for EcosystemCount { + fn from(row: EcosystemRow) -> Self { + Self { + package_manager: row.package_manager.unwrap_or_default(), + components: row.components, + with_cve: row.with_cve, + } + } +} + +/// The aggregation counting the components of target `repo_id` per package +/// manager in the database, so only one row per ecosystem leaves it (never +/// the components with their vulnerability lists, #67). +fn pipeline(repo_id: &str) -> Vec { + vec![ + doc! { "$match": { "repo_id": repo_id } }, + doc! { "$group": { + "_id": "$package_manager", + "components": { "$sum": 1 }, + // A component stored without the list counts as without a CVE. + "with_cve": { "$sum": { "$cond": [ + { "$gt": [{ "$size": { "$ifNull": ["$known_vulnerabilities", []] } }, 0] }, + 1, + 0, + ] } }, + } }, + ] +} + +/// GET /api/v1/targets/{id}/sbom-ecosystems — the SBOM components of target +/// `id` per ecosystem the component table can filter by, the largest first. +/// +/// # Errors +/// +/// `500` when the aggregation fails, so the dashboard says so instead of +/// showing an empty chart. +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn list_sbom_ecosystems( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> ApiResult> { + let db = tenant_db(&agent, &tenant).await?; + let fail = |e: mongodb::error::Error| { + tracing::warn!("Failed to count the SBOM ecosystems: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + }; + let rows: Vec = db + .sbom_entries() + .aggregate(pipeline(&id)) + .await + .map_err(fail)? + .try_collect() + .await + .map_err(fail)?; + let counts = rows + .into_iter() + .filter_map(|row| mongodb::bson::from_document::(row).ok()) + .map(EcosystemCount::from) + .collect(); + let ecosystems = rank(counts); + Ok(Json(ApiResponse { + total: Some(ecosystems.len() as u64), + data: ecosystems, + page: None, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pipeline_counts_one_target_per_package_manager() { + let stages = pipeline("t1"); + assert_eq!(stages.len(), 2); + assert_eq!(stages[0], doc! { "$match": { "repo_id": "t1" } }); + let group = stages[1].get_document("$group").expect("a $group stage"); + assert_eq!(group.get_str("_id").ok(), Some("$package_manager")); + assert_eq!( + group.get_document("components").ok(), + Some(&doc! { "$sum": 1 }) + ); + assert!(group.contains_key("with_cve")); + } + + #[test] + fn a_row_reads_as_its_count_whatever_integer_width_mongo_sums_in() { + let row: EcosystemRow = mongodb::bson::from_document( + doc! { "_id": "npm", "components": 412_i32, "with_cve": 7_i64 }, + ) + .expect("a row"); + assert_eq!( + EcosystemCount::from(row), + EcosystemCount { + package_manager: "npm".into(), + components: 412, + with_cve: 7, + } + ); + let nameless: EcosystemRow = mongodb::bson::from_document( + doc! { "_id": null, "components": 2_i32, "with_cve": 0_i32 }, + ) + .expect("a row without a package manager"); + assert_eq!(EcosystemCount::from(nameless).package_manager, ""); + } +} diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 8045e1e..e066373 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -126,6 +126,11 @@ pub fn build_router() -> Router { "/api/v1/targets/{id}/cve-groups/vex", patch(handlers::vex::set_group_vex), ) + // The target's SBOM components per ecosystem (#957). + .route( + "/api/v1/targets/{id}/sbom-ecosystems", + get(handlers::sbom_ecosystems::list_sbom_ecosystems), + ) .route( "/api/v1/targets/{id}/evidence-pack", get(handlers::evidence::evidence_pack), diff --git a/compliance-core/src/lib.rs b/compliance-core/src/lib.rs index d539415..4f706f6 100644 --- a/compliance-core/src/lib.rs +++ b/compliance-core/src/lib.rs @@ -16,6 +16,7 @@ pub mod models; pub mod net_guard; pub mod purl; pub mod sbom_docs; +pub mod sbom_ecosystems; pub mod scan_matrix; pub mod spdx_license; #[cfg(feature = "telemetry")] diff --git a/compliance-core/src/sbom_ecosystems.rs b/compliance-core/src/sbom_ecosystems.rs new file mode 100644 index 0000000..5986cd7 --- /dev/null +++ b/compliance-core/src/sbom_ecosystems.rs @@ -0,0 +1,109 @@ +//! A target's SBOM components counted per ecosystem (package manager), and +//! how many of them carry a known vulnerability (#957): the "Komponenten nach +//! Ökosystem" chart, each bar opening the component table filtered to it. + +use serde::{Deserialize, Serialize}; + +/// The components of one ecosystem in a target's SBOM. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct EcosystemCount { + /// The package manager as the SBOM names it (`npm`, `cargo`), the value + /// the component table's package-manager filter takes. + pub package_manager: String, + /// How many components it has. + pub components: u64, + /// How many of them have at least one known vulnerability. + pub with_cve: u64, +} + +/// Whether `package_manager` names an ecosystem the component table can be +/// filtered by: not empty, and neither `unknown` nor `file` (a component +/// found as a file, not from a manifest). +pub fn is_filterable_manager(package_manager: &str) -> bool { + !package_manager.is_empty() && package_manager != "unknown" && package_manager != "file" +} + +/// The filterable ecosystems of `counts`, the one with the most components +/// first (then by name, so equal counts keep a stable order). +/// +/// # Examples +/// +/// ``` +/// use compliance_core::sbom_ecosystems::{rank, EcosystemCount}; +/// +/// let count = |pm: &str, components| EcosystemCount { +/// package_manager: pm.into(), +/// components, +/// with_cve: 0, +/// }; +/// let ranked = rank(vec![count("cargo", 3), count("file", 9), count("npm", 12)]); +/// assert_eq!(ranked, [count("npm", 12), count("cargo", 3)]); +/// ``` +pub fn rank(counts: Vec) -> Vec { + let mut ranked: Vec = counts + .into_iter() + .filter(|c| is_filterable_manager(&c.package_manager)) + .collect(); + // `sort_unstable_by` is fine: the name breaks every tie, as one + // aggregation yields each package manager once. + ranked.sort_unstable_by(|a, b| { + b.components + .cmp(&a.components) + .then_with(|| a.package_manager.cmp(&b.package_manager)) + }); + ranked +} + +#[cfg(test)] +mod tests { + use super::*; + + fn count(package_manager: &str, components: u64, with_cve: u64) -> EcosystemCount { + EcosystemCount { + package_manager: package_manager.into(), + components, + with_cve, + } + } + + #[test] + fn the_largest_ecosystem_comes_first_then_by_name() { + let ranked = rank(vec![ + count("pip", 4, 0), + count("npm", 412, 7), + count("cargo", 4, 1), + ]); + assert_eq!( + ranked, + [ + count("npm", 412, 7), + count("cargo", 4, 1), + count("pip", 4, 0) + ] + ); + } + + #[test] + fn what_the_table_cannot_filter_by_is_left_out() { + assert!(rank(vec![ + count("", 2, 0), + count("unknown", 5, 1), + count("file", 3, 0) + ]) + .is_empty()); + assert!(is_filterable_manager("nuget")); + assert!(!is_filterable_manager("file")); + } + + #[test] + fn a_count_names_its_fields_on_the_wire() { + assert_eq!( + serde_json::to_value(count("npm", 12, 3)).ok(), + Some(serde_json::json!({ + "package_manager": "npm", + "components": 12, + "with_cve": 3, + })) + ); + } +} diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index d9ddc18..ba703e7 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -6094,3 +6094,160 @@ input[type="file"] { .license-policy-forbid { border-left: 3px solid var(--danger); } + +/* The components view of one target (#957): updates by the CVEs they + remove and components per ecosystem, as horizontal bars (one series, + one hue in both themes). */ +.co-view { + --co-bar: #2a78d6; + margin-bottom: 16px; +} + +.co-toggle { + display: inline-flex; + gap: 2px; + padding: 2px; + margin-bottom: 10px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--bg-elevated); +} + +.co-toggle-btn { + padding: 4px 12px; + border: none; + border-radius: var(--radius-sm); + background: none; + color: var(--text-secondary); + font-size: 13px; + cursor: pointer; +} + +.co-toggle-btn.active { + background: var(--bg-card); + color: var(--text-primary); + box-shadow: var(--shadow-pop); +} + +.co-charts { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 380px), 1fr)); + gap: 12px; +} + +.co-chart { + margin-bottom: 0; + min-width: 0; +} + +.co-chart-title { + margin: 0; + font-family: var(--font-display); + font-size: 15px; + font-weight: 600; +} + +.co-chart-hint { + margin: 2px 0 12px; + color: var(--text-tertiary); + font-size: 12.5px; +} + +.co-bars { + display: grid; + gap: 2px; + margin: 0; + padding: 0; + list-style: none; +} + +.co-bar { + display: grid; + grid-template-columns: minmax(0, 2fr) minmax(0, 3fr) auto; + gap: 10px; + align-items: center; + width: 100%; + padding: 4px 6px; + border: none; + border-radius: var(--radius-sm); + background: none; + color: var(--text-primary); + font: inherit; + font-size: 13px; + text-align: left; + cursor: pointer; +} + +.co-bar:hover, +.co-bar:focus-visible { + background: var(--bg-card-hover); +} + +.co-bar-label { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.co-bar-track { + display: block; + height: 16px; +} + +.co-bar-fill { + display: block; + height: 100%; + border-radius: 0 4px 4px 0; + background: var(--co-bar); +} + +.co-bar:hover .co-bar-fill { + filter: brightness(1.1); +} + +.co-bar-value { + color: var(--text-secondary); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.co-more { + margin-top: 8px; +} + +.co-table .co-num { + text-align: right; + font-variant-numeric: tabular-nums; +} + +.co-link { + padding: 0; + border: none; + background: none; + color: var(--accent); + font: inherit; + text-align: left; + cursor: pointer; +} + +.co-link:hover { + text-decoration: underline; +} + +.co-breadcrumb { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px 8px; + margin-bottom: 12px; + font-size: 14px; +} + +.co-breadcrumb-root, +.co-breadcrumb-sep { + color: var(--text-tertiary); +} + +.co-back { + margin-left: auto; +} diff --git a/compliance-dashboard/src/app.rs b/compliance-dashboard/src/app.rs index 4add56e..cbf6520 100644 --- a/compliance-dashboard/src/app.rs +++ b/compliance-dashboard/src/app.rs @@ -26,6 +26,10 @@ pub enum Route { // `?target=` opens the list filtered to one target. #[route("/sbom?:target")] SbomPage { target: String }, + // The SBOM page with its component table filtered to one ecosystem, + // opened from the components view (#957). + #[route("/sbom/ecosystem/:ecosystem?:target", SbomPage)] + SbomEcosystemPage { ecosystem: String, target: String }, #[route("/issues")] IssuesPage {}, // The code graph opens from its card on the target page. @@ -99,4 +103,21 @@ mod tests { Ok(Route::SbomPage { target }) if target.is_empty() )); } + + #[test] + fn an_ecosystem_of_the_sbom_page_is_in_its_url() { + let filtered = Route::SbomEcosystemPage { + ecosystem: "npm".to_string(), + target: "665f1c2ab0c4d1e2f3a4b5c6".to_string(), + }; + assert_eq!( + filtered.to_string(), + "/sbom/ecosystem/npm?target=665f1c2ab0c4d1e2f3a4b5c6" + ); + assert!(matches!( + Route::from_str("/sbom/ecosystem/cargo?target=665f"), + Ok(Route::SbomEcosystemPage { ecosystem, target }) + if ecosystem == "cargo" && target == "665f" + )); + } } diff --git a/compliance-dashboard/src/components/component_overview.rs b/compliance-dashboard/src/components/component_overview.rs new file mode 100644 index 0000000..aeae282 --- /dev/null +++ b/compliance-dashboard/src/components/component_overview.rs @@ -0,0 +1,451 @@ +//! The "Komponenten" view of one target (#957), at the top of the SBOM +//! page's component tab: which update removes the most CVEs (from the CVE +//! groups of #949) and the components per ecosystem, as horizontal bars. +//! An update bar opens that component's CVE group card in place; an +//! ecosystem bar filters the component table below to it. "Tabelle" shows +//! the same numbers as plain tables. + +use std::collections::HashSet; + +use dioxus::prelude::*; + +use compliance_core::cve_groups::{CveGroup, PackageKey}; +use compliance_core::models::CveAlert; +use compliance_core::sbom_ecosystems::EcosystemCount; + +use crate::components::severity_badge::SeverityBadge; +use crate::components::vex_panel::CveGroupCard; +use crate::i18n::texts::{common, component_overview as tx}; +use crate::i18n::{format_count, use_lang}; +use crate::infrastructure::sbom_ecosystems::fetch_sbom_ecosystems; +use crate::infrastructure::vex::{fetch_cve_groups, fetch_enisa_candidates, fetch_target_cves}; +use crate::pages::sbom::pm_display_name; + +/// How many update bars show before "Alle anzeigen". +const TOP_UPDATES: usize = 10; + +/// The CVE groups an update helps with, the one removing the most CVEs +/// first (then the most severe, then by component). The groups and their +/// counts are #949's; this only filters and orders them. +pub fn rank_updates(groups: &[CveGroup]) -> Vec<&CveGroup> { + let mut ranked: Vec<&CveGroup> = groups + .iter() + .filter(|g| g.fix_version.is_some() && g.fixable > 0) + .collect(); + ranked.sort_unstable_by(|a, b| { + b.fixable + .cmp(&a.fixable) + .then_with(|| b.counts.max().cmp(&a.counts.max())) + .then_with(|| a.key.cmp(&b.key)) + }); + ranked +} + +/// An update's label: `openssl 3.0.11 → 3.0.15`. +fn update_label(group: &CveGroup) -> String { + let fix = group.fix_version.as_deref().unwrap_or_default(); + format!("{} {} → {fix}", group.key.package, group.key.version) +} + +/// The width of a bar of `value` against the largest one, `max`, as a CSS +/// percentage (at least a sliver, so a small bar stays visible). +fn bar_width(value: u64, max: u64) -> String { + // Lossy `as f64` is fine: counts this large do not exist, and the result + // is a CSS width. + let percent = if max == 0 { + 0.0 + } else { + value as f64 * 100.0 / max as f64 + }; + format!("width: {:.1}%", percent.max(2.0)) +} + +/// The "Komponenten" overview of target `target_id`. `ecosystem` is the +/// component table's package-manager filter; `on_ecosystem` sets it (an +/// empty name clears it). +#[component] +pub fn ComponentOverview( + target_id: ReadSignal, + ecosystem: String, + on_ecosystem: EventHandler, +) -> Element { + let lang = use_lang()(); + let mut groups = use_resource(move || async move { fetch_cve_groups(target_id()).await.ok() }); + let ecosystems = + use_resource(move || async move { fetch_sbom_ecosystems(target_id()).await.ok() }); + let mut as_table = use_signal(|| false); + let mut opened = use_signal(|| Option::::None); + // Another target picked on the page closes the open group card. + use_effect(move || { + target_id(); + opened.set(None); + }); + + if let Some(key) = opened() { + let open_group = groups + .read() + .as_ref() + .and_then(|found| found.as_ref()) + .and_then(|found| found.iter().find(|g| g.key == key).cloned()); + return rsx! { + div { class: "co-view", + Breadcrumb { + selection: format!("{} {}", key.package, key.version), + on_back: move |()| opened.set(None), + } + match open_group { + Some(group) => rsx! { + OpenGroup { + target_id, + group, + on_saved: move |()| groups.restart(), + } + }, + None if groups.read().is_none() => rsx! { + div { class: "loading", {common::LOADING.get(lang)} } + }, + None => rsx! { p { class: "target-muted", {tx::GROUP_SETTLED.get(lang)} } }, + } + } + }; + } + if !ecosystem.is_empty() { + return rsx! { + div { class: "co-view", + Breadcrumb { + selection: pm_display_name(&ecosystem).to_string(), + on_back: move |()| on_ecosystem.call(String::new()), + } + } + }; + } + + rsx! { + div { class: "co-view", + div { class: "co-toggle", role: "group", + for (table, label) in [(false, tx::VIEW_CHART), (true, tx::VIEW_TABLE)] { + button { + class: if as_table() == table { "co-toggle-btn active" } else { "co-toggle-btn" }, + "aria-pressed": if as_table() == table { "true" } else { "false" }, + onclick: move |_| as_table.set(table), + {label.get(lang)} + } + } + } + div { class: "co-charts", + section { class: "card co-chart", + h3 { class: "co-chart-title", {tx::UPDATES_TITLE.get(lang)} } + p { class: "co-chart-hint", {tx::UPDATES_HINT.get(lang)} } + match &*groups.read() { + None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, + Some(None) => rsx! { p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } }, + Some(Some(found)) => rsx! { + UpdateBars { + groups: found.clone(), + as_table: as_table(), + on_open: move |key: PackageKey| opened.set(Some(key)), + } + }, + } + } + section { class: "card co-chart", + h3 { class: "co-chart-title", {tx::ECOSYSTEMS_TITLE.get(lang)} } + p { class: "co-chart-hint", {tx::ECOSYSTEMS_HINT.get(lang)} } + match &*ecosystems.read() { + None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, + Some(None) => rsx! { p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } }, + Some(Some(found)) if found.is_empty() => rsx! { + p { class: "target-muted", {tx::NO_ECOSYSTEMS.get(lang)} } + }, + Some(Some(found)) => rsx! { + EcosystemBars { ecosystems: found.clone(), as_table: as_table(), on_ecosystem } + }, + } + } + } + } + } +} + +/// "Komponenten › `selection`" with the way back to the charts. +#[component] +fn Breadcrumb(selection: String, on_back: EventHandler<()>) -> Element { + let lang = use_lang()(); + rsx! { + nav { class: "co-breadcrumb", "aria-label": tx::BREADCRUMB.get(lang), + span { class: "co-breadcrumb-root", {tx::BREADCRUMB.get(lang)} } + span { class: "co-breadcrumb-sep", "aria-hidden": "true", "›" } + strong { "{selection}" } + button { + class: "btn btn-ghost btn-sm co-back", + onclick: move |_| on_back.call(()), + {tx::BACK.get(lang)} + } + } + } +} + +/// The update bars (or their table) of `groups`, the top 10 until "Alle +/// anzeigen"; `on_open` receives the component of a clicked bar. +#[component] +fn UpdateBars(groups: Vec, as_table: bool, on_open: EventHandler) -> Element { + let lang = use_lang()(); + let mut show_all = use_signal(|| false); + let ranked = rank_updates(&groups); + if ranked.is_empty() { + return rsx! { p { class: "target-muted", {tx::NO_UPDATES.get(lang)} } }; + } + let total = ranked.len(); + let shown = if show_all() { + total + } else { + total.min(TOP_UPDATES) + }; + let max = ranked.first().map_or(0, |g| g.fixable as u64); + rsx! { + if as_table { + div { class: "table-wrapper", + table { class: "co-table", + thead { + tr { + th { {tx::COL_UPDATE.get(lang)} } + th { class: "co-num", {tx::COL_REMOVES.get(lang)} } + th { {tx::COL_SEVERITY.get(lang)} } + } + } + tbody { + for group in ranked.iter().take(shown) { + { + let label = update_label(group); + let key = group.key.clone(); + rsx! { + tr { + td { + button { + class: "co-link", + "aria-label": tx::update_action(&label, group.fixable, lang), + onclick: move |_| on_open.call(key.clone()), + "{label}" + } + } + td { class: "co-num", {tx::removes(group.fixable)} } + td { SeverityBadge { severity: group.counts.max().as_str().to_string() } } + } + } + } + } + } + } + } + } else { + ol { class: "co-bars", + for group in ranked.iter().take(shown) { + { + let label = update_label(group); + let action = tx::update_action(&label, group.fixable, lang); + let key = group.key.clone(); + rsx! { + li { + button { + class: "co-bar", + "aria-label": "{action}", + title: "{action}", + onclick: move |_| on_open.call(key.clone()), + span { class: "co-bar-label", "{label}" } + span { class: "co-bar-track", + span { class: "co-bar-fill", style: bar_width(group.fixable as u64, max) } + } + span { class: "co-bar-value", {tx::removes(group.fixable)} } + } + } + } + } + } + } + } + if total > TOP_UPDATES { + button { + class: "btn btn-ghost btn-sm co-more", + "aria-expanded": if show_all() { "true" } else { "false" }, + onclick: move |_| show_all.toggle(), + if show_all() { {tx::TOP_ONLY.get(lang)} } else { {tx::show_all(total, lang)} } + } + } + } +} + +/// The ecosystem bars (or their table) of `ecosystems`; a click sends the +/// package manager to `on_ecosystem`. +#[component] +fn EcosystemBars( + ecosystems: Vec, + as_table: bool, + on_ecosystem: EventHandler, +) -> Element { + let lang = use_lang()(); + let max = ecosystems.iter().map(|e| e.components).max().unwrap_or(0); + rsx! { + if as_table { + div { class: "table-wrapper", + table { class: "co-table", + thead { + tr { + th { {tx::COL_ECOSYSTEM.get(lang)} } + th { class: "co-num", {tx::COL_COMPONENTS.get(lang)} } + th { class: "co-num", {tx::COL_WITH_CVE.get(lang)} } + } + } + tbody { + for count in ecosystems.iter() { + { + let name = pm_display_name(&count.package_manager); + let action = tx::ecosystem_action(name, count.components, count.with_cve, lang); + let manager = count.package_manager.clone(); + rsx! { + tr { + td { + button { + class: "co-link", + "aria-label": "{action}", + onclick: move |_| on_ecosystem.call(manager.clone()), + "{name}" + } + } + td { class: "co-num", {format_count(count.components, lang)} } + td { class: "co-num", {format_count(count.with_cve, lang)} } + } + } + } + } + } + } + } + } else { + ol { class: "co-bars", + for count in ecosystems.iter() { + { + let name = pm_display_name(&count.package_manager); + let action = tx::ecosystem_action(name, count.components, count.with_cve, lang); + let manager = count.package_manager.clone(); + rsx! { + li { + button { + class: "co-bar", + "aria-label": "{action}", + title: "{action}", + onclick: move |_| on_ecosystem.call(manager.clone()), + span { class: "co-bar-label", "{name}" } + span { class: "co-bar-track", + span { class: "co-bar-fill", style: bar_width(count.components, max) } + } + span { class: "co-bar-value", + {tx::ecosystem_value(count.components, count.with_cve, lang)} + } + } + } + } + } + } + } + } + } +} + +/// The CVE group card of #949 for `group`, with its alerts and the CRA +/// Article 14 candidates it needs, loaded when it opens. +#[component] +fn OpenGroup( + target_id: ReadSignal, + group: CveGroup, + on_saved: EventHandler<()>, +) -> Element { + let lang = use_lang()(); + let mut alerts = use_resource(move || async move { fetch_target_cves(target_id()).await.ok() }); + let mut enisa = use_resource(move || async move { + fetch_enisa_candidates(target_id()) + .await + .unwrap_or_default() + }); + let ids: HashSet<&str> = group.alert_ids.iter().map(String::as_str).collect(); + let members: Option> = alerts.read().as_ref().map(|loaded| { + loaded + .iter() + .flatten() + .filter(|a| a.id.is_some_and(|id| ids.contains(id.to_hex().as_str()))) + .cloned() + .collect() + }); + let candidates = enisa.read().clone().unwrap_or_default(); + match members { + None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, + Some(members) => rsx! { + CveGroupCard { + target_id: target_id(), + group, + alerts: members, + candidates, + on_saved: move |()| { + alerts.restart(); + enisa.restart(); + on_saved.call(()); + }, + } + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::cve_groups::SeverityCounts; + + fn group(package: &str, fixable: usize, fix: Option<&str>, counts: SeverityCounts) -> CveGroup { + CveGroup { + key: PackageKey { + package: package.into(), + version: "1.0.0".into(), + purl: None, + }, + fix_version: fix.map(String::from), + fixable, + counts, + kev: false, + epss_max: None, + cve_ids: Vec::new(), + alert_ids: Vec::new(), + } + } + + #[test] + fn updates_rank_by_the_cves_they_remove_then_by_severity() { + let high = SeverityCounts { + high: 1, + ..SeverityCounts::default() + }; + let low = SeverityCounts { + low: 1, + ..SeverityCounts::default() + }; + let groups = vec![ + group("lodash", 1, Some("4.17.21"), low), + group("vite", 3, Some("8.3.3"), low), + group("openssl", 1, Some("3.0.15"), high), + // No fix named: no update to rank. + group("left-pad", 0, None, high), + ]; + let ranked: Vec<&str> = rank_updates(&groups) + .iter() + .map(|g| g.key.package.as_str()) + .collect(); + assert_eq!(ranked, ["vite", "openssl", "lodash"]); + assert_eq!(update_label(&groups[1]), "vite 1.0.0 → 8.3.3"); + } + + #[test] + fn a_bar_is_as_wide_as_its_share_of_the_largest() { + assert_eq!(bar_width(3, 3), "width: 100.0%"); + assert_eq!(bar_width(1, 4), "width: 25.0%"); + assert_eq!(bar_width(1, 1000), "width: 2.0%"); + assert_eq!(bar_width(0, 0), "width: 2.0%"); + } +} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index a20aa3b..d79e12c 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -4,6 +4,7 @@ pub mod attack_chain; pub mod billing_swap; pub mod code_inspector; pub mod code_snippet; +pub mod component_overview; pub mod copy_button; pub mod cra_bar; pub mod demo_targets; diff --git a/compliance-dashboard/src/components/sidebar.rs b/compliance-dashboard/src/components/sidebar.rs index d61e224..fb8c25e 100644 --- a/compliance-dashboard/src/components/sidebar.rs +++ b/compliance-dashboard/src/components/sidebar.rs @@ -163,6 +163,7 @@ pub fn Sidebar() -> Element { let is_active = match (¤t_route, &item.route) { (Route::FindingDetailPage { .. } | Route::FindingsPage { .. }, Route::FindingsPage { .. }) => true, (Route::SbomPage { .. }, Route::SbomPage { .. }) => true, + (Route::SbomEcosystemPage { .. }, Route::SbomPage { .. }) => true, (Route::CompliancePage { .. }, Route::TargetsPage {}) => true, (Route::DastTargetsPage {}, Route::DastOverviewPage {}) => true, (Route::DastFindingsPage {}, Route::DastOverviewPage {}) => true, diff --git a/compliance-dashboard/src/components/vex_panel.rs b/compliance-dashboard/src/components/vex_panel.rs index 02b9b84..0a45376 100644 --- a/compliance-dashboard/src/components/vex_panel.rs +++ b/compliance-dashboard/src/components/vex_panel.rs @@ -232,7 +232,7 @@ fn CveGroups( /// One component's open CVEs: what updating it fixes, the decision for all of /// them, and the CVEs themselves on demand. #[component] -fn CveGroupCard( +pub fn CveGroupCard( target_id: String, group: CveGroup, alerts: Vec, diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 70ecfd1..5d88c6a 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -5135,3 +5135,165 @@ pub mod graph { } } } + +/// The "Komponenten" view of one target (#957): which update removes the +/// most CVEs, and the components per ecosystem, each bar opening what it +/// counts. +pub mod component_overview { + use super::super::{format_count, Lang}; + use super::Text; + + pub const UPDATES_TITLE: Text = Text { + de: "Welches Update entfernt die meisten CVEs", + en: "Which update removes the most CVEs", + }; + pub const UPDATES_HINT: Text = Text { + de: "Je Komponente das Update auf die höchste behobene Version und wie viele offene CVEs es behebt. Ein Klick öffnet die CVE-Gruppe.", + en: "Per component, the update to the highest fixed version and how many open CVEs it fixes. A click opens the CVE group.", + }; + pub const ECOSYSTEMS_TITLE: Text = Text { + de: "Komponenten nach Ökosystem", + en: "Components by ecosystem", + }; + pub const ECOSYSTEMS_HINT: Text = Text { + de: "Je Paketmanager die Komponenten der Stückliste. Ein Klick zeigt sie in der Tabelle.", + en: "Per package manager, the components of the SBOM. A click shows them in the table.", + }; + pub const VIEW_CHART: Text = Text { + de: "Diagramm", + en: "Chart", + }; + pub const VIEW_TABLE: Text = Text { + de: "Tabelle", + en: "Table", + }; + pub const BREADCRUMB: Text = Text { + de: "Komponenten", + en: "Components", + }; + pub const BACK: Text = Text { + de: "← Zurück zum Diagramm", + en: "← Back to the chart", + }; + pub const TOP_ONLY: Text = Text { + de: "Nur die 10 größten", + en: "Top 10 only", + }; + pub const NO_UPDATES: Text = Text { + de: "Kein Update behebt eine offene CVE.", + en: "No update fixes an open CVE.", + }; + pub const NO_ECOSYSTEMS: Text = Text { + de: "Die Stückliste nennt keine Komponente mit Paketmanager.", + en: "The SBOM names no component with a package manager.", + }; + pub const LOAD_FAILED: Text = Text { + de: "Konnte nicht geladen werden.", + en: "Could not be loaded.", + }; + pub const GROUP_SETTLED: Text = Text { + de: "Diese Komponente hat keine offene CVE mehr.", + en: "This component has no open CVE left.", + }; + pub const COL_UPDATE: Text = Text { + de: "Update", + en: "Update", + }; + pub const COL_REMOVES: Text = Text { + de: "Entfernt", + en: "Removes", + }; + pub const COL_SEVERITY: Text = Text { + de: "Höchste Schwere", + en: "Highest severity", + }; + pub const COL_ECOSYSTEM: Text = Text { + de: "Ökosystem", + en: "Ecosystem", + }; + pub const COL_COMPONENTS: Text = Text { + de: "Komponenten", + en: "Components", + }; + pub const COL_WITH_CVE: Text = Text { + de: "Mit CVE", + en: "With a CVE", + }; + + /// The CVEs an update removes, as its bar's value: `−3 CVEs`, `−1 CVE`. + pub fn removes(count: usize) -> String { + let cves = if count == 1 { "CVE" } else { "CVEs" }; + format!("−{count} {cves}") + } + + /// The "alle anzeigen" button under the top 10: `Alle anzeigen (23)`. + pub fn show_all(count: usize, lang: Lang) -> String { + match lang { + Lang::De => format!("Alle anzeigen ({count})"), + Lang::En => format!("Show all ({count})"), + } + } + + /// An ecosystem bar's value: `412 · 7 mit CVE`, just `412` when none + /// has one. + pub fn ecosystem_value(components: u64, with_cve: u64, lang: Lang) -> String { + let components = format_count(components, lang); + match (with_cve, lang) { + (0, _) => components, + (n, Lang::De) => format!("{components} · {} mit CVE", format_count(n, lang)), + (n, Lang::En) => format!("{components} · {} with a CVE", format_count(n, lang)), + } + } + + /// What an update bar does, for screen readers and its tooltip: + /// `openssl 3.0.11 → 3.0.15 entfernt 3 CVEs. CVE-Gruppe öffnen`. + pub fn update_action(update: &str, count: usize, lang: Lang) -> String { + let cves = if count == 1 { "CVE" } else { "CVEs" }; + match lang { + Lang::De => format!("{update} entfernt {count} {cves}. CVE-Gruppe öffnen"), + Lang::En => format!("{update} removes {count} {cves}. Open the CVE group"), + } + } + + /// What an ecosystem bar does: `npm: 412 Komponenten, 7 mit CVE. In der + /// Tabelle zeigen`. + pub fn ecosystem_action(name: &str, components: u64, with_cve: u64, lang: Lang) -> String { + let all = format_count(components, lang); + let vulnerable = format_count(with_cve, lang); + match lang { + Lang::De => { + format!("{name}: {all} Komponenten, {vulnerable} mit CVE. In der Tabelle zeigen") + } + Lang::En => { + format!("{name}: {all} components, {vulnerable} with a CVE. Show in the table") + } + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn an_update_names_the_cves_it_removes() { + assert_eq!(removes(3), "−3 CVEs"); + assert_eq!(removes(1), "−1 CVE"); + assert_eq!( + update_action("openssl 3.0.11 → 3.0.15", 1, Lang::De), + "openssl 3.0.11 → 3.0.15 entfernt 1 CVE. CVE-Gruppe öffnen" + ); + assert_eq!(show_all(23, Lang::En), "Show all (23)"); + } + + #[test] + fn an_ecosystem_names_its_vulnerable_components_only_when_there_are_some() { + assert_eq!(ecosystem_value(1412, 7, Lang::De), "1.412 · 7 mit CVE"); + assert_eq!(ecosystem_value(1412, 7, Lang::En), "1,412 · 7 with a CVE"); + assert_eq!(ecosystem_value(12, 0, Lang::De), "12"); + assert_eq!( + ecosystem_action("Cargo", 4, 0, Lang::En), + "Cargo: 4 components, 0 with a CVE. Show in the table" + ); + } + } +} diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index 60a7950..0d5b902 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -20,6 +20,7 @@ pub mod platform; pub mod projects; #[allow(clippy::too_many_arguments)] pub mod sbom; +pub mod sbom_ecosystems; pub mod scans; pub mod stats; pub mod support; diff --git a/compliance-dashboard/src/infrastructure/sbom_ecosystems.rs b/compliance-dashboard/src/infrastructure/sbom_ecosystems.rs new file mode 100644 index 0000000..c70cdc4 --- /dev/null +++ b/compliance-dashboard/src/infrastructure/sbom_ecosystems.rs @@ -0,0 +1,33 @@ +//! The SBOM components of one target per ecosystem (#957), for the +//! "Komponenten nach Ökosystem" chart. + +use dioxus::prelude::*; + +use compliance_core::sbom_ecosystems::EcosystemCount; + +/// The agent's `/sbom-ecosystems` reply (read on the server only). +#[cfg(feature = "server")] +#[derive(Debug, serde::Deserialize)] +struct EcosystemsResponse { + data: Vec, +} + +/// The SBOM components of target `target_id` per ecosystem, the largest +/// first (`GET /api/v1/targets/{id}/sbom-ecosystems`). +/// +/// # Errors +/// +/// The agent's refusal or an unreachable agent, as a [`ServerFnError`]. +#[server] +pub async fn fetch_sbom_ecosystems( + target_id: String, +) -> Result, ServerFnError> { + let resp = + super::agent_client::agent_get(&format!("/api/v1/targets/{target_id}/sbom-ecosystems")) + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let body: EcosystemsResponse = super::agent_client::json_or_error(resp).await?; + Ok(body.data) +} diff --git a/compliance-dashboard/src/pages/sbom.rs b/compliance-dashboard/src/pages/sbom.rs index 2b6ea88..e3f3e9a 100644 --- a/compliance-dashboard/src/pages/sbom.rs +++ b/compliance-dashboard/src/pages/sbom.rs @@ -1,6 +1,8 @@ use compliance_core::models::{LicenseConclusion, YOCTO_RECIPE_MANAGER}; use dioxus::prelude::*; +use crate::app::Route; +use crate::components::component_overview::ComponentOverview; use crate::components::license_editor::{category_class, confirmed_title, LicenseEditor}; use crate::components::license_review::{ action_class, reasons_text, review_title, LicenseCheckPanel, @@ -14,21 +16,45 @@ use crate::i18n::{use_lang, Lang}; use crate::infrastructure::sbom::*; use compliance_core::models::ReviewDecision; +/// The SBOM page. `target` filters it to one target; `ecosystem` (from +/// `/sbom/ecosystem/:ecosystem`, #957) to one package manager. #[component] -pub fn SbomPage(target: String) -> Element { +pub fn SbomPage(target: String, #[props(default)] ecosystem: String) -> Element { let lang = use_lang()(); let mut toasts = use_context::(); // ── Filter signals ── let mut page = use_signal(|| 1u64); // Opened from a target (`?target=`): filtered to it. let mut repo_filter = use_signal(|| target.clone()); - let mut pm_filter = use_signal(String::new); + let mut pm_filter = use_signal(|| ecosystem.clone()); let mut search_q = use_signal(String::new); let mut vuln_toggle = use_signal(|| Option::::None); let mut license_filter = use_signal(String::new); // Only the components an image declares (`Some(true)`), or all. let mut in_image_filter = use_signal(|| Option::::None); + // Back and forward between two ecosystems keep this page mounted with + // new props: the filter follows the URL. + use_effect(use_reactive!(|ecosystem| { + if *pm_filter.peek() != ecosystem { + pm_filter.set(ecosystem); + page.set(1); + } + })); + // A bar of the components view (#957) filters the table to its + // ecosystem, and puts it in the URL; an empty one clears the filter. + let navigator = use_navigator(); + let on_ecosystem = move |ecosystem: String| { + pm_filter.set(ecosystem.clone()); + page.set(1); + let target = repo_filter(); + navigator.push(if ecosystem.is_empty() { + Route::SbomPage { target } + } else { + Route::SbomEcosystemPage { ecosystem, target } + }); + }; + // ── Active tab: "packages" | "licenses" | "diff" ── let mut active_tab = use_signal(|| "packages".to_string()); @@ -143,6 +169,10 @@ pub fn SbomPage(target: String) -> Element { // ═══════════════ PACKAGES TAB ═══════════════ if active_tab() == "packages" { + // ── The components view of one target (#957) ── + if !repo_filter().is_empty() { + ComponentOverview { target_id: repo_filter(), ecosystem: pm_filter(), on_ecosystem } + } // ── Filter bar ── div { class: "sbom-filter-bar", select { @@ -175,7 +205,7 @@ pub fn SbomPage(target: String) -> Element { { let val = pm.clone(); let label = pm_display_name(&val); - rsx! { option { value: "{val}", "{label}" } } + rsx! { option { value: "{val}", selected: pm_filter() == val, "{label}" } } } } }, @@ -911,7 +941,7 @@ pub fn SbomPage(target: String) -> Element { } } -fn pm_display_name(pm: &str) -> &str { +pub(crate) fn pm_display_name(pm: &str) -> &str { match pm { "npm" => "npm", "cargo" => "Cargo", diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index a45feec..ca0c3c4 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -123,6 +123,26 @@ complete scan. Open **Stückliste** in the sidebar. The **Pakete** (Packages) tab lists the components of all targets, 50 per page. +### Charts for one target + +With one target picked, two bar charts open the tab ("Diagramm"; "Tabelle" +shows the same numbers as tables): + +- **Welches Update entfernt die meisten CVEs** -- per component with open CVEs, + the update to the highest fixed version (`openssl 3.0.11 → 3.0.15`) and how + many CVEs it removes (`−3 CVEs`), the top 10 until **Alle anzeigen**. A bar + opens that component's CVE group (see [VEX](#vex-the-status-of-each-vulnerability)), + with **Nicht betroffen (alle N)** and its CVEs. +- **Komponenten nach Ökosystem** -- per package manager, the components and how + many have a known vulnerability. A bar filters the table below to it; the + URL (`/sbom/ecosystem/npm?target=`) keeps the filter. + +**← Zurück zum Diagramm** returns to the charts. + +API: `GET /api/v1/targets/{id}/sbom-ecosystems` lists `package_manager`, +`components` and `with_cve` per ecosystem, the largest first; the updates come +from `GET /api/v1/targets/{id}/cve-groups`. + ### Filtering - **Alle Prüfobjekte** -- one target, or all