From 31c3db9819b2cb8030b4a89a905ea5116045c6d8 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:15:06 +0100 Subject: [PATCH] feat(agent): Heute inbox API with urgency buckets and dated resubmission (#950) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /api/v1/inbox sorts the open findings and CVE alerts into four buckets (Heute handeln, Diese Woche, Später, KI: wohl Fehlalarm), one card per decision: a finding, or the CVE alerts of one package version. Decisions on a card go through the findings' bulk-status and the VEX handlers, undo restores the previous open state, and snoozes live in inbox_snoozes. 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 + 8 files changed, 2482 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 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 344bdc5..b0fa69b 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -9,6 +9,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 bb63086..a3e1725 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 e4c4357..74432ca 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -107,6 +107,15 @@ pub fn build_router() -> Router { "/api/v1/findings/{id}/feedback", patch(handlers::update_finding_feedback), ) + // 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 d80b6a4..3348bbe 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -8,6 +8,7 @@ pub mod exclude_paths; pub mod finding; pub mod git_source; pub mod graph; +pub mod inbox; pub mod issue; pub mod license; pub mod license_policy;