From d6986d23b1cacd495b031c6ab54620cb8f679f50 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Tue, 10 Nov 2026 17:22:59 +0000 Subject: [PATCH] feat(dashboard): Heute inbox with urgency buckets and dated resubmission (#950) (#965) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new landing page "Heute" (the overview moves to /overview and stays in the sidebar): the Erstbewertung, target chips, the four bucket tiles and the cards of the chosen bucket with their decisions, "Später" with one week, one month or a date, "Details", an undo strip after each decision, and the keys j/k/f/a/s on this page only. The sidebar's "Heute" entry shows the workspace's "Heute handeln" count. Co-Authored-By: Claude Opus 5.5 --- compliance-agent/src/api/handlers/inbox.rs | 549 ++++++ compliance-agent/src/api/handlers/mod.rs | 1 + .../src/api/role_gate/router_tests.rs | 5 + compliance-agent/src/api/routes.rs | 9 + compliance-agent/src/database.rs | 19 + compliance-agent/tests/inbox.rs | 380 +++++ compliance-core/src/models/inbox.rs | 1518 +++++++++++++++++ compliance-core/src/models/mod.rs | 1 + compliance-dashboard/assets/main.css | 425 +++++ compliance-dashboard/src/app.rs | 13 + .../src/components/sidebar.rs | 40 + compliance-dashboard/src/i18n/texts.rs | 307 ++++ .../src/infrastructure/inbox.rs | 94 + .../src/infrastructure/mod.rs | 1 + compliance-dashboard/src/pages/inbox.rs | 918 ++++++++++ compliance-dashboard/src/pages/mod.rs | 2 + 16 files changed, 4282 insertions(+) create mode 100644 compliance-agent/src/api/handlers/inbox.rs create mode 100644 compliance-agent/tests/inbox.rs create mode 100644 compliance-core/src/models/inbox.rs create mode 100644 compliance-dashboard/src/infrastructure/inbox.rs create mode 100644 compliance-dashboard/src/pages/inbox.rs diff --git a/compliance-agent/src/api/handlers/inbox.rs b/compliance-agent/src/api/handlers/inbox.rs new file mode 100644 index 0000000..77d0331 --- /dev/null +++ b/compliance-agent/src/api/handlers/inbox.rs @@ -0,0 +1,549 @@ +//! The "Heute" inbox (#950): the workspace's open decisions as cards in four +//! urgency buckets, decisions on a whole card, undo, and putting a card off +//! until a date ("Wiedervorlage"). +//! +//! The bucket rules and the cards are [`compliance_core::models::inbox`]'s; +//! this module loads what they are made of and applies decisions through +//! the existing endpoints' code: a finding's status as +//! `PATCH /api/v1/findings/bulk-status` sets it, a CVE alert's VEX statement +//! as `PATCH /api/v1/cves/{id}/vex` does. Writes are role-gated by the org +//! role middleware like every other write. + +use std::collections::{BTreeMap, HashMap}; + +use axum::extract::{Extension, Path, Query}; +use axum::http::StatusCode; +use axum::Json; +use chrono::{DateTime, Utc}; +use futures_util::StreamExt; +use mongodb::bson::{doc, oid::ObjectId, Bson, Document}; +use serde::Deserialize; + +use compliance_core::models::inbox::{ + alert_undecided, apply_snoozes, cve_cards, finding_cards, view, Bucket, BucketRules, CardKey, + DecideRequest, DecideResponse, InboxAction, InboxCard, InboxFinding, InboxSnooze, InboxView, + OneCardPerFinding, PreviousState, Progress, SnoozeRequest, SnoozeResponse, UndoRequest, + ViewRequest, DECIDED_STATUSES, DECIDING_VEX, UNDECIDED_STATUSES, +}; +use compliance_core::models::{CveAlert, FindingStatus, VexStatus}; +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::{ + collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult, BulkUpdateStatusRequest, +}; +use super::findings::{bulk_update_finding_status, Actor}; +use super::vex::{set_cve_vex, VexRequest}; +use crate::database::Database; + +/// Cards listed when the request names no limit. +const DEFAULT_LIMIT: usize = 100; +/// The most cards one request lists; the counts always cover all. +const MAX_LIMIT: usize = 500; + +/// A refusal with its reason, the shape `PATCH /api/v1/cves/{id}/vex` answers +/// with, so the dashboard shows why. +type Refusal = (StatusCode, Json); + +fn refuse(code: StatusCode, error: &str) -> Refusal { + (code, Json(serde_json::json!({ "error": error }))) +} + +/// A database error as a refusal, logged. +fn store_error(e: mongodb::error::Error) -> Refusal { + tracing::warn!("inbox: database error: {e}"); + refuse(StatusCode::INTERNAL_SERVER_ERROR, "store") +} + +/// The query of [`get_inbox`]. +#[derive(Debug, Deserialize)] +pub struct InboxQuery { + /// Only this target's cards, counts and Erstbewertung. + #[serde(default)] + pub target: Option, + /// The bucket whose cards to list (default `today`). + #[serde(default)] + pub bucket: Option, + /// The most cards to list (default 100, at most 500). + #[serde(default)] + pub limit: Option, +} + +/// The bucket rules as configured: the CVE issues' EPSS threshold +/// (`CVE_ISSUE_EPSS_PERCENTILE`, default 0.95), at `now`. +fn rules(now: DateTime) -> BucketRules { + BucketRules { + epss_percentile: crate::pipeline::cve_issues::epss_percentile( + std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(), + ), + now, + } +} + +/// `values` as a BSON array for an `$in`. +fn bson_list(values: &[T]) -> Bson { + mongodb::bson::to_bson(values).unwrap_or_else(|_| Bson::Array(Vec::new())) +} + +/// The findings waiting for a decision ([`UNDECIDED_STATUSES`]) matching +/// `filter`, with only the fields the inbox reads. +async fn open_findings( + db: &Database, + mut filter: Document, +) -> Result, mongodb::error::Error> { + filter.insert("status", doc! { "$in": bson_list(&UNDECIDED_STATUSES) }); + let projection: Document = InboxFinding::FIELDS + .iter() + .map(|field| ((*field).to_string(), Bson::Int32(1))) + .collect(); + let cursor = db + .findings() + .clone_with_type::() + .find(filter) + .projection(projection) + .await?; + Ok(collect_cursor_async(cursor).await) +} + +/// The CVE alerts waiting for a decision ([`alert_undecided`]) matching +/// `filter`. +async fn open_alerts( + db: &Database, + mut filter: Document, +) -> Result, mongodb::error::Error> { + filter.insert("resolved_at", Bson::Null); + filter.insert( + "$or", + vec![ + doc! { "vex": Bson::Null }, + doc! { "vex.status": VexStatus::UnderInvestigation.as_str() }, + ], + ); + let cursor = db.cve_alerts().find(filter).await?; + let alerts: Vec = collect_cursor_async(cursor).await; + Ok(alerts.into_iter().filter(alert_undecided).collect()) +} + +/// When each card key was put off until. +async fn snoozes(db: &Database) -> Result>, mongodb::error::Error> { + let cursor = db.inbox_snoozes().find(doc! {}).await?; + let snoozes: Vec = collect_cursor_async(cursor).await; + Ok(snoozes.into_iter().map(|s| (s.key, s.until)).collect()) +} + +/// The targets' names by id. +async fn target_names(db: &Database) -> Result, mongodb::error::Error> { + let mut cursor = db + .onboarded_targets() + .clone_with_type::() + .find(doc! {}) + .projection(doc! { "name": 1 }) + .await?; + let mut names = HashMap::new(); + while let Some(target) = cursor.next().await { + let target = target?; + if let (Ok(id), Ok(name)) = (target.get_object_id("_id"), target.get_str("name")) { + names.insert(id.to_hex(), name.to_string()); + } + } + Ok(names) +} + +/// The Erstbewertung of `scope` (the workspace, or one target): the open +/// items already loaded, plus the decided ones counted in the database. See +/// [`Progress`] for what counts as decided. +async fn progress( + db: &Database, + target: Option<&str>, + findings: &[InboxFinding], + alerts: &[CveAlert], +) -> Result { + let in_scope = |repo_id: &str| target.is_none_or(|t| t == repo_id); + let scope = || target.map_or_else(Document::new, |t| doc! { "repo_id": t }); + let mut decided_findings = scope(); + decided_findings.insert("status", doc! { "$in": bson_list(&DECIDED_STATUSES) }); + let mut decided_alerts = scope(); + decided_alerts.insert("resolved_at", Bson::Null); + decided_alerts.insert("vex.status", doc! { "$in": bson_list(&DECIDING_VEX) }); + let decided = db.findings().count_documents(decided_findings).await? + + db.cve_alerts().count_documents(decided_alerts).await?; + let open = findings.iter().filter(|f| in_scope(&f.repo_id)).count() + + alerts.iter().filter(|a| in_scope(&a.repo_id)).count(); + Ok(Progress { + decided, + total: decided + open as u64, + }) +} + +/// GET /api/v1/inbox[?target=&bucket=&limit=] — the bucket +/// counts, the Erstbewertung, the targets with cards, and the cards of one +/// bucket (default `today`), most urgent first. +/// +/// Cards: one per finding, one per target, package and version for CVE +/// alerts. Cards put off until a date are left out until then and come back +/// under `later`. +#[tracing::instrument(skip_all, fields(target = ?query.target, bucket = ?query.bucket))] +pub async fn get_inbox( + Extension(agent): AgentExt, + tenant: TenantCtx, + Query(query): Query, +) -> ApiResult { + let db = tenant_db(&agent, &tenant).await?; + let failed = |e: mongodb::error::Error| { + tracing::warn!("inbox: failed to load: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + }; + let now = Utc::now(); + let findings = open_findings(&db, Document::new()).await.map_err(failed)?; + let alerts = open_alerts(&db, Document::new()).await.map_err(failed)?; + let snoozes = snoozes(&db).await.map_err(failed)?; + let names = target_names(&db).await.map_err(failed)?; + let target = query.target.as_deref().filter(|t| !t.is_empty()); + let progress = progress(&db, target, &findings, &alerts) + .await + .map_err(failed)?; + + let mut cards = finding_cards(&findings, &OneCardPerFinding); + cards.extend(cve_cards(&alerts, &rules(now))); + let request = ViewRequest { + target, + bucket: query.bucket.unwrap_or_default(), + limit: query.limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT), + }; + let view = view( + apply_snoozes(cards, &snoozes, now), + &names, + progress, + request, + ); + Ok(Json(ApiResponse { + data: view, + total: None, + page: None, + })) +} + +/// The card `key` names as it stands now, with what each item is, or why +/// there is none: 400 for a malformed key, 409 when nothing on it waits for +/// a decision any more. +async fn resolve_card( + db: &Database, + key: &str, +) -> Result<(InboxCard, Vec), Refusal> { + let gone = || { + refuse( + StatusCode::CONFLICT, + "nothing on this card waits for a decision", + ) + }; + match CardKey::parse(key).ok_or_else(|| refuse(StatusCode::BAD_REQUEST, "bad key"))? { + CardKey::Finding { id } => { + let oid = + ObjectId::parse_str(&id).map_err(|_| refuse(StatusCode::BAD_REQUEST, "bad key"))?; + let findings = open_findings(db, doc! { "_id": oid }) + .await + .map_err(store_error)?; + let card = finding_cards(&findings, &OneCardPerFinding) + .into_iter() + .find(|c| c.key == key) + .ok_or_else(gone)?; + let previous = findings + .into_iter() + .map(|f| PreviousState::Finding { + id: f.id.to_hex(), + status: f.status, + }) + .collect(); + Ok((card, previous)) + } + CardKey::CvePackage { target_id } => { + let alerts = open_alerts(db, doc! { "repo_id": &target_id }) + .await + .map_err(store_error)?; + let card = cve_cards(&alerts, &rules(Utc::now())) + .into_iter() + .find(|c| c.key == key) + .ok_or_else(gone)?; + let previous = alerts + .into_iter() + .filter_map(|a| { + let id = a.id?.to_hex(); + card.item_ids.contains(&id).then(|| PreviousState::Cve { + id, + vex: a.vex.map(|v| v.status), + }) + }) + .collect(); + Ok((card, previous)) + } + } +} + +/// Set `status` on the findings `ids` the way +/// `PATCH /api/v1/findings/bulk-status` does: recorded in their history with +/// who and why, and their tracker issues closed or reopened. +async fn set_finding_status( + agent: &AgentExt, + tenant: &TenantCtx, + ids: Vec, + status: FindingStatus, + reason: Option, +) -> Result<(), Refusal> { + let request = BulkUpdateStatusRequest { + ids, + status, + reason, + }; + bulk_update_finding_status(agent.clone(), tenant.clone(), Json(request)) + .await + .map(|_| ()) + .map_err(|code| match code { + StatusCode::UNPROCESSABLE_ENTITY => refuse(code, "a reason is required"), + other => refuse(other, "status"), + }) +} + +/// State `request()` on the alerts `ids` the way `PATCH /api/v1/cves/{id}/vex` +/// does; the first refusal (a missing justification) stops before anything +/// is stored, as every alert gets the same statement. +async fn set_vex( + agent: &AgentExt, + tenant: &TenantCtx, + ids: &[String], + request: impl Fn() -> VexRequest, +) -> Result<(), Refusal> { + for id in ids { + // The answer (the stored statement) is not needed here. + let _stored = set_cve_vex( + agent.clone(), + tenant.clone(), + Path(id.clone()), + Json(request()), + ) + .await?; + } + Ok(()) +} + +/// POST /api/v1/inbox/decide `{key, action, reason?, justification?, +/// statement?}` — apply `action` to every item of card `key`, through the +/// findings' and the VEX endpoints' code, and answer what each item was +/// before (for `POST /api/v1/inbox/undo`). The card's resubmission, if any, +/// is dropped. 409 when nothing on the card waits any more, 422 for an action +/// the card does not offer or without the reason, justification or statement +/// it needs. +#[tracing::instrument(skip_all, fields(key = %req.key, action = ?req.action))] +pub async fn decide( + agent: AgentExt, + tenant: TenantCtx, + Json(req): Json, +) -> Result, Refusal> { + let db = tenant_db(&agent, &tenant) + .await + .map_err(|code| refuse(code, "tenant"))?; + let (card, previous) = resolve_card(&db, &req.key).await?; + if !card.actions.contains(&req.action) { + return Err(refuse( + StatusCode::UNPROCESSABLE_ENTITY, + "the card does not offer this action", + )); + } + let text = |s: &Option| { + s.as_deref() + .map(str::trim) + .filter(|t| !t.is_empty()) + .map(String::from) + }; + let vex = |status, justification, impact_statement, action_statement| { + move || VexRequest { + status, + justification, + impact_statement: Option::clone(&impact_statement), + action_statement: Option::clone(&action_statement), + } + }; + let ids = card.item_ids; + match req.action { + InboxAction::FalsePositive => { + set_finding_status(&agent, &tenant, ids, FindingStatus::FalsePositive, None).await?; + } + InboxAction::AcceptedRisk => { + let reason = text(&req.reason); + set_finding_status(&agent, &tenant, ids, FindingStatus::AcceptedRisk, reason).await?; + } + InboxAction::Confirm => { + set_finding_status(&agent, &tenant, ids, FindingStatus::Triaged, None).await?; + } + InboxAction::NotAffected => { + let statement = vex( + VexStatus::NotAffected, + req.justification, + text(&req.statement), + None, + ); + set_vex(&agent, &tenant, &ids, statement).await?; + } + InboxAction::Affected => { + let statement = vex(VexStatus::Affected, None, None, text(&req.statement)); + set_vex(&agent, &tenant, &ids, statement).await?; + } + } + db.inbox_snoozes() + .delete_one(doc! { "key": &req.key }) + .await + .map_err(store_error)?; + Ok(Json(DecideResponse { + key: req.key, + action: req.action, + previous, + })) +} + +/// Whether the items of `previous` are those of card `key`: the finding the +/// key names, or alerts of the key's package version. +async fn belongs_to(db: &Database, key: &str, previous: &[PreviousState]) -> Result { + match CardKey::parse(key).ok_or_else(|| refuse(StatusCode::BAD_REQUEST, "bad key"))? { + CardKey::Finding { id } => Ok(previous + .iter() + .all(|p| matches!(p, PreviousState::Finding { id: item, .. } if *item == id))), + CardKey::CvePackage { .. } => { + let mut oids = Vec::with_capacity(previous.len()); + for state in previous { + let PreviousState::Cve { id, .. } = state else { + return Ok(false); + }; + oids.push( + ObjectId::parse_str(id) + .map_err(|_| refuse(StatusCode::BAD_REQUEST, "bad id"))?, + ); + } + let cursor = db + .cve_alerts() + .find(doc! { "_id": { "$in": &oids } }) + .await + .map_err(store_error)?; + let alerts: Vec = collect_cursor_async(cursor).await; + Ok(alerts.len() == oids.len() + && alerts.iter().all(|a| { + CardKey::cve_package(&a.repo_id, &a.affected_package, &a.affected_version) + == key + })) + } + } +} + +/// POST /api/v1/inbox/undo `{key, previous}` — put the items of a decision +/// on card `key` back, through the same code the decision went through: a +/// finding gets its previous status (a new entry in its history, which keeps +/// the decision on record), an alert `under_investigation` (also when it had +/// no statement before; both leave it open). 422 when an item does not +/// belong to the card or its previous state was not an open one. +#[tracing::instrument(skip_all, fields(key = %req.key))] +pub async fn undo( + agent: AgentExt, + tenant: TenantCtx, + Json(req): Json, +) -> Result, Refusal> { + let db = tenant_db(&agent, &tenant) + .await + .map_err(|code| refuse(code, "tenant"))?; + if req.previous.is_empty() || !belongs_to(&db, &req.key, &req.previous).await? { + return Err(refuse( + StatusCode::UNPROCESSABLE_ENTITY, + "the items do not belong to the card", + )); + } + let mut by_status: BTreeMap> = BTreeMap::new(); + let mut alerts = Vec::new(); + for state in req.previous { + match state { + PreviousState::Finding { id, status } if UNDECIDED_STATUSES.contains(&status) => { + by_status.entry(status).or_default().push(id); + } + PreviousState::Cve { + id, + vex: None | Some(VexStatus::UnderInvestigation), + } => { + alerts.push(id); + } + PreviousState::Finding { .. } | PreviousState::Cve { .. } => { + return Err(refuse( + StatusCode::UNPROCESSABLE_ENTITY, + "only an open state can be restored", + )); + } + } + } + for (status, ids) in by_status { + set_finding_status(&agent, &tenant, ids, status, None).await?; + } + set_vex(&agent, &tenant, &alerts, || VexRequest { + status: VexStatus::UnderInvestigation, + justification: None, + impact_statement: None, + action_statement: None, + }) + .await?; + Ok(Json(serde_json::json!({ "status": "restored" }))) +} + +/// POST /api/v1/inbox/snooze `{key, for}` — put card `key` off: one week, one +/// month, or until a date (`{"kind": "date", "date": "2026-12-01"}`). It is +/// hidden until then and comes back under `later`. A second snooze replaces +/// the first. 400 for a malformed key, 422 for a date that is not in the +/// future. +#[tracing::instrument(skip_all, fields(key = %req.key))] +pub async fn snooze( + Extension(agent): AgentExt, + tenant: TenantCtx, + Json(req): Json, +) -> Result, Refusal> { + if CardKey::parse(&req.key).is_none() { + return Err(refuse(StatusCode::BAD_REQUEST, "bad key")); + } + let now = Utc::now(); + let until = req + .snooze_for + .until(now) + .map_err(|e| refuse(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()))?; + let actor = Actor::of(&tenant.0); + let record = InboxSnooze { + key: req.key.clone(), + until, + by: actor.id.to_string(), + by_name: actor.name, + at: now, + }; + let db = tenant_db(&agent, &tenant) + .await + .map_err(|code| refuse(code, "tenant"))?; + db.inbox_snoozes() + .replace_one(doc! { "key": &req.key }, &record) + .upsert(true) + .await + .map_err(store_error)?; + Ok(Json(SnoozeResponse { + key: req.key, + until, + })) +} + +/// DELETE /api/v1/inbox/snooze/{key} — take card `key`'s resubmission back +/// (the undo of a snooze); nothing to take back is no error. +#[tracing::instrument(skip_all, fields(key = %key))] +pub async fn unsnooze( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(key): Path, +) -> Result, Refusal> { + if CardKey::parse(&key).is_none() { + return Err(refuse(StatusCode::BAD_REQUEST, "bad key")); + } + let db = tenant_db(&agent, &tenant) + .await + .map_err(|code| refuse(code, "tenant"))?; + db.inbox_snoozes() + .delete_one(doc! { "key": &key }) + .await + .map_err(store_error)?; + Ok(Json(serde_json::json!({ "status": "deleted" }))) +} diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index c49251a..f6da802 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -13,6 +13,7 @@ pub mod git_source; pub mod graph; pub mod health; pub mod help_chat; +pub mod inbox; pub mod issues; pub mod licenses; pub mod manual_findings; diff --git a/compliance-agent/src/api/role_gate/router_tests.rs b/compliance-agent/src/api/role_gate/router_tests.rs index 2143856..675ffbd 100644 --- a/compliance-agent/src/api/role_gate/router_tests.rs +++ b/compliance-agent/src/api/role_gate/router_tests.rs @@ -126,6 +126,11 @@ fn routes() -> Vec<(Method, String, bool)> { (Method::GET, format!("/api/v1/findings/{ID}"), false), (Method::PATCH, format!("/api/v1/findings/{ID}/status"), true), (Method::PATCH, "/api/v1/findings/bulk-status".into(), true), + (Method::GET, "/api/v1/inbox".into(), false), + (Method::POST, "/api/v1/inbox/decide".into(), true), + (Method::POST, "/api/v1/inbox/undo".into(), true), + (Method::POST, "/api/v1/inbox/snooze".into(), true), + (Method::DELETE, format!("/api/v1/inbox/snooze/f-{ID}"), true), ( Method::PATCH, format!("/api/v1/findings/{ID}/feedback"), diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index e234f77..03c1dfb 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -116,6 +116,15 @@ pub fn build_router() -> Router { "/api/v1/finding-groups/decide", post(handlers::finding_groups::decide_finding_group), ) + // The "Heute" inbox (#950): open decisions in urgency buckets. + .route("/api/v1/inbox", get(handlers::inbox::get_inbox)) + .route("/api/v1/inbox/decide", post(handlers::inbox::decide)) + .route("/api/v1/inbox/undo", post(handlers::inbox::undo)) + .route("/api/v1/inbox/snooze", post(handlers::inbox::snooze)) + .route( + "/api/v1/inbox/snooze/{key}", + delete(handlers::inbox::unsnooze), + ) // VEX on a target's CVE alerts (#498). .route( "/api/v1/targets/{id}/cves", diff --git a/compliance-agent/src/database.rs b/compliance-agent/src/database.rs index adec508..8794c9b 100644 --- a/compliance-agent/src/database.rs +++ b/compliance-agent/src/database.rs @@ -618,6 +618,19 @@ impl Database { ) .await?; + // inbox_snoozes (#950): one per card key, and the resubmissions due + self.inbox_snoozes() + .create_index( + IndexModel::builder() + .keys(doc! { "key": 1 }) + .options(IndexOptions::builder().unique(true).build()) + .build(), + ) + .await?; + self.inbox_snoozes() + .create_index(IndexModel::builder().keys(doc! { "until": 1 }).build()) + .await?; + tracing::info!("Database indexes ensured"); Ok(()) } @@ -785,6 +798,12 @@ impl Database { self.inner.collection("werkbank_jobs") } + /// The cards of the "Heute" inbox put off until a date (#950). + pub fn inbox_snoozes(&self) -> Collection { + self.inner + .collection(compliance_core::models::inbox::SNOOZES_COLLECTION) + } + #[allow(dead_code)] pub fn raw_collection(&self, name: &str) -> Collection { self.inner.collection(name) diff --git a/compliance-agent/tests/inbox.rs b/compliance-agent/tests/inbox.rs new file mode 100644 index 0000000..0d3096c --- /dev/null +++ b/compliance-agent/tests/inbox.rs @@ -0,0 +1,380 @@ +//! The "Heute" inbox (#950) through the real API: cards in their buckets, +//! decisions on a card through the findings' and VEX code, undo, and +//! resubmission dates. +//! +//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without +//! one. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +mod common; + +use chrono::{Duration, Utc}; +use compliance_core::models::inbox::{CardKey, InboxSnooze}; +use compliance_core::models::{CveAlert, CveSource, Exploitation, KevEntry}; +use mongodb::bson::{doc, oid::ObjectId, Document}; +use serde_json::{json, Value}; + +use common::TestServer; + +/// A target id and its name. +const TARGET: &str = "665f1c2ab0c4d1e2f3a4b5c6"; + +/// Whether a Mongo answers at the test URI. +async fn mongo_reachable() -> bool { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let Ok(client) = mongodb::Client::with_uri_str(&uri).await else { + return false; + }; + client + .database("admin") + .run_command(doc! { "ping": 1 }) + .await + .is_ok() +} + +async fn tenant_db(server: &TestServer) -> mongodb::Database { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + mongodb::Client::with_uri_str(&uri) + .await + .unwrap() + .database(&server.tenant_db_name()) +} + +/// Store a finding; its id. +async fn finding( + db: &mongodb::Database, + title: &str, + scan_type: &str, + severity: &str, + status: &str, + file: &str, +) -> String { + let id = ObjectId::new(); + let now = mongodb::bson::DateTime::now(); + db.collection::("findings") + .insert_one(doc! { + "_id": id, + "repo_id": TARGET, + "fingerprint": format!("fp-{title}"), + "scanner": "test", + "scan_type": scan_type, + "title": title, + "description": title, + "severity": severity, + "status": status, + "file_path": file, + "line_number": 7, + "triage_action": if status == "needs_review" { "dismiss" } else { "confirm" }, + "status_history": [], + "created_at": now, + "updated_at": now, + }) + .await + .unwrap(); + id.to_hex() +} + +/// Store a CVE alert of log4j-core 2.14.1; its id. +async fn alert(db: &mongodb::Database, cve: &str, kev: bool) -> String { + let mut a = CveAlert::new( + cve.into(), + TARGET.into(), + "log4j-core".into(), + "2.14.1".into(), + CveSource::Osv, + ); + let id = ObjectId::new(); + a.id = Some(id); + a.severity = Some("CRITICAL".into()); + a.fixed_versions = vec!["2.17.1".into()]; + if kev { + a.exploitation = Some(Exploitation { + kev: Some(KevEntry { + date_added: "2021-12-10".into(), + known_ransomware: true, + }), + ..Exploitation::default() + }); + a.exploited_seen_at = Some(Utc::now() - Duration::hours(2)); + } + db.collection::("cve_alerts") + .insert_one(&a) + .await + .unwrap(); + id.to_hex() +} + +async fn inbox(server: &TestServer, query: &str) -> Value { + let resp = server.get(&format!("/api/v1/inbox{query}")).await; + assert_eq!(resp.status(), 200); + let body: Value = resp.json().await.unwrap(); + body["data"].clone() +} + +fn counts(view: &Value) -> [u64; 4] { + let c = &view["counts"]; + [ + c["today"].as_u64().unwrap(), + c["this_week"].as_u64().unwrap(), + c["later"].as_u64().unwrap(), + c["likely_false_positive"].as_u64().unwrap(), + ] +} + +#[tokio::test] +async fn the_inbox_buckets_decides_undoes_and_resubmits() { + if !mongo_reachable().await { + eprintln!("SKIP inbox: no MongoDB reachable"); + return; + } + let server = TestServer::start().await; + let db = tenant_db(&server).await; + db.collection::("onboarded_targets") + .insert_one(doc! { "_id": ObjectId::parse_str(TARGET).unwrap(), "name": "Pumpe", "target_type": "software" }) + .await + .unwrap(); + let secret = finding( + &db, + "AWS key", + "secretdetection", + "medium", + "open", + "src/config.rs", + ) + .await; + let _test_secret = finding( + &db, + "Test key", + "secretdetection", + "low", + "open", + "tests/keys.env", + ) + .await; + let high = finding(&db, "SQL injection", "sast", "high", "triaged", "src/db.rs").await; + let ai = finding( + &db, + "Weak hash", + "sast", + "medium", + "needs_review", + "src/hash.rs", + ) + .await; + finding( + &db, + "Old decision", + "sast", + "low", + "false_positive", + "src/a.rs", + ) + .await; + let a1 = alert(&db, "CVE-2021-44228", true).await; + let a2 = alert(&db, "CVE-2021-45046", false).await; + + // Today: the secret in code and log4j (KEV); this week: the high finding; + // later: the test secret; the AI's: the dismissed one. + let all = inbox(&server, "").await; + assert_eq!(counts(&all), [2, 1, 1, 1]); + assert_eq!(all["progress"], json!({ "decided": 1, "total": 7 })); + assert_eq!( + all["targets"], + json!([{ "id": TARGET, "name": "Pumpe", "cards": 5 }]) + ); + let today = all["cards"].as_array().unwrap(); + let log4j = today + .iter() + .find(|c| c["kind"] == "cve_package") + .unwrap() + .clone(); + let log4j_key = CardKey::cve_package(TARGET, "log4j-core", "2.14.1"); + assert_eq!(log4j["key"], log4j_key); + assert_eq!(log4j["count"], 2); + assert_eq!(log4j["fix_version"], "2.17.1"); + assert_eq!(log4j["reasons"][0]["kind"], "kev"); + assert!(today + .iter() + .any(|c| c["item_ids"] == json!([secret]) && c["reasons"][0]["kind"] == "secret_in_code")); + let ai_card = inbox(&server, "?bucket=likely_false_positive").await["cards"][0].clone(); + assert_eq!(ai_card["actions"], json!(["false_positive", "confirm"])); + assert_eq!(inbox(&server, "?target=other").await["counts"]["today"], 0); + + // A CVE decision needs its justification; with it, every alert of the + // card gets the statement, and undo puts them back to open. + let refused = server + .post( + "/api/v1/inbox/decide", + &json!({ "key": log4j_key, "action": "not_affected" }), + ) + .await; + assert_eq!(refused.status(), 422); + let decided = server + .post( + "/api/v1/inbox/decide", + &json!({ + "key": log4j_key, + "action": "not_affected", + "justification": "vulnerable_code_not_in_execute_path", + }), + ) + .await; + assert_eq!(decided.status(), 200); + let decided: Value = decided.json().await.unwrap(); + let mut previous = decided["previous"].as_array().unwrap().clone(); + previous.sort_by_key(|p| p["id"].as_str().unwrap().to_string()); + let mut expected = vec![ + json!({ "kind": "cve", "id": a1, "vex": null }), + json!({ "kind": "cve", "id": a2, "vex": null }), + ]; + expected.sort_by_key(|p| p["id"].as_str().unwrap().to_string()); + assert_eq!(previous, expected); + let stored = db + .collection::("cve_alerts") + .find_one(doc! { "_id": ObjectId::parse_str(&a1).unwrap() }) + .await + .unwrap() + .unwrap(); + assert_eq!( + stored.vex.map(|v| v.status), + Some(compliance_core::models::VexStatus::NotAffected) + ); + let after = inbox(&server, "").await; + assert_eq!(counts(&after), [1, 1, 1, 1]); + assert_eq!(after["progress"], json!({ "decided": 3, "total": 7 })); + let again = server + .post( + "/api/v1/inbox/decide", + &json!({ "key": log4j_key, "action": "affected", "statement": "Update" }), + ) + .await; + assert_eq!(again.status(), 409, "nothing left to decide"); + let undone = server + .post( + "/api/v1/inbox/undo", + &json!({ "key": log4j_key, "previous": decided["previous"] }), + ) + .await; + assert_eq!(undone.status(), 200); + assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 1]); + + // A finding's risk needs a reason; the status change is recorded as the + // findings endpoint records it, and undo restores the previous status. + let high_key = CardKey::finding(&high); + let no_reason = server + .post( + "/api/v1/inbox/decide", + &json!({ "key": high_key, "action": "accepted_risk" }), + ) + .await; + assert_eq!(no_reason.status(), 422); + let not_offered = server + .post( + "/api/v1/inbox/decide", + &json!({ "key": high_key, "action": "confirm" }), + ) + .await; + assert_eq!(not_offered.status(), 422); + let accepted: Value = server + .post( + "/api/v1/inbox/decide", + &json!({ "key": high_key, "action": "accepted_risk", "reason": "isolated network" }), + ) + .await + .json() + .await + .unwrap(); + assert_eq!( + accepted["previous"], + json!([{ "kind": "finding", "id": high, "status": "triaged" }]) + ); + let stored = db + .collection::("findings") + .find_one(doc! { "_id": ObjectId::parse_str(&high).unwrap() }) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.get_str("status").ok(), Some("accepted_risk")); + let history = stored.get_array("status_history").unwrap(); + assert_eq!( + history[0].as_document().unwrap().get_str("reason").ok(), + Some("isolated network") + ); + assert_eq!(counts(&inbox(&server, "").await), [2, 0, 1, 1]); + let undone = server + .post( + "/api/v1/inbox/undo", + &json!({ "key": high_key, "previous": accepted["previous"] }), + ) + .await; + assert_eq!(undone.status(), 200); + assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 1]); + // Undo only touches the card's own items. + let foreign = server + .post( + "/api/v1/inbox/undo", + &json!({ "key": high_key, "previous": [{ "kind": "finding", "id": ai, "status": "open" }] }), + ) + .await; + assert_eq!(foreign.status(), 422); + + // The AI was right: the dismissed finding is a false positive. + let confirmed = server + .post( + "/api/v1/inbox/decide", + &json!({ "key": CardKey::finding(&ai), "action": "false_positive" }), + ) + .await; + assert_eq!(confirmed.status(), 200); + assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 0]); + + // Put off: hidden until the date, then back under "later". + let secret_key = CardKey::finding(&secret); + let past = server + .post( + "/api/v1/inbox/snooze", + &json!({ "key": secret_key, "for": { "kind": "date", "date": "2020-01-01" } }), + ) + .await; + assert_eq!(past.status(), 422); + let snoozed = server + .post( + "/api/v1/inbox/snooze", + &json!({ "key": secret_key, "for": { "kind": "week" } }), + ) + .await; + assert_eq!(snoozed.status(), 200); + assert_eq!(counts(&inbox(&server, "").await), [1, 1, 1, 0]); + let record = db + .collection::("inbox_snoozes") + .find_one(doc! { "key": &secret_key }) + .await + .unwrap() + .unwrap(); + assert_eq!(record.by, "dev-user"); + assert!(record.until > Utc::now() + Duration::days(6)); + db.collection::("inbox_snoozes") + .update_one( + doc! { "key": &secret_key }, + doc! { "$set": { "until": mongodb::bson::DateTime::from_chrono(Utc::now() - Duration::hours(1)) } }, + ) + .await + .unwrap(); + let due = inbox(&server, "?bucket=later").await; + assert_eq!(counts(&due), [1, 1, 2, 0]); + assert!(due["cards"] + .as_array() + .unwrap() + .iter() + .any(|c| c["key"] == secret_key && c["reasons"][0]["kind"] == "resubmission")); + let unsnoozed = server + .delete(&format!("/api/v1/inbox/snooze/{secret_key}")) + .await; + assert_eq!(unsnoozed.status(), 200); + assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 0]); + + server.cleanup().await; +} diff --git a/compliance-core/src/models/inbox.rs b/compliance-core/src/models/inbox.rs new file mode 100644 index 0000000..ff03ef5 --- /dev/null +++ b/compliance-core/src/models/inbox.rs @@ -0,0 +1,1518 @@ +//! The "Heute" inbox (#950): the open decisions of a workspace, one card per +//! decision, sorted into four urgency buckets. +//! +//! A card is one decision about one or more items: a finding, or the CVE +//! alerts of one package version in one target. Which bucket it lands in is +//! [`natural_bucket`] of its [`Signals`]; a card someone put off +//! ("Wiedervorlage", [`InboxSnooze`]) is hidden until its date and then shown +//! under [`Bucket::Later`] ([`place`]). +//! +//! Everything here is pure: the agent loads the items and the snoozes, the +//! dashboard reads the same types back. + +use std::collections::{BTreeSet, HashMap}; + +use chrono::{DateTime, Months, NaiveDate, Utc}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use super::cve::CveAlert; +use super::finding::{FindingStatus, Occurrence, Severity}; +use super::notification::{parse_severity, NotificationSeverity}; +use super::scan::ScanType; +use super::vex::{VexJustification, VexStatus}; +use crate::enisa_docs::{self, Reportability}; + +/// The collection the snoozes are stored in, one tenant database each. +pub const SNOOZES_COLLECTION: &str = "inbox_snoozes"; + +/// The finding statuses that still wait for a person's decision. A finding +/// with any other status is decided ([`DECIDED_STATUSES`]) or resolved. +pub const UNDECIDED_STATUSES: [FindingStatus; 3] = [ + FindingStatus::Open, + FindingStatus::Triaged, + FindingStatus::NeedsReview, +]; + +/// The finding statuses a person decided: a false alarm (rule or CRA +/// mapping), ignored, or a risk accepted. Resolved findings (fixed, or gone +/// from the code) are neither decided nor open: they leave the Erstbewertung. +pub const DECIDED_STATUSES: [FindingStatus; 4] = [ + FindingStatus::FalsePositive, + FindingStatus::Ignored, + FindingStatus::AcceptedRisk, + FindingStatus::WrongMapping, +]; + +/// The VEX statuses that decide an alert. `under_investigation` says the +/// alert is not assessed yet, so it leaves the alert open. +pub const DECIDING_VEX: [VexStatus; 3] = [ + VexStatus::Affected, + VexStatus::NotAffected, + VexStatus::Fixed, +]; + +/// What the AI triage writes into `triage_action` for a finding it thinks +/// is a false alarm. +pub const AI_DISMISS: &str = "dismiss"; + +/// The four urgency buckets of the inbox. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Bucket { + /// "Heute handeln": exploited or likely to be (CISA KEV, high EPSS), a + /// CRA reporting deadline running, a secret in the product's code. + #[default] + Today, + /// "Diese Woche": high and critical, or a fix is available. + ThisWeek, + /// "Später": everything else, and every resubmission that is due. + Later, + /// "KI: wohl Fehlalarm": what the AI triage dismissed, for a person to + /// confirm or overrule. + LikelyFalsePositive, +} + +impl Bucket { + /// Every bucket, in the order the dashboard shows them. + pub const ALL: [Self; 4] = [ + Self::Today, + Self::ThisWeek, + Self::Later, + Self::LikelyFalsePositive, + ]; + + /// The name in URLs (`this_week`). + pub const fn as_str(self) -> &'static str { + match self { + Self::Today => "today", + Self::ThisWeek => "this_week", + Self::Later => "later", + Self::LikelyFalsePositive => "likely_false_positive", + } + } + + /// The bucket a URL names, if any. + pub fn parse(name: &str) -> Option { + Self::ALL.into_iter().find(|b| b.as_str() == name) + } +} + +/// What a card decides about. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CardKind { + /// One finding (later, #951: the findings of one rule in one file). + Finding, + /// The CVE alerts of one package version in one target. + CvePackage, +} + +/// Why a card is where it is: the chips on it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Reason { + /// The AI triage dismissed it as a false alarm. + AiDismissed, + /// A CVE in CISA's Known Exploited Vulnerabilities catalog. + Kev, + /// A CVE whose EPSS percentile reaches the threshold; the highest one. + Epss { percentile: f64 }, + /// A CRA Article 14 notification is due; the most urgent stage. + EnisaDeadline { + /// `early_warning`, `vulnerability_notification` or `final_report`; + /// `None` until a scan recorded when the exploitation was found. + stage: Option, + due_at: Option>, + overdue: bool, + hours_left: Option, + }, + /// A secret in the product's code (not in test code or test data). + SecretInCode, + /// A fixed version is known; the highest one named. + FixAvailable { version: String }, + /// Put off until `since`, and due now. + Resubmission { since: DateTime }, +} + +/// A decision a card offers. Each is applied to every item of the card. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum InboxAction { + /// The finding is not real: status `false_positive`. + FalsePositive, + /// Known and deliberately not fixed: status `accepted_risk`; needs a + /// reason. + AcceptedRisk, + /// The AI was wrong, the finding is real: status `triaged`. The card + /// moves to the bucket its severity puts it in. + Confirm, + /// VEX `not_affected`; needs a justification or an impact statement. + NotAffected, + /// VEX `affected`; needs an action statement (e.g. the update to make). + Affected, +} + +impl InboxAction { + /// Whether the person has to add something before it can be applied: a + /// reason, a justification or an action statement. + pub const fn needs_input(self) -> bool { + match self { + Self::AcceptedRisk | Self::NotAffected | Self::Affected => true, + Self::FalsePositive | Self::Confirm => false, + } + } + + /// Whether it applies to findings (else to CVE alerts). + pub const fn for_findings(self) -> bool { + match self { + Self::FalsePositive | Self::AcceptedRisk | Self::Confirm => true, + Self::NotAffected | Self::Affected => false, + } + } +} + +/// One decision in the inbox. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct InboxCard { + /// Stable across loads and URL-safe: `f-`, or + /// `c--` (see [`CardKey`]). + pub key: String, + pub kind: CardKind, + pub bucket: Bucket, + pub target_id: String, + /// The finding's title, or `package version`. + pub title: String, + /// The finding's place (`src/db.rs:42`), or the CVE ids. + pub subtitle: String, + /// The finding's severity, or the highest of the alerts. + pub severity: Severity, + /// For a CVE card the number of CVEs, for a finding its places. + pub count: usize, + pub reasons: Vec, + /// The ids of the findings or CVE alerts the decision applies to. + pub item_ids: Vec, + /// The decisions offered, the primary one first. + pub actions: Vec, + /// The highest fixed version a CVE card's advisories name. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fix_version: Option, + /// Why the AI dismissed it, for an AI-dismissed finding. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub note: Option, +} + +/// The parsed form of an [`InboxCard::key`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CardKey { + /// `f-`. + Finding { id: String }, + /// `c--`: the hash of package and version. + CvePackage { target_id: String }, +} + +impl CardKey { + /// The key of a single finding's card. + pub fn finding(id: &str) -> String { + format!("f-{id}") + } + + /// The key of the card of `package` `version` in target `target_id`: + /// hashed, because package names and versions hold any character + /// (`@scope/pkg`, `1:2.3-4`) and the key goes into URLs. + pub fn cve_package(target_id: &str, package: &str, version: &str) -> String { + let mut hasher = Sha256::new(); + hasher.update(package.as_bytes()); + hasher.update([0]); + hasher.update(version.as_bytes()); + let digest = hex::encode(hasher.finalize()); + format!("c-{target_id}-{}", &digest[..16]) + } + + /// What `key` names, if it is a card key. + pub fn parse(key: &str) -> Option { + let is_id = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric()); + if let Some(id) = key.strip_prefix("f-") { + return is_id(id).then(|| Self::Finding { id: id.to_string() }); + } + let (target_id, hash) = key.strip_prefix("c-")?.split_once('-')?; + (is_id(target_id) && is_id(hash)).then(|| Self::CvePackage { + target_id: target_id.to_string(), + }) + } +} + +/// The fields of a stored finding the inbox reads (a projection of +/// [`super::Finding`]). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct InboxFinding { + #[serde(rename = "_id")] + pub id: bson::oid::ObjectId, + pub repo_id: String, + pub scan_type: ScanType, + #[serde(default)] + pub rule_id: Option, + pub title: String, + pub severity: Severity, + pub status: FindingStatus, + #[serde(default)] + pub file_path: Option, + #[serde(default)] + pub line_number: Option, + #[serde(default)] + pub triage_action: Option, + #[serde(default)] + pub triage_rationale: Option, + #[serde(default)] + pub occurrences: Vec, +} + +impl InboxFinding { + /// The fields to load, as a Mongo projection's keys. + pub const FIELDS: [&'static str; 12] = [ + "_id", + "repo_id", + "scan_type", + "rule_id", + "title", + "severity", + "status", + "file_path", + "line_number", + "triage_action", + "triage_rationale", + "occurrences.file", + ]; + + /// Whether the AI triage dismissed it and no person has decided yet. + /// + /// Note: PR #958 adds `Finding::review_reason()` for this; once merged, + /// this predicate becomes a call to it. + pub fn ai_dismissed(&self) -> bool { + self.status == FindingStatus::NeedsReview + && self.triage_action.as_deref() == Some(AI_DISMISS) + } + + /// Whether it is a secret in the product's code: a secret-detection + /// finding with a place outside test code (a finding from the git history + /// without a path counts as code). + pub fn secret_in_code(&self) -> bool { + if self.scan_type != ScanType::SecretDetection { + return false; + } + if self.occurrences.is_empty() { + return self.file_path.as_deref().is_none_or(|p| !is_test_path(p)); + } + self.occurrences.iter().any(|o| !is_test_path(&o.file)) + } + + /// Where it is, `path:line`; empty without a path. + pub fn location(&self) -> String { + match (&self.file_path, self.line_number) { + (Some(path), Some(line)) => format!("{path}:{line}"), + (Some(path), None) => path.clone(), + (None, _) => String::new(), + } + } +} + +/// Whether a repo-relative `path` lies in test code or test data: a `test`, +/// `tests`, `fixtures`, `testdata` or `__mocks__` directory, or a test file by +/// name (`_test.go`, `.test.ts`, `.spec.js`, `test_x.py`), the patterns the +/// secret scan and the AI triage go by. +pub fn is_test_path(path: &str) -> bool { + const DIRS: [&str; 7] = [ + "test", + "tests", + "fixtures", + "__fixtures__", + "testdata", + "test_data", + "__mocks__", + ]; + let lower = path.to_ascii_lowercase(); + let mut parts = lower.split(['/', '\\']).filter(|p| !p.is_empty()); + let Some(file) = parts.next_back() else { + return false; + }; + if parts.any(|dir| DIRS.contains(&dir)) { + return true; + } + let stem = file.split('.').next().unwrap_or(file); + stem.ends_with("_test") + || stem.starts_with("test_") + || file.contains(".test.") + || file.contains(".spec.") + || file.contains("mock") +} + +/// What decides a card's bucket. +#[derive(Debug, Clone, PartialEq)] +pub struct Signals { + /// In CISA's KEV catalog. + pub kev: bool, + /// The highest EPSS percentile, when it reaches the threshold. + pub epss_high: Option, + /// A CRA Article 14 notification is due ([`Reportability::Reportable`]). + pub enisa_reportable: bool, + /// A secret in the product's code. + pub secret_in_code: bool, + pub severity: Severity, + /// The highest fixed version known. + pub fix_version: Option, + /// The AI triage dismissed it. + pub ai_dismissed: bool, +} + +impl Default for Signals { + /// Nothing pressing, severity info. + fn default() -> Self { + Self { + kev: false, + epss_high: None, + enisa_reportable: false, + secret_in_code: false, + severity: Severity::Info, + fix_version: None, + ai_dismissed: false, + } + } +} + +/// The bucket a card belongs in by its signals, in this order: +/// +/// 1. the AI dismissed it → [`Bucket::LikelyFalsePositive`] (the decision is +/// to confirm or overrule the AI, whatever else it is); +/// 2. KEV, high EPSS, a CRA notification due, or a secret in code → +/// [`Bucket::Today`]; +/// 3. high or critical, or a fix available → [`Bucket::ThisWeek`]; +/// 4. everything else (medium, low, info) → [`Bucket::Later`]. +pub fn natural_bucket(signals: &Signals) -> Bucket { + if signals.ai_dismissed { + Bucket::LikelyFalsePositive + } else if signals.kev + || signals.epss_high.is_some() + || signals.enisa_reportable + || signals.secret_in_code + { + Bucket::Today + } else if signals.severity >= Severity::High || signals.fix_version.is_some() { + Bucket::ThisWeek + } else { + Bucket::Later + } +} + +/// Where a card in `natural` shows, given its snooze: hidden (`None`) until +/// `until`, under [`Bucket::Later`] from then on, in `natural` when it was +/// never put off. +pub fn place(natural: Bucket, until: Option>, now: DateTime) -> Option { + match until { + Some(until) if until > now => None, + Some(_) => Some(Bucket::Later), + None => Some(natural), + } +} + +/// Whether a finding with `status` waits for a decision. +pub fn finding_undecided(status: &FindingStatus) -> bool { + UNDECIDED_STATUSES.contains(status) +} + +/// Whether an alert waits for a decision: still reported (not resolved by a +/// scan), and without a VEX statement other than `under_investigation`. +pub fn alert_undecided(alert: &CveAlert) -> bool { + alert.resolved_at.is_none() + && alert + .vex + .as_ref() + .is_none_or(|v| !DECIDING_VEX.contains(&v.status)) +} + +/// What the bucket rules depend on besides the items. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct BucketRules { + /// The EPSS percentile from which a CVE is likely exploited (the CVE + /// issues' threshold, `CVE_ISSUE_EPSS_PERCENTILE`); `None`: EPSS is + /// not used. + pub epss_percentile: Option, + pub now: DateTime, +} + +/// How findings become cards: one card per finding now; #951 groups them by +/// rule and file. A grouping returns the groups, each a card. +pub trait FindingGrouping { + /// The groups of `findings`, each non-empty, each one card. + fn groups<'a>(&self, findings: &'a [InboxFinding]) -> Vec>; + + /// The card key of `group` (its first member's for a single finding). + fn key(&self, group: &[&InboxFinding]) -> String; +} + +/// One card per finding. +#[derive(Debug, Clone, Copy, Default)] +pub struct OneCardPerFinding; + +impl FindingGrouping for OneCardPerFinding { + fn groups<'a>(&self, findings: &'a [InboxFinding]) -> Vec> { + findings.iter().map(|f| vec![f]).collect() + } + + fn key(&self, group: &[&InboxFinding]) -> String { + group + .first() + .map(|f| CardKey::finding(&f.id.to_hex())) + .unwrap_or_default() + } +} + +/// The reasons `signals` give, most pressing first. +fn reasons(signals: &Signals, enisa: Option) -> Vec { + let mut reasons = Vec::new(); + if signals.ai_dismissed { + reasons.push(Reason::AiDismissed); + } + if signals.kev { + reasons.push(Reason::Kev); + } + if let Some(percentile) = signals.epss_high { + reasons.push(Reason::Epss { percentile }); + } + reasons.extend(enisa); + if signals.secret_in_code { + reasons.push(Reason::SecretInCode); + } + if let Some(version) = &signals.fix_version { + reasons.push(Reason::FixAvailable { + version: version.clone(), + }); + } + reasons +} + +/// The cards of `findings`, grouped by `grouping`, in their natural buckets. +pub fn finding_cards(findings: &[InboxFinding], grouping: &impl FindingGrouping) -> Vec { + grouping + .groups(findings) + .into_iter() + .filter_map(|group| { + let first = *group.first()?; + let signals = Signals { + secret_in_code: group.iter().any(|f| f.secret_in_code()), + severity: group.iter().map(|f| f.severity.clone()).max()?, + ai_dismissed: group.iter().all(|f| f.ai_dismissed()), + ..Signals::default() + }; + let bucket = natural_bucket(&signals); + let actions = if bucket == Bucket::LikelyFalsePositive { + vec![InboxAction::FalsePositive, InboxAction::Confirm] + } else { + vec![InboxAction::FalsePositive, InboxAction::AcceptedRisk] + }; + Some(InboxCard { + key: grouping.key(&group), + kind: CardKind::Finding, + bucket, + target_id: first.repo_id.clone(), + title: first.title.clone(), + subtitle: first.location(), + severity: signals.severity.clone(), + count: group.iter().map(|f| f.occurrences.len().max(1)).sum(), + reasons: reasons(&signals, None), + item_ids: group.iter().map(|f| f.id.to_hex()).collect(), + actions, + fix_version: None, + note: signals + .ai_dismissed + .then(|| first.triage_rationale.clone()) + .flatten(), + }) + }) + .collect() +} + +/// A finding severity for a CVE alert's rating. +fn severity_of(alert: &CveAlert) -> Severity { + match parse_severity(alert.severity.as_deref(), alert.cvss_score) { + NotificationSeverity::Critical => Severity::Critical, + NotificationSeverity::High => Severity::High, + NotificationSeverity::Medium => Severity::Medium, + NotificationSeverity::Low => Severity::Low, + } +} + +/// The most urgent CRA deadline of `alerts` (one package version's), as a +/// reason; `None` when none of them is to be notified. +fn enisa_reason(alerts: &[&CveAlert], now: DateTime) -> Option { + let mut cves: Vec<&str> = alerts + .iter() + .filter(|a| enisa_docs::reportability(a) == Reportability::Reportable) + .map(|a| a.cve()) + .collect(); + if cves.is_empty() { + return None; + } + cves.sort_unstable(); + cves.dedup(); + let most_urgent = cves + .iter() + .flat_map(|cve| { + let group: Vec<&CveAlert> = + alerts.iter().copied().filter(|a| a.cve() == *cve).collect(); + enisa_docs::exploited_seen_at(&group) + .map(|seen| enisa_docs::deadlines(&group, seen, now)) + .unwrap_or_default() + }) + .filter(|stage| stage.due_at.is_some()) + .min_by_key(|stage| stage.due_at); + Some(match most_urgent { + Some(stage) => Reason::EnisaDeadline { + stage: Some(stage.stage.to_string()), + due_at: stage.due_at, + overdue: stage.overdue, + hours_left: stage.hours_left, + }, + None => Reason::EnisaDeadline { + stage: None, + due_at: None, + overdue: false, + hours_left: None, + }, + }) +} + +/// The cards of `alerts`: one per target, package and version, of the +/// alerts still waiting for a decision ([`alert_undecided`]), in their +/// natural buckets. +pub fn cve_cards(alerts: &[CveAlert], rules: &BucketRules) -> Vec { + let mut groups: HashMap<(&str, &str, &str), Vec<&CveAlert>> = HashMap::new(); + for alert in alerts + .iter() + .filter(|a| alert_undecided(a) && a.id.is_some()) + { + groups + .entry(( + alert.repo_id.as_str(), + alert.affected_package.as_str(), + alert.affected_version.as_str(), + )) + .or_default() + .push(alert); + } + groups + .into_iter() + .map(|((target_id, package, version), group)| { + cve_card(target_id, package, version, &group, rules) + }) + .collect() +} + +/// The card of one package version's `group` of alerts. +fn cve_card( + target_id: &str, + package: &str, + version: &str, + group: &[&CveAlert], + rules: &BucketRules, +) -> InboxCard { + let epss_high = group + .iter() + .filter_map(|a| a.exploitation.as_ref()?.epss.as_ref().map(|e| e.percentile)) + .filter(|p| { + rules + .epss_percentile + .is_some_and(|threshold| *p >= threshold) + }) + .max_by(f64::total_cmp); + let fix_version = group + .iter() + .flat_map(|a| a.fixed_versions.iter()) + .max_by(|a, b| crate::version::cmp_dotted(a, b)) + .cloned(); + let enisa = enisa_reason(group, rules.now); + let signals = Signals { + kev: group + .iter() + .any(|a| a.exploitation.as_ref().is_some_and(|e| e.kev.is_some())), + epss_high, + enisa_reportable: enisa.is_some(), + severity: group + .iter() + .map(|a| severity_of(a)) + .max() + .unwrap_or(Severity::Info), + fix_version, + ..Signals::default() + }; + let cve_ids: BTreeSet<&str> = group.iter().map(|a| a.cve()).collect(); + let actions = if signals.fix_version.is_some() { + vec![InboxAction::Affected, InboxAction::NotAffected] + } else { + vec![InboxAction::NotAffected, InboxAction::Affected] + }; + InboxCard { + key: CardKey::cve_package(target_id, package, version), + kind: CardKind::CvePackage, + bucket: natural_bucket(&signals), + target_id: target_id.to_string(), + title: format!("{package} {version}"), + subtitle: cve_ids.iter().copied().collect::>().join(", "), + severity: signals.severity.clone(), + count: cve_ids.len(), + reasons: reasons(&signals, enisa), + item_ids: group + .iter() + .filter_map(|a| a.id.map(|o| o.to_hex())) + .collect(), + actions, + fix_version: signals.fix_version, + note: None, + } +} + +/// `cards` as they show at `now`: those put off and not due yet are left +/// out, those due move to [`Bucket::Later`] with a [`Reason::Resubmission`]. +/// +/// # Arguments +/// +/// * `cards` - the cards in their natural buckets +/// * `snoozes` - when each card key was put off until +/// * `now` - the moment to evaluate the snoozes at +pub fn apply_snoozes( + cards: Vec, + snoozes: &HashMap>, + now: DateTime, +) -> Vec { + cards + .into_iter() + .filter_map(|mut card| { + let until = snoozes.get(&card.key).copied(); + card.bucket = place(card.bucket, until, now)?; + if let Some(since) = until { + card.reasons.insert(0, Reason::Resubmission { since }); + } + Some(card) + }) + .collect() +} + +/// How many cards each bucket holds. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct InboxCounts { + pub today: u64, + pub this_week: u64, + pub later: u64, + pub likely_false_positive: u64, +} + +impl InboxCounts { + /// The count of `bucket`. + pub const fn get(&self, bucket: Bucket) -> u64 { + match bucket { + Bucket::Today => self.today, + Bucket::ThisWeek => self.this_week, + Bucket::Later => self.later, + Bucket::LikelyFalsePositive => self.likely_false_positive, + } + } + + /// The counts of `cards`. + pub fn of<'a>(cards: impl IntoIterator) -> Self { + cards.into_iter().fold(Self::default(), |mut counts, card| { + *match card.bucket { + Bucket::Today => &mut counts.today, + Bucket::ThisWeek => &mut counts.this_week, + Bucket::Later => &mut counts.later, + Bucket::LikelyFalsePositive => &mut counts.likely_false_positive, + } += 1; + counts + }) + } + + /// Every bucket's cards together. + pub const fn total(&self) -> u64 { + self.today + self.this_week + self.later + self.likely_false_positive + } +} + +/// The Erstbewertung: of the items in scope (every finding that is not +/// resolved, every CVE alert still reported), how many a person decided. +/// +/// Decided means a finding with a status in [`DECIDED_STATUSES`], or an +/// alert with a VEX statement in [`DECIDING_VEX`]. Open findings +/// ([`UNDECIDED_STATUSES`]) and alerts without a statement or +/// `under_investigation` are what is left to decide. Items count one by one, +/// not by card: a package card with five CVEs is five alerts. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Progress { + pub decided: u64, + pub total: u64, +} + +impl Progress { + /// The decided share in whole percent, 0 when nothing is in scope. + pub fn percent(&self) -> u64 { + if self.total == 0 { + return 0; + } + self.decided.min(self.total) * 100 / self.total + } +} + +/// One target in the chips above the cards. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct InboxTarget { + pub id: String, + pub name: String, + /// Its cards in all buckets. + pub cards: u64, +} + +/// `GET /api/v1/inbox`: the counts, the Erstbewertung, the targets with cards +/// and the cards of one bucket. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct InboxView { + /// The bucket whose cards are listed. + pub bucket: Bucket, + pub counts: InboxCounts, + pub progress: Progress, + /// Every target with cards (of the whole workspace, also when one target + /// is chosen), the most cards first. + pub targets: Vec, + /// The bucket's cards, most urgent first, at most the request's limit. + pub cards: Vec, +} + +/// The order of cards within a bucket: due resubmissions and the most +/// pressing reasons first, then by severity, then by the number of items. +fn urgency(card: &InboxCard) -> impl Ord { + ( + std::cmp::Reverse(card.severity.clone()), + std::cmp::Reverse(card.reasons.len()), + std::cmp::Reverse(card.count), + card.title.clone(), + ) +} + +/// What a [`view`] is made of besides the cards. +#[derive(Debug, Clone, Copy)] +pub struct ViewRequest<'a> { + /// Only this target's cards and counts. + pub target: Option<&'a str>, + pub bucket: Bucket, + /// The most cards to list. + pub limit: usize, +} + +/// The view of `cards` (every visible card of the workspace) for `request`. +/// +/// # Arguments +/// +/// * `cards` - every card after [`apply_snoozes`] +/// * `names` - the targets' names by id; a target without one shows its id +/// * `progress` - the Erstbewertung of the chosen scope +/// * `request` - the target, bucket and limit asked for +pub fn view( + cards: Vec, + names: &HashMap, + progress: Progress, + request: ViewRequest<'_>, +) -> InboxView { + let mut per_target: HashMap<&str, u64> = HashMap::new(); + for card in &cards { + *per_target.entry(card.target_id.as_str()).or_default() += 1; + } + let mut targets: Vec = per_target + .into_iter() + .map(|(id, count)| InboxTarget { + id: id.to_string(), + name: names.get(id).cloned().unwrap_or_else(|| id.to_string()), + cards: count, + }) + .collect(); + targets.sort_by(|a, b| b.cards.cmp(&a.cards).then_with(|| a.name.cmp(&b.name))); + let in_scope: Vec = cards + .into_iter() + .filter(|c| request.target.is_none_or(|t| c.target_id == t)) + .collect(); + let counts = InboxCounts::of(&in_scope); + let mut listed: Vec = in_scope + .into_iter() + .filter(|c| c.bucket == request.bucket) + .collect(); + listed.sort_by_cached_key(urgency); + listed.truncate(request.limit); + InboxView { + bucket: request.bucket, + counts, + progress, + targets, + cards: listed, + } +} + +/// `POST /api/v1/inbox/decide`: apply `action` to every item of card `key`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct DecideRequest { + pub key: String, + pub action: InboxAction, + /// Why a risk is accepted. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason: Option, + /// Why the product is not affected (`not_affected`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub justification: Option, + /// The VEX text: the impact statement of a `not_affected`, the action + /// statement of an `affected`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub statement: Option, +} + +/// What an item was before a decision, to undo it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum PreviousState { + /// A finding and its status. + Finding { id: String, status: FindingStatus }, + /// A CVE alert and its VEX status (`None`: no statement). + Cve { id: String, vex: Option }, +} + +/// The answer to a decision: what each item was before. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DecideResponse { + pub key: String, + pub action: InboxAction, + pub previous: Vec, +} + +/// `POST /api/v1/inbox/undo`: put the items of a decision back. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct UndoRequest { + pub key: String, + pub previous: Vec, +} + +/// How long a card is put off. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum SnoozeFor { + /// Seven days. + Week, + /// One calendar month. + Month, + /// Until the start of `date` (UTC). + Date { date: NaiveDate }, +} + +/// Why a card cannot be put off. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum SnoozeError { + #[error("the resubmission date must lie in the future")] + NotInFuture, +} + +impl SnoozeFor { + /// When a card put off at `now` comes back. + /// + /// # Errors + /// + /// [`SnoozeError::NotInFuture`] for a date that has begun or passed. + pub fn until(self, now: DateTime) -> Result, SnoozeError> { + let until = match self { + Self::Week => now + chrono::Duration::days(7), + Self::Month => now + .checked_add_months(Months::new(1)) + .ok_or(SnoozeError::NotInFuture)?, + Self::Date { date } => date.and_time(chrono::NaiveTime::MIN).and_utc(), + }; + if until <= now { + return Err(SnoozeError::NotInFuture); + } + Ok(until) + } +} + +/// `POST /api/v1/inbox/snooze`: put card `key` off. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SnoozeRequest { + pub key: String, + #[serde(rename = "for")] + pub snooze_for: SnoozeFor, +} + +/// The answer to a snooze: when the card comes back. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SnoozeResponse { + pub key: String, + pub until: DateTime, +} + +/// A card put off ("Wiedervorlage"), in [`SNOOZES_COLLECTION`] of the +/// tenant's database: one per card key. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct InboxSnooze { + pub key: String, + #[serde(with = "super::serde_helpers::bson_datetime")] + pub until: DateTime, + /// The user id of whoever put it off. + pub by: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub by_name: Option, + #[serde(with = "super::serde_helpers::bson_datetime")] + pub at: DateTime, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::models::cve::{CveSource, EpssScore, Exploitation, KevEntry}; + use crate::models::vex::VexAssessment; + use chrono::TimeZone; + + fn now() -> DateTime { + Utc.with_ymd_and_hms(2026, 11, 10, 12, 0, 0) + .single() + .unwrap_or_default() + } + + fn rules() -> BucketRules { + BucketRules { + epss_percentile: Some(0.95), + now: now(), + } + } + + fn finding(severity: Severity) -> InboxFinding { + InboxFinding { + id: bson::oid::ObjectId::new(), + repo_id: "t1".into(), + scan_type: ScanType::Sast, + rule_id: Some("rule".into()), + title: "SQL injection".into(), + severity, + status: FindingStatus::Open, + file_path: Some("src/db.rs".into()), + line_number: Some(42), + triage_action: None, + triage_rationale: None, + occurrences: Vec::new(), + } + } + + fn alert(cve: &str, package: &str, version: &str) -> CveAlert { + let mut a = CveAlert::new( + cve.into(), + "t1".into(), + package.into(), + version.into(), + CveSource::Osv, + ); + a.id = Some(bson::oid::ObjectId::new()); + a.severity = Some("MEDIUM".into()); + a + } + + fn bucket_of(signals: Signals) -> Bucket { + natural_bucket(&signals) + } + + #[test] + fn exploited_likely_exploited_reportable_and_secrets_are_for_today() { + for signals in [ + Signals { + kev: true, + ..Signals::default() + }, + Signals { + epss_high: Some(0.97), + ..Signals::default() + }, + Signals { + enisa_reportable: true, + ..Signals::default() + }, + Signals { + secret_in_code: true, + ..Signals::default() + }, + ] { + assert_eq!(bucket_of(signals.clone()), Bucket::Today, "{signals:?}"); + } + } + + #[test] + fn high_and_critical_and_fixable_are_for_this_week() { + for severity in [Severity::High, Severity::Critical] { + assert_eq!( + bucket_of(Signals { + severity, + ..Signals::default() + }), + Bucket::ThisWeek + ); + } + assert_eq!( + bucket_of(Signals { + severity: Severity::Low, + fix_version: Some("2.17.1".into()), + ..Signals::default() + }), + Bucket::ThisWeek + ); + } + + #[test] + fn medium_low_and_info_are_for_later() { + for severity in [Severity::Medium, Severity::Low, Severity::Info] { + assert_eq!( + bucket_of(Signals { + severity, + ..Signals::default() + }), + Bucket::Later + ); + } + } + + #[test] + fn what_the_ai_dismissed_is_its_own_bucket_whatever_else_it_is() { + assert_eq!( + bucket_of(Signals { + ai_dismissed: true, + secret_in_code: true, + severity: Severity::Critical, + ..Signals::default() + }), + Bucket::LikelyFalsePositive + ); + } + + #[test] + fn a_snoozed_card_hides_until_its_date_then_comes_back_under_later() { + let tomorrow = now() + chrono::Duration::days(1); + let yesterday = now() - chrono::Duration::days(1); + assert_eq!(place(Bucket::Today, Some(tomorrow), now()), None); + assert_eq!( + place(Bucket::Today, Some(yesterday), now()), + Some(Bucket::Later) + ); + assert_eq!( + place(Bucket::Today, Some(now()), now()), + Some(Bucket::Later) + ); + assert_eq!(place(Bucket::ThisWeek, None, now()), Some(Bucket::ThisWeek)); + } + + #[test] + fn snoozes_hide_or_resubmit_cards() { + let due = finding(Severity::High); + let hidden = finding(Severity::High); + let open = finding(Severity::High); + let cards = finding_cards( + &[due.clone(), hidden.clone(), open.clone()], + &OneCardPerFinding, + ); + let since = now() - chrono::Duration::hours(1); + let snoozes = HashMap::from([ + (CardKey::finding(&due.id.to_hex()), since), + ( + CardKey::finding(&hidden.id.to_hex()), + now() + chrono::Duration::days(7), + ), + ]); + let shown = apply_snoozes(cards, &snoozes, now()); + assert_eq!(shown.len(), 2); + let resubmitted = shown + .iter() + .find(|c| c.item_ids == [due.id.to_hex()]) + .cloned(); + assert_eq!(resubmitted.as_ref().map(|c| c.bucket), Some(Bucket::Later)); + assert_eq!( + resubmitted.map(|c| c.reasons), + Some(vec![Reason::Resubmission { since }]) + ); + assert!(shown + .iter() + .any(|c| c.item_ids == [open.id.to_hex()] && c.bucket == Bucket::ThisWeek)); + } + + #[test] + fn a_finding_is_one_card_with_its_actions() { + let mut ai = finding(Severity::Medium); + ai.status = FindingStatus::NeedsReview; + ai.triage_action = Some(AI_DISMISS.into()); + ai.triage_rationale = Some("test helper".into()); + let mut unsure = finding(Severity::Medium); + unsure.status = FindingStatus::NeedsReview; + unsure.triage_action = Some("control_not_confirmed".into()); + let cards = finding_cards(&[ai.clone(), unsure], &OneCardPerFinding); + assert_eq!(cards[0].key, format!("f-{}", ai.id.to_hex())); + assert_eq!(cards[0].bucket, Bucket::LikelyFalsePositive); + assert_eq!( + cards[0].actions, + [InboxAction::FalsePositive, InboxAction::Confirm] + ); + assert_eq!(cards[0].note.as_deref(), Some("test helper")); + assert_eq!(cards[0].subtitle, "src/db.rs:42"); + assert_eq!(cards[0].reasons, [Reason::AiDismissed]); + // Needs review for another reason: the severity decides. + assert_eq!(cards[1].bucket, Bucket::Later); + assert_eq!( + cards[1].actions, + [InboxAction::FalsePositive, InboxAction::AcceptedRisk] + ); + } + + #[test] + fn a_secret_counts_in_code_but_not_in_tests() { + let mut secret = finding(Severity::Medium); + secret.scan_type = ScanType::SecretDetection; + assert!(secret.secret_in_code()); + secret.file_path = Some("tests/fixtures/keys.env".into()); + assert!(!secret.secret_in_code()); + secret.occurrences = vec![ + Occurrence { + file: "src/config_test.go".into(), + line: None, + variant: None, + decision: None, + }, + Occurrence { + file: "src/config.go".into(), + line: None, + variant: None, + decision: None, + }, + ]; + assert!(secret.secret_in_code()); + secret.file_path = None; + secret.occurrences.clear(); + assert!(secret.secret_in_code(), "a secret from the history counts"); + let mut sast = finding(Severity::Medium); + sast.file_path = Some("src/main.rs".into()); + assert!(!sast.secret_in_code()); + } + + #[test] + fn test_paths_are_recognised_narrowly() { + for path in [ + "tests/app.py", + "src/test/java/AppTest.java", + "pkg/parser/testdata/x.json", + "web/src/app.spec.ts", + "web/src/app.test.js", + "cmd/main_test.go", + "test_config.py", + "src/__mocks__/api.js", + "Fixtures\\keys.pem", + ] { + assert!(is_test_path(path), "{path}"); + } + for path in [ + "src/main.rs", + "contest/app.py", + "src/latest.rs", + "", + "testing.md", + ] { + assert!(!is_test_path(path), "{path}"); + } + } + + #[test] + fn alerts_of_one_package_version_are_one_card() { + let mut kev = alert("CVE-2021-44228", "log4j-core", "2.14.1"); + kev.exploitation = Some(Exploitation { + kev: Some(KevEntry { + date_added: "2021-12-10".into(), + known_ransomware: true, + }), + ..Exploitation::default() + }); + kev.exploited_seen_at = Some(now() - chrono::Duration::hours(10)); + kev.fixed_versions = vec!["2.15.0".into()]; + let mut other = alert("CVE-2021-45046", "log4j-core", "2.14.1"); + other.severity = Some("CRITICAL".into()); + other.fixed_versions = vec!["2.16.0".into(), "2.12.2".into()]; + let elsewhere = alert("CVE-2020-1", "commons-text", "1.9"); + let cards = cve_cards(&[kev.clone(), other, elsewhere], &rules()); + assert_eq!(cards.len(), 2); + let log4j = cards + .iter() + .find(|c| c.title == "log4j-core 2.14.1") + .cloned(); + let Some(log4j) = log4j else { + panic!("no log4j card"); + }; + assert_eq!( + log4j.key, + CardKey::cve_package("t1", "log4j-core", "2.14.1") + ); + assert_eq!(log4j.kind, CardKind::CvePackage); + assert_eq!(log4j.bucket, Bucket::Today); + assert_eq!(log4j.count, 2); + assert_eq!(log4j.subtitle, "CVE-2021-44228, CVE-2021-45046"); + assert_eq!(log4j.severity, Severity::Critical); + assert_eq!(log4j.fix_version.as_deref(), Some("2.16.0")); + assert_eq!(log4j.item_ids.len(), 2); + assert_eq!( + log4j.actions, + [InboxAction::Affected, InboxAction::NotAffected] + ); + assert_eq!(log4j.reasons[0], Reason::Kev); + assert!(matches!( + &log4j.reasons[1], + Reason::EnisaDeadline { stage: Some(stage), overdue: false, hours_left: Some(14), .. } + if stage == "early_warning" + )); + assert_eq!( + log4j.reasons[2], + Reason::FixAvailable { + version: "2.16.0".into() + } + ); + let commons = cards.iter().find(|c| c.title == "commons-text 1.9"); + assert_eq!(commons.map(|c| c.bucket), Some(Bucket::Later)); + assert_eq!( + commons.map(|c| c.actions.clone()), + Some(vec![InboxAction::NotAffected, InboxAction::Affected]) + ); + } + + #[test] + fn a_high_epss_is_for_today_below_the_threshold_it_is_not() { + let mut likely = alert("CVE-2024-1", "pkg", "1.0"); + likely.exploitation = Some(Exploitation { + epss: Some(EpssScore { + score: 0.4, + percentile: 0.97, + date: String::new(), + }), + ..Exploitation::default() + }); + let cards = cve_cards(std::slice::from_ref(&likely), &rules()); + assert_eq!(cards[0].bucket, Bucket::Today); + assert_eq!(cards[0].reasons, [Reason::Epss { percentile: 0.97 }]); + let off = BucketRules { + epss_percentile: None, + now: now(), + }; + assert_eq!(cve_cards(&[likely], &off)[0].bucket, Bucket::Later); + } + + #[test] + fn decided_and_resolved_alerts_make_no_card() { + let statement = |status| VexAssessment { + status, + justification: None, + impact_statement: None, + action_statement: None, + by: "u1".into(), + by_name: None, + at: now(), + by_scan: false, + }; + let mut investigating = alert("CVE-2024-1", "a", "1"); + investigating.vex = Some(statement(VexStatus::UnderInvestigation)); + let mut affected = alert("CVE-2024-2", "b", "1"); + affected.vex = Some(statement(VexStatus::Affected)); + let mut gone = alert("CVE-2024-3", "c", "1"); + gone.resolved_at = Some(now()); + assert!(alert_undecided(&investigating)); + assert!(!alert_undecided(&affected)); + assert!(!alert_undecided(&gone)); + let cards = cve_cards(&[investigating, affected, gone], &rules()); + assert_eq!(cards.len(), 1); + assert_eq!(cards[0].title, "a 1"); + } + + #[test] + fn only_open_triaged_and_needs_review_findings_wait() { + for status in UNDECIDED_STATUSES { + assert!(finding_undecided(&status)); + } + for status in DECIDED_STATUSES { + assert!(!finding_undecided(&status)); + } + assert!(!finding_undecided(&FindingStatus::Resolved)); + } + + #[test] + fn card_keys_are_stable_url_safe_and_parse_back() { + let a = CardKey::cve_package("665f1c2ab0c4d1e2f3a4b5c6", "@scope/pkg", "1:2.3-4"); + assert_eq!( + a, + CardKey::cve_package("665f1c2ab0c4d1e2f3a4b5c6", "@scope/pkg", "1:2.3-4") + ); + assert_ne!( + a, + CardKey::cve_package("665f1c2ab0c4d1e2f3a4b5c6", "@scope/pk", "g1:2.3-4") + ); + assert!(a.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')); + assert_eq!( + CardKey::parse(&a), + Some(CardKey::CvePackage { + target_id: "665f1c2ab0c4d1e2f3a4b5c6".into() + }) + ); + assert_eq!( + CardKey::parse("f-665f1c2ab0c4d1e2f3a4b5c6"), + Some(CardKey::Finding { + id: "665f1c2ab0c4d1e2f3a4b5c6".into() + }) + ); + for bad in ["", "f-", "x-1", "c-abc", "f-../x", "c-a-b/c"] { + assert_eq!(CardKey::parse(bad), None, "{bad}"); + } + } + + #[test] + fn snooze_dates_lie_in_the_future() { + assert_eq!( + SnoozeFor::Week.until(now()), + Ok(now() + chrono::Duration::days(7)) + ); + assert_eq!( + SnoozeFor::Month.until(now()).map(|d| d.date_naive()), + Ok(NaiveDate::from_ymd_opt(2026, 12, 10).unwrap_or_default()) + ); + let date = |d| NaiveDate::from_ymd_opt(2026, 11, d).unwrap_or_default(); + assert_eq!( + SnoozeFor::Date { date: date(11) } + .until(now()) + .map(|d| d.to_rfc3339()), + Ok("2026-11-11T00:00:00+00:00".to_string()) + ); + assert_eq!( + SnoozeFor::Date { date: date(10) }.until(now()), + Err(SnoozeError::NotInFuture) + ); + assert_eq!( + serde_json::from_value::( + serde_json::json!({ "kind": "date", "date": "2026-12-24" }) + ) + .ok(), + Some(SnoozeFor::Date { + date: NaiveDate::from_ymd_opt(2026, 12, 24).unwrap_or_default() + }) + ); + } + + #[test] + fn the_view_counts_lists_one_bucket_and_scopes_to_a_target() { + let mut high = finding(Severity::High); + high.repo_id = "t2".into(); + let medium = finding(Severity::Medium); + let critical = finding(Severity::Critical); + let cards = finding_cards(&[high, medium, critical], &OneCardPerFinding); + let names = HashMap::from([("t1".to_string(), "Pumpe".to_string())]); + let progress = Progress { + decided: 1, + total: 4, + }; + let all = view( + cards.clone(), + &names, + progress, + ViewRequest { + target: None, + bucket: Bucket::ThisWeek, + limit: 10, + }, + ); + assert_eq!(all.counts.this_week, 2); + assert_eq!(all.counts.later, 1); + assert_eq!(all.counts.total(), 3); + assert_eq!(all.cards.len(), 2); + assert_eq!( + all.cards[0].severity, + Severity::Critical, + "most severe first" + ); + assert_eq!(all.targets[0].name, "Pumpe"); + assert_eq!(all.targets[0].cards, 2); + assert_eq!( + all.targets[1].name, "t2", + "a target without a name shows its id" + ); + let one = view( + cards, + &names, + progress, + ViewRequest { + target: Some("t2"), + bucket: Bucket::ThisWeek, + limit: 10, + }, + ); + assert_eq!(one.counts.total(), 1); + assert_eq!(one.targets.len(), 2, "the chips keep every target"); + let limited = view( + Vec::new(), + &names, + Progress::default(), + ViewRequest { + target: None, + bucket: Bucket::Today, + limit: 0, + }, + ); + assert!(limited.cards.is_empty()); + } + + #[test] + fn progress_is_a_share_of_the_items_in_scope() { + assert_eq!( + Progress { + decided: 1, + total: 3 + } + .percent(), + 33 + ); + assert_eq!( + Progress { + decided: 0, + total: 0 + } + .percent(), + 0 + ); + assert_eq!( + Progress { + decided: 5, + total: 5 + } + .percent(), + 100 + ); + } + + #[test] + fn the_wire_names_are_stable() { + assert_eq!( + serde_json::to_value(Bucket::LikelyFalsePositive).ok(), + Some(serde_json::json!("likely_false_positive")) + ); + for bucket in Bucket::ALL { + assert_eq!(Bucket::parse(bucket.as_str()), Some(bucket)); + assert_eq!( + serde_json::to_value(bucket).ok(), + Some(serde_json::json!(bucket.as_str())) + ); + } + assert_eq!( + serde_json::to_value(PreviousState::Cve { + id: "a".into(), + vex: None + }) + .ok(), + Some(serde_json::json!({ "kind": "cve", "id": "a", "vex": null })) + ); + assert!(InboxAction::AcceptedRisk.needs_input()); + assert!(!InboxAction::FalsePositive.needs_input()); + assert!(InboxAction::Confirm.for_findings()); + assert!(!InboxAction::Affected.for_findings()); + } +} diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 0cce5de..729f7e6 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -9,6 +9,7 @@ pub mod finding; pub mod finding_group; pub mod git_source; pub mod graph; +pub mod inbox; pub mod issue; pub mod license; pub mod license_policy; diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 7235427..c0bcf8e 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -7117,3 +7117,428 @@ input[type="file"] { .ticket-links a:hover { text-decoration: underline; } + +/* ── Heute: the inbox of open decisions (#950) ── */ + +/* The page takes the keyboard (j/k/f/a/s); no ring around the whole page. */ +.inbox-page:focus { + outline: none; +} + +.nav-count { + margin-left: auto; + min-width: 18px; + padding: 0 5px; + border-radius: 9px; + background: var(--danger); + color: #fff; + font-family: var(--font-mono); + font-size: 10.5px; + font-weight: 600; + line-height: 18px; + text-align: center; +} + +.sidebar.collapsed .nav-count { + position: absolute; + top: 1px; + right: 1px; + min-width: 15px; + line-height: 15px; + font-size: 9px; +} + +.inbox-progress { + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + padding: 12px 14px; + margin-bottom: 12px; +} + +.inbox-progress-head { + display: flex; + align-items: baseline; + gap: 10px; + margin-bottom: 8px; + font-size: 12.5px; +} + +.inbox-progress-label { + font-weight: 600; + color: var(--text-primary); +} + +.inbox-progress-value { + color: var(--text-tertiary); +} + +.inbox-progress-percent { + margin-left: auto; + font-family: var(--font-mono); + color: var(--text-secondary); +} + +.inbox-progress-track { + height: 6px; + border-radius: 3px; + background: var(--bg-elevated); + overflow: hidden; +} + +.inbox-progress-fill { + height: 100%; + background: var(--success); + border-radius: 3px; + transition: width 0.4s var(--ease-out); +} + +.inbox-targets { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-bottom: 12px; +} + +.inbox-target { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + border: 1px solid var(--border-bright); + border-radius: 999px; + background: var(--bg-card); + color: var(--text-secondary); + font-family: var(--font-body); + font-size: 12px; + cursor: pointer; +} + +.inbox-target:hover { + border-color: var(--border-strong); + color: var(--text-primary); +} + +.inbox-target.is-active { + border-color: var(--border-accent); + background: var(--accent-muted); + color: var(--accent); + font-weight: 600; +} + +.inbox-target-count { + font-family: var(--font-mono); + font-size: 10.5px; + color: var(--text-faint); +} + +.inbox-buckets { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 8px; + margin-bottom: 14px; +} + +.inbox-bucket { + --tone: var(--text-tertiary); + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 2px; + padding: 11px 13px 12px; + border: 1px solid var(--border); + border-top: 3px solid var(--tone); + border-radius: var(--radius-lg); + background: var(--bg-card); + color: var(--text-primary); + font-family: var(--font-body); + text-align: left; + cursor: pointer; + transition: background 0.1s, border-color 0.1s; +} + +.inbox-bucket:hover { + background: var(--bg-card-hover); +} + +.inbox-bucket.is-active { + border-color: var(--tone); + background: color-mix(in oklch, var(--tone) 7%, var(--bg-card)); +} + +.inbox-bucket.tone-danger { --tone: var(--danger); } +.inbox-bucket.tone-warning { --tone: var(--orange); } +.inbox-bucket.tone-neutral { --tone: var(--info); } +.inbox-bucket.tone-accent { --tone: var(--accent); } + +.inbox-bucket-count { + font-family: var(--font-mono); + font-size: 24px; + font-weight: 600; + line-height: 1.1; + color: var(--tone); +} + +.inbox-bucket-label { + font-size: 13px; + font-weight: 600; +} + +.inbox-bucket-hint { + font-size: 11.5px; + color: var(--text-tertiary); +} + +.inbox-cards { + display: flex; + flex-direction: column; + gap: 8px; +} + +.inbox-card { + background: var(--bg-card); + border: 1px solid var(--border); + border-left: 3px solid transparent; + border-radius: var(--radius-lg); + padding: 12px 14px; + cursor: default; +} + +.inbox-card.is-selected { + border-color: var(--border-accent); + border-left-color: var(--accent); + box-shadow: var(--shadow-pop); +} + +.inbox-card-head { + display: flex; + align-items: center; + gap: 9px; +} + +.inbox-card-title { + font-family: var(--font-display); + font-size: 14px; + font-weight: 600; + color: var(--text-primary); + letter-spacing: -0.01em; + overflow-wrap: anywhere; +} + +.inbox-card-sub { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 4px 10px; + margin-top: 4px; + font-size: 12px; + color: var(--text-tertiary); +} + +.inbox-card-target { + font-weight: 500; + color: var(--text-secondary); +} + +.inbox-card-place { + font-family: var(--font-mono); + font-size: 11.5px; + overflow-wrap: anywhere; +} + +.inbox-chips { + display: flex; + flex-wrap: wrap; + gap: 5px; + margin-top: 8px; +} + +.inbox-chip { + --tone: var(--text-tertiary); + padding: 1px 8px; + border-radius: 999px; + border: 1px solid color-mix(in oklch, var(--tone) 32%, transparent); + background: color-mix(in oklch, var(--tone) 10%, transparent); + color: var(--tone); + font-size: 11px; + font-weight: 500; + white-space: nowrap; +} + +.inbox-chip.tone-danger { --tone: var(--danger); } +.inbox-chip.tone-warning { --tone: var(--orange); } +.inbox-chip.tone-success { --tone: var(--success); } +.inbox-chip.tone-info { --tone: var(--info); } +.inbox-chip.tone-accent { --tone: var(--accent); } + +.inbox-card-note { + margin-top: 8px; + font-size: 12px; + color: var(--text-secondary); +} + +.inbox-card-note-label { + font-weight: 600; + margin-right: 6px; +} + +.inbox-actions, +.inbox-input { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + margin-top: 10px; +} + +.inbox-later { + position: relative; +} + +.inbox-later > summary { + list-style: none; +} + +.inbox-later > summary::-webkit-details-marker { + display: none; +} + +.inbox-later-menu { + position: absolute; + z-index: 20; + top: calc(100% + 4px); + left: 0; + display: flex; + flex-direction: column; + gap: 6px; + min-width: 210px; + padding: 8px; + border: 1px solid var(--border-bright); + border-radius: var(--radius-lg); + background: var(--bg-card-solid); + box-shadow: var(--shadow-pop); +} + +.inbox-later-option { + padding: 5px 8px; + border: none; + border-radius: var(--radius-sm); + background: transparent; + color: var(--text-primary); + font-family: var(--font-body); + font-size: 12.5px; + text-align: left; + cursor: pointer; +} + +.inbox-later-option:hover { + background: var(--bg-elevated); +} + +.inbox-later-date { + display: flex; + flex-direction: column; + gap: 3px; + padding: 4px 8px 0; + font-size: 11.5px; + color: var(--text-tertiary); +} + +.inbox-later-date input, +.inbox-input-text, +.inbox-input-select { + padding: 5px 8px; + border: 1px solid var(--border-bright); + border-radius: var(--radius); + background: var(--bg-secondary); + color: var(--text-primary); + font-family: var(--font-body); + font-size: 12.5px; +} + +.inbox-input-text { + flex: 1 1 240px; + min-width: 0; +} + +.inbox-details { + margin-left: auto; + font-size: 12.5px; + color: var(--accent); + text-decoration: none; +} + +.inbox-details:hover { + text-decoration: underline; +} + +.inbox-empty { + text-align: center; + color: var(--text-tertiary); + padding: 28px 16px; +} + +.inbox-empty .btn { + margin-top: 10px; +} + +.inbox-shortcuts { + margin-top: 12px; + font-family: var(--font-mono); + font-size: 11px; + color: var(--text-faint); +} + +.inbox-undo { + position: fixed; + left: 50%; + bottom: 22px; + z-index: 210; + transform: translateX(-50%); + display: flex; + align-items: center; + gap: 14px; + max-width: calc(100vw - 32px); + padding: 9px 10px 9px 16px; + border-radius: var(--radius-lg); + background: var(--text-primary); + color: var(--bg-primary); + font-size: 13px; + box-shadow: var(--shadow-pop); +} + +.inbox-undo > span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.inbox-undo-btn { + background: transparent; + border-color: color-mix(in oklch, var(--bg-primary) 40%, transparent); + color: var(--bg-primary); + font-weight: 600; +} + +.inbox-undo-btn:hover { + background: color-mix(in oklch, var(--bg-primary) 14%, transparent); + color: var(--bg-primary); + border-color: var(--bg-primary); +} + +@media (max-width: 900px) { + .inbox-buckets { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +@media (max-width: 480px) { + .inbox-details { + margin-left: 0; + } + + .inbox-later-menu { + position: static; + margin-top: 4px; + } +} diff --git a/compliance-dashboard/src/app.rs b/compliance-dashboard/src/app.rs index 80cfe74..be63df1 100644 --- a/compliance-dashboard/src/app.rs +++ b/compliance-dashboard/src/app.rs @@ -8,7 +8,10 @@ use crate::pages::*; #[allow(clippy::enum_variant_names)] pub enum Route { #[layout(AppShell)] + // The landing page: the open decisions (#950). #[route("/")] + HeutePage {}, + #[route("/overview")] OverviewPage {}, #[route("/targets")] TargetsPage {}, @@ -119,6 +122,16 @@ mod tests { use super::Route; use std::str::FromStr; + #[test] + fn heute_is_the_landing_page_and_the_overview_stays_reachable() { + assert!(matches!(Route::from_str("/"), Ok(Route::HeutePage {}))); + assert!(matches!( + Route::from_str("/overview"), + Ok(Route::OverviewPage {}) + )); + assert_eq!(Route::OverviewPage {}.to_string(), "/overview"); + } + #[test] fn the_sbom_page_carries_its_target_in_the_query() { let filtered = Route::SbomPage { diff --git a/compliance-dashboard/src/components/sidebar.rs b/compliance-dashboard/src/components/sidebar.rs index 0e2c74e..36e9fd4 100644 --- a/compliance-dashboard/src/components/sidebar.rs +++ b/compliance-dashboard/src/components/sidebar.rs @@ -166,6 +166,11 @@ pub fn Sidebar() -> Element { } } div { class: "sidebar-nav", + TodayNavItem { + collapsed: collapsed(), + active: current_route == (Route::HeutePage {}), + on_navigate: move |_| mobile_open.set(false), + } for item in nav_items.into_iter().filter(|i| can_write || !i.write_only) { { let is_active = match (¤t_route, &item.route) { @@ -290,6 +295,41 @@ pub fn Sidebar() -> Element { } } +/// The sidebar's "Heute" entry with the workspace's "Heute handeln" count +/// (#950): fetched once, then kept current by the page. +#[component] +fn TodayNavItem(collapsed: bool, active: bool, on_navigate: EventHandler<()>) -> Element { + use crate::infrastructure::inbox::fetch_inbox; + use crate::pages::inbox::TODAY_COUNT; + use compliance_core::models::inbox::Bucket; + + let lang = use_lang()(); + let _count = use_resource(|| async { + if TODAY_COUNT.peek().is_none() { + if let Ok(view) = fetch_inbox(String::new(), Bucket::Today, Some(0)).await { + *TODAY_COUNT.write() = Some(view.counts.today); + } + } + }); + let label = crate::i18n::texts::inbox::NAV.get(lang); + let today = TODAY_COUNT().filter(|n| *n > 0); + rsx! { + Link { + to: Route::HeutePage {}, + class: if active { "nav-item active" } else { "nav-item" }, + title: "{label}", + onclick: move |_| on_navigate.call(()), + Icon { icon: BsInbox, width: 18, height: 18 } + if !collapsed { + span { "{label}" } + } + if let Some(today) = today { + span { class: "nav-count", "{today}" } + } + } + } +} + /// The BreakPilot wordmark, as on breakpilot.com and the portal: the chevron, /// and unless `with_name` is off, "BreakPilot" with "Prüfwerk" beneath. #[component] diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 8c06ec9..afdf3a0 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -6133,3 +6133,310 @@ pub mod finding_breakdown { } } } + +/// The "Heute" inbox (#950): open decisions in four urgency buckets. +pub mod inbox { + use super::super::Lang; + use super::Text; + + pub const NAV: Text = Text { + de: "Heute", + en: "Today", + }; + pub const TITLE: Text = Text { + de: "Heute", + en: "Today", + }; + pub const SUBTITLE: Text = Text { + de: "Offene Entscheidungen, nach Dringlichkeit sortiert. Eine Karte, eine Entscheidung.", + en: "Open decisions, sorted by urgency. One card, one decision.", + }; + pub const PROGRESS: Text = Text { + de: "Erstbewertung", + en: "First assessment", + }; + pub const PROGRESS_HINT: Text = Text { + de: "Befunde und Schwachstellen, über die schon entschieden ist (Fehlalarm, \ + Risiko akzeptiert, VEX-Aussage), von allen, die nicht behoben sind.", + en: "Findings and vulnerabilities already decided (false alarm, risk accepted, VEX \ + statement), of all that are not resolved.", + }; + pub const ALL_TARGETS: Text = Text { + de: "Alle Prüfobjekte", + en: "All targets", + }; + pub const TODAY: Text = Text { + de: "Heute handeln", + en: "Act today", + }; + pub const THIS_WEEK: Text = Text { + de: "Diese Woche", + en: "This week", + }; + pub const LATER: Text = Text { + de: "Später", + en: "Later", + }; + pub const AI: Text = Text { + de: "KI: wohl Fehlalarm", + en: "AI: likely false alarm", + }; + pub const TODAY_HINT: Text = Text { + de: "Ausgenutzt, CRA-Frist läuft, Secret im Code", + en: "Exploited, CRA deadline running, secret in code", + }; + pub const THIS_WEEK_HINT: Text = Text { + de: "Hoch und kritisch, oder ein Fix ist da", + en: "High and critical, or a fix is available", + }; + pub const LATER_HINT: Text = Text { + de: "Mittel und niedrig, fällige Wiedervorlagen", + en: "Medium and low, resubmissions due", + }; + pub const AI_HINT: Text = Text { + de: "Von der KI verworfen, bitte bestätigen", + en: "Dismissed by the AI, please confirm", + }; + pub const EMPTY_TODAY: Text = Text { + de: "Heute ist nichts dringend.", + en: "Nothing is urgent today.", + }; + pub const EMPTY_THIS_WEEK: Text = Text { + de: "Für diese Woche ist nichts offen.", + en: "Nothing is open for this week.", + }; + pub const EMPTY_LATER: Text = Text { + de: "Für später ist nichts offen.", + en: "Nothing is open for later.", + }; + pub const EMPTY_AI: Text = Text { + de: "Die KI hat nichts verworfen, das auf Sie wartet.", + en: "The AI dismissed nothing that waits for you.", + }; + pub const LOAD_FAILED: Text = Text { + de: "Die Entscheidungen konnten nicht geladen werden.", + en: "The decisions could not be loaded.", + }; + pub const KEV: Text = Text { + de: "Aktiv ausgenutzt (CISA KEV)", + en: "Exploited (CISA KEV)", + }; + pub const SECRET_IN_CODE: Text = Text { + de: "Secret im Code", + en: "Secret in code", + }; + pub const AI_DISMISSED: Text = Text { + de: "Von der KI verworfen", + en: "Dismissed by the AI", + }; + pub const CRA_DUTY: Text = Text { + de: "CRA-Meldepflicht", + en: "CRA notification due", + }; + pub const FALSE_POSITIVE: Text = Text { + de: "Fehlalarm", + en: "False alarm", + }; + pub const CONFIRM_FALSE_POSITIVE: Text = Text { + de: "Fehlalarm bestätigen", + en: "Confirm false alarm", + }; + pub const CONFIRM: Text = Text { + de: "Doch echt", + en: "It is real", + }; + pub const ACCEPT_RISK: Text = Text { + de: "Risiko akzeptieren", + en: "Accept the risk", + }; + pub const NOT_AFFECTED: Text = Text { + de: "Nicht betroffen", + en: "Not affected", + }; + pub const AFFECTED: Text = Text { + de: "Betroffen, Update geplant", + en: "Affected, update planned", + }; + pub const LATER_MENU: Text = Text { + de: "Später", + en: "Later", + }; + pub const ONE_WEEK: Text = Text { + de: "In 1 Woche", + en: "In 1 week", + }; + pub const ONE_MONTH: Text = Text { + de: "In 1 Monat", + en: "In 1 month", + }; + pub const ON_DATE: Text = Text { + de: "Am Datum", + en: "On a date", + }; + pub const SET_DATE: Text = Text { + de: "Wiedervorlage setzen", + en: "Set the resubmission", + }; + pub const DETAILS: Text = Text { + de: "Details →", + en: "Details →", + }; + pub const REASON: Text = Text { + de: "Warum wird das Risiko akzeptiert?", + en: "Why is the risk accepted?", + }; + pub const DECIDE: Text = Text { + de: "Entscheiden", + en: "Decide", + }; + pub const CANCEL: Text = Text { + de: "Abbrechen", + en: "Cancel", + }; + pub const DECIDED: Text = Text { + de: "Entschieden", + en: "Decided", + }; + pub const UNDO: Text = Text { + de: "Rückgängig", + en: "Undo", + }; + pub const UNDONE: Text = Text { + de: "Rückgängig gemacht", + en: "Undone", + }; + pub const FAILED: Text = Text { + de: "Das hat nicht geklappt", + en: "That did not work", + }; + pub const SHORTCUTS: Text = Text { + de: "Tasten: j / k wählen · f Fehlalarm · a Risiko akzeptiert · s später (1 Woche)", + en: "Keys: j / k move · f false alarm · a risk accepted · s later (1 week)", + }; + pub const AI_NOTE: Text = Text { + de: "Begründung der KI", + en: "The AI's reasoning", + }; + + /// "42 von 180 entschieden", "42 of 180 decided". + pub fn progress_line(decided: u64, total: u64, lang: Lang) -> String { + match lang { + Lang::De => format!("{decided} von {total} entschieden"), + Lang::En => format!("{decided} of {total} decided"), + } + } + + /// The EPSS chip: "EPSS 97. Perzentil", "EPSS 97th percentile". + pub fn epss(percentile: f64, lang: Lang) -> String { + // Whole percentiles; the fraction runs from 0 to 1. + let whole = (percentile * 100.0).floor(); + match lang { + Lang::De => format!("EPSS {whole}. Perzentil"), + Lang::En => format!("EPSS {whole}th percentile"), + } + } + + /// A CRA Article 14 stage, by its name in the agent's answer. + pub fn stage(stage: &str, lang: Lang) -> &'static str { + let text = match stage { + "early_warning" => Text { + de: "Frühwarnung", + en: "early warning", + }, + "vulnerability_notification" => Text { + de: "Schwachstellenmeldung", + en: "vulnerability notification", + }, + _ => Text { + de: "Abschlussbericht", + en: "final report", + }, + }; + text.get(lang) + } + + /// The CRA deadline chip: "CRA-Frühwarnung in 14 h", "… überfällig". + pub fn enisa(stage_name: &str, overdue: bool, hours_left: Option, lang: Lang) -> String { + let stage = stage(stage_name, lang); + match (lang, overdue, hours_left) { + (Lang::De, true, _) => format!("CRA-{stage} überfällig"), + (Lang::En, true, _) => format!("CRA {stage} overdue"), + (Lang::De, false, Some(h)) => format!("CRA-{stage} in {h} h"), + (Lang::En, false, Some(h)) => format!("CRA {stage} in {h} h"), + (Lang::De, false, None) => format!("CRA-{stage} fällig"), + (Lang::En, false, None) => format!("CRA {stage} due"), + } + } + + /// The fix chip: "Fix: 2.17.1". + pub fn fix(version: &str) -> String { + format!("Fix: {version}") + } + + /// The resubmission chip: "Wiedervorlage seit 01.12.2026". + pub fn resubmission(date: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("Wiedervorlage seit {date}"), + Lang::En => format!("Resubmission since {date}"), + } + } + + /// The undo toast after a snooze: "Wiedervorlage am 01.12.2026". + pub fn snoozed(date: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("Wiedervorlage am {date}"), + Lang::En => format!("Back on {date}"), + } + } + + /// A CVE card's size: "1 CVE", "3 CVEs". + pub fn cves(count: usize) -> String { + match count { + 1 => "1 CVE".to_string(), + n => format!("{n} CVEs"), + } + } + + /// A finding's places when it has several: "3 Stellen", "3 places". + pub fn places(count: usize, lang: Lang) -> String { + match lang { + Lang::De => format!("{count} Stellen"), + Lang::En => format!("{count} places"), + } + } + + /// The action statement an update is prefilled with. + pub fn update_to(version: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("Auf Version {version} aktualisieren."), + Lang::En => format!("Update to version {version}."), + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn chips_read_in_both_languages() { + assert_eq!(progress_line(42, 180, Lang::De), "42 von 180 entschieden"); + assert_eq!(progress_line(42, 180, Lang::En), "42 of 180 decided"); + assert_eq!(epss(0.973, Lang::De), "EPSS 97. Perzentil"); + assert_eq!( + enisa("early_warning", false, Some(14), Lang::De), + "CRA-Frühwarnung in 14 h" + ); + assert_eq!( + enisa("vulnerability_notification", true, Some(-3), Lang::En), + "CRA vulnerability notification overdue" + ); + assert_eq!(cves(1), "1 CVE"); + assert_eq!(cves(4), "4 CVEs"); + assert_eq!( + update_to("2.17.1", Lang::De), + "Auf Version 2.17.1 aktualisieren." + ); + assert_eq!(places(3, Lang::En), "3 places"); + } + } +} diff --git a/compliance-dashboard/src/infrastructure/inbox.rs b/compliance-dashboard/src/infrastructure/inbox.rs new file mode 100644 index 0000000..8d0dda2 --- /dev/null +++ b/compliance-dashboard/src/infrastructure/inbox.rs @@ -0,0 +1,94 @@ +//! The "Heute" inbox (#950): the cards of a bucket, decisions on a card, +//! undo, and resubmission dates. The agent does the work; these only carry +//! the session's token there and back. + +use dioxus::prelude::*; + +use compliance_core::models::inbox::{ + Bucket, DecideRequest, DecideResponse, InboxView, SnoozeRequest, SnoozeResponse, UndoRequest, +}; + +/// The agent's `{ data }` reply (read on the server only). +#[cfg(feature = "server")] +#[derive(Debug, serde::Deserialize)] +struct ViewResponse { + data: InboxView, +} + +/// The counts, the Erstbewertung, the targets and the cards of `bucket`, for +/// the whole workspace or, with a non-empty `target`, one target; at most +/// `limit` cards (the agent's default without one). +#[server] +pub async fn fetch_inbox( + target: String, + bucket: Bucket, + limit: Option, +) -> Result { + let mut request = super::agent_client::agent_get("/api/v1/inbox") + .await? + .query(&[("bucket", bucket.as_str())]); + if !target.is_empty() { + request = request.query(&[("target", target.as_str())]); + } + if let Some(limit) = limit { + request = request.query(&[("limit", limit)]); + } + let resp = request + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let body: ViewResponse = super::agent_client::json_or_error(resp).await?; + Ok(body.data) +} + +/// Apply a decision to every item of a card; what they were before, for +/// [`undo_decision`]. The agent's refusal (a missing reason, a card already +/// decided, a read-only role) is the error. +#[server] +pub async fn decide_card(request: DecideRequest) -> Result { + let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/inbox/decide") + .await? + .json(&request) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::json_or_error(resp).await +} + +/// Put the items of a decision back. +#[server] +pub async fn undo_decision(request: UndoRequest) -> Result<(), ServerFnError> { + let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/inbox/undo") + .await? + .json(&request) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await +} + +/// Put a card off; when it comes back. +#[server] +pub async fn snooze_card(request: SnoozeRequest) -> Result { + let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/inbox/snooze") + .await? + .json(&request) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::json_or_error(resp).await +} + +/// Take a card's resubmission back (the undo of [`snooze_card`]). +#[server] +pub async fn unsnooze_card(key: String) -> Result<(), ServerFnError> { + let resp = super::agent_client::agent_request( + reqwest::Method::DELETE, + &format!("/api/v1/inbox/snooze/{key}"), + ) + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await +} diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index bfd8348..4e7fffa 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -12,6 +12,7 @@ pub mod finding_groups; pub mod findings; pub mod graph; pub mod help_chat; +pub mod inbox; pub mod issues; pub mod manual_findings; pub mod mcp; diff --git a/compliance-dashboard/src/pages/inbox.rs b/compliance-dashboard/src/pages/inbox.rs new file mode 100644 index 0000000..57b784d --- /dev/null +++ b/compliance-dashboard/src/pages/inbox.rs @@ -0,0 +1,918 @@ +//! "Heute" (#950), the landing page: the workspace's open decisions in four +//! urgency buckets, one card per decision, with the decision, "Später" with +//! a resubmission date, and undo, all from here. +//! +//! Keyboard (on this page only, never while typing): `j`/`k` move between +//! cards, `f` false alarm (VEX `not_affected` on a CVE card), `a` risk +//! accepted (VEX `affected` on a CVE card), `s` later (one week), `Esc` +//! closes an open input. + +use std::collections::HashSet; +use std::rc::Rc; + +use chrono::{DateTime, NaiveDate, Utc}; +use dioxus::prelude::*; + +use compliance_core::models::inbox::{ + Bucket, CardKind, DecideRequest, InboxAction, InboxCard, InboxView, Reason, SnoozeFor, + SnoozeRequest, UndoRequest, +}; +use compliance_core::models::VexJustification; + +use crate::app::Route; +use crate::components::no_access::use_can_write; +use crate::components::page_header::PageHeader; +use crate::components::severity_badge::SeverityBadge; +use crate::components::toast::{ToastType, Toasts}; +use crate::i18n::texts::{common, inbox as tx, vex as vex_tx}; +use crate::i18n::{use_lang, Lang, Text}; +use crate::infrastructure::inbox::{ + decide_card, fetch_inbox, snooze_card, undo_decision, unsnooze_card, +}; + +/// The workspace's "Heute handeln" cards, for the sidebar: fetched once, +/// then kept current by this page. +pub static TODAY_COUNT: GlobalSignal> = Signal::global(|| None); + +/// How long the undo strip stays after a decision. +#[cfg(feature = "web")] +const UNDO_MS: u32 = 8_000; + +/// The VEX justifications in the "Nicht betroffen" choice, with their labels. +const JUSTIFICATIONS: [(VexJustification, Text); 5] = [ + ( + VexJustification::ComponentNotPresent, + vex_tx::COMPONENT_NOT_PRESENT, + ), + ( + VexJustification::VulnerableCodeNotPresent, + vex_tx::CODE_NOT_PRESENT, + ), + ( + VexJustification::VulnerableCodeNotInExecutePath, + vex_tx::CODE_NOT_IN_EXECUTE_PATH, + ), + ( + VexJustification::VulnerableCodeCannotBeControlledByAdversary, + vex_tx::CODE_NOT_CONTROLLABLE, + ), + ( + VexJustification::InlineMitigationsAlreadyExist, + vex_tx::MITIGATIONS_EXIST, + ), +]; + +/// A decision that needs a word first: the reason of an accepted risk, the +/// justification of a `not_affected`, the action of an `affected`. +#[derive(Debug, Clone, PartialEq)] +struct Pending { + key: String, + action: InboxAction, + text: String, + justification: Option, +} + +impl Pending { + /// Whether it carries what the agent asks for. + fn ready(&self) -> bool { + let has_text = !self.text.trim().is_empty(); + match self.action { + InboxAction::NotAffected => self.justification.is_some() || has_text, + InboxAction::AcceptedRisk | InboxAction::Affected => has_text, + InboxAction::FalsePositive | InboxAction::Confirm => true, + } + } + + /// The request deciding card `key` with it. + fn request(&self) -> DecideRequest { + let text = Some(self.text.trim().to_string()).filter(|t| !t.is_empty()); + let (reason, statement) = match self.action { + InboxAction::AcceptedRisk => (text, None), + InboxAction::NotAffected | InboxAction::Affected => (None, text), + InboxAction::FalsePositive | InboxAction::Confirm => (None, None), + }; + DecideRequest { + key: self.key.clone(), + action: self.action, + reason, + justification: self + .justification + .filter(|_| self.action == InboxAction::NotAffected), + statement, + } + } +} + +/// What the undo strip takes back. +#[derive(Debug, Clone, PartialEq)] +enum UndoKind { + Decision(UndoRequest), + Snooze(String), +} + +/// The undo strip's offer; `id` tells a newer offer from the one a timer +/// was started for. +#[derive(Debug, Clone, PartialEq)] +struct UndoOffer { + id: u64, + kind: UndoKind, + message: String, +} + +/// The labels of a bucket: name, what goes in it, and what an empty one says. +const fn bucket_texts(bucket: Bucket) -> (Text, Text, Text) { + match bucket { + Bucket::Today => (tx::TODAY, tx::TODAY_HINT, tx::EMPTY_TODAY), + Bucket::ThisWeek => (tx::THIS_WEEK, tx::THIS_WEEK_HINT, tx::EMPTY_THIS_WEEK), + Bucket::Later => (tx::LATER, tx::LATER_HINT, tx::EMPTY_LATER), + Bucket::LikelyFalsePositive => (tx::AI, tx::AI_HINT, tx::EMPTY_AI), + } +} + +/// The CSS tone of a bucket's tile. +const fn bucket_tone(bucket: Bucket) -> &'static str { + match bucket { + Bucket::Today => "tone-danger", + Bucket::ThisWeek => "tone-warning", + Bucket::Later => "tone-neutral", + Bucket::LikelyFalsePositive => "tone-accent", + } +} + +/// An action's button label; the AI bucket's false alarm confirms the AI. +fn action_label(action: InboxAction, bucket: Bucket) -> Text { + match action { + InboxAction::FalsePositive if bucket == Bucket::LikelyFalsePositive => { + tx::CONFIRM_FALSE_POSITIVE + } + InboxAction::FalsePositive => tx::FALSE_POSITIVE, + InboxAction::AcceptedRisk => tx::ACCEPT_RISK, + InboxAction::Confirm => tx::CONFIRM, + InboxAction::NotAffected => tx::NOT_AFFECTED, + InboxAction::Affected => tx::AFFECTED, + } +} + +/// The action key `f` or `a` stands for on `card`, if the card offers it: +/// false alarm and accepted risk, on a CVE card their VEX counterparts. +fn shortcut_action(key: &str, card: &InboxCard) -> Option { + let wanted = match (key, card.kind) { + ("f", CardKind::Finding) => InboxAction::FalsePositive, + ("f", CardKind::CvePackage) => InboxAction::NotAffected, + ("a", CardKind::Finding) => InboxAction::AcceptedRisk, + ("a", CardKind::CvePackage) => InboxAction::Affected, + _ => return None, + }; + card.actions.contains(&wanted).then_some(wanted) +} + +/// A day in the reader's convention: `01.12.2026`, `2026-12-01`. +fn format_day(time: &DateTime, lang: Lang) -> String { + match lang { + Lang::De => time.format("%d.%m.%Y").to_string(), + Lang::En => time.format("%Y-%m-%d").to_string(), + } +} + +/// A reason as a chip: its text and tone. +fn chip(reason: &Reason, lang: Lang) -> (String, &'static str) { + match reason { + Reason::AiDismissed => (tx::AI_DISMISSED.get(lang).to_string(), "tone-accent"), + Reason::Kev => (tx::KEV.get(lang).to_string(), "tone-danger"), + Reason::Epss { percentile } => (tx::epss(*percentile, lang), "tone-warning"), + Reason::EnisaDeadline { + stage: Some(stage), + overdue, + hours_left, + .. + } => (tx::enisa(stage, *overdue, *hours_left, lang), "tone-danger"), + Reason::EnisaDeadline { stage: None, .. } => { + (tx::CRA_DUTY.get(lang).to_string(), "tone-danger") + } + Reason::SecretInCode => (tx::SECRET_IN_CODE.get(lang).to_string(), "tone-danger"), + Reason::FixAvailable { version } => (tx::fix(version), "tone-success"), + Reason::Resubmission { since } => ( + tx::resubmission(&format_day(since, lang), lang), + "tone-info", + ), + } +} + +/// The page's state and what it does with it; every field is a copyable +/// handle, so event handlers take the whole of it. +#[derive(Clone, Copy)] +struct Inbox { + view: Resource>, + hidden: Signal>, + pending: Signal>, + undo: Signal>, + offers: Signal, + busy: Signal, + page: Signal>>, + toasts: Toasts, + lang: Lang, +} + +impl Inbox { + /// Start `action` on `card`: at once, or by asking for its input first. + fn begin(mut self, card: &InboxCard, action: InboxAction) { + if !action.needs_input() { + self.decide( + card.title.clone(), + Pending { + key: card.key.clone(), + action, + text: String::new(), + justification: None, + }, + ); + return; + } + let text = match (action, &card.fix_version) { + (InboxAction::Affected, Some(version)) => tx::update_to(version, self.lang), + _ => String::new(), + }; + self.pending.set(Some(Pending { + key: card.key.clone(), + action, + text, + justification: None, + })); + } + + /// Apply `decision` to the card titled `title`, then offer to undo it. + fn decide(mut self, title: String, decision: Pending) { + if *self.busy.peek() || !decision.ready() { + return; + } + self.busy.set(true); + spawn(async move { + match decide_card(decision.request()).await { + Ok(answer) => { + self.hidden.write().insert(answer.key.clone()); + self.pending.set(None); + let message = format!("{}: {title}", tx::DECIDED.get(self.lang)); + self.offer( + UndoKind::Decision(UndoRequest { + key: answer.key, + previous: answer.previous, + }), + message, + ); + self.view.restart(); + } + Err(e) => self.failed(&e), + } + self.busy.set(false); + self.refocus().await; + }); + } + + /// Put `card` off as `choice` says, then offer to undo it. + fn snooze(mut self, card: &InboxCard, choice: SnoozeFor) { + if *self.busy.peek() { + return; + } + self.busy.set(true); + let request = SnoozeRequest { + key: card.key.clone(), + snooze_for: choice, + }; + spawn(async move { + match snooze_card(request).await { + Ok(answer) => { + self.hidden.write().insert(answer.key.clone()); + self.pending.set(None); + let message = tx::snoozed(&format_day(&answer.until, self.lang), self.lang); + self.offer(UndoKind::Snooze(answer.key), message); + self.view.restart(); + } + Err(e) => self.failed(&e), + } + self.busy.set(false); + self.refocus().await; + }); + } + + /// Take the offered decision or snooze back. + fn undo(mut self) { + let Some(offer) = self.undo.write().take() else { + return; + }; + spawn(async move { + let (key, result) = match offer.kind { + UndoKind::Decision(request) => (request.key.clone(), undo_decision(request).await), + UndoKind::Snooze(key) => (key.clone(), unsnooze_card(key).await), + }; + match result { + Ok(()) => { + self.hidden.write().remove(&key); + self.toasts.push(ToastType::Info, tx::UNDONE.get(self.lang)); + self.view.restart(); + } + Err(e) => self.failed(&e), + } + self.refocus().await; + }); + } + + /// Show the undo strip with `message` for a while. + fn offer(mut self, kind: UndoKind, message: String) { + let id = *self.offers.peek() + 1; + self.offers.set(id); + self.undo.set(Some(UndoOffer { id, kind, message })); + #[cfg(feature = "web")] + { + let mut undo = self.undo; + spawn(async move { + gloo_timers::future::TimeoutFuture::new(UNDO_MS).await; + if undo.peek().as_ref().is_some_and(|o| o.id == id) { + undo.set(None); + } + }); + } + } + + fn failed(mut self, error: &ServerFnError) { + self.toasts.push( + ToastType::Error, + format!("{}: {error}", tx::FAILED.get(self.lang)), + ); + } + + /// Give the keyboard back to the page (a removed card took the focus + /// with it). + async fn refocus(self) { + let page = self.page.peek().clone(); + if let Some(page) = page { + // Focusing can only fail when the page has gone; nothing to do then. + let _focused = page.set_focus(true).await; + } + } +} + +#[component] +pub fn HeutePage() -> Element { + let lang = use_lang()(); + let can_write = use_can_write(); + let target = use_signal(String::new); + let bucket = use_signal(|| Bucket::Today); + let mut selected = use_signal(|| 0_usize); + let view = use_resource(move || async move { fetch_inbox(target(), bucket(), None).await }); + let inbox = Inbox { + view, + hidden: use_signal(HashSet::new), + pending: use_signal(|| None), + undo: use_signal(|| None), + offers: use_signal(|| 0), + busy: use_signal(|| false), + page: use_signal(|| None), + toasts: use_context::(), + lang, + }; + + // The sidebar shows the workspace's count, not one target's. + use_effect(move || { + if let Some(Ok(view)) = &*view.read() { + if target.peek().is_empty() && *bucket.peek() == view.bucket { + *TODAY_COUNT.write() = Some(view.counts.today); + } + } + }); + // Keep the chosen card in sight. + use_effect(move || { + let _ = selected(); + let _scrolled = document::eval( + "document.querySelector('.inbox-card.is-selected')?.scrollIntoView({block: 'nearest'})", + ); + }); + + let current = view.read().clone(); + let cards: Vec = match ¤t { + Some(Ok(v)) => { + let hidden = inbox.hidden.read(); + v.cards + .iter() + .filter(|c| !hidden.contains(&c.key)) + .cloned() + .collect() + } + _ => Vec::new(), + }; + let chosen = selected().min(cards.len().saturating_sub(1)); + let key_cards = cards.clone(); + let mut pending = inbox.pending; + let onkeydown = move |e: KeyboardEvent| { + let modifiers = e.modifiers(); + if modifiers.ctrl() || modifiers.meta() || modifiers.alt() { + return; + } + let key = match e.key() { + Key::Character(c) => c, + Key::Escape => { + pending.set(None); + return; + } + _ => return, + }; + let card = key_cards.get(chosen); + match (key.as_str(), card) { + ("j", Some(_)) => selected.set((chosen + 1).min(key_cards.len() - 1)), + ("k", Some(_)) => selected.set(chosen.saturating_sub(1)), + ("f" | "a", Some(card)) if can_write => { + if let Some(action) = shortcut_action(&key, card) { + e.prevent_default(); + inbox.begin(card, action); + } + } + ("s", Some(card)) if can_write => { + e.prevent_default(); + inbox.snooze(card, SnoozeFor::Week); + } + _ => {} + } + }; + + rsx! { + div { + class: "inbox-page", + tabindex: "0", + onkeydown, + onmounted: move |e| { + let page = e.data(); + let mut handle = inbox.page; + handle.set(Some(page.clone())); + spawn(async move { + let _focused = page.set_focus(true).await; + }); + }, + PageHeader { + title: tx::TITLE.get(lang).to_string(), + description: tx::SUBTITLE.get(lang).to_string(), + } + match current { + None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, + Some(Err(_)) => rsx! { + div { class: "card inbox-empty", + p { {tx::LOAD_FAILED.get(lang)} } + button { + class: "btn btn-secondary btn-sm", + onclick: move |_| { let mut view = view; view.restart(); }, + {common::RETRY.get(lang)} + } + } + }, + Some(Ok(v)) => rsx! { + InboxHeader { view: v.clone(), target, bucket, selected, pending } + if cards.is_empty() { + div { class: "card inbox-empty", + p { {bucket_texts(v.bucket).2.get(lang)} } + } + } else { + div { class: "inbox-cards", + for (i, card) in cards.into_iter().enumerate() { + CardView { + key: "{card.key}", + target_name: v + .targets + .iter() + .find(|t| t.id == card.target_id) + .map_or_else(|| card.target_id.clone(), |t| t.name.clone()), + selected: i == chosen, + can_write, + pending: inbox + .pending + .read() + .clone() + .filter(|p| p.key == card.key), + on_select: move |_| selected.set(i), + on_action: { + let card = card.clone(); + move |action| inbox.begin(&card, action) + }, + on_snooze: { + let card = card.clone(); + move |choice| inbox.snooze(&card, choice) + }, + on_edit: move |next| pending.set(Some(next)), + on_submit: { + let title = card.title.clone(); + move |decision| inbox.decide(title.clone(), decision) + }, + on_cancel: move |_| pending.set(None), + card, + } + } + } + if can_write { + p { class: "inbox-shortcuts", {tx::SHORTCUTS.get(lang)} } + } + } + }, + } + if let Some(offer) = (inbox.undo)() { + div { class: "inbox-undo", role: "status", + span { "{offer.message}" } + button { + class: "btn btn-sm inbox-undo-btn", + onclick: move |_| inbox.undo(), + {tx::UNDO.get(lang)} + } + } + } + } + } +} + +/// The Erstbewertung, the target chips and the bucket tiles. +#[component] +fn InboxHeader( + view: InboxView, + target: Signal, + bucket: Signal, + selected: Signal, + pending: Signal>, +) -> Element { + let lang = use_lang()(); + let progress = view.progress; + let percent = progress.percent(); + let mut choose_bucket = move |b: Bucket| { + bucket.set(b); + selected.set(0); + pending.set(None); + }; + let mut choose_target = move |id: String| { + target.set(id); + selected.set(0); + pending.set(None); + }; + rsx! { + section { class: "inbox-progress", title: tx::PROGRESS_HINT.get(lang), + div { class: "inbox-progress-head", + span { class: "inbox-progress-label", {tx::PROGRESS.get(lang)} } + span { class: "inbox-progress-value", + {tx::progress_line(progress.decided, progress.total, lang)} + } + span { class: "inbox-progress-percent", "{percent} %" } + } + div { + class: "inbox-progress-track", + role: "progressbar", + "aria-valuemin": "0", + "aria-valuemax": "100", + "aria-valuenow": "{percent}", + div { class: "inbox-progress-fill", style: "width: {percent}%" } + } + } + if !view.targets.is_empty() { + div { class: "inbox-targets", + button { + class: if target().is_empty() { "inbox-target is-active" } else { "inbox-target" }, + onclick: move |_| choose_target(String::new()), + {tx::ALL_TARGETS.get(lang)} + } + for t in view.targets.iter().cloned() { + button { + key: "{t.id}", + class: if target() == t.id { "inbox-target is-active" } else { "inbox-target" }, + onclick: move |_| choose_target(t.id.clone()), + "{t.name}" + span { class: "inbox-target-count", "{t.cards}" } + } + } + } + } + div { class: "inbox-buckets", role: "tablist", + for b in Bucket::ALL { + { + let (label, hint, _) = bucket_texts(b); + let active = view.bucket == b; + let tone = bucket_tone(b); + let count = view.counts.get(b); + rsx! { + button { + key: "{b.as_str()}", + class: if active { "inbox-bucket {tone} is-active" } else { "inbox-bucket {tone}" }, + role: "tab", + "aria-selected": if active { "true" } else { "false" }, + onclick: move |_| choose_bucket(b), + span { class: "inbox-bucket-count", "{count}" } + span { class: "inbox-bucket-label", {label.get(lang)} } + span { class: "inbox-bucket-hint", {hint.get(lang)} } + } + } + } + } + } + } +} + +/// One card: what it is, why it is here, and its decisions. +#[component] +fn CardView( + card: InboxCard, + target_name: String, + selected: bool, + can_write: bool, + pending: Option, + on_select: EventHandler<()>, + on_action: EventHandler, + on_snooze: EventHandler, + on_edit: EventHandler, + on_submit: EventHandler, + on_cancel: EventHandler<()>, +) -> Element { + let lang = use_lang()(); + let mut date = use_signal(String::new); + let details = match card.kind { + CardKind::Finding => Route::FindingDetailPage { + id: card.item_ids.first().cloned().unwrap_or_default(), + }, + CardKind::CvePackage => Route::target(card.target_id.clone()), + }; + let size = match card.kind { + CardKind::CvePackage => Some(tx::cves(card.count)), + CardKind::Finding if card.count > 1 => Some(tx::places(card.count, lang)), + CardKind::Finding => None, + }; + let chips: Vec<(String, &'static str)> = card.reasons.iter().map(|r| chip(r, lang)).collect(); + let bucket = card.bucket; + rsx! { + article { + class: if selected { "inbox-card is-selected" } else { "inbox-card" }, + onclick: move |_| on_select.call(()), + div { class: "inbox-card-head", + SeverityBadge { severity: card.severity.to_string() } + h3 { class: "inbox-card-title", "{card.title}" } + } + p { class: "inbox-card-sub", + span { class: "inbox-card-target", "{target_name}" } + if !card.subtitle.is_empty() { + code { class: "inbox-card-place", "{card.subtitle}" } + } + if let Some(size) = size { + span { class: "inbox-card-size", "{size}" } + } + } + if !chips.is_empty() { + div { class: "inbox-chips", + for (label, tone) in chips { + span { class: "inbox-chip {tone}", "{label}" } + } + } + } + if let Some(note) = card.note.clone() { + p { class: "inbox-card-note", + span { class: "inbox-card-note-label", {tx::AI_NOTE.get(lang)} } + "{note}" + } + } + if let Some(decision) = pending { + DecisionInput { decision, on_edit, on_submit, on_cancel } + } else { + div { class: "inbox-actions", + if can_write { + for (i, action) in card.actions.iter().copied().enumerate() { + button { + key: "{i}", + class: if i == 0 { "btn btn-primary btn-sm" } else { "btn btn-secondary btn-sm" }, + onclick: move |e| { + e.stop_propagation(); + on_action.call(action); + }, + {action_label(action, bucket).get(lang)} + } + } + details { + class: "inbox-later", + onclick: move |e| e.stop_propagation(), + summary { class: "btn btn-ghost btn-sm", {tx::LATER_MENU.get(lang)} " ▾" } + div { class: "inbox-later-menu", + button { + class: "inbox-later-option", + onclick: move |_| on_snooze.call(SnoozeFor::Week), + {tx::ONE_WEEK.get(lang)} + } + button { + class: "inbox-later-option", + onclick: move |_| on_snooze.call(SnoozeFor::Month), + {tx::ONE_MONTH.get(lang)} + } + label { class: "inbox-later-date", + span { {tx::ON_DATE.get(lang)} } + input { + r#type: "date", + value: "{date}", + oninput: move |e| date.set(e.value()), + onkeydown: move |e| e.stop_propagation(), + } + } + button { + class: "btn btn-secondary btn-sm", + disabled: NaiveDate::parse_from_str(&date(), "%Y-%m-%d").is_err(), + onclick: move |_| { + if let Ok(day) = NaiveDate::parse_from_str(&date(), "%Y-%m-%d") { + on_snooze.call(SnoozeFor::Date { date: day }); + } + }, + {tx::SET_DATE.get(lang)} + } + } + } + } + Link { + class: "inbox-details", + to: details, + onclick: move |e: MouseEvent| e.stop_propagation(), + {tx::DETAILS.get(lang)} + } + } + } + } + } +} + +/// The input a decision needs before it can be made. +#[component] +fn DecisionInput( + decision: Pending, + on_edit: EventHandler, + on_submit: EventHandler, + on_cancel: EventHandler<()>, +) -> Element { + let lang = use_lang()(); + let placeholder = match decision.action { + InboxAction::NotAffected => vex_tx::IMPACT_STATEMENT, + InboxAction::Affected => vex_tx::ACTION_STATEMENT, + InboxAction::AcceptedRisk | InboxAction::FalsePositive | InboxAction::Confirm => tx::REASON, + }; + let ready = decision.ready(); + let typed = decision.clone(); + let chosen = decision.clone(); + let submitted = decision.clone(); + let on_key = decision.clone(); + let justification = decision + .justification + .map(VexJustification::as_str) + .unwrap_or_default(); + rsx! { + div { + class: "inbox-input", + onclick: move |e| e.stop_propagation(), + if decision.action == InboxAction::NotAffected { + select { + class: "inbox-input-select", + value: "{justification}", + "aria-label": vex_tx::JUSTIFICATION.get(lang), + onkeydown: move |e| e.stop_propagation(), + onchange: move |e| { + let mut next = chosen.clone(); + next.justification = JUSTIFICATIONS + .iter() + .map(|(j, _)| *j) + .find(|j| j.as_str() == e.value()); + on_edit.call(next); + }, + option { value: "", {vex_tx::NO_JUSTIFICATION.get(lang)} } + for (j, label) in JUSTIFICATIONS { + option { key: "{j.as_str()}", value: j.as_str(), {label.get(lang)} } + } + } + } + input { + class: "inbox-input-text", + r#type: "text", + value: "{decision.text}", + placeholder: placeholder.get(lang), + "aria-label": placeholder.get(lang), + onmounted: move |e| async move { + // Focusing can only fail when the input has gone. + let _focused = e.data().set_focus(true).await; + }, + oninput: move |e| { + let mut next = typed.clone(); + next.text = e.value(); + on_edit.call(next); + }, + onkeydown: move |e| { + e.stop_propagation(); + match e.key() { + Key::Enter if on_key.ready() => on_submit.call(on_key.clone()), + Key::Escape => on_cancel.call(()), + _ => {} + } + }, + } + button { + class: "btn btn-primary btn-sm", + disabled: !ready, + onclick: move |_| on_submit.call(submitted.clone()), + {tx::DECIDE.get(lang)} + } + button { + class: "btn btn-ghost btn-sm", + onclick: move |_| on_cancel.call(()), + {tx::CANCEL.get(lang)} + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::models::Severity; + + fn card(kind: CardKind, actions: Vec) -> InboxCard { + InboxCard { + key: "f-1".into(), + kind, + bucket: Bucket::Today, + target_id: "t1".into(), + title: "t".into(), + subtitle: String::new(), + severity: Severity::High, + count: 1, + reasons: Vec::new(), + item_ids: vec!["1".into()], + actions, + fix_version: None, + note: None, + } + } + + #[test] + fn shortcuts_pick_the_card_s_matching_action() { + use InboxAction::*; + let finding = card(CardKind::Finding, vec![FalsePositive, AcceptedRisk]); + assert_eq!(shortcut_action("f", &finding), Some(FalsePositive)); + assert_eq!(shortcut_action("a", &finding), Some(AcceptedRisk)); + assert_eq!(shortcut_action("x", &finding), None); + let ai = card(CardKind::Finding, vec![FalsePositive, Confirm]); + assert_eq!(shortcut_action("a", &ai), None, "not offered"); + let cve = card(CardKind::CvePackage, vec![Affected, NotAffected]); + assert_eq!(shortcut_action("f", &cve), Some(NotAffected)); + assert_eq!(shortcut_action("a", &cve), Some(Affected)); + } + + #[test] + fn a_decision_needs_its_input_and_sends_it_in_the_right_field() { + let mut risk = Pending { + key: "f-1".into(), + action: InboxAction::AcceptedRisk, + text: " ".into(), + justification: None, + }; + assert!(!risk.ready()); + risk.text = " isolated ".into(); + assert!(risk.ready()); + assert_eq!(risk.request().reason.as_deref(), Some("isolated")); + assert_eq!(risk.request().statement, None); + let mut not_affected = Pending { + key: "c-1-2".into(), + action: InboxAction::NotAffected, + text: String::new(), + justification: None, + }; + assert!(!not_affected.ready()); + not_affected.justification = Some(VexJustification::VulnerableCodeNotPresent); + assert!(not_affected.ready()); + assert_eq!( + not_affected.request().justification, + Some(VexJustification::VulnerableCodeNotPresent) + ); + let affected = Pending { + key: "c-1-2".into(), + action: InboxAction::Affected, + text: "Update to version 2.17.1.".into(), + justification: Some(VexJustification::ComponentNotPresent), + }; + assert_eq!( + affected.request().statement.as_deref(), + Some("Update to version 2.17.1.") + ); + assert_eq!(affected.request().justification, None); + } + + #[test] + fn chips_name_their_reason() { + let (label, tone) = chip(&Reason::Kev, Lang::De); + assert_eq!(label, "Aktiv ausgenutzt (CISA KEV)"); + assert_eq!(tone, "tone-danger"); + let (label, _) = chip( + &Reason::FixAvailable { + version: "2.17.1".into(), + }, + Lang::En, + ); + assert_eq!(label, "Fix: 2.17.1"); + assert_eq!( + action_label(InboxAction::FalsePositive, Bucket::LikelyFalsePositive), + tx::CONFIRM_FALSE_POSITIVE + ); + assert_eq!( + action_label(InboxAction::FalsePositive, Bucket::Today), + tx::FALSE_POSITIVE + ); + } +} diff --git a/compliance-dashboard/src/pages/mod.rs b/compliance-dashboard/src/pages/mod.rs index f893a84..bf98dd7 100644 --- a/compliance-dashboard/src/pages/mod.rs +++ b/compliance-dashboard/src/pages/mod.rs @@ -10,6 +10,7 @@ pub mod findings; pub mod graph_explorer; pub(crate) mod graph_view; pub mod impact_analysis; +pub mod inbox; pub mod issues; pub mod mcp_servers; pub mod mcp_tokens; @@ -32,6 +33,7 @@ pub use finding_detail::FindingDetailPage; pub use findings::FindingsPage; pub use graph_explorer::GraphExplorerPage; pub use impact_analysis::ImpactAnalysisPage; +pub use inbox::HeutePage; pub use issues::IssuesPage; pub use mcp_servers::McpServersPage; pub use mcp_tokens::McpTokensPage;