From 6746f2eb20986a283ad55e6ab123844d483f38d8 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 28 Sep 2026 23:51:06 +0200 Subject: [PATCH] fix(dashboard): help assistant signs in, scan list follows a started scan, catalog controls readable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The help assistant called the agent without the session's token; the agent refused it with an empty 401 that read as "Failed to parse response". It now goes through the agent client like every other call. - The scan runs list only polled while a run was running or the history was empty, so a scan started next to finished runs never appeared until a reload. "Prüfung starten" now tells the list, which looks for the new run for up to a minute. - "+N Kontrollen aus dem BreakPilot-Katalog" listed the ids only in a hover tooltip. GET /api/v1/controls?ids= describes master controls from the catalog (loaded once per agent process), and the finding page folds them out with their label and first requirement. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/api/handlers/evidence.rs | 32 ++++- compliance-agent/src/api/routes.rs | 4 + compliance-agent/src/controls/lookup.rs | 109 ++++++++++++++++++ compliance-agent/src/controls/mod.rs | 2 + compliance-agent/src/controls/scan_triage.rs | 2 +- compliance-dashboard/assets/main.css | 14 +++ .../src/components/scan_runs.rs | 49 ++++++-- .../src/infrastructure/evidence.rs | 26 +++++ .../src/infrastructure/help_chat.rs | 23 +--- .../src/pages/finding_detail.rs | 45 +++++++- compliance-dashboard/src/pages/target.rs | 8 +- 11 files changed, 281 insertions(+), 33 deletions(-) create mode 100644 compliance-agent/src/controls/lookup.rs diff --git a/compliance-agent/src/api/handlers/evidence.rs b/compliance-agent/src/api/handlers/evidence.rs index 88cbfe8..38655f1 100644 --- a/compliance-agent/src/api/handlers/evidence.rs +++ b/compliance-agent/src/api/handlers/evidence.rs @@ -2,7 +2,7 @@ //! (see [`crate::evidence`]), for the dashboard's download and for //! breakpilot's document service to pull. -use axum::extract::{Extension, Path}; +use axum::extract::{Extension, Path, Query}; use axum::http::{header, HeaderValue, StatusCode}; use axum::response::IntoResponse; use axum::Json; @@ -211,3 +211,33 @@ pub async fn evidence_pack( zip, )) } + +/// Most control ids one lookup describes. +const MAX_CONTROL_LOOKUP: usize = 50; + +/// The query of [`describe_controls`]: comma-separated control ids. +#[derive(Debug, serde::Deserialize)] +pub struct ControlIdsQuery { + ids: String, +} + +/// GET /api/v1/controls?ids=mc-1,mc-2 — what the master controls stamped on +/// a finding require, for the finding page. Unknown ids are left out; at +/// most [`MAX_CONTROL_LOOKUP`] are described. +#[tracing::instrument(skip_all)] +pub async fn describe_controls( + Extension(agent): AgentExt, + _tenant: TenantCtx, + Query(query): Query, +) -> Json { + let ids: Vec = query + .ids + .split(',') + .map(str::trim) + .filter(|id| !id.is_empty()) + .take(MAX_CONTROL_LOOKUP) + .map(String::from) + .collect(); + let controls = crate::controls::describe_master_controls(&agent.config, &ids).await; + Json(serde_json::json!({ "data": controls })) +} diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 6df97c2..fcb46f6 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -86,6 +86,10 @@ pub fn build_router() -> Router { "/api/v1/compliance/summary", get(handlers::evidence::compliance_summary), ) + .route( + "/api/v1/controls", + get(handlers::evidence::describe_controls), + ) // Findings from a manual DAST run or penetration test. .route( "/api/v1/targets/{id}/findings", diff --git a/compliance-agent/src/controls/lookup.rs b/compliance-agent/src/controls/lookup.rs new file mode 100644 index 0000000..4fef60b --- /dev/null +++ b/compliance-agent/src/controls/lookup.rs @@ -0,0 +1,109 @@ +//! What a master control says, for a reader looking at a finding mapped to it. +//! +//! The semantic pass stamps master-control ids (`mc-10056`) on findings; the +//! dashboard has no catalog of its own, so it asks the agent what they mean. + +use std::collections::HashMap; + +use serde::Serialize; +use tokio::sync::OnceCell; + +use compliance_core::traits::Control; +use compliance_core::AgentConfig; + +use super::scan_triage::provider_for; + +/// A master control as a reader sees it next to a finding. +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +pub struct ControlSummary { + /// The id stamped on findings (`mc-10056`). + pub id: String, + /// The catalog's label (`MC-10056`). + pub label: String, + /// What the control requires: the first requirement of its statement. + pub statement: String, +} + +/// The master-controls catalog by id, loaded once per agent process. The +/// catalog ships with the image, so a new one arrives with a redeploy. A +/// failed load is not cached: the next lookup tries again. +static MASTER_CONTROLS: OnceCell> = OnceCell::const_new(); + +/// Describe `ids` from the master-controls catalog, in the order given. +/// Ids the catalog does not know (a CRA id, a control since removed) are left +/// out. +/// +/// # Returns +/// +/// Empty when no catalog is configured or it cannot be loaded (logged). +pub async fn describe_master_controls(config: &AgentConfig, ids: &[String]) -> Vec { + let catalog = MASTER_CONTROLS + .get_or_try_init(|| async { + let provider = provider_for(config).ok_or("no controls catalog configured")?; + let doc = provider.load_master_controls().await.map_err(|e| { + tracing::warn!(error = %e, "master-controls catalog unavailable"); + "master-controls catalog unavailable" + })?; + Ok::<_, &str>(by_id(&doc.to_controls())) + }) + .await; + match catalog { + Ok(catalog) => ids + .iter() + .filter_map(|id| catalog.get(id).cloned()) + .collect(), + Err(_) => Vec::new(), + } +} + +/// Index `controls` by id, each with its first requirement as the statement. +/// The catalog joins a master control's requirements with ` | `. +fn by_id(controls: &[Control]) -> HashMap { + controls + .iter() + .map(|c| { + let statement = c.text.split(" | ").next().unwrap_or_default().trim(); + let summary = ControlSummary { + id: c.id.clone(), + label: c.id.to_ascii_uppercase(), + statement: statement.to_string(), + }; + (c.id.clone(), summary) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::models::onboarding::ComplianceFramework; + + fn control(id: &str, text: &str) -> Control { + Control { + id: id.to_string(), + framework: ComplianceFramework::Cra, + title: "slug_title".to_string(), + text: text.to_string(), + source: None, + severity: None, + evidence_type: None, + } + } + + #[test] + fn a_control_reads_as_its_label_and_first_requirement() { + let catalog = by_id(&[control( + "mc-10056", + "Erklärung unterzeichnen. | Zugang gewähren. | Kopie aufbewahren.", + )]); + + assert_eq!( + catalog.get("mc-10056"), + Some(&ControlSummary { + id: "mc-10056".to_string(), + label: "MC-10056".to_string(), + statement: "Erklärung unterzeichnen.".to_string(), + }) + ); + } +} diff --git a/compliance-agent/src/controls/mod.rs b/compliance-agent/src/controls/mod.rs index f08ffd7..4b86c1e 100644 --- a/compliance-agent/src/controls/mod.rs +++ b/compliance-agent/src/controls/mod.rs @@ -8,6 +8,7 @@ mod checker; mod index; mod judge; +mod lookup; mod oscal_provider; mod scan_triage; mod semantic; @@ -17,6 +18,7 @@ mod triage; pub use checker::GroundedControlChecker; pub use index::ControlIndex; pub use judge::{ControlJudge, JudgeError, LlmControlJudge, PROMPT_VERSION}; +pub use lookup::{describe_master_controls, ControlSummary}; pub use oscal_provider::OscalControlsProvider; pub use scan_triage::{ cra_catalog, grounded_surface_findings, semantic_stamp_findings, triage_repo_findings, diff --git a/compliance-agent/src/controls/scan_triage.rs b/compliance-agent/src/controls/scan_triage.rs index f7cab81..0e5d79a 100644 --- a/compliance-agent/src/controls/scan_triage.rs +++ b/compliance-agent/src/controls/scan_triage.rs @@ -115,7 +115,7 @@ pub async fn triage_repo_findings( /// The catalog source for this agent: the breakpilot backend when /// `BREAKPILOT_BASE_URL` is set, else the baked/previously written snapshots /// under `BREAKPILOT_SNAPSHOT_DIR`. `None` = control triage is off. -fn provider_for(config: &AgentConfig) -> Option { +pub(super) fn provider_for(config: &AgentConfig) -> Option { let snapshot_dir = Path::new(&config.breakpilot.snapshot_dir); if config.breakpilot.base_url.is_none() && !OscalControlsProvider::has_snapshots(snapshot_dir) { return None; diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 0f8d105..39295a8 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -5099,3 +5099,17 @@ input[type="file"] { .scan-sub-step { font-weight: 400; } + +.catalog-controls summary { + cursor: pointer; +} + +.catalog-controls ul { + list-style: none; + margin: 6px 0 0; + padding: 0; + display: grid; + gap: 6px; + color: var(--text-secondary); + font-size: 13px; +} diff --git a/compliance-dashboard/src/components/scan_runs.rs b/compliance-dashboard/src/components/scan_runs.rs index 43333bf..df3a98b 100644 --- a/compliance-dashboard/src/components/scan_runs.rs +++ b/compliance-dashboard/src/components/scan_runs.rs @@ -22,16 +22,34 @@ const REVEAL_LIMIT: u32 = 6; #[cfg(feature = "web")] const POLL_MS: u32 = 5_000; +/// How many polls to wait for a just-started scan's run to show up. +#[cfg(feature = "web")] +const EXPECT_RUN_POLLS: u32 = 12; + /// The scan runs of one target, newest first. Refreshes itself while a run is /// in progress (or none is recorded yet), so the customer sees it move /// without reloading. +/// +/// `started` counts the scans started on this page: each one makes the list +/// look again until the new run shows up, even when every run before it +/// had finished. #[component] -pub fn ScanRunList(target_id: String) -> Element { +pub fn ScanRunList(target_id: String, started: Option>) -> Element { let lang = use_lang()(); let id = use_signal(|| target_id.clone()); + // A scan was started here and its run has not been seen running yet. + let mut expect_run = use_signal(|| false); // Only the browser build restarts it (the polling below). #[cfg_attr(not(feature = "web"), allow(unused_mut))] - let mut runs = use_resource(move || async move { fetch_target_scan_runs(id()).await.ok() }); + let mut runs = use_resource(move || async move { + // Reading `started` reruns this as soon as a scan is started. + if let Some(started) = started { + if started() > 0 { + expect_run.set(true); + } + } + fetch_target_scan_runs(id()).await.ok() + }); // Runs seen running, and those that finished while this page was open: // only those are revealed, not every run in the history. let mut seen_running = use_signal(HashSet::::new); @@ -43,6 +61,7 @@ pub fn ScanRunList(target_id: String) -> Element { for run in &list { let id = run.id.map(|id| id.to_hex()).unwrap_or_default(); if run.status == ScanRunStatus::Running { + expect_run.set(false); seen_running.write().insert(id); } else if seen_running.peek().contains(&id) && !finished_here.peek().contains(&id) { finished_here.write().insert(id); @@ -53,17 +72,29 @@ pub fn ScanRunList(target_id: String) -> Element { use_future(move || async move { // Only the browser polls; a server render must not leave a loop behind. #[cfg(feature = "web")] + let mut expecting_polls = 0u32; + #[cfg(feature = "web")] loop { gloo_timers::future::TimeoutFuture::new(POLL_MS).await; + // A run that finished before it was ever seen running must not + // keep the page polling: stop expecting it after a minute. + if *expect_run.peek() { + expecting_polls += 1; + if expecting_polls > EXPECT_RUN_POLLS { + expect_run.set(false); + expecting_polls = 0; + } + } // Also while the history is empty: a scan just started may not // be recorded yet when the first request lands. - let waiting = runs - .peek() - .as_ref() - .and_then(|r| r.as_ref()) - .is_some_and(|list| { - list.is_empty() || list.iter().any(|r| r.status == ScanRunStatus::Running) - }); + let waiting = *expect_run.peek() + || runs + .peek() + .as_ref() + .and_then(|r| r.as_ref()) + .is_some_and(|list| { + list.is_empty() || list.iter().any(|r| r.status == ScanRunStatus::Running) + }); if waiting { runs.restart(); } diff --git a/compliance-dashboard/src/infrastructure/evidence.rs b/compliance-dashboard/src/infrastructure/evidence.rs index 1fe8fe8..20d8d3d 100644 --- a/compliance-dashboard/src/infrastructure/evidence.rs +++ b/compliance-dashboard/src/infrastructure/evidence.rs @@ -72,6 +72,32 @@ pub async fn fetch_compliance_summary() -> Result, Ser serde_json::from_value(body["data"].clone()).map_err(|e| ServerFnError::new(e.to_string())) } +/// A master control from the BreakPilot catalog, as the agent describes it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct CatalogControl { + /// The id stamped on findings (`mc-10056`). + pub id: String, + /// The catalog's label (`MC-10056`). + pub label: String, + /// What the control requires. + pub statement: String, +} + +/// What the master controls `ids` require (`GET /api/v1/controls`). +#[server] +pub async fn fetch_catalog_controls( + ids: Vec, +) -> Result, ServerFnError> { + let resp = super::agent_client::agent_get("/api/v1/controls") + .await? + .query(&[("ids", ids.join(","))]) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let body: serde_json::Value = super::agent_client::json_or_error(resp).await?; + serde_json::from_value(body["data"].clone()).map_err(|e| ServerFnError::new(e.to_string())) +} + /// The target's state against every CRA Annex I control /// (`GET /api/v1/targets/{id}/compliance`), as the agent sends it. #[server] diff --git a/compliance-dashboard/src/infrastructure/help_chat.rs b/compliance-dashboard/src/infrastructure/help_chat.rs index 6286854..8437d05 100644 --- a/compliance-dashboard/src/infrastructure/help_chat.rs +++ b/compliance-dashboard/src/infrastructure/help_chat.rs @@ -28,17 +28,11 @@ pub async fn send_help_chat_message( message: String, history: Vec, ) -> Result { - let state: super::server_state::ServerState = - dioxus_fullstack::FullstackContext::extract().await?; - - let url = format!("{}/api/v1/help/chat", state.agent_api_url); - let client = reqwest::Client::builder() + // Through the agent client, which signs the request in: the agent + // refuses an anonymous one, and its empty 401 read as a parse error. + let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/help/chat") + .await? .timeout(std::time::Duration::from_secs(120)) - .build() - .map_err(|e| ServerFnError::new(e.to_string()))?; - - let resp = client - .post(&url) .json(&serde_json::json!({ "message": message, "history": history, @@ -46,14 +40,7 @@ pub async fn send_help_chat_message( .send() .await .map_err(|e| ServerFnError::new(format!("Help chat request failed: {e}")))?; - - let text = resp - .text() - .await - .map_err(|e| ServerFnError::new(format!("Failed to read response: {e}")))?; - - let body: HelpChatApiResponse = serde_json::from_str(&text) - .map_err(|e| ServerFnError::new(format!("Failed to parse response: {e}")))?; + let body: HelpChatApiResponse = super::agent_client::json_or_error(resp).await?; Ok(body) } diff --git a/compliance-dashboard/src/pages/finding_detail.rs b/compliance-dashboard/src/pages/finding_detail.rs index 1623f31..8a73aea 100644 --- a/compliance-dashboard/src/pages/finding_detail.rs +++ b/compliance-dashboard/src/pages/finding_detail.rs @@ -8,6 +8,7 @@ use crate::components::page_header::PageHeader; use crate::components::severity_badge::SeverityBadge; use crate::i18n::texts::{common, findings as tx}; use crate::i18n::{format_time, use_lang}; +use crate::infrastructure::evidence::{fetch_catalog_controls, CatalogControl}; use crate::infrastructure::findings::{location, mask_secrets, wire_name}; use crate::pages::findings::status_icon; use compliance_core::models::{FindingStatus, ScanType}; @@ -169,8 +170,8 @@ pub fn FindingDetailPage(id: String) -> Element { } } if !catalog_refs.is_empty() { - li { class: "finding-refs-catalog", title: "{catalog_refs.join(\", \")}", - "+{catalog_refs.len()} {tx::CATALOG_CONTROLS.get(lang)}" + li { class: "finding-refs-catalog", + CatalogControls { ids: catalog_refs.clone() } } } } @@ -392,3 +393,43 @@ fn SaveNote(state: SaveState) -> Element { }, } } + +/// The BreakPilot catalog controls a finding was mapped to, folded under +/// their count: each with its label and what it requires. Shows the bare +/// ids while the descriptions load, or when the agent cannot give them. +#[component] +fn CatalogControls(ids: Vec) -> Element { + let lang = use_lang()(); + let count = ids.len(); + let wanted = use_signal(|| ids.clone()); + let described = use_resource(move || async move { + fetch_catalog_controls(wanted()) + .await + .ok() + .filter(|c| !c.is_empty()) + }); + let controls: Vec = described.read().clone().flatten().unwrap_or_else(|| { + ids.iter() + .map(|id| CatalogControl { + id: id.clone(), + label: id.to_ascii_uppercase(), + statement: String::new(), + }) + .collect() + }); + rsx! { + details { class: "catalog-controls", + summary { "+{count} {tx::CATALOG_CONTROLS.get(lang)}" } + ul { + for c in controls { + li { key: "{c.id}", + span { class: "badge badge-info", "{c.label}" } + if !c.statement.is_empty() { + span { " {c.statement}" } + } + } + } + } + } + } +} diff --git a/compliance-dashboard/src/pages/target.rs b/compliance-dashboard/src/pages/target.rs index 8d5b1f3..a07f84d 100644 --- a/compliance-dashboard/src/pages/target.rs +++ b/compliance-dashboard/src/pages/target.rs @@ -93,6 +93,7 @@ pub fn TargetPage(id: String) -> Element { let mut confirm_delete = use_signal(|| false); let mut adding_manual = use_signal(|| false); let mut starting = use_signal(|| false); + let mut scans_started = use_signal(|| 0u32); let snapshot = target.read().clone(); let Some(Some(resp)) = snapshot else { @@ -151,7 +152,10 @@ pub fn TargetPage(id: String) -> Element { starting.set(true); spawn(async move { match trigger_target_scan(target_id()).await { - Ok(_) => toasts.push(ToastType::Success, tx::SCAN_STARTED.get(lang)), + Ok(_) => { + toasts.push(ToastType::Success, tx::SCAN_STARTED.get(lang)); + scans_started += 1; + } Err(e) => toasts.push(ToastType::Error, e.to_string()), } starting.set(false); @@ -253,7 +257,7 @@ pub fn TargetPage(id: String) -> Element { div { class: "target-columns", section { class: "card", div { class: "target-card-head", h3 { {tx::SCAN_RUNS.get(lang)} } } - div { class: "target-card-body", ScanRunList { target_id: id.clone() } } + div { class: "target-card-body", ScanRunList { target_id: id.clone(), started: scans_started } } } section { class: "card", div { class: "target-card-head", h3 { {tx::SCOPE.get(lang)} } }