diff --git a/compliance-agent/src/api/handlers/evidence.rs b/compliance-agent/src/api/handlers/evidence.rs index 3d8d92a..88cbfe8 100644 --- a/compliance-agent/src/api/handlers/evidence.rs +++ b/compliance-agent/src/api/handlers/evidence.rs @@ -87,6 +87,66 @@ async fn load_inputs( }) } +/// How many controls are in each state, keyed as the API names the states. +fn state_counts(controls: &[crate::evidence::compliance::ControlStatus]) -> serde_json::Value { + let count = |state: ControlState| controls.iter().filter(|c| c.state == state).count(); + serde_json::json!({ + "not_satisfied": count(ControlState::NotSatisfied), + "no_violation_found": count(ControlState::NoViolationFound), + "not_assessed": count(ControlState::NotAssessed), + "not_code_checkable": count(ControlState::NotCodeCheckable), + }) +} + +/// Targets whose CRA status is computed at the same time for the summary. +const SUMMARY_CONCURRENCY: usize = 4; + +/// GET /api/v1/compliance/summary — every target's CRA state counts, for the +/// overview. A target too large to evaluate in memory is listed with +/// `counts: null` rather than failing the whole summary. +#[tracing::instrument(skip_all)] +pub async fn compliance_summary( + Extension(agent): AgentExt, + tenant: TenantCtx, +) -> Result, StatusCode> { + use futures_util::StreamExt; + + let db = tenant_db(&agent, &tenant).await?; + let ids: Vec = collect_cursor_async( + db.onboarded_targets() + .clone_with_type::() + .find(doc! {}) + .projection(doc! { "_id": 1 }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?, + ) + .await + .into_iter() + .filter_map(|d| d.get_object_id("_id").ok().map(|oid| oid.to_hex())) + .collect(); + + let (agent, db) = (&agent, &db); + let rows: Vec = futures_util::stream::iter(ids) + .map(|id| async move { + match load_inputs(agent, db, &id).await { + Ok(inputs) => serde_json::json!({ + "target_id": id, + "counts": state_counts(&compliance_of(&inputs)), + "sbom_components": inputs.sbom.len(), + "cve_alerts": inputs.cves.len(), + }), + Err(status) => { + tracing::warn!(target_id = %id, %status, "compliance summary: skipped"); + serde_json::json!({ "target_id": id, "counts": null }) + } + } + }) + .buffered(SUMMARY_CONCURRENCY) + .collect() + .await; + Ok(Json(serde_json::json!({ "data": rows }))) +} + /// GET /api/v1/targets/{id}/compliance — the target's state against every CRA /// Annex I control, with the findings against each and the last scan. #[tracing::instrument(skip_all, fields(target_id = %id))] @@ -98,17 +158,11 @@ pub async fn compliance_view( let db = tenant_db(&agent, &tenant).await?; let inputs = load_inputs(&agent, &db, &id).await?; let controls = compliance_of(&inputs); - let count = |state: ControlState| controls.iter().filter(|c| c.state == state).count(); Ok(Json(serde_json::json!({ "data": { "target_id": id, "target_name": inputs.target.name, - "counts": { - "not_satisfied": count(ControlState::NotSatisfied), - "no_violation_found": count(ControlState::NoViolationFound), - "not_assessed": count(ControlState::NotAssessed), - "not_code_checkable": count(ControlState::NotCodeCheckable), - }, + "counts": state_counts(&controls), "last_scan": inputs.last_run, "sbom_components": inputs.sbom.len(), "cve_alerts": inputs.cves.len(), diff --git a/compliance-agent/src/api/handlers/health.rs b/compliance-agent/src/api/handlers/health.rs index 1d934aa..b4ba8fc 100644 --- a/compliance-agent/src/api/handlers/health.rs +++ b/compliance-agent/src/api/handlers/health.rs @@ -10,6 +10,41 @@ pub async fn health() -> Json { Json(serde_json::json!({ "status": "ok" })) } +/// Findings that still need someone's attention: not resolved, not a false +/// positive, not an accepted risk and not ignored. +const OPEN_STATUSES: [&str; 3] = ["open", "triaged", "needs_review"]; + +/// How many open findings there are of each severity, by severity name. +async fn open_findings_by_severity( + db: &crate::database::Database, +) -> std::collections::HashMap { + use futures_util::TryStreamExt; + + let pipeline = vec![ + doc! { "$match": { "status": { "$in": OPEN_STATUSES.to_vec() } } }, + doc! { "$group": { "_id": "$severity", "n": { "$sum": 1 } } }, + ]; + let rows: Vec = match db.findings().aggregate(pipeline).await { + Ok(cursor) => cursor.try_collect().await.unwrap_or_default(), + Err(e) => { + tracing::warn!("overview: counting open findings failed: {e}"); + Vec::new() + } + }; + rows.into_iter() + .filter_map(|row| { + let severity = row.get_str("_id").ok()?.to_string(); + // `$sum` of 1s is an int32 until it overflows into int64. + let n = row + .get_i32("n") + .map(i64::from) + .or_else(|_| row.get_i64("n")) + .ok()?; + Some((severity, u64::try_from(n).ok()?)) + }) + .collect() +} + #[tracing::instrument(skip_all)] pub async fn stats_overview( axum::extract::Extension(agent): AgentExt, @@ -18,43 +53,36 @@ pub async fn stats_overview( let db = tenant_db(&agent, &tenant).await?; let db = &db; - let total_repositories = db - .onboarded_targets() - .count_documents(doc! {}) - .await - .unwrap_or(0); - let total_findings = db.findings().count_documents(doc! {}).await.unwrap_or(0); - let critical_findings = db - .findings() - .count_documents(doc! { "severity": "critical" }) - .await - .unwrap_or(0); - let high_findings = db - .findings() - .count_documents(doc! { "severity": "high" }) - .await - .unwrap_or(0); - let medium_findings = db - .findings() - .count_documents(doc! { "severity": "medium" }) - .await - .unwrap_or(0); - let low_findings = db - .findings() - .count_documents(doc! { "severity": "low" }) - .await - .unwrap_or(0); - let total_sbom_entries = db - .sbom_entries() - .count_documents(doc! {}) - .await - .unwrap_or(0); - let total_cve_alerts = db.cve_alerts().count_documents(doc! {}).await.unwrap_or(0); - let total_issues = db - .tracker_issues() - .count_documents(doc! {}) - .await - .unwrap_or(0); + let (total_repositories, total_sbom_entries, total_cve_alerts, total_issues, by_severity) = tokio::join!( + async { + db.onboarded_targets() + .count_documents(doc! {}) + .await + .unwrap_or(0) + }, + async { + db.sbom_entries() + .count_documents(doc! {}) + .await + .unwrap_or(0) + }, + async { db.cve_alerts().count_documents(doc! {}).await.unwrap_or(0) }, + async { + db.tracker_issues() + .count_documents(doc! {}) + .await + .unwrap_or(0) + }, + open_findings_by_severity(db), + ); + let severity = |name: &str| by_severity.get(name).copied().unwrap_or(0); + let total_findings = by_severity.values().sum(); + let (critical_findings, high_findings, medium_findings, low_findings) = ( + severity("critical"), + severity("high"), + severity("medium"), + severity("low"), + ); let recent_scans: Vec = match db .scan_runs() diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 1f7bee6..6df97c2 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -82,6 +82,10 @@ pub fn build_router() -> Router { "/api/v1/targets/{id}/compliance", get(handlers::evidence::compliance_view), ) + .route( + "/api/v1/compliance/summary", + get(handlers::evidence::compliance_summary), + ) // Findings from a manual DAST run or penetration test. .route( "/api/v1/targets/{id}/findings", diff --git a/compliance-agent/tests/evidence.rs b/compliance-agent/tests/evidence.rs index 551b090..a30e85d 100644 --- a/compliance-agent/tests/evidence.rs +++ b/compliance-agent/tests/evidence.rs @@ -90,5 +90,17 @@ async fn a_target_s_evidence_pack_holds_its_findings_and_hashes() { assert_eq!(view["data"]["counts"]["no_violation_found"], 0); assert_eq!(view["data"]["counts"]["not_code_checkable"], 19); + // The overview's summary: the same counts, for every target at once. + let summary: serde_json::Value = server + .get("/api/v1/compliance/summary") + .await + .json() + .await + .unwrap(); + let rows = summary["data"].as_array().unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0]["target_id"], id.as_str()); + assert_eq!(rows[0]["counts"], view["data"]["counts"]); + server.cleanup().await; } diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index f88ad1e..c042a50 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -4280,3 +4280,298 @@ tbody tr:last-child td { font-size: 12px; color: var(--text-tertiary); } + +/* ── CRA bar: a target's Annex I status at a glance ── */ +.cra-bar { + display: grid; + gap: 8px; +} + +.cra-bar-compact { + grid-template-columns: minmax(80px, 1fr) auto; + align-items: center; + gap: 10px; +} + +.cra-bar-track { + display: flex; + gap: 2px; + height: 8px; + border-radius: 99px; + overflow: hidden; + background: var(--bg-elevated); +} + +.cra-bar-seg { + min-width: 3px; +} + +.cra-violated { background: var(--danger); } +.cra-open { background: var(--warning); } +.cra-clear { background: var(--success); } +.cra-process { background: color-mix(in srgb, var(--accent) 28%, var(--bg-elevated)); } + +.cra-bar-note { + font-size: 12px; + color: var(--text-tertiary); + white-space: nowrap; + font-variant-numeric: tabular-nums; +} + +.cra-bar-violated { + color: var(--danger); + font-weight: 600; +} + +.cra-bar-legend { + list-style: none; + display: grid; + grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); + gap: 6px 18px; + font-size: 12px; +} + +.cra-bar-legend li { + display: flex; + align-items: center; + gap: 8px; +} + +.cra-dot { + width: 8px; + height: 8px; + border-radius: 2px; + flex-shrink: 0; +} + +.cra-legend-label { + color: var(--text-secondary); +} + +.cra-legend-n { + margin-left: auto; + font-family: var(--font-mono); + color: var(--text-primary); + font-variant-numeric: tabular-nums; +} + +/* ── Overview ── */ +.ov-empty { + display: grid; + gap: 10px; + justify-items: start; + padding: 24px; +} + +.ov-empty p { + color: var(--text-secondary); + max-width: 62ch; +} + +.ov-figures { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + margin-bottom: 20px; + overflow: hidden; +} + +.ov-figure { + display: grid; + gap: 4px; + align-content: start; + padding: 16px 18px; + color: inherit; + text-decoration: none; + border-right: 1px solid var(--border); + transition: background 0.15s var(--ease-out); +} + +.ov-figure:last-child { + border-right: none; +} + +.ov-figure:hover { + background: var(--bg-card-hover); +} + +.ov-figure-label { + font-family: var(--font-mono); + font-size: 10.5px; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--text-tertiary); +} + +.ov-figure-value { + font-size: 28px; + font-weight: 600; + letter-spacing: -0.02em; + font-variant-numeric: tabular-nums; +} + +.ov-figure-sub { + font-size: 12px; + 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); + gap: 20px; + align-items: start; +} + +.ov-section-head { + display: grid; + gap: 2px; + padding: 16px 18px 12px; + border-bottom: 1px solid var(--border); +} + +.ov-section-head h3 { + font-size: 14px; + font-weight: 600; +} + +.ov-section-head p, +.ov-muted { + font-size: 12px; + color: var(--text-tertiary); +} + +.ov-muted { + 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); + gap: 12px; + align-items: start; + padding: 12px 18px; + border-bottom: 1px solid var(--border); +} + +.ov-next-body { + display: grid; + gap: 2px; + min-width: 0; +} + +.ov-next-title { + color: var(--text-primary); + font-weight: 500; + text-decoration: none; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.ov-next-title:hover { + color: var(--accent); +} + +.ov-next-meta { + font-size: 12px; + color: var(--text-tertiary); + overflow-wrap: anywhere; +} + +.ov-next-meta code { + font-family: var(--font-mono); + font-size: 11.5px; +} + +.ov-more { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 12px 18px; + font-weight: 500; + color: var(--accent); + text-decoration: none; +} + +@media (max-width: 1100px) { + .ov-grid { + grid-template-columns: 1fr; + } +} + +@media (max-width: 720px) { + .ov-figures { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .ov-figure:nth-child(2) { + border-right: none; + } + + .ov-figure:nth-child(-n+2) { + border-bottom: 1px solid var(--border); + } + + .ov-target { + grid-template-columns: 1fr; + gap: 6px; + } + + .ov-target-scan { + justify-self: start; + } +} diff --git a/compliance-dashboard/src/components/cra_bar.rs b/compliance-dashboard/src/components/cra_bar.rs new file mode 100644 index 0000000..0fc561c --- /dev/null +++ b/compliance-dashboard/src/components/cra_bar.rs @@ -0,0 +1,64 @@ +//! A target's CRA Annex I status at a glance: one bar, one segment per +//! state, in the same order and colours everywhere it appears. + +use dioxus::prelude::*; + +use crate::i18n::texts::compliance as tx; +use crate::i18n::{use_lang, Text}; +use crate::infrastructure::evidence::CraCounts; + +/// The states in reading order: what needs work first, process evidence last. +/// Each is (label, CSS modifier, count). +fn segments(counts: &CraCounts) -> [(Text, &'static str, u32); 4] { + [ + (tx::NOT_SATISFIED, "violated", counts.not_satisfied), + (tx::NOT_ASSESSED, "open", counts.not_assessed), + (tx::NO_VIOLATION, "clear", counts.no_violation_found), + (tx::NOT_CODE_CHECKABLE, "process", counts.not_code_checkable), + ] +} + +/// The bar, with its legend below unless `compact` (then the legend is the +/// bar's tooltip and only the violated count is written out). +#[component] +pub fn CraBar(counts: CraCounts, #[props(default)] compact: bool) -> Element { + let lang = use_lang()(); + let parts = segments(&counts); + let summary = parts + .iter() + .map(|(label, _, n)| format!("{} {n}", label.get(lang))) + .collect::>() + .join(" · "); + + rsx! { + div { class: if compact { "cra-bar cra-bar-compact" } else { "cra-bar" }, + div { class: "cra-bar-track", role: "img", "aria-label": "{summary}", title: "{summary}", + for (_, modifier, n) in parts { + if n > 0 { + span { + class: "cra-bar-seg cra-{modifier}", + // Grow from zero in proportion to the count. + style: "flex: {n} 0 0;", + } + } + } + } + if compact { + span { + class: if counts.not_satisfied > 0 { "cra-bar-note cra-bar-violated" } else { "cra-bar-note" }, + "{counts.not_satisfied} {tx::VIOLATED_COUNT.get(lang)}" + } + } else { + ul { class: "cra-bar-legend", + for (label, modifier, n) in parts { + li { + span { class: "cra-dot cra-{modifier}" } + span { class: "cra-legend-label", {label.get(lang)} } + span { class: "cra-legend-n", "{n}" } + } + } + } + } + } + } +} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index a24f5dc..6b6e501 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -3,6 +3,7 @@ pub mod attack_chain; pub mod code_inspector; pub mod code_snippet; pub mod copy_button; +pub mod cra_bar; pub mod demo_targets; pub mod file_tree; pub mod help_chat; diff --git a/compliance-dashboard/src/i18n/mod.rs b/compliance-dashboard/src/i18n/mod.rs index 596e55f..22d73c9 100644 --- a/compliance-dashboard/src/i18n/mod.rs +++ b/compliance-dashboard/src/i18n/mod.rs @@ -103,6 +103,31 @@ pub fn format_time(time: &chrono::DateTime, lang: Lang) -> String { time.format(pattern).to_string() } +/// How long ago `time` was, as of `now`: `vor 5 Min.`, `vor 2 Std.`, +/// `vor 3 Tagen`, then the date. `now` is passed in so the text is testable. +pub fn format_ago( + time: &chrono::DateTime, + now: &chrono::DateTime, + lang: Lang, +) -> String { + let minutes = (*now - *time).num_minutes().max(0); + let (hours, days) = (minutes / 60, minutes / (60 * 24)); + match (lang, minutes, hours, days) { + (Lang::De, 0, _, _) => "gerade eben".to_string(), + (Lang::En, 0, _, _) => "just now".to_string(), + (Lang::De, m, 0, _) => format!("vor {m} Min."), + (Lang::En, m, 0, _) => format!("{m} min ago"), + (Lang::De, _, h, 0) => format!("vor {h} Std."), + (Lang::En, _, h, 0) => format!("{h} h ago"), + (Lang::De, _, _, 1) => "vor 1 Tag".to_string(), + (Lang::En, _, _, 1) => "1 day ago".to_string(), + (Lang::De, _, _, d) if d < 7 => format!("vor {d} Tagen"), + (Lang::En, _, _, d) if d < 7 => format!("{d} days ago"), + (Lang::De, ..) => time.format("%d.%m.%Y").to_string(), + (Lang::En, ..) => time.format("%Y-%m-%d").to_string(), + } +} + /// Provide the language to the whole app. Call once, in the app shell. /// /// Server rendering and the first client render use German so hydration @@ -169,6 +194,25 @@ fn set_document_lang(lang: Lang) { #[cfg(test)] mod tests { + + #[test] + fn a_moment_reads_as_how_long_ago_it_was() { + use chrono::{Duration, TimeZone, Utc}; + let now = Utc.with_ymd_and_hms(2026, 9, 30, 12, 0, 0).unwrap(); + let ago = |d: Duration, lang| format_ago(&(now - d), &now, lang); + assert_eq!(ago(Duration::seconds(30), Lang::De), "gerade eben"); + assert_eq!(ago(Duration::minutes(5), Lang::De), "vor 5 Min."); + assert_eq!(ago(Duration::hours(2), Lang::De), "vor 2 Std."); + assert_eq!(ago(Duration::days(1), Lang::De), "vor 1 Tag"); + assert_eq!(ago(Duration::days(3), Lang::En), "3 days ago"); + assert_eq!(ago(Duration::days(10), Lang::De), "20.09.2026"); + assert_eq!(ago(Duration::days(10), Lang::En), "2026-09-20"); + // A clock a little ahead of the server's is "just now", not negative. + assert_eq!( + format_ago(&(now + Duration::minutes(1)), &now, Lang::En), + "just now" + ); + } use super::*; #[test] diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index e2a1a16..d6e71c9 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -163,32 +163,72 @@ pub mod overview { en: "Overview", }; pub const SUBTITLE: Text = Text { - de: "Sicherheits- und Compliance-Stand Ihrer Prüfobjekte", - en: "Security and compliance status of your targets", + de: "Wo Ihre Prüfobjekte gegenüber dem Cyber Resilience Act stehen", + en: "Where your targets stand against the Cyber Resilience Act", }; pub const TARGETS: Text = Text { de: "Prüfobjekte", en: "Targets", }; - pub const FINDINGS: Text = Text { - de: "Befunde gesamt", - en: "Total findings", + pub const OPEN_FINDINGS: Text = Text { + de: "Offene Befunde", + en: "Open findings", }; - pub const DEPENDENCIES: Text = Text { - de: "Abhängigkeiten", - en: "Dependencies", + pub const CRITICAL_LC: Text = Text { + de: "kritisch", + en: "critical", }; - pub const CVE_ALERTS: Text = Text { - de: "CVE-Warnungen", - en: "CVE alerts", + pub const HIGH_LC: Text = Text { + de: "hoch", + en: "high", }; - pub const TRACKER_ISSUES: Text = Text { - de: "Tickets", - en: "Tracker issues", + pub const COMPONENTS: Text = Text { + de: "Komponenten", + en: "Components", }; - pub const SEVERITY_DISTRIBUTION: Text = Text { - de: "Befunde nach Schweregrad", - en: "Findings by severity", + 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", + }; + pub const NEXT: Text = Text { + de: "Als Nächstes", + en: "Next up", + }; + pub const NEXT_HINT: Text = Text { + de: "Die schwersten offenen Befunde", + en: "The most severe open findings", + }; + pub const NEXT_EMPTY: Text = Text { + 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", }; pub const EMPTY_TITLE: Text = Text { de: "Noch keine Prüfobjekte", @@ -1732,6 +1772,10 @@ pub mod compliance { de: "Kein Verstoß gefunden", en: "No violation found", }; + pub const VIOLATED_COUNT: Text = Text { + de: "nicht erfüllt", + en: "violated", + }; pub const NOT_ASSESSED: Text = Text { de: "Nicht bewertet", en: "Not assessed", diff --git a/compliance-dashboard/src/infrastructure/evidence.rs b/compliance-dashboard/src/infrastructure/evidence.rs index 04b0869..1fe8fe8 100644 --- a/compliance-dashboard/src/infrastructure/evidence.rs +++ b/compliance-dashboard/src/infrastructure/evidence.rs @@ -2,6 +2,7 @@ //! browser, never held here whole. use dioxus::prelude::*; +use serde::{Deserialize, Serialize}; /// Where the browser downloads a target's evidence pack. pub fn evidence_pack_url(target_id: &str) -> String { @@ -33,6 +34,44 @@ pub async fn download_evidence_pack( )) } +/// How many of the 40 CRA Annex I controls are in each state. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CraCounts { + /// Violated: at least one open finding against the control. + pub not_satisfied: u32, + /// Not assessed: no rule for the scanned code, or a tool did not finish. + pub not_assessed: u32, + /// Checked in the code, and nothing found. + pub no_violation_found: u32, + /// A design or process requirement, evidenced outside the code. + pub not_code_checkable: u32, +} + +/// One target's line in the overview: its CRA counts (`None` when the agent +/// could not evaluate it), and its components and known vulnerabilities. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct ComplianceSummaryRow { + pub target_id: String, + #[serde(default)] + pub counts: Option, + #[serde(default)] + pub sbom_components: u64, + #[serde(default)] + pub cve_alerts: u64, +} + +/// Every target's CRA counts (`GET /api/v1/compliance/summary`). +#[server] +pub async fn fetch_compliance_summary() -> Result, ServerFnError> { + let resp = super::agent_client::agent_get("/api/v1/compliance/summary") + .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())) +} + /// The target's state against every CRA Annex I control /// (`GET /api/v1/targets/{id}/compliance`), as the agent sends it. #[server] @@ -50,6 +89,30 @@ pub async fn fetch_compliance(id: String) -> Result, + /// The last scan's status, and when it finished (or started, if running). + last_scan: Option<(ScanRunStatus, chrono::DateTime)>, +} + +/// The targets joined with their CRA counts, those with the most violated +/// requirements first, then by name. +fn target_lines( + targets: &[serde_json::Value], + summary: &[ComplianceSummaryRow], +) -> Vec { + let mut lines: Vec = targets + .iter() + .filter_map(|t| { + let id = t.get("_id")?.get("$oid")?.as_str()?.to_string(); + Some(TargetLine { + summary: summary.iter().find(|s| s.target_id == id).cloned(), + name: t.get("name")?.as_str()?.to_string(), + target_type: t + .get("target_type") + .and_then(|v| v.as_str()) + .unwrap_or_default() + .to_string(), + last_scan: t + .get("last_scan") + .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))), + id, + }) + }) + .collect(); + let violated = |l: &TargetLine| { + l.summary + .as_ref() + .and_then(|s| s.counts) + .map_or(0, |c| c.not_satisfied) + }; + lines.sort_by(|a, b| { + violated(b) + .cmp(&violated(a)) + .then_with(|| a.name.cmp(&b.name)) + }); + lines +} #[component] pub fn OverviewPage() -> Element { - let stats = use_resource(move || async move { - #[cfg(feature = "server")] - { - fetch_overview_stats().await.ok() - } - #[cfg(not(feature = "server"))] - { - crate::infrastructure::stats::fetch_overview_stats() - .await - .ok() - } - }); - let lang = use_lang()(); // AI chat and MCP need the runtime a source-only deployment does not have, // so they are not advertised there. let source_only = use_source_only(); - let repos = use_resource(|| async { fetch_targets().await.ok() }); - // Probe the MCP health endpoints first so the seeded cards reflect the - // live status (running / stopped) instead of the stored default. - let mcp_servers = use_resource(|| async { - let _ = refresh_mcp_status().await; - fetch_mcp_servers().await.ok() + 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 next_up = use_resource(|| async { + fetch_findings(FindingsQuery { + page: 1, + status: "open".to_string(), + sort_by: "severity".to_string(), + sort_order: "desc".to_string(), + ..Default::default() + }) + .await + .ok() }); rsx! { @@ -48,187 +101,136 @@ pub fn OverviewPage() -> Element { } match &*stats.read() { - Some(Some(s)) => rsx! { - if s.total_repositories == 0 { - div { class: "card", - div { class: "card-header", {overview::EMPTY_TITLE.get(lang)} } - p { style: "padding: 0 1rem; color: var(--text-secondary);", - {overview::EMPTY_BODY.get(lang)} - } - div { style: "padding: 0 1rem 1rem;", - Link { to: Route::OnboardingPage {}, class: "btn btn-primary", - {overview::EMPTY_ACTION.get(lang)} - } - } + Some(Some(s)) if s.total_repositories == 0 => rsx! { + div { class: "card ov-empty", + h3 { {overview::EMPTY_TITLE.get(lang)} } + p { {overview::EMPTY_BODY.get(lang)} } + Link { to: Route::OnboardingPage {}, class: "btn btn-primary", + {overview::EMPTY_ACTION.get(lang)} } } - div { class: "stat-cards", - StatCard { label: overview::TARGETS.get(lang), value: s.total_repositories.to_string() } - StatCard { label: overview::FINDINGS.get(lang), value: s.total_findings.to_string() } - StatCard { - label: common::CRITICAL.get(lang), - value: s.critical_findings.to_string(), - color: "var(--sev-critical)", + }, + 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}" } } - StatCard { - label: common::HIGH.get(lang), - value: s.high_findings.to_string(), - color: "var(--sev-high)", + Link { to: Route::FindingsPage { target: 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)}" } + } } - StatCard { - label: common::MEDIUM.get(lang), - value: s.medium_findings.to_string(), - color: "var(--sev-medium)", + Link { to: Route::SbomPage {}, 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)} } } - StatCard { - label: common::LOW.get(lang), - value: s.low_findings.to_string(), - color: "var(--sev-low)", + Link { to: Route::SbomPage {}, 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)} } } - StatCard { label: overview::DEPENDENCIES.get(lang), value: s.total_sbom_entries.to_string() } - StatCard { label: overview::CVE_ALERTS.get(lang), value: s.total_cve_alerts.to_string() } - StatCard { label: overview::TRACKER_ISSUES.get(lang), value: s.total_issues.to_string() } } - div { class: "card", - div { class: "card-header", {overview::SEVERITY_DISTRIBUTION.get(lang)} } - div { class: "severity-chart", - SeverityBar { label: common::CRITICAL.get(lang), count: s.critical_findings, max: s.total_findings, color: "var(--sev-critical)" } - SeverityBar { label: common::HIGH.get(lang), count: s.high_findings, max: s.total_findings, color: "var(--sev-high)" } - SeverityBar { label: common::MEDIUM.get(lang), count: s.medium_findings, max: s.total_findings, color: "var(--sev-medium)" } - SeverityBar { label: common::LOW.get(lang), count: s.low_findings, max: s.total_findings, color: "var(--sev-low)" } + div { class: "ov-grid", + section { class: "card ov-cra", + div { class: "ov-section-head", + h3 { {overview::CRA_BY_TARGET.get(lang)} } + p { {overview::CRA_BY_TARGET_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; + 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 } + } + } + } + } + (Some(None), _) => rsx! { p { class: "ov-muted", {overview::LIST_LOAD_FAILED.get(lang)} } }, + _ => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, + } + } + + section { class: "card ov-next", + div { class: "ov-section-head", + h3 { {overview::NEXT.get(lang)} } + p { {overview::NEXT_HINT.get(lang)} } + } + match &*next_up.read() { + Some(Some(resp)) if resp.data.is_empty() => rsx! { + p { class: "ov-muted", {overview::NEXT_EMPTY.get(lang)} } + }, + Some(Some(resp)) => { + let names: std::collections::HashMap = targets + .read() + .as_ref() + .and_then(|t| t.as_ref()) + .map(|t| { + t.data + .iter() + .filter_map(|t| { + Some(( + t.get("_id")?.get("$oid")?.as_str()?.to_string(), + t.get("name")?.as_str()?.to_string(), + )) + }) + .collect() + }) + .unwrap_or_default(); + rsx! { + ul { class: "ov-next-list", + for f in resp.data.iter().take(NEXT_UP) { + { + let id = f.id.as_ref().map(|i| i.to_hex()).unwrap_or_default(); + let place = location(f.file_path.as_deref(), f.line_number); + let target = names.get(&f.repo_id).cloned().unwrap_or_default(); + rsx! { + li { + SeverityBadge { severity: f.severity.to_string() } + div { class: "ov-next-body", + Link { to: Route::FindingDetailPage { id }, class: "ov-next-title", "{f.title}" } + span { class: "ov-next-meta", + "{target}" + if let Some(place) = place { + " · " + code { "{place}" } + } + } + } + } + } + } + } + } + Link { to: Route::FindingsPage { target: String::new() }, class: "ov-more", + {overview::ALL_FINDINGS.get(lang)} + Icon { icon: BsArrowRight, width: 14, height: 14 } + } + } + } + Some(None) => rsx! { p { class: "ov-muted", {overview::LIST_LOAD_FAILED.get(lang)} } }, + None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, + } } } if !source_only { - // AI Chat section - div { class: "card", - div { class: "card-header", {overview::AI_CHAT.get(lang)} } - match &*repos.read() { - Some(Some(data)) => { - let repo_list = &data.data; - if repo_list.is_empty() { - rsx! { - p { style: "padding: 1rem; color: var(--text-secondary);", - {overview::NO_TARGETS_FOR_CHAT.get(lang)} - } - } - } else { - rsx! { - div { - class: "grid", - style: "display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; padding: 1rem;", - for repo in repo_list { - { - let repo_id = repo.get("_id").and_then(|o| o.get("$oid")).and_then(|s| s.as_str()).unwrap_or_default().to_string(); - let name = repo.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); - rsx! { - Link { - to: Route::ChatPage { repo_id }, - class: "graph-repo-card", - div { class: "graph-repo-card-header", - div { class: "graph-repo-card-icon", - Icon { icon: BsChatDots, width: 20, height: 20 } - } - h3 { class: "graph-repo-card-name", "{name}" } - } - } - } - } - } - } - } - } - }, - Some(None) => rsx! { - p { style: "padding: 1rem; color: var(--text-secondary);", - {overview::LIST_LOAD_FAILED.get(lang)} - } - }, - None => rsx! { - div { class: "loading", {common::LOADING.get(lang)} } - }, - } - } - - // MCP Servers section - div { class: "card", - div { class: "card-header", {overview::MCP_SERVERS.get(lang)} } - match &*mcp_servers.read() { - Some(Some(resp)) => { - if resp.data.is_empty() { - rsx! { - p { style: "padding: 1rem; color: var(--text-secondary);", - {overview::NO_MCP_SERVERS.get(lang)} - } - div { style: "padding: 0 1rem 1rem; display: flex; gap: 8px;", - Link { to: Route::McpServersPage {}, class: "btn btn-primary btn-sm", {overview::MANAGE.get(lang)} } - Link { to: Route::McpTokensPage {}, class: "btn btn-secondary btn-sm", {overview::MCP_TOKENS.get(lang)} } - } - } - } else { - rsx! { - div { - style: "display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; padding: 1rem;", - for server in resp.data.iter() { - { - let status_color = match server.status { - compliance_core::models::McpServerStatus::Running => "var(--success)", - compliance_core::models::McpServerStatus::Stopped => "var(--text-secondary)", - compliance_core::models::McpServerStatus::Error => "var(--danger)", - }; - let status_label = format!("{}", server.status); - let endpoint = server.endpoint_url.clone(); - let name = server.name.clone(); - rsx! { - div { class: "card", - style: "padding: 0.75rem;", - div { - style: "display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem;", - span { - style: "width: 8px; height: 8px; border-radius: 50%; background: {status_color}; display: inline-block;", - } - strong { "{name}" } - } - p { - style: "font-size: 0.8rem; color: var(--text-secondary); margin: 0; word-break: break-all;", - "{endpoint}" - } - p { - style: "font-size: 0.75rem; color: var(--text-secondary); margin-top: 0.25rem;", - "{status_label}" - } - } - } - } - } - } - div { style: "padding: 0 1rem 1rem; display: flex; gap: 8px; flex-wrap: wrap;", - Link { - to: Route::McpServersPage {}, - class: "btn btn-primary btn-sm", - {overview::MANAGE.get(lang)} - } - Link { - to: Route::McpTokensPage {}, - class: "btn btn-secondary btn-sm", - title: overview::MCP_TOKENS_HINT.get(lang), - {overview::MCP_TOKENS.get(lang)} - } - } - } - } - }, - Some(None) => rsx! { - p { style: "padding: 1rem; color: var(--text-secondary);", - {overview::LIST_LOAD_FAILED.get(lang)} - } - }, - None => rsx! { - div { class: "loading", {common::LOADING.get(lang)} } - }, - } - } + RuntimeSections {} } }, Some(None) => rsx! { @@ -245,22 +247,185 @@ 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. #[component] -fn SeverityBar(label: String, count: u64, max: u64, color: String) -> Element { - let height_pct = if max > 0 { - (count as f64 / max as f64) * 100.0 - } else { - 0.0 - }; - +fn TargetRow(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); + ( + badge, + label.get(lang), + format_ago(when, &now, lang), + *status == ScanRunStatus::Completed, + ) + }); rsx! { - div { class: "severity-bar", - div { class: "severity-bar-count", "{count}" } - div { - class: "severity-bar-fill", - style: "height: {height_pct.max(2.0)}%; background: {color};", + li { class: "ov-target", + div { class: "ov-target-name", + Link { to: Route::CompliancePage { id: 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)} } }, + } + } + 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)} } }, + } + } + } + } +} + +/// AI chat and the MCP servers: only where the deployment runs them. +#[component] +fn RuntimeSections() -> Element { + let lang = use_lang()(); + let repos = use_resource(|| async { fetch_targets().await.ok() }); + // Probe the MCP health endpoints first so the seeded cards reflect the + // live status (running / stopped) instead of the stored default. + let mcp_servers = use_resource(|| async { + let _ = refresh_mcp_status().await; + fetch_mcp_servers().await.ok() + }); + rsx! { + // AI Chat section + div { class: "card", + div { class: "card-header", {overview::AI_CHAT.get(lang)} } + match &*repos.read() { + Some(Some(data)) => { + let repo_list = &data.data; + if repo_list.is_empty() { + rsx! { + p { style: "padding: 1rem; color: var(--text-secondary);", + {overview::NO_TARGETS_FOR_CHAT.get(lang)} + } + } + } else { + rsx! { + div { + class: "grid", + style: "display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; padding: 1rem;", + for repo in repo_list { + { + let repo_id = repo.get("_id").and_then(|o| o.get("$oid")).and_then(|s| s.as_str()).unwrap_or_default().to_string(); + let name = repo.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); + rsx! { + Link { + to: Route::ChatPage { repo_id }, + class: "graph-repo-card", + div { class: "graph-repo-card-header", + div { class: "graph-repo-card-icon", + Icon { icon: BsChatDots, width: 20, height: 20 } + } + h3 { class: "graph-repo-card-name", "{name}" } + } + } + } + } + } + } + } + } + }, + Some(None) => rsx! { + p { style: "padding: 1rem; color: var(--text-secondary);", + {overview::LIST_LOAD_FAILED.get(lang)} + } + }, + None => rsx! { + div { class: "loading", {common::LOADING.get(lang)} } + }, + } + } + + // MCP Servers section + div { class: "card", + div { class: "card-header", {overview::MCP_SERVERS.get(lang)} } + match &*mcp_servers.read() { + Some(Some(resp)) => { + if resp.data.is_empty() { + rsx! { + p { style: "padding: 1rem; color: var(--text-secondary);", + {overview::NO_MCP_SERVERS.get(lang)} + } + div { style: "padding: 0 1rem 1rem; display: flex; gap: 8px;", + Link { to: Route::McpServersPage {}, class: "btn btn-primary btn-sm", {overview::MANAGE.get(lang)} } + Link { to: Route::McpTokensPage {}, class: "btn btn-secondary btn-sm", {overview::MCP_TOKENS.get(lang)} } + } + } + } else { + rsx! { + div { + style: "display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; padding: 1rem;", + for server in resp.data.iter() { + { + let status_color = match server.status { + compliance_core::models::McpServerStatus::Running => "var(--success)", + compliance_core::models::McpServerStatus::Stopped => "var(--text-secondary)", + compliance_core::models::McpServerStatus::Error => "var(--danger)", + }; + let status_label = format!("{}", server.status); + let endpoint = server.endpoint_url.clone(); + let name = server.name.clone(); + rsx! { + div { class: "card", + style: "padding: 0.75rem;", + div { + style: "display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem;", + span { + style: "width: 8px; height: 8px; border-radius: 50%; background: {status_color}; display: inline-block;", + } + strong { "{name}" } + } + p { + style: "font-size: 0.8rem; color: var(--text-secondary); margin: 0; word-break: break-all;", + "{endpoint}" + } + p { + style: "font-size: 0.75rem; color: var(--text-secondary); margin-top: 0.25rem;", + "{status_label}" + } + } + } + } + } + } + div { style: "padding: 0 1rem 1rem; display: flex; gap: 8px; flex-wrap: wrap;", + Link { + to: Route::McpServersPage {}, + class: "btn btn-primary btn-sm", + {overview::MANAGE.get(lang)} + } + Link { + to: Route::McpTokensPage {}, + class: "btn btn-secondary btn-sm", + title: overview::MCP_TOKENS_HINT.get(lang), + {overview::MCP_TOKENS.get(lang)} + } + } + } + } + }, + Some(None) => rsx! { + p { style: "padding: 1rem; color: var(--text-secondary);", + {overview::LIST_LOAD_FAILED.get(lang)} + } + }, + None => rsx! { + div { class: "loading", {common::LOADING.get(lang)} } + }, } - div { class: "severity-bar-label", "{label}" } } } }