diff --git a/compliance-agent/src/api/handlers/inbox.rs b/compliance-agent/src/api/handlers/inbox.rs index 77d0331..b0d5850 100644 --- a/compliance-agent/src/api/handlers/inbox.rs +++ b/compliance-agent/src/api/handlers/inbox.rs @@ -22,7 +22,7 @@ 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, + OneCardPerFinding, PreviousState, Progress, Reason, SnoozeRequest, SnoozeResponse, UndoRequest, ViewRequest, DECIDED_STATUSES, DECIDING_VEX, UNDECIDED_STATUSES, }; use compliance_core::models::{CveAlert, FindingStatus, VexStatus}; @@ -123,11 +123,11 @@ async fn open_alerts( 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> { +/// The snooze of each card key. +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()) + Ok(snoozes.into_iter().map(|s| (s.key.clone(), s)).collect()) } /// The targets' names by id. @@ -488,9 +488,11 @@ pub async fn undo( /// 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. +/// hidden until then and comes back in its own bucket, or earlier when a new +/// CVE or a KEV entry joins it: the snooze records the card's items and +/// whether it was KEV. A second snooze replaces the first. 400 for a +/// malformed key, 409 when nothing on the card waits for a decision, 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, @@ -505,6 +507,10 @@ pub async fn snooze( .snooze_for .until(now) .map_err(|e| refuse(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()))?; + let db = tenant_db(&agent, &tenant) + .await + .map_err(|code| refuse(code, "tenant"))?; + let (card, _) = resolve_card(&db, &req.key).await?; let actor = Actor::of(&tenant.0); let record = InboxSnooze { key: req.key.clone(), @@ -512,10 +518,9 @@ pub async fn snooze( by: actor.id.to_string(), by_name: actor.name, at: now, + kev: card.reasons.contains(&Reason::Kev), + items: card.item_ids, }; - 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) diff --git a/compliance-agent/tests/inbox.rs b/compliance-agent/tests/inbox.rs index 0d3096c..245c2ea 100644 --- a/compliance-agent/tests/inbox.rs +++ b/compliance-agent/tests/inbox.rs @@ -331,7 +331,7 @@ async fn the_inbox_buckets_decides_undoes_and_resubmits() { 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". + // Put off: hidden until the date, then back in its own bucket (today). let secret_key = CardKey::finding(&secret); let past = server .post( @@ -356,6 +356,8 @@ async fn the_inbox_buckets_decides_undoes_and_resubmits() { .unwrap(); assert_eq!(record.by, "dev-user"); assert!(record.until > Utc::now() + Duration::days(6)); + // The card's items are recorded, so a new one would end the snooze early. + assert_eq!(record.items, std::slice::from_ref(&secret)); db.collection::("inbox_snoozes") .update_one( doc! { "key": &secret_key }, @@ -363,8 +365,8 @@ async fn the_inbox_buckets_decides_undoes_and_resubmits() { ) .await .unwrap(); - let due = inbox(&server, "?bucket=later").await; - assert_eq!(counts(&due), [1, 1, 2, 0]); + let due = inbox(&server, "?bucket=today").await; + assert_eq!(counts(&due), [2, 1, 1, 0]); assert!(due["cards"] .as_array() .unwrap() diff --git a/compliance-core/src/models/inbox.rs b/compliance-core/src/models/inbox.rs index ff03ef5..d3c3d38 100644 --- a/compliance-core/src/models/inbox.rs +++ b/compliance-core/src/models/inbox.rs @@ -5,7 +5,8 @@ //! 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`]). +//! in its own bucket again ([`place`]); a CVE card comes back early when a +//! new CVE or a KEV entry joins it ([`apply_snoozes`]). //! //! Everything here is pure: the agent loads the items and the snoozes, the //! dashboard reads the same types back. @@ -66,7 +67,7 @@ pub enum Bucket { Today, /// "Diese Woche": high and critical, or a fix is available. ThisWeek, - /// "Später": everything else, and every resubmission that is due. + /// "Später": everything else. Later, /// "KI: wohl Fehlalarm": what the AI triage dismissed, for a person to /// confirm or overrule. @@ -133,6 +134,9 @@ pub enum Reason { FixAvailable { version: String }, /// Put off until `since`, and due now. Resubmission { since: DateTime }, + /// Put off at `since`, but a CVE or a KEV entry joined it since, so it + /// is back before its date. + NewSinceResubmission { since: DateTime }, } /// A decision a card offers. Each is applied to every item of the card. @@ -381,20 +385,19 @@ impl Default for Signals { /// 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`]. +/// 1. a secret in the product's code → [`Bucket::Today`], even when the AI +/// dismissed it: a real secret missed costs more than a click; +/// 2. the AI dismissed it → [`Bucket::LikelyFalsePositive`] (the decision is +/// to confirm or overrule the AI); +/// 3. KEV, high EPSS or a CRA notification due → [`Bucket::Today`]; +/// 4. high or critical, or a fix available → [`Bucket::ThisWeek`]; +/// 5. everything else (medium, low, info) → [`Bucket::Later`]. pub fn natural_bucket(signals: &Signals) -> Bucket { - if signals.ai_dismissed { + if signals.secret_in_code { + Bucket::Today + } else if signals.ai_dismissed { Bucket::LikelyFalsePositive - } else if signals.kev - || signals.epss_high.is_some() - || signals.enisa_reportable - || signals.secret_in_code - { + } else if signals.kev || signals.epss_high.is_some() || signals.enisa_reportable { Bucket::Today } else if signals.severity >= Severity::High || signals.fix_version.is_some() { Bucket::ThisWeek @@ -404,13 +407,12 @@ pub fn natural_bucket(signals: &Signals) -> Bucket { } /// 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. +/// `until`, back in `natural` from then on (a resubmission returns to where +/// it was put off from), 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), + Some(_) | None => Some(natural), } } @@ -504,7 +506,7 @@ pub fn finding_cards(findings: &[InboxFinding], grouping: &impl FindingGrouping) ..Signals::default() }; let bucket = natural_bucket(&signals); - let actions = if bucket == Bucket::LikelyFalsePositive { + let actions = if signals.ai_dismissed { vec![InboxAction::FalsePositive, InboxAction::Confirm] } else { vec![InboxAction::FalsePositive, InboxAction::AcceptedRisk] @@ -671,26 +673,39 @@ fn cve_card( } /// `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`]. +/// out, those due are back in their own bucket with a +/// [`Reason::Resubmission`]. A snooze no longer holds once an item joined the +/// card or it became KEV since ([`InboxSnooze::outdated_by`]): the card shows +/// at once, with a [`Reason::NewSinceResubmission`]. /// /// # Arguments /// /// * `cards` - the cards in their natural buckets -/// * `snoozes` - when each card key was put off until +/// * `snoozes` - the snooze of each card key /// * `now` - the moment to evaluate the snoozes at pub fn apply_snoozes( cards: Vec, - snoozes: &HashMap>, + 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 }); + let Some(snooze) = snoozes.get(&card.key) else { + return Some(card); + }; + if snooze.outdated_by(&card) { + card.reasons + .insert(0, Reason::NewSinceResubmission { since: snooze.at }); + return Some(card); } + card.bucket = place(card.bucket, Some(snooze.until), now)?; + card.reasons.insert( + 0, + Reason::Resubmission { + since: snooze.until, + }, + ); Some(card) }) .collect() @@ -961,6 +976,28 @@ pub struct InboxSnooze { pub by_name: Option, #[serde(with = "super::serde_helpers::bson_datetime")] pub at: DateTime, + /// The card's items when it was put off; empty for snoozes stored before + /// they were recorded, which then hold until their date. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub items: Vec, + /// Whether the card was KEV when it was put off. + #[serde(default)] + pub kev: bool, +} + +impl InboxSnooze { + /// Whether `card` changed since it was put off so that the snooze no + /// longer holds: an item joined it (a new CVE on the package), or it is + /// KEV now and was not then. A snooze without recorded items never is. + pub fn outdated_by(&self, card: &InboxCard) -> bool { + if self.items.is_empty() { + return false; + } + let known: BTreeSet<&str> = self.items.iter().map(String::as_str).collect(); + let joined = card.item_ids.iter().any(|id| !known.contains(id.as_str())); + let newly_kev = !self.kev && card.reasons.contains(&Reason::Kev); + joined || newly_kev + } } #[cfg(test)] @@ -1076,34 +1113,119 @@ mod tests { } #[test] - fn what_the_ai_dismissed_is_its_own_bucket_whatever_else_it_is() { + fn what_the_ai_dismissed_is_its_own_bucket_unless_it_is_a_secret_in_code() { assert_eq!( bucket_of(Signals { ai_dismissed: true, - secret_in_code: true, severity: Severity::Critical, ..Signals::default() }), Bucket::LikelyFalsePositive ); + // A real secret missed costs more than a click: it stays for today. + assert_eq!( + bucket_of(Signals { + ai_dismissed: true, + secret_in_code: true, + ..Signals::default() + }), + Bucket::Today + ); } #[test] - fn a_snoozed_card_hides_until_its_date_then_comes_back_under_later() { + fn an_ai_dismissed_secret_keeps_the_ai_actions_for_today() { + let mut secret = finding(Severity::Medium); + secret.scan_type = ScanType::SecretDetection; + secret.status = FindingStatus::NeedsReview; + secret.triage_action = Some(AI_DISMISS.into()); + let cards = finding_cards(&[secret], &OneCardPerFinding); + assert_eq!(cards[0].bucket, Bucket::Today); + assert_eq!( + cards[0].actions, + [InboxAction::FalsePositive, InboxAction::Confirm] + ); + assert_eq!( + cards[0].reasons, + [Reason::AiDismissed, Reason::SecretInCode] + ); + } + + #[test] + fn a_snoozed_card_hides_until_its_date_then_comes_back_to_its_bucket() { 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) + Some(Bucket::Today) ); assert_eq!( - place(Bucket::Today, Some(now()), now()), - Some(Bucket::Later) + place(Bucket::ThisWeek, Some(now()), now()), + Some(Bucket::ThisWeek) ); assert_eq!(place(Bucket::ThisWeek, None, now()), Some(Bucket::ThisWeek)); } + /// A snooze of `key` until `until`, put off an hour ago with `items`. + fn snooze(key: String, until: DateTime, items: &[String], kev: bool) -> InboxSnooze { + InboxSnooze { + key, + until, + by: "u1".into(), + by_name: None, + at: now() - chrono::Duration::hours(1), + items: items.to_vec(), + kev, + } + } + + #[test] + fn a_new_cve_or_a_kev_entry_ends_a_snooze_early() { + let next_week = now() + chrono::Duration::days(7); + let card = |ids: &[&str], kev: bool| InboxCard { + item_ids: ids.iter().map(|s| s.to_string()).collect(), + reasons: if kev { vec![Reason::Kev] } else { vec![] }, + ..finding_cards(&[finding(Severity::High)], &OneCardPerFinding).remove(0) + }; + let key = |c: &InboxCard| c.key.clone(); + let before = ["a1".to_string()]; + + // Unchanged: hidden until its date. + let same = card(&["a1"], false); + let snoozes = HashMap::from([(key(&same), snooze(key(&same), next_week, &before, false))]); + assert!(apply_snoozes(vec![same], &snoozes, now()).is_empty()); + + // A CVE joined the package: back now, in its own bucket. + let joined = card(&["a1", "a2"], false); + let snoozes = HashMap::from([( + key(&joined), + snooze(key(&joined), next_week, &before, false), + )]); + let shown = apply_snoozes(vec![joined], &snoozes, now()); + assert_eq!(shown.len(), 1); + assert_eq!(shown[0].bucket, Bucket::ThisWeek); + assert!(matches!( + shown[0].reasons.first(), + Some(Reason::NewSinceResubmission { .. }) + )); + + // It became KEV since. + let kev = card(&["a1"], true); + let snoozes = HashMap::from([(key(&kev), snooze(key(&kev), next_week, &before, false))]); + assert_eq!(apply_snoozes(vec![kev], &snoozes, now()).len(), 1); + + // KEV already when put off: the snooze holds. + let kev = card(&["a1"], true); + let snoozes = HashMap::from([(key(&kev), snooze(key(&kev), next_week, &before, true))]); + assert!(apply_snoozes(vec![kev], &snoozes, now()).is_empty()); + + // A snooze stored before the items were recorded holds until its date. + let legacy = card(&["a1", "a2"], true); + let snoozes = HashMap::from([(key(&legacy), snooze(key(&legacy), next_week, &[], false))]); + assert!(apply_snoozes(vec![legacy], &snoozes, now()).is_empty()); + } + #[test] fn snoozes_hide_or_resubmit_cards() { let due = finding(Severity::High); @@ -1114,11 +1236,21 @@ mod tests { &OneCardPerFinding, ); let since = now() - chrono::Duration::hours(1); + let due_key = CardKey::finding(&due.id.to_hex()); + let hidden_key = CardKey::finding(&hidden.id.to_hex()); let snoozes = HashMap::from([ - (CardKey::finding(&due.id.to_hex()), since), ( - CardKey::finding(&hidden.id.to_hex()), - now() + chrono::Duration::days(7), + due_key.clone(), + snooze(due_key, since, &[due.id.to_hex()], false), + ), + ( + hidden_key.clone(), + snooze( + hidden_key, + now() + chrono::Duration::days(7), + &[hidden.id.to_hex()], + false, + ), ), ]); let shown = apply_snoozes(cards, &snoozes, now()); @@ -1127,7 +1259,11 @@ mod tests { .iter() .find(|c| c.item_ids == [due.id.to_hex()]) .cloned(); - assert_eq!(resubmitted.as_ref().map(|c| c.bucket), Some(Bucket::Later)); + // Back where it was put off from: a high finding is for this week. + assert_eq!( + resubmitted.as_ref().map(|c| c.bucket), + Some(Bucket::ThisWeek) + ); assert_eq!( resubmitted.map(|c| c.reasons), Some(vec![Reason::Resubmission { since }]) diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 387d80b..eb382a3 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -6381,6 +6381,15 @@ pub mod inbox { } } + /// A card back before its resubmission date: a CVE or a KEV entry joined + /// it since it was put off on `date`. + pub fn new_since_resubmission(date: &str, lang: Lang) -> String { + match lang { + Lang::De => format!("Neu seit Wiedervorlage am {date}"), + Lang::En => format!("New since put off on {date}"), + } + } + /// The undo toast after a snooze: "Wiedervorlage am 01.12.2026". pub fn snoozed(date: &str, lang: Lang) -> String { match lang { diff --git a/compliance-dashboard/src/pages/inbox.rs b/compliance-dashboard/src/pages/inbox.rs index 57b784d..6ab27e9 100644 --- a/compliance-dashboard/src/pages/inbox.rs +++ b/compliance-dashboard/src/pages/inbox.rs @@ -195,6 +195,10 @@ fn chip(reason: &Reason, lang: Lang) -> (String, &'static str) { tx::resubmission(&format_day(since, lang), lang), "tone-info", ), + Reason::NewSinceResubmission { since } => ( + tx::new_since_resubmission(&format_day(since, lang), lang), + "tone-danger", + ), } }