feat(dashboard): Heute inbox with urgency buckets and dated resubmission (#950) (#965)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 2m35s
CI / Deploy Dashboard (push) Successful in 7m58s
CI / Deploy Agent (push) Successful in 9m56s

A new landing page "Heute" (the overview moves to /overview and stays in
the sidebar): the Erstbewertung, target chips, the four bucket tiles and
the cards of the chosen bucket with their decisions, "Später" with one
week, one month or a date, "Details", an undo strip after each decision,
and the keys j/k/f/a/s on this page only. The sidebar's "Heute" entry
shows the workspace's "Heute handeln" count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit was merged in pull request #965.
This commit is contained in:
sharangandClaude Opus 5.5 committed 2026-11-10 17:22:59 +00:00
1 parent 7b7731f46d
commit d6986d23b1
16 files changed
+4282

No files matched your search

+549
View File
@@ -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<serde_json::Value>);
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<String>,
/// The bucket whose cards to list (default `today`).
#[serde(default)]
pub bucket: Option<Bucket>,
/// The most cards to list (default 100, at most 500).
#[serde(default)]
pub limit: Option<usize>,
}
/// The bucket rules as configured: the CVE issues' EPSS threshold
/// (`CVE_ISSUE_EPSS_PERCENTILE`, default 0.95), at `now`.
fn rules(now: DateTime<Utc>) -> 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<T: serde::Serialize>(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<Vec<InboxFinding>, 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::<InboxFinding>()
.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<Vec<CveAlert>, 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<CveAlert> = 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<HashMap<String, DateTime<Utc>>, mongodb::error::Error> {
let cursor = db.inbox_snoozes().find(doc! {}).await?;
let snoozes: Vec<InboxSnooze> = 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<HashMap<String, String>, mongodb::error::Error> {
let mut cursor = db
.onboarded_targets()
.clone_with_type::<Document>()
.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<Progress, mongodb::error::Error> {
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=<id>&bucket=<bucket>&limit=<n>] — 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<InboxQuery>,
) -> ApiResult<InboxView> {
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<PreviousState>), 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<String>,
status: FindingStatus,
reason: Option<String>,
) -> 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<DecideRequest>,
) -> Result<Json<DecideResponse>, 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<String>| {
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<bool, Refusal> {
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<CveAlert> = 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<UndoRequest>,
) -> Result<Json<serde_json::Value>, 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<FindingStatus, Vec<String>> = 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<SnoozeRequest>,
) -> Result<Json<SnoozeResponse>, 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<String>,
) -> Result<Json<serde_json::Value>, 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" })))
}
+1
View File
@@ -13,6 +13,7 @@ pub mod git_source;
pub mod graph;
pub mod health;
pub mod help_chat;
pub mod inbox;
pub mod issues;
pub mod licenses;
pub mod manual_findings;
@@ -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"),
+9
View File
@@ -116,6 +116,15 @@ pub fn build_router() -> Router {
"/api/v1/finding-groups/decide",
post(handlers::finding_groups::decide_finding_group),
)
// The "Heute" inbox (#950): open decisions in urgency buckets.
.route("/api/v1/inbox", get(handlers::inbox::get_inbox))
.route("/api/v1/inbox/decide", post(handlers::inbox::decide))
.route("/api/v1/inbox/undo", post(handlers::inbox::undo))
.route("/api/v1/inbox/snooze", post(handlers::inbox::snooze))
.route(
"/api/v1/inbox/snooze/{key}",
delete(handlers::inbox::unsnooze),
)
// VEX on a target's CVE alerts (#498).
.route(
"/api/v1/targets/{id}/cves",
+19
View File
@@ -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<compliance_core::models::inbox::InboxSnooze> {
self.inner
.collection(compliance_core::models::inbox::SNOOZES_COLLECTION)
}
#[allow(dead_code)]
pub fn raw_collection(&self, name: &str) -> Collection<mongodb::bson::Document> {
self.inner.collection(name)
+380
View File
@@ -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::<Document>("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::<CveAlert>("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::<Document>("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::<CveAlert>("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::<Document>("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::<InboxSnooze>("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::<Document>("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;
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -9,6 +9,7 @@ pub mod finding;
pub mod finding_group;
pub mod git_source;
pub mod graph;
pub mod inbox;
pub mod issue;
pub mod license;
pub mod license_policy;
+425
View File
@@ -7117,3 +7117,428 @@ input[type="file"] {
.ticket-links a:hover {
text-decoration: underline;
}
/* ── Heute: the inbox of open decisions (#950) ── */
/* The page takes the keyboard (j/k/f/a/s); no ring around the whole page. */
.inbox-page:focus {
outline: none;
}
.nav-count {
margin-left: auto;
min-width: 18px;
padding: 0 5px;
border-radius: 9px;
background: var(--danger);
color: #fff;
font-family: var(--font-mono);
font-size: 10.5px;
font-weight: 600;
line-height: 18px;
text-align: center;
}
.sidebar.collapsed .nav-count {
position: absolute;
top: 1px;
right: 1px;
min-width: 15px;
line-height: 15px;
font-size: 9px;
}
.inbox-progress {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 12px 14px;
margin-bottom: 12px;
}
.inbox-progress-head {
display: flex;
align-items: baseline;
gap: 10px;
margin-bottom: 8px;
font-size: 12.5px;
}
.inbox-progress-label {
font-weight: 600;
color: var(--text-primary);
}
.inbox-progress-value {
color: var(--text-tertiary);
}
.inbox-progress-percent {
margin-left: auto;
font-family: var(--font-mono);
color: var(--text-secondary);
}
.inbox-progress-track {
height: 6px;
border-radius: 3px;
background: var(--bg-elevated);
overflow: hidden;
}
.inbox-progress-fill {
height: 100%;
background: var(--success);
border-radius: 3px;
transition: width 0.4s var(--ease-out);
}
.inbox-targets {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 12px;
}
.inbox-target {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border: 1px solid var(--border-bright);
border-radius: 999px;
background: var(--bg-card);
color: var(--text-secondary);
font-family: var(--font-body);
font-size: 12px;
cursor: pointer;
}
.inbox-target:hover {
border-color: var(--border-strong);
color: var(--text-primary);
}
.inbox-target.is-active {
border-color: var(--border-accent);
background: var(--accent-muted);
color: var(--accent);
font-weight: 600;
}
.inbox-target-count {
font-family: var(--font-mono);
font-size: 10.5px;
color: var(--text-faint);
}
.inbox-buckets {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
margin-bottom: 14px;
}
.inbox-bucket {
--tone: var(--text-tertiary);
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 2px;
padding: 11px 13px 12px;
border: 1px solid var(--border);
border-top: 3px solid var(--tone);
border-radius: var(--radius-lg);
background: var(--bg-card);
color: var(--text-primary);
font-family: var(--font-body);
text-align: left;
cursor: pointer;
transition: background 0.1s, border-color 0.1s;
}
.inbox-bucket:hover {
background: var(--bg-card-hover);
}
.inbox-bucket.is-active {
border-color: var(--tone);
background: color-mix(in oklch, var(--tone) 7%, var(--bg-card));
}
.inbox-bucket.tone-danger { --tone: var(--danger); }
.inbox-bucket.tone-warning { --tone: var(--orange); }
.inbox-bucket.tone-neutral { --tone: var(--info); }
.inbox-bucket.tone-accent { --tone: var(--accent); }
.inbox-bucket-count {
font-family: var(--font-mono);
font-size: 24px;
font-weight: 600;
line-height: 1.1;
color: var(--tone);
}
.inbox-bucket-label {
font-size: 13px;
font-weight: 600;
}
.inbox-bucket-hint {
font-size: 11.5px;
color: var(--text-tertiary);
}
.inbox-cards {
display: flex;
flex-direction: column;
gap: 8px;
}
.inbox-card {
background: var(--bg-card);
border: 1px solid var(--border);
border-left: 3px solid transparent;
border-radius: var(--radius-lg);
padding: 12px 14px;
cursor: default;
}
.inbox-card.is-selected {
border-color: var(--border-accent);
border-left-color: var(--accent);
box-shadow: var(--shadow-pop);
}
.inbox-card-head {
display: flex;
align-items: center;
gap: 9px;
}
.inbox-card-title {
font-family: var(--font-display);
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
letter-spacing: -0.01em;
overflow-wrap: anywhere;
}
.inbox-card-sub {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 4px 10px;
margin-top: 4px;
font-size: 12px;
color: var(--text-tertiary);
}
.inbox-card-target {
font-weight: 500;
color: var(--text-secondary);
}
.inbox-card-place {
font-family: var(--font-mono);
font-size: 11.5px;
overflow-wrap: anywhere;
}
.inbox-chips {
display: flex;
flex-wrap: wrap;
gap: 5px;
margin-top: 8px;
}
.inbox-chip {
--tone: var(--text-tertiary);
padding: 1px 8px;
border-radius: 999px;
border: 1px solid color-mix(in oklch, var(--tone) 32%, transparent);
background: color-mix(in oklch, var(--tone) 10%, transparent);
color: var(--tone);
font-size: 11px;
font-weight: 500;
white-space: nowrap;
}
.inbox-chip.tone-danger { --tone: var(--danger); }
.inbox-chip.tone-warning { --tone: var(--orange); }
.inbox-chip.tone-success { --tone: var(--success); }
.inbox-chip.tone-info { --tone: var(--info); }
.inbox-chip.tone-accent { --tone: var(--accent); }
.inbox-card-note {
margin-top: 8px;
font-size: 12px;
color: var(--text-secondary);
}
.inbox-card-note-label {
font-weight: 600;
margin-right: 6px;
}
.inbox-actions,
.inbox-input {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
margin-top: 10px;
}
.inbox-later {
position: relative;
}
.inbox-later > summary {
list-style: none;
}
.inbox-later > summary::-webkit-details-marker {
display: none;
}
.inbox-later-menu {
position: absolute;
z-index: 20;
top: calc(100% + 4px);
left: 0;
display: flex;
flex-direction: column;
gap: 6px;
min-width: 210px;
padding: 8px;
border: 1px solid var(--border-bright);
border-radius: var(--radius-lg);
background: var(--bg-card-solid);
box-shadow: var(--shadow-pop);
}
.inbox-later-option {
padding: 5px 8px;
border: none;
border-radius: var(--radius-sm);
background: transparent;
color: var(--text-primary);
font-family: var(--font-body);
font-size: 12.5px;
text-align: left;
cursor: pointer;
}
.inbox-later-option:hover {
background: var(--bg-elevated);
}
.inbox-later-date {
display: flex;
flex-direction: column;
gap: 3px;
padding: 4px 8px 0;
font-size: 11.5px;
color: var(--text-tertiary);
}
.inbox-later-date input,
.inbox-input-text,
.inbox-input-select {
padding: 5px 8px;
border: 1px solid var(--border-bright);
border-radius: var(--radius);
background: var(--bg-secondary);
color: var(--text-primary);
font-family: var(--font-body);
font-size: 12.5px;
}
.inbox-input-text {
flex: 1 1 240px;
min-width: 0;
}
.inbox-details {
margin-left: auto;
font-size: 12.5px;
color: var(--accent);
text-decoration: none;
}
.inbox-details:hover {
text-decoration: underline;
}
.inbox-empty {
text-align: center;
color: var(--text-tertiary);
padding: 28px 16px;
}
.inbox-empty .btn {
margin-top: 10px;
}
.inbox-shortcuts {
margin-top: 12px;
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-faint);
}
.inbox-undo {
position: fixed;
left: 50%;
bottom: 22px;
z-index: 210;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 14px;
max-width: calc(100vw - 32px);
padding: 9px 10px 9px 16px;
border-radius: var(--radius-lg);
background: var(--text-primary);
color: var(--bg-primary);
font-size: 13px;
box-shadow: var(--shadow-pop);
}
.inbox-undo > span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.inbox-undo-btn {
background: transparent;
border-color: color-mix(in oklch, var(--bg-primary) 40%, transparent);
color: var(--bg-primary);
font-weight: 600;
}
.inbox-undo-btn:hover {
background: color-mix(in oklch, var(--bg-primary) 14%, transparent);
color: var(--bg-primary);
border-color: var(--bg-primary);
}
@media (max-width: 900px) {
.inbox-buckets {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 480px) {
.inbox-details {
margin-left: 0;
}
.inbox-later-menu {
position: static;
margin-top: 4px;
}
}
+13
View File
@@ -8,7 +8,10 @@ use crate::pages::*;
#[allow(clippy::enum_variant_names)]
pub enum Route {
#[layout(AppShell)]
// The landing page: the open decisions (#950).
#[route("/")]
HeutePage {},
#[route("/overview")]
OverviewPage {},
#[route("/targets")]
TargetsPage {},
@@ -119,6 +122,16 @@ mod tests {
use super::Route;
use std::str::FromStr;
#[test]
fn heute_is_the_landing_page_and_the_overview_stays_reachable() {
assert!(matches!(Route::from_str("/"), Ok(Route::HeutePage {})));
assert!(matches!(
Route::from_str("/overview"),
Ok(Route::OverviewPage {})
));
assert_eq!(Route::OverviewPage {}.to_string(), "/overview");
}
#[test]
fn the_sbom_page_carries_its_target_in_the_query() {
let filtered = Route::SbomPage {
@@ -166,6 +166,11 @@ pub fn Sidebar() -> Element {
}
}
div { class: "sidebar-nav",
TodayNavItem {
collapsed: collapsed(),
active: current_route == (Route::HeutePage {}),
on_navigate: move |_| mobile_open.set(false),
}
for item in nav_items.into_iter().filter(|i| can_write || !i.write_only) {
{
let is_active = match (&current_route, &item.route) {
@@ -290,6 +295,41 @@ pub fn Sidebar() -> Element {
}
}
/// The sidebar's "Heute" entry with the workspace's "Heute handeln" count
/// (#950): fetched once, then kept current by the page.
#[component]
fn TodayNavItem(collapsed: bool, active: bool, on_navigate: EventHandler<()>) -> Element {
use crate::infrastructure::inbox::fetch_inbox;
use crate::pages::inbox::TODAY_COUNT;
use compliance_core::models::inbox::Bucket;
let lang = use_lang()();
let _count = use_resource(|| async {
if TODAY_COUNT.peek().is_none() {
if let Ok(view) = fetch_inbox(String::new(), Bucket::Today, Some(0)).await {
*TODAY_COUNT.write() = Some(view.counts.today);
}
}
});
let label = crate::i18n::texts::inbox::NAV.get(lang);
let today = TODAY_COUNT().filter(|n| *n > 0);
rsx! {
Link {
to: Route::HeutePage {},
class: if active { "nav-item active" } else { "nav-item" },
title: "{label}",
onclick: move |_| on_navigate.call(()),
Icon { icon: BsInbox, width: 18, height: 18 }
if !collapsed {
span { "{label}" }
}
if let Some(today) = today {
span { class: "nav-count", "{today}" }
}
}
}
}
/// The BreakPilot wordmark, as on breakpilot.com and the portal: the chevron,
/// and unless `with_name` is off, "BreakPilot" with "Prüfwerk" beneath.
#[component]
+307
View File
@@ -6133,3 +6133,310 @@ pub mod finding_breakdown {
}
}
}
/// The "Heute" inbox (#950): open decisions in four urgency buckets.
pub mod inbox {
use super::super::Lang;
use super::Text;
pub const NAV: Text = Text {
de: "Heute",
en: "Today",
};
pub const TITLE: Text = Text {
de: "Heute",
en: "Today",
};
pub const SUBTITLE: Text = Text {
de: "Offene Entscheidungen, nach Dringlichkeit sortiert. Eine Karte, eine Entscheidung.",
en: "Open decisions, sorted by urgency. One card, one decision.",
};
pub const PROGRESS: Text = Text {
de: "Erstbewertung",
en: "First assessment",
};
pub const PROGRESS_HINT: Text = Text {
de: "Befunde und Schwachstellen, über die schon entschieden ist (Fehlalarm, \
Risiko akzeptiert, VEX-Aussage), von allen, die nicht behoben sind.",
en: "Findings and vulnerabilities already decided (false alarm, risk accepted, VEX \
statement), of all that are not resolved.",
};
pub const ALL_TARGETS: Text = Text {
de: "Alle Prüfobjekte",
en: "All targets",
};
pub const TODAY: Text = Text {
de: "Heute handeln",
en: "Act today",
};
pub const THIS_WEEK: Text = Text {
de: "Diese Woche",
en: "This week",
};
pub const LATER: Text = Text {
de: "Später",
en: "Later",
};
pub const AI: Text = Text {
de: "KI: wohl Fehlalarm",
en: "AI: likely false alarm",
};
pub const TODAY_HINT: Text = Text {
de: "Ausgenutzt, CRA-Frist läuft, Secret im Code",
en: "Exploited, CRA deadline running, secret in code",
};
pub const THIS_WEEK_HINT: Text = Text {
de: "Hoch und kritisch, oder ein Fix ist da",
en: "High and critical, or a fix is available",
};
pub const LATER_HINT: Text = Text {
de: "Mittel und niedrig, fällige Wiedervorlagen",
en: "Medium and low, resubmissions due",
};
pub const AI_HINT: Text = Text {
de: "Von der KI verworfen, bitte bestätigen",
en: "Dismissed by the AI, please confirm",
};
pub const EMPTY_TODAY: Text = Text {
de: "Heute ist nichts dringend.",
en: "Nothing is urgent today.",
};
pub const EMPTY_THIS_WEEK: Text = Text {
de: "Für diese Woche ist nichts offen.",
en: "Nothing is open for this week.",
};
pub const EMPTY_LATER: Text = Text {
de: "Für später ist nichts offen.",
en: "Nothing is open for later.",
};
pub const EMPTY_AI: Text = Text {
de: "Die KI hat nichts verworfen, das auf Sie wartet.",
en: "The AI dismissed nothing that waits for you.",
};
pub const LOAD_FAILED: Text = Text {
de: "Die Entscheidungen konnten nicht geladen werden.",
en: "The decisions could not be loaded.",
};
pub const KEV: Text = Text {
de: "Aktiv ausgenutzt (CISA KEV)",
en: "Exploited (CISA KEV)",
};
pub const SECRET_IN_CODE: Text = Text {
de: "Secret im Code",
en: "Secret in code",
};
pub const AI_DISMISSED: Text = Text {
de: "Von der KI verworfen",
en: "Dismissed by the AI",
};
pub const CRA_DUTY: Text = Text {
de: "CRA-Meldepflicht",
en: "CRA notification due",
};
pub const FALSE_POSITIVE: Text = Text {
de: "Fehlalarm",
en: "False alarm",
};
pub const CONFIRM_FALSE_POSITIVE: Text = Text {
de: "Fehlalarm bestätigen",
en: "Confirm false alarm",
};
pub const CONFIRM: Text = Text {
de: "Doch echt",
en: "It is real",
};
pub const ACCEPT_RISK: Text = Text {
de: "Risiko akzeptieren",
en: "Accept the risk",
};
pub const NOT_AFFECTED: Text = Text {
de: "Nicht betroffen",
en: "Not affected",
};
pub const AFFECTED: Text = Text {
de: "Betroffen, Update geplant",
en: "Affected, update planned",
};
pub const LATER_MENU: Text = Text {
de: "Später",
en: "Later",
};
pub const ONE_WEEK: Text = Text {
de: "In 1 Woche",
en: "In 1 week",
};
pub const ONE_MONTH: Text = Text {
de: "In 1 Monat",
en: "In 1 month",
};
pub const ON_DATE: Text = Text {
de: "Am Datum",
en: "On a date",
};
pub const SET_DATE: Text = Text {
de: "Wiedervorlage setzen",
en: "Set the resubmission",
};
pub const DETAILS: Text = Text {
de: "Details →",
en: "Details →",
};
pub const REASON: Text = Text {
de: "Warum wird das Risiko akzeptiert?",
en: "Why is the risk accepted?",
};
pub const DECIDE: Text = Text {
de: "Entscheiden",
en: "Decide",
};
pub const CANCEL: Text = Text {
de: "Abbrechen",
en: "Cancel",
};
pub const DECIDED: Text = Text {
de: "Entschieden",
en: "Decided",
};
pub const UNDO: Text = Text {
de: "Rückgängig",
en: "Undo",
};
pub const UNDONE: Text = Text {
de: "Rückgängig gemacht",
en: "Undone",
};
pub const FAILED: Text = Text {
de: "Das hat nicht geklappt",
en: "That did not work",
};
pub const SHORTCUTS: Text = Text {
de: "Tasten: j / k wählen · f Fehlalarm · a Risiko akzeptiert · s später (1 Woche)",
en: "Keys: j / k move · f false alarm · a risk accepted · s later (1 week)",
};
pub const AI_NOTE: Text = Text {
de: "Begründung der KI",
en: "The AI's reasoning",
};
/// "42 von 180 entschieden", "42 of 180 decided".
pub fn progress_line(decided: u64, total: u64, lang: Lang) -> String {
match lang {
Lang::De => format!("{decided} von {total} entschieden"),
Lang::En => format!("{decided} of {total} decided"),
}
}
/// The EPSS chip: "EPSS 97. Perzentil", "EPSS 97th percentile".
pub fn epss(percentile: f64, lang: Lang) -> String {
// Whole percentiles; the fraction runs from 0 to 1.
let whole = (percentile * 100.0).floor();
match lang {
Lang::De => format!("EPSS {whole}. Perzentil"),
Lang::En => format!("EPSS {whole}th percentile"),
}
}
/// A CRA Article 14 stage, by its name in the agent's answer.
pub fn stage(stage: &str, lang: Lang) -> &'static str {
let text = match stage {
"early_warning" => Text {
de: "Frühwarnung",
en: "early warning",
},
"vulnerability_notification" => Text {
de: "Schwachstellenmeldung",
en: "vulnerability notification",
},
_ => Text {
de: "Abschlussbericht",
en: "final report",
},
};
text.get(lang)
}
/// The CRA deadline chip: "CRA-Frühwarnung in 14 h", "… überfällig".
pub fn enisa(stage_name: &str, overdue: bool, hours_left: Option<i64>, lang: Lang) -> String {
let stage = stage(stage_name, lang);
match (lang, overdue, hours_left) {
(Lang::De, true, _) => format!("CRA-{stage} überfällig"),
(Lang::En, true, _) => format!("CRA {stage} overdue"),
(Lang::De, false, Some(h)) => format!("CRA-{stage} in {h} h"),
(Lang::En, false, Some(h)) => format!("CRA {stage} in {h} h"),
(Lang::De, false, None) => format!("CRA-{stage} fällig"),
(Lang::En, false, None) => format!("CRA {stage} due"),
}
}
/// The fix chip: "Fix: 2.17.1".
pub fn fix(version: &str) -> String {
format!("Fix: {version}")
}
/// The resubmission chip: "Wiedervorlage seit 01.12.2026".
pub fn resubmission(date: &str, lang: Lang) -> String {
match lang {
Lang::De => format!("Wiedervorlage seit {date}"),
Lang::En => format!("Resubmission since {date}"),
}
}
/// The undo toast after a snooze: "Wiedervorlage am 01.12.2026".
pub fn snoozed(date: &str, lang: Lang) -> String {
match lang {
Lang::De => format!("Wiedervorlage am {date}"),
Lang::En => format!("Back on {date}"),
}
}
/// A CVE card's size: "1 CVE", "3 CVEs".
pub fn cves(count: usize) -> String {
match count {
1 => "1 CVE".to_string(),
n => format!("{n} CVEs"),
}
}
/// A finding's places when it has several: "3 Stellen", "3 places".
pub fn places(count: usize, lang: Lang) -> String {
match lang {
Lang::De => format!("{count} Stellen"),
Lang::En => format!("{count} places"),
}
}
/// The action statement an update is prefilled with.
pub fn update_to(version: &str, lang: Lang) -> String {
match lang {
Lang::De => format!("Auf Version {version} aktualisieren."),
Lang::En => format!("Update to version {version}."),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn chips_read_in_both_languages() {
assert_eq!(progress_line(42, 180, Lang::De), "42 von 180 entschieden");
assert_eq!(progress_line(42, 180, Lang::En), "42 of 180 decided");
assert_eq!(epss(0.973, Lang::De), "EPSS 97. Perzentil");
assert_eq!(
enisa("early_warning", false, Some(14), Lang::De),
"CRA-Frühwarnung in 14 h"
);
assert_eq!(
enisa("vulnerability_notification", true, Some(-3), Lang::En),
"CRA vulnerability notification overdue"
);
assert_eq!(cves(1), "1 CVE");
assert_eq!(cves(4), "4 CVEs");
assert_eq!(
update_to("2.17.1", Lang::De),
"Auf Version 2.17.1 aktualisieren."
);
assert_eq!(places(3, Lang::En), "3 places");
}
}
}
@@ -0,0 +1,94 @@
//! The "Heute" inbox (#950): the cards of a bucket, decisions on a card,
//! undo, and resubmission dates. The agent does the work; these only carry
//! the session's token there and back.
use dioxus::prelude::*;
use compliance_core::models::inbox::{
Bucket, DecideRequest, DecideResponse, InboxView, SnoozeRequest, SnoozeResponse, UndoRequest,
};
/// The agent's `{ data }` reply (read on the server only).
#[cfg(feature = "server")]
#[derive(Debug, serde::Deserialize)]
struct ViewResponse {
data: InboxView,
}
/// The counts, the Erstbewertung, the targets and the cards of `bucket`, for
/// the whole workspace or, with a non-empty `target`, one target; at most
/// `limit` cards (the agent's default without one).
#[server]
pub async fn fetch_inbox(
target: String,
bucket: Bucket,
limit: Option<u32>,
) -> Result<InboxView, ServerFnError> {
let mut request = super::agent_client::agent_get("/api/v1/inbox")
.await?
.query(&[("bucket", bucket.as_str())]);
if !target.is_empty() {
request = request.query(&[("target", target.as_str())]);
}
if let Some(limit) = limit {
request = request.query(&[("limit", limit)]);
}
let resp = request
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: ViewResponse = super::agent_client::json_or_error(resp).await?;
Ok(body.data)
}
/// Apply a decision to every item of a card; what they were before, for
/// [`undo_decision`]. The agent's refusal (a missing reason, a card already
/// decided, a read-only role) is the error.
#[server]
pub async fn decide_card(request: DecideRequest) -> Result<DecideResponse, ServerFnError> {
let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/inbox/decide")
.await?
.json(&request)
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
super::agent_client::json_or_error(resp).await
}
/// Put the items of a decision back.
#[server]
pub async fn undo_decision(request: UndoRequest) -> Result<(), ServerFnError> {
let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/inbox/undo")
.await?
.json(&request)
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
super::agent_client::ok_or_error(resp).await
}
/// Put a card off; when it comes back.
#[server]
pub async fn snooze_card(request: SnoozeRequest) -> Result<SnoozeResponse, ServerFnError> {
let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/inbox/snooze")
.await?
.json(&request)
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
super::agent_client::json_or_error(resp).await
}
/// Take a card's resubmission back (the undo of [`snooze_card`]).
#[server]
pub async fn unsnooze_card(key: String) -> Result<(), ServerFnError> {
let resp = super::agent_client::agent_request(
reqwest::Method::DELETE,
&format!("/api/v1/inbox/snooze/{key}"),
)
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
super::agent_client::ok_or_error(resp).await
}
@@ -12,6 +12,7 @@ pub mod finding_groups;
pub mod findings;
pub mod graph;
pub mod help_chat;
pub mod inbox;
pub mod issues;
pub mod manual_findings;
pub mod mcp;
+918
View File
@@ -0,0 +1,918 @@
//! "Heute" (#950), the landing page: the workspace's open decisions in four
//! urgency buckets, one card per decision, with the decision, "Später" with
//! a resubmission date, and undo, all from here.
//!
//! Keyboard (on this page only, never while typing): `j`/`k` move between
//! cards, `f` false alarm (VEX `not_affected` on a CVE card), `a` risk
//! accepted (VEX `affected` on a CVE card), `s` later (one week), `Esc`
//! closes an open input.
use std::collections::HashSet;
use std::rc::Rc;
use chrono::{DateTime, NaiveDate, Utc};
use dioxus::prelude::*;
use compliance_core::models::inbox::{
Bucket, CardKind, DecideRequest, InboxAction, InboxCard, InboxView, Reason, SnoozeFor,
SnoozeRequest, UndoRequest,
};
use compliance_core::models::VexJustification;
use crate::app::Route;
use crate::components::no_access::use_can_write;
use crate::components::page_header::PageHeader;
use crate::components::severity_badge::SeverityBadge;
use crate::components::toast::{ToastType, Toasts};
use crate::i18n::texts::{common, inbox as tx, vex as vex_tx};
use crate::i18n::{use_lang, Lang, Text};
use crate::infrastructure::inbox::{
decide_card, fetch_inbox, snooze_card, undo_decision, unsnooze_card,
};
/// The workspace's "Heute handeln" cards, for the sidebar: fetched once,
/// then kept current by this page.
pub static TODAY_COUNT: GlobalSignal<Option<u64>> = Signal::global(|| None);
/// How long the undo strip stays after a decision.
#[cfg(feature = "web")]
const UNDO_MS: u32 = 8_000;
/// The VEX justifications in the "Nicht betroffen" choice, with their labels.
const JUSTIFICATIONS: [(VexJustification, Text); 5] = [
(
VexJustification::ComponentNotPresent,
vex_tx::COMPONENT_NOT_PRESENT,
),
(
VexJustification::VulnerableCodeNotPresent,
vex_tx::CODE_NOT_PRESENT,
),
(
VexJustification::VulnerableCodeNotInExecutePath,
vex_tx::CODE_NOT_IN_EXECUTE_PATH,
),
(
VexJustification::VulnerableCodeCannotBeControlledByAdversary,
vex_tx::CODE_NOT_CONTROLLABLE,
),
(
VexJustification::InlineMitigationsAlreadyExist,
vex_tx::MITIGATIONS_EXIST,
),
];
/// A decision that needs a word first: the reason of an accepted risk, the
/// justification of a `not_affected`, the action of an `affected`.
#[derive(Debug, Clone, PartialEq)]
struct Pending {
key: String,
action: InboxAction,
text: String,
justification: Option<VexJustification>,
}
impl Pending {
/// Whether it carries what the agent asks for.
fn ready(&self) -> bool {
let has_text = !self.text.trim().is_empty();
match self.action {
InboxAction::NotAffected => self.justification.is_some() || has_text,
InboxAction::AcceptedRisk | InboxAction::Affected => has_text,
InboxAction::FalsePositive | InboxAction::Confirm => true,
}
}
/// The request deciding card `key` with it.
fn request(&self) -> DecideRequest {
let text = Some(self.text.trim().to_string()).filter(|t| !t.is_empty());
let (reason, statement) = match self.action {
InboxAction::AcceptedRisk => (text, None),
InboxAction::NotAffected | InboxAction::Affected => (None, text),
InboxAction::FalsePositive | InboxAction::Confirm => (None, None),
};
DecideRequest {
key: self.key.clone(),
action: self.action,
reason,
justification: self
.justification
.filter(|_| self.action == InboxAction::NotAffected),
statement,
}
}
}
/// What the undo strip takes back.
#[derive(Debug, Clone, PartialEq)]
enum UndoKind {
Decision(UndoRequest),
Snooze(String),
}
/// The undo strip's offer; `id` tells a newer offer from the one a timer
/// was started for.
#[derive(Debug, Clone, PartialEq)]
struct UndoOffer {
id: u64,
kind: UndoKind,
message: String,
}
/// The labels of a bucket: name, what goes in it, and what an empty one says.
const fn bucket_texts(bucket: Bucket) -> (Text, Text, Text) {
match bucket {
Bucket::Today => (tx::TODAY, tx::TODAY_HINT, tx::EMPTY_TODAY),
Bucket::ThisWeek => (tx::THIS_WEEK, tx::THIS_WEEK_HINT, tx::EMPTY_THIS_WEEK),
Bucket::Later => (tx::LATER, tx::LATER_HINT, tx::EMPTY_LATER),
Bucket::LikelyFalsePositive => (tx::AI, tx::AI_HINT, tx::EMPTY_AI),
}
}
/// The CSS tone of a bucket's tile.
const fn bucket_tone(bucket: Bucket) -> &'static str {
match bucket {
Bucket::Today => "tone-danger",
Bucket::ThisWeek => "tone-warning",
Bucket::Later => "tone-neutral",
Bucket::LikelyFalsePositive => "tone-accent",
}
}
/// An action's button label; the AI bucket's false alarm confirms the AI.
fn action_label(action: InboxAction, bucket: Bucket) -> Text {
match action {
InboxAction::FalsePositive if bucket == Bucket::LikelyFalsePositive => {
tx::CONFIRM_FALSE_POSITIVE
}
InboxAction::FalsePositive => tx::FALSE_POSITIVE,
InboxAction::AcceptedRisk => tx::ACCEPT_RISK,
InboxAction::Confirm => tx::CONFIRM,
InboxAction::NotAffected => tx::NOT_AFFECTED,
InboxAction::Affected => tx::AFFECTED,
}
}
/// The action key `f` or `a` stands for on `card`, if the card offers it:
/// false alarm and accepted risk, on a CVE card their VEX counterparts.
fn shortcut_action(key: &str, card: &InboxCard) -> Option<InboxAction> {
let wanted = match (key, card.kind) {
("f", CardKind::Finding) => InboxAction::FalsePositive,
("f", CardKind::CvePackage) => InboxAction::NotAffected,
("a", CardKind::Finding) => InboxAction::AcceptedRisk,
("a", CardKind::CvePackage) => InboxAction::Affected,
_ => return None,
};
card.actions.contains(&wanted).then_some(wanted)
}
/// A day in the reader's convention: `01.12.2026`, `2026-12-01`.
fn format_day(time: &DateTime<Utc>, lang: Lang) -> String {
match lang {
Lang::De => time.format("%d.%m.%Y").to_string(),
Lang::En => time.format("%Y-%m-%d").to_string(),
}
}
/// A reason as a chip: its text and tone.
fn chip(reason: &Reason, lang: Lang) -> (String, &'static str) {
match reason {
Reason::AiDismissed => (tx::AI_DISMISSED.get(lang).to_string(), "tone-accent"),
Reason::Kev => (tx::KEV.get(lang).to_string(), "tone-danger"),
Reason::Epss { percentile } => (tx::epss(*percentile, lang), "tone-warning"),
Reason::EnisaDeadline {
stage: Some(stage),
overdue,
hours_left,
..
} => (tx::enisa(stage, *overdue, *hours_left, lang), "tone-danger"),
Reason::EnisaDeadline { stage: None, .. } => {
(tx::CRA_DUTY.get(lang).to_string(), "tone-danger")
}
Reason::SecretInCode => (tx::SECRET_IN_CODE.get(lang).to_string(), "tone-danger"),
Reason::FixAvailable { version } => (tx::fix(version), "tone-success"),
Reason::Resubmission { since } => (
tx::resubmission(&format_day(since, lang), lang),
"tone-info",
),
}
}
/// The page's state and what it does with it; every field is a copyable
/// handle, so event handlers take the whole of it.
#[derive(Clone, Copy)]
struct Inbox {
view: Resource<Result<InboxView, ServerFnError>>,
hidden: Signal<HashSet<String>>,
pending: Signal<Option<Pending>>,
undo: Signal<Option<UndoOffer>>,
offers: Signal<u64>,
busy: Signal<bool>,
page: Signal<Option<Rc<MountedData>>>,
toasts: Toasts,
lang: Lang,
}
impl Inbox {
/// Start `action` on `card`: at once, or by asking for its input first.
fn begin(mut self, card: &InboxCard, action: InboxAction) {
if !action.needs_input() {
self.decide(
card.title.clone(),
Pending {
key: card.key.clone(),
action,
text: String::new(),
justification: None,
},
);
return;
}
let text = match (action, &card.fix_version) {
(InboxAction::Affected, Some(version)) => tx::update_to(version, self.lang),
_ => String::new(),
};
self.pending.set(Some(Pending {
key: card.key.clone(),
action,
text,
justification: None,
}));
}
/// Apply `decision` to the card titled `title`, then offer to undo it.
fn decide(mut self, title: String, decision: Pending) {
if *self.busy.peek() || !decision.ready() {
return;
}
self.busy.set(true);
spawn(async move {
match decide_card(decision.request()).await {
Ok(answer) => {
self.hidden.write().insert(answer.key.clone());
self.pending.set(None);
let message = format!("{}: {title}", tx::DECIDED.get(self.lang));
self.offer(
UndoKind::Decision(UndoRequest {
key: answer.key,
previous: answer.previous,
}),
message,
);
self.view.restart();
}
Err(e) => self.failed(&e),
}
self.busy.set(false);
self.refocus().await;
});
}
/// Put `card` off as `choice` says, then offer to undo it.
fn snooze(mut self, card: &InboxCard, choice: SnoozeFor) {
if *self.busy.peek() {
return;
}
self.busy.set(true);
let request = SnoozeRequest {
key: card.key.clone(),
snooze_for: choice,
};
spawn(async move {
match snooze_card(request).await {
Ok(answer) => {
self.hidden.write().insert(answer.key.clone());
self.pending.set(None);
let message = tx::snoozed(&format_day(&answer.until, self.lang), self.lang);
self.offer(UndoKind::Snooze(answer.key), message);
self.view.restart();
}
Err(e) => self.failed(&e),
}
self.busy.set(false);
self.refocus().await;
});
}
/// Take the offered decision or snooze back.
fn undo(mut self) {
let Some(offer) = self.undo.write().take() else {
return;
};
spawn(async move {
let (key, result) = match offer.kind {
UndoKind::Decision(request) => (request.key.clone(), undo_decision(request).await),
UndoKind::Snooze(key) => (key.clone(), unsnooze_card(key).await),
};
match result {
Ok(()) => {
self.hidden.write().remove(&key);
self.toasts.push(ToastType::Info, tx::UNDONE.get(self.lang));
self.view.restart();
}
Err(e) => self.failed(&e),
}
self.refocus().await;
});
}
/// Show the undo strip with `message` for a while.
fn offer(mut self, kind: UndoKind, message: String) {
let id = *self.offers.peek() + 1;
self.offers.set(id);
self.undo.set(Some(UndoOffer { id, kind, message }));
#[cfg(feature = "web")]
{
let mut undo = self.undo;
spawn(async move {
gloo_timers::future::TimeoutFuture::new(UNDO_MS).await;
if undo.peek().as_ref().is_some_and(|o| o.id == id) {
undo.set(None);
}
});
}
}
fn failed(mut self, error: &ServerFnError) {
self.toasts.push(
ToastType::Error,
format!("{}: {error}", tx::FAILED.get(self.lang)),
);
}
/// Give the keyboard back to the page (a removed card took the focus
/// with it).
async fn refocus(self) {
let page = self.page.peek().clone();
if let Some(page) = page {
// Focusing can only fail when the page has gone; nothing to do then.
let _focused = page.set_focus(true).await;
}
}
}
#[component]
pub fn HeutePage() -> Element {
let lang = use_lang()();
let can_write = use_can_write();
let target = use_signal(String::new);
let bucket = use_signal(|| Bucket::Today);
let mut selected = use_signal(|| 0_usize);
let view = use_resource(move || async move { fetch_inbox(target(), bucket(), None).await });
let inbox = Inbox {
view,
hidden: use_signal(HashSet::new),
pending: use_signal(|| None),
undo: use_signal(|| None),
offers: use_signal(|| 0),
busy: use_signal(|| false),
page: use_signal(|| None),
toasts: use_context::<Toasts>(),
lang,
};
// The sidebar shows the workspace's count, not one target's.
use_effect(move || {
if let Some(Ok(view)) = &*view.read() {
if target.peek().is_empty() && *bucket.peek() == view.bucket {
*TODAY_COUNT.write() = Some(view.counts.today);
}
}
});
// Keep the chosen card in sight.
use_effect(move || {
let _ = selected();
let _scrolled = document::eval(
"document.querySelector('.inbox-card.is-selected')?.scrollIntoView({block: 'nearest'})",
);
});
let current = view.read().clone();
let cards: Vec<InboxCard> = match &current {
Some(Ok(v)) => {
let hidden = inbox.hidden.read();
v.cards
.iter()
.filter(|c| !hidden.contains(&c.key))
.cloned()
.collect()
}
_ => Vec::new(),
};
let chosen = selected().min(cards.len().saturating_sub(1));
let key_cards = cards.clone();
let mut pending = inbox.pending;
let onkeydown = move |e: KeyboardEvent| {
let modifiers = e.modifiers();
if modifiers.ctrl() || modifiers.meta() || modifiers.alt() {
return;
}
let key = match e.key() {
Key::Character(c) => c,
Key::Escape => {
pending.set(None);
return;
}
_ => return,
};
let card = key_cards.get(chosen);
match (key.as_str(), card) {
("j", Some(_)) => selected.set((chosen + 1).min(key_cards.len() - 1)),
("k", Some(_)) => selected.set(chosen.saturating_sub(1)),
("f" | "a", Some(card)) if can_write => {
if let Some(action) = shortcut_action(&key, card) {
e.prevent_default();
inbox.begin(card, action);
}
}
("s", Some(card)) if can_write => {
e.prevent_default();
inbox.snooze(card, SnoozeFor::Week);
}
_ => {}
}
};
rsx! {
div {
class: "inbox-page",
tabindex: "0",
onkeydown,
onmounted: move |e| {
let page = e.data();
let mut handle = inbox.page;
handle.set(Some(page.clone()));
spawn(async move {
let _focused = page.set_focus(true).await;
});
},
PageHeader {
title: tx::TITLE.get(lang).to_string(),
description: tx::SUBTITLE.get(lang).to_string(),
}
match current {
None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
Some(Err(_)) => rsx! {
div { class: "card inbox-empty",
p { {tx::LOAD_FAILED.get(lang)} }
button {
class: "btn btn-secondary btn-sm",
onclick: move |_| { let mut view = view; view.restart(); },
{common::RETRY.get(lang)}
}
}
},
Some(Ok(v)) => rsx! {
InboxHeader { view: v.clone(), target, bucket, selected, pending }
if cards.is_empty() {
div { class: "card inbox-empty",
p { {bucket_texts(v.bucket).2.get(lang)} }
}
} else {
div { class: "inbox-cards",
for (i, card) in cards.into_iter().enumerate() {
CardView {
key: "{card.key}",
target_name: v
.targets
.iter()
.find(|t| t.id == card.target_id)
.map_or_else(|| card.target_id.clone(), |t| t.name.clone()),
selected: i == chosen,
can_write,
pending: inbox
.pending
.read()
.clone()
.filter(|p| p.key == card.key),
on_select: move |_| selected.set(i),
on_action: {
let card = card.clone();
move |action| inbox.begin(&card, action)
},
on_snooze: {
let card = card.clone();
move |choice| inbox.snooze(&card, choice)
},
on_edit: move |next| pending.set(Some(next)),
on_submit: {
let title = card.title.clone();
move |decision| inbox.decide(title.clone(), decision)
},
on_cancel: move |_| pending.set(None),
card,
}
}
}
if can_write {
p { class: "inbox-shortcuts", {tx::SHORTCUTS.get(lang)} }
}
}
},
}
if let Some(offer) = (inbox.undo)() {
div { class: "inbox-undo", role: "status",
span { "{offer.message}" }
button {
class: "btn btn-sm inbox-undo-btn",
onclick: move |_| inbox.undo(),
{tx::UNDO.get(lang)}
}
}
}
}
}
}
/// The Erstbewertung, the target chips and the bucket tiles.
#[component]
fn InboxHeader(
view: InboxView,
target: Signal<String>,
bucket: Signal<Bucket>,
selected: Signal<usize>,
pending: Signal<Option<Pending>>,
) -> Element {
let lang = use_lang()();
let progress = view.progress;
let percent = progress.percent();
let mut choose_bucket = move |b: Bucket| {
bucket.set(b);
selected.set(0);
pending.set(None);
};
let mut choose_target = move |id: String| {
target.set(id);
selected.set(0);
pending.set(None);
};
rsx! {
section { class: "inbox-progress", title: tx::PROGRESS_HINT.get(lang),
div { class: "inbox-progress-head",
span { class: "inbox-progress-label", {tx::PROGRESS.get(lang)} }
span { class: "inbox-progress-value",
{tx::progress_line(progress.decided, progress.total, lang)}
}
span { class: "inbox-progress-percent", "{percent} %" }
}
div {
class: "inbox-progress-track",
role: "progressbar",
"aria-valuemin": "0",
"aria-valuemax": "100",
"aria-valuenow": "{percent}",
div { class: "inbox-progress-fill", style: "width: {percent}%" }
}
}
if !view.targets.is_empty() {
div { class: "inbox-targets",
button {
class: if target().is_empty() { "inbox-target is-active" } else { "inbox-target" },
onclick: move |_| choose_target(String::new()),
{tx::ALL_TARGETS.get(lang)}
}
for t in view.targets.iter().cloned() {
button {
key: "{t.id}",
class: if target() == t.id { "inbox-target is-active" } else { "inbox-target" },
onclick: move |_| choose_target(t.id.clone()),
"{t.name}"
span { class: "inbox-target-count", "{t.cards}" }
}
}
}
}
div { class: "inbox-buckets", role: "tablist",
for b in Bucket::ALL {
{
let (label, hint, _) = bucket_texts(b);
let active = view.bucket == b;
let tone = bucket_tone(b);
let count = view.counts.get(b);
rsx! {
button {
key: "{b.as_str()}",
class: if active { "inbox-bucket {tone} is-active" } else { "inbox-bucket {tone}" },
role: "tab",
"aria-selected": if active { "true" } else { "false" },
onclick: move |_| choose_bucket(b),
span { class: "inbox-bucket-count", "{count}" }
span { class: "inbox-bucket-label", {label.get(lang)} }
span { class: "inbox-bucket-hint", {hint.get(lang)} }
}
}
}
}
}
}
}
/// One card: what it is, why it is here, and its decisions.
#[component]
fn CardView(
card: InboxCard,
target_name: String,
selected: bool,
can_write: bool,
pending: Option<Pending>,
on_select: EventHandler<()>,
on_action: EventHandler<InboxAction>,
on_snooze: EventHandler<SnoozeFor>,
on_edit: EventHandler<Pending>,
on_submit: EventHandler<Pending>,
on_cancel: EventHandler<()>,
) -> Element {
let lang = use_lang()();
let mut date = use_signal(String::new);
let details = match card.kind {
CardKind::Finding => Route::FindingDetailPage {
id: card.item_ids.first().cloned().unwrap_or_default(),
},
CardKind::CvePackage => Route::target(card.target_id.clone()),
};
let size = match card.kind {
CardKind::CvePackage => Some(tx::cves(card.count)),
CardKind::Finding if card.count > 1 => Some(tx::places(card.count, lang)),
CardKind::Finding => None,
};
let chips: Vec<(String, &'static str)> = card.reasons.iter().map(|r| chip(r, lang)).collect();
let bucket = card.bucket;
rsx! {
article {
class: if selected { "inbox-card is-selected" } else { "inbox-card" },
onclick: move |_| on_select.call(()),
div { class: "inbox-card-head",
SeverityBadge { severity: card.severity.to_string() }
h3 { class: "inbox-card-title", "{card.title}" }
}
p { class: "inbox-card-sub",
span { class: "inbox-card-target", "{target_name}" }
if !card.subtitle.is_empty() {
code { class: "inbox-card-place", "{card.subtitle}" }
}
if let Some(size) = size {
span { class: "inbox-card-size", "{size}" }
}
}
if !chips.is_empty() {
div { class: "inbox-chips",
for (label, tone) in chips {
span { class: "inbox-chip {tone}", "{label}" }
}
}
}
if let Some(note) = card.note.clone() {
p { class: "inbox-card-note",
span { class: "inbox-card-note-label", {tx::AI_NOTE.get(lang)} }
"{note}"
}
}
if let Some(decision) = pending {
DecisionInput { decision, on_edit, on_submit, on_cancel }
} else {
div { class: "inbox-actions",
if can_write {
for (i, action) in card.actions.iter().copied().enumerate() {
button {
key: "{i}",
class: if i == 0 { "btn btn-primary btn-sm" } else { "btn btn-secondary btn-sm" },
onclick: move |e| {
e.stop_propagation();
on_action.call(action);
},
{action_label(action, bucket).get(lang)}
}
}
details {
class: "inbox-later",
onclick: move |e| e.stop_propagation(),
summary { class: "btn btn-ghost btn-sm", {tx::LATER_MENU.get(lang)} " ▾" }
div { class: "inbox-later-menu",
button {
class: "inbox-later-option",
onclick: move |_| on_snooze.call(SnoozeFor::Week),
{tx::ONE_WEEK.get(lang)}
}
button {
class: "inbox-later-option",
onclick: move |_| on_snooze.call(SnoozeFor::Month),
{tx::ONE_MONTH.get(lang)}
}
label { class: "inbox-later-date",
span { {tx::ON_DATE.get(lang)} }
input {
r#type: "date",
value: "{date}",
oninput: move |e| date.set(e.value()),
onkeydown: move |e| e.stop_propagation(),
}
}
button {
class: "btn btn-secondary btn-sm",
disabled: NaiveDate::parse_from_str(&date(), "%Y-%m-%d").is_err(),
onclick: move |_| {
if let Ok(day) = NaiveDate::parse_from_str(&date(), "%Y-%m-%d") {
on_snooze.call(SnoozeFor::Date { date: day });
}
},
{tx::SET_DATE.get(lang)}
}
}
}
}
Link {
class: "inbox-details",
to: details,
onclick: move |e: MouseEvent| e.stop_propagation(),
{tx::DETAILS.get(lang)}
}
}
}
}
}
}
/// The input a decision needs before it can be made.
#[component]
fn DecisionInput(
decision: Pending,
on_edit: EventHandler<Pending>,
on_submit: EventHandler<Pending>,
on_cancel: EventHandler<()>,
) -> Element {
let lang = use_lang()();
let placeholder = match decision.action {
InboxAction::NotAffected => vex_tx::IMPACT_STATEMENT,
InboxAction::Affected => vex_tx::ACTION_STATEMENT,
InboxAction::AcceptedRisk | InboxAction::FalsePositive | InboxAction::Confirm => tx::REASON,
};
let ready = decision.ready();
let typed = decision.clone();
let chosen = decision.clone();
let submitted = decision.clone();
let on_key = decision.clone();
let justification = decision
.justification
.map(VexJustification::as_str)
.unwrap_or_default();
rsx! {
div {
class: "inbox-input",
onclick: move |e| e.stop_propagation(),
if decision.action == InboxAction::NotAffected {
select {
class: "inbox-input-select",
value: "{justification}",
"aria-label": vex_tx::JUSTIFICATION.get(lang),
onkeydown: move |e| e.stop_propagation(),
onchange: move |e| {
let mut next = chosen.clone();
next.justification = JUSTIFICATIONS
.iter()
.map(|(j, _)| *j)
.find(|j| j.as_str() == e.value());
on_edit.call(next);
},
option { value: "", {vex_tx::NO_JUSTIFICATION.get(lang)} }
for (j, label) in JUSTIFICATIONS {
option { key: "{j.as_str()}", value: j.as_str(), {label.get(lang)} }
}
}
}
input {
class: "inbox-input-text",
r#type: "text",
value: "{decision.text}",
placeholder: placeholder.get(lang),
"aria-label": placeholder.get(lang),
onmounted: move |e| async move {
// Focusing can only fail when the input has gone.
let _focused = e.data().set_focus(true).await;
},
oninput: move |e| {
let mut next = typed.clone();
next.text = e.value();
on_edit.call(next);
},
onkeydown: move |e| {
e.stop_propagation();
match e.key() {
Key::Enter if on_key.ready() => on_submit.call(on_key.clone()),
Key::Escape => on_cancel.call(()),
_ => {}
}
},
}
button {
class: "btn btn-primary btn-sm",
disabled: !ready,
onclick: move |_| on_submit.call(submitted.clone()),
{tx::DECIDE.get(lang)}
}
button {
class: "btn btn-ghost btn-sm",
onclick: move |_| on_cancel.call(()),
{tx::CANCEL.get(lang)}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::Severity;
fn card(kind: CardKind, actions: Vec<InboxAction>) -> InboxCard {
InboxCard {
key: "f-1".into(),
kind,
bucket: Bucket::Today,
target_id: "t1".into(),
title: "t".into(),
subtitle: String::new(),
severity: Severity::High,
count: 1,
reasons: Vec::new(),
item_ids: vec!["1".into()],
actions,
fix_version: None,
note: None,
}
}
#[test]
fn shortcuts_pick_the_card_s_matching_action() {
use InboxAction::*;
let finding = card(CardKind::Finding, vec![FalsePositive, AcceptedRisk]);
assert_eq!(shortcut_action("f", &finding), Some(FalsePositive));
assert_eq!(shortcut_action("a", &finding), Some(AcceptedRisk));
assert_eq!(shortcut_action("x", &finding), None);
let ai = card(CardKind::Finding, vec![FalsePositive, Confirm]);
assert_eq!(shortcut_action("a", &ai), None, "not offered");
let cve = card(CardKind::CvePackage, vec![Affected, NotAffected]);
assert_eq!(shortcut_action("f", &cve), Some(NotAffected));
assert_eq!(shortcut_action("a", &cve), Some(Affected));
}
#[test]
fn a_decision_needs_its_input_and_sends_it_in_the_right_field() {
let mut risk = Pending {
key: "f-1".into(),
action: InboxAction::AcceptedRisk,
text: " ".into(),
justification: None,
};
assert!(!risk.ready());
risk.text = " isolated ".into();
assert!(risk.ready());
assert_eq!(risk.request().reason.as_deref(), Some("isolated"));
assert_eq!(risk.request().statement, None);
let mut not_affected = Pending {
key: "c-1-2".into(),
action: InboxAction::NotAffected,
text: String::new(),
justification: None,
};
assert!(!not_affected.ready());
not_affected.justification = Some(VexJustification::VulnerableCodeNotPresent);
assert!(not_affected.ready());
assert_eq!(
not_affected.request().justification,
Some(VexJustification::VulnerableCodeNotPresent)
);
let affected = Pending {
key: "c-1-2".into(),
action: InboxAction::Affected,
text: "Update to version 2.17.1.".into(),
justification: Some(VexJustification::ComponentNotPresent),
};
assert_eq!(
affected.request().statement.as_deref(),
Some("Update to version 2.17.1.")
);
assert_eq!(affected.request().justification, None);
}
#[test]
fn chips_name_their_reason() {
let (label, tone) = chip(&Reason::Kev, Lang::De);
assert_eq!(label, "Aktiv ausgenutzt (CISA KEV)");
assert_eq!(tone, "tone-danger");
let (label, _) = chip(
&Reason::FixAvailable {
version: "2.17.1".into(),
},
Lang::En,
);
assert_eq!(label, "Fix: 2.17.1");
assert_eq!(
action_label(InboxAction::FalsePositive, Bucket::LikelyFalsePositive),
tx::CONFIRM_FALSE_POSITIVE
);
assert_eq!(
action_label(InboxAction::FalsePositive, Bucket::Today),
tx::FALSE_POSITIVE
);
}
}
+2
View File
@@ -10,6 +10,7 @@ pub mod findings;
pub mod graph_explorer;
pub(crate) mod graph_view;
pub mod impact_analysis;
pub mod inbox;
pub mod issues;
pub mod mcp_servers;
pub mod mcp_tokens;
@@ -32,6 +33,7 @@ pub use finding_detail::FindingDetailPage;
pub use findings::FindingsPage;
pub use graph_explorer::GraphExplorerPage;
pub use impact_analysis::ImpactAnalysisPage;
pub use inbox::HeutePage;
pub use issues::IssuesPage;
pub use mcp_servers::McpServersPage;
pub use mcp_tokens::McpTokensPage;